All files / pub-keystore/couchdb index.js

94.29% Statements 413/438
77.03% Branches 104/135
72.72% Functions 16/22
94.29% Lines 413/438

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 4401x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 563x 563x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 424x 424x 424x 424x 15x 15x 409x 409x 424x 424x 140x 140x 140x 140x 253x 253x 253x 253x 140x 140x 140x 140x 140x 140x 140x 140x 224x 224x 224x     224x 224x 224x     224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 224x 140x 140x 140x 6x 6x 6x 6x 6x         6x 6x                         140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 564x 1x 1x 1x 1x 1034x 1034x 1025x 1034x 1034x 560x 560x 465x 465x 465x 465x 465x 465x 465x 465x 281x 281x 465x 1x 1x 1x 64x 64x 64x 64x 64x 64x 56x 56x 56x 56x 64x 392x 392x 392x 392x 280x 280x 392x 56x 56x 64x 1x 1x 1x 856x 856x 848x 856x 856x 560x 560x 288x 288x 288x 288x 280x 288x 1x 1x 1x 945x 945x 937x 945x 945x 560x 560x 377x 377x 377x 377x 281x 377x 1x 1x 1x 237x 237x 237x 236x 236x 236x 237x 237x 237x 237x 237x 237x 237x 8x 8x 229x 229x 229x 229x 229x 237x 237x 3x 3x 3x 2x 3x 237x 226x 226x 226x 226x 226x 226x 226x 226x 226x 226x 226x 226x 226x 226x 45x 45x 181x 181x 181x 181x 226x 226x 226x 226x 226x 226x 226x 226x 226x 44x 44x 44x 44x 44x 44x 44x       182x 182x 226x 226x 1x 1x 1x 97x 97x 97x 97x 97x 97x 97x 8x 8x 89x 89x 89x 89x 89x 89x 89x 45x 89x 1x 1x 1x 579x 579x 579x 134x 134x 134x 134x 445x 445x 1x 1x 1x 579x 579x 567x 567x 567x 567x 567x 1x 1x 1x 563x 563x 563x 563x 563x 563x 563x 563x 563x 1x 1x 1x 302x 302x 302x 302x 302x 302x 302x 302x 302x 302x 302x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 301x 302x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x     16x 16x 16x 1x 1x 1x 36x 36x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 4x 4x 32x 32x 32x 32x 32x 32x 32x 1x 1x 1x 564x 564x 1x    
/*jslint node: true, nomen: true, forin: true */
"use strict";
 
var events = require('events'),
    util = require('util'),
    crypto = require('crypto'),
    nano = require('nano'),
    axios = require('axios'),
    design = require('./design'),
    status_not_found = 404,
    status_conflict = 409,
    status_db_exists = 412;
 
function PubKeyStoreCouchDB(config, cb)
{
    events.EventEmitter.call(this);
 
    var ths = this,
        called_back = false;
 
    this._config = config;
 
    this.db_host = config.db_host || 'http://127.0.0.1';
    this.db_port = config.db_port || 5984;
 
    const requestDefaults = {
        auth: config.username ? {
            username: config.username,
            password: config.password
        } : undefined,
        strictSSL: true,
        ca: config.ca,
        pool: {
            maxSockets: config.maxSockets || Infinity
        }
    };
 
    this._nano = nano(
    {
        url: this.db_host + ':' + this.db_port,
        requestDefaults
    });
 
    this.db_name = config.db_name || 'pub-keys';
    this._db = this._nano.use(this.db_name);
 
    if (config.no_changes)
    {
        return this._db.info(function (err)
        {
            if (err && (err.statusCode === status_not_found))
            {
                return cb(new Error('not_found'), ths);
            }
 
            return cb(err, ths);
        });
    }
 
    const relax = this._db.changesReader.request;
 
    this._db.changesReader.request = async function (opts)
    {
        const promise = relax(opts);
        process.nextTick(() => ths._feed.emit('confirm'));
        return await promise;
    };
 
    this._feed = this._db.changesReader.start(
    {
        since: 'now'
    });
 
    this._feed.on('change', function (change)
    {
        if (change.id.lastIndexOf('_design/', 0) === 0)
        {
            return;
        }
 
        if (config.verbose)
        {
            console.log('database change', change);
        }
 
        var rev, changes = change.changes, i, chng, crev;
 
        for (i = 0; i < changes.length; i += 1)
        {
            chng = changes[i];
            crev = chng.rev;
 
            if (crev !== undefined)
            {
                rev = crev;
            }
        }
 
        ths.emit('change', change.id, rev, !!change.deleted);
    });
 
    this._feed.on('error', function (err)
    {
        if (!this._feed)
        {
            return;
        }

        err.feed_error = true;

        if ((err.statusCode === status_not_found) ||
            (err.message && (err.message.indexOf('missing_target') >= 0)))
        {
            err.message = 'not_found';
        }

        if (called_back)
        {
            ths.emit('error', err);
        }
        else
        {
            called_back = true;
            cb(err, ths);
        }
    });
 
    this._feed.once('confirm', function ()
    {
        if (!called_back)
        {
            called_back = true;
            cb(null, ths);
        }
    });
}
 
util.inherits(PubKeyStoreCouchDB, events.EventEmitter);
 
PubKeyStoreCouchDB.prototype.get_pub_key_by_issuer_id = function (issuer_id, cb)
{
    if (!this._db) { return cb(new Error('not_open')); }
 
    if ((issuer_id === null) || (issuer_id === undefined))
    {
        return cb(null, null);
    }
 
    this._db.view('pub_keys', 'by_issuer_id',
    {
        key: issuer_id
    }, function (err, res)
    {
        if (err) { return cb(err); }
        if (res.rows.length === 0) { return cb(null, null); }
        var res0 = res.rows[0];
        cb(null, res0.value.pub_key, res0.id, res0.value.rev);
    });
};
 
PubKeyStoreCouchDB.prototype.get_uris = function (cb)
{
    if (!this._db) { return cb(new Error('not_open')); }
 
    this._db.list(function (err, res)
    {
        if (err) { return cb(err); }
 
        var i, key, uris = [];
 
        for (i = 0; i < res.rows.length; i += 1)
        {
            key = res.rows[i].key;
 
            if (key.lastIndexOf('_design/', 0) !== 0)
            {
                uris.push(key);
            }
        }
 
        cb(null, uris);
    });
};
 
PubKeyStoreCouchDB.prototype.get_issuer_id = function (uri, cb)
{
    if (!this._db) { return cb(new Error('not_open')); }
 
    if ((uri === null) || (uri === undefined))
    {
        return cb(null, null);
    }
 
    this._db.get(uri, function (err, doc)
    {
        if (err) { return cb(err.statusCode === status_not_found ? null : err, null); }
        cb(null, doc.issuer_id, doc._rev);
    });
};
 
PubKeyStoreCouchDB.prototype.get_pub_key_by_uri = function (uri, cb)
{
    if (!this._db) { return cb(new Error('not_open')); }
 
    if ((uri === null) || (uri === undefined))
    {
        return cb(null, null);
    }
 
    this._db.get(uri, function (err, doc)
    {
        if (err) { return cb(err.statusCode === status_not_found ? null : err, null); }
        cb(null, doc.pub_key, doc.issuer_id, doc._rev);
    });
};
 
PubKeyStoreCouchDB.prototype.add_pub_key = function (uri, pub_key, options, cb)
{
    if (typeof options === 'function')
    {
        cb = options;
        options = {};
    }
    options = options || {};
    cb = cb || function () { return undefined; };
 
    if (!this._db) { return cb(new Error('not_open')); }
 
    if ((uri === null) || (uri === undefined))
    {
        return cb(new Error('invalid_uri'));
    }
 
    var ths = this,
        issuer_id = crypto.randomBytes(64).toString('hex'),
        doc = { issuer_id: issuer_id, pub_key: pub_key };
 
    if (this._config.no_updates && !options.allow_update)
    {
        return this._db.insert(doc, uri, function (err, res)
        {
            if (err) { return cb(err); }
            cb(null, issuer_id, res.rev);
        });
    }    
 
    // Find existing revision first otherwise revision may start from 1
    // (if doc has been deleted), meaning subsequent deletions will have
    // revision 2. When replicating, if the replica has a doc with a higher
    // revision, the deletion is lost.
 
    this._db.fetch({ keys: [ uri ] }, function (err, res)
    {
        if (err) { return cb(err); }
 
        var row = res.rows[0];
 
        if (row.error)
        {
            if (row.error !== 'not_found') { return cb(row.error); }
        }
        else
        {
            doc._rev = row.value.rev;
        }
 
        if (!ths._db) { return cb(new Error('not_open')); }
        
        ths._db.insert(doc, uri, function (err, res)
        {
            // if conflict then try again
 
            if (err)
            {
                if (err.statusCode === status_conflict)
                {
                    return setTimeout(function ()
                    {
                        ths.add_pub_key(uri, pub_key, cb);
                    }, 1000 + Math.random() * 1000);
                }
                
                return cb(err);
            }
 
            cb(null, issuer_id, res.rev);
        });
    });
};
 
PubKeyStoreCouchDB.prototype.remove_pub_key = function (uri, cb)
{
    cb = cb || function () { return undefined; };
 
    if (!this._db) { return cb(new Error('not_open')); }
 
    if ((uri === null) || (uri === undefined))
    {
        return cb(new Error('invalid_uri'));
    }
 
    var ths = this;
 
    this._db.get(uri, function (err, doc)
    {
        if (err) { return cb(err.statusCode === status_not_found ? null : err); }
        if (!ths._db) { return cb(new Error('not_open')); }
        ths._db.destroy(uri, doc._rev, cb);
    });
};
 
PubKeyStoreCouchDB.prototype._stop = function (cb)
{
    if (this._feed && this._db.changesReader.started)
    {
        this._feed.once('end', cb);
        this._feed = null;
        return this._db.changesReader.stop();
    }
 
    cb();
};
 
PubKeyStoreCouchDB.prototype._close_nano = function (cb)
{
    if (!this._nano) { return cb(new Error('not_open')); }
 
    this._nano = null;
    this._db = null;
 
    cb();
};
 
PubKeyStoreCouchDB.prototype.close = function (cb)
{
    cb = cb || function () { return undefined; };
 
    var ths = this;
 
    this._stop(function ()
    {
        ths._close_nano(cb);
    });
};
 
PubKeyStoreCouchDB.prototype.create = function (cb)
{
    cb = cb || function () { return undefined; };
 
    if (!this._db) { return cb(new Error('not_open')); }
 
    var ths = this;
 
    this._nano.db.create(this.db_name, function (err)
    {
        if (err && (err.statusCode !== status_db_exists)) { return cb(err); }
        if (!ths._db) { return cb(new Error('not_open')); }
 
        /*jslint unparam: true */
        ths._db.insert(
        {
            views: {},
            validate_doc_update: design.validate.toString().replace('DB_NAME', ths.db_name)
        }, '_design/_auth', function (err)
        {
            if (err && (err.statusCode !== status_conflict)) { return cb(err); }
            if (!ths._db) { return cb(new Error('not_open')); }
 
            ths._db.insert(
            {
                views: {
                    by_issuer_id: {
                        map: design.by_issuer_id
                    }
                }
            }, '_design/pub_keys', function (err)
            {
                if (err && (err.statusCode !== status_conflict)) { return cb(err); }
                if (!ths._db) { return cb(new Error('not_open')); }
                cb();
            });
        });
        /*jslint unparam: false */
    });
};
 
PubKeyStoreCouchDB.prototype.destroy = function (cb)
{
    cb = cb || function () { return undefined; };
 
    var ths = this;
 
    this._stop(function ()
    {
        if (!ths._db) { return cb(new Error('not_open')); }
 
        ths._nano.db.destroy(ths.db_name, function (err)
        {
            if (err && (err.statusCode != status_not_found))
            {
                return cb(err);
            }
            ths._close_nano(cb);
        });
    });
};
 
PubKeyStoreCouchDB.prototype.deploy = function (cb)
{
    if (cb) { cb(); }
};
 
PubKeyStoreCouchDB.prototype.replicate = function (opts, cb)
{
    if (typeof opts === 'function')
    {
        cb = opts;
    }
 
    cb = cb || (() => {});
 
    if (!this._db)
    {
        return cb(new Error('not_open'));
    }
 
    this.emit('replicated', function (cb)
    {
        cb();
    });
 
    cb();
};
 
module.exports = function (config, cb)
{
    return new PubKeyStoreCouchDB(config, cb);
};