All files / pub-keystore/sql index.js

100% Statements 408/408
96.96% Branches 128/132
92.59% Functions 25/27
100% Lines 408/408

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 4091x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 568x 6746x 43x 43x 6703x 568x 568x 568x 568x 568x 568x 568x 4x 4x 4x 4x 4x 4x 4x 568x 568x 563x 563x 563x 563x 563x 563x 568x 568x 1x 1x 568x 568x 568x 568x 567x 567x 567x 567x 426x 426x 141x 141x 141x 141x 141x 141x 125x 125x 141x 141x 141x 141x 567x 568x 568x 1x 1x 313x 313x 1x 1x 184x 43x 43x 43x 43x 39x 39x 39x 43x 43x 43x 43x 43x 43x 43x 43x 225x 225x 225x 43x 43x 43x 43x 43x 184x 184x 1x 1x 580x 567x 567x 567x 567x 567x 567x 567x 567x 4x 4x 567x 567x 563x 563x 567x 567x 567x 567x 567x 567x 567x 580x 580x 1x 1x 946x 938x 938x 938x 938x 938x 656x 656x 282x 938x 946x 946x 1x 1x 1036x 1036x 1026x 1026x 1026x 1026x 1026x 1026x 568x 568x 458x 458x 458x 458x 458x 176x 176x 282x 458x 1026x 1026x 1036x 1036x 1x 1x 856x 848x 848x 848x 848x 848x 568x 568x 280x 848x 856x 856x 1x 1x 64x 64x 64x 64x 64x 64x 64x 64x 64x 1x 1x 292x 292x 290x 290x 290x 292x 292x 292x 8x 8x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 284x 2x 2x 2x 2x 2x 282x 282x 282x 282x 270x 270x 270x 270x 224x 270x 282x 284x 284x 284x 292x 1x 1x 107x 8x 8x 99x 99x 99x 99x 99x 99x 99x 99x 44x 44x 55x 55x 55x 55x 99x 99x 99x 107x 1x 1x 307x 307x 307x 1x 1x 16x 12x 16x 16x 16x 1x 1x 36x 36x 36x 36x 4x 4x 32x 32x 36x 1x 1x 36x 36x 36x 1x 1x 3417x 3417x 104x 2x 2x 2x 102x 102x 102x 3313x 3313x 3417x 3417x 1x 1x 1409x 1411x 64x 64x 64x 64x 64x 64x 64x 64x 1347x 1347x 1347x 1347x 1347x 1347x 1347x 1411x 9x 9x 1411x 1411x 1409x 1409x 1409x 1409x 1x 1x 1419x 1419x 1419x 1419x 9x 9x 1419x 1419x 1410x 1410x 1419x 1419x 1419x 1419x 1419x 1419x 1x 1x 1x 1x 1x 1x 1x 1x 3169x 3169x 24x 24x 3169x 3169x 3145x 3145x 3169x 3169x 1x 1x 107x 107x 1x 1x 107x 107x 106x 106x 107x 107x 1x 1x 4064x 4064x 16x 16x 4064x 4064x 4048x 4048x 4064x 4064x 1x 1x 1x 568x 1x  
/*jslint node: true */
 
const { EventEmitter } = require('events');
const { randomBytes } = require('crypto');
const { Database } = require('sqlite3');
const { Client } = require('pg');
const { queue, waterfall } = require('async');
const iferr = require('iferr');
 
class PubKeyStoreSQL extends EventEmitter {
    constructor(options, cb) {
        super();
 
        this._options = Object.assign({
            db_type: 'sqlite',
            busy_wait: 1000,
            check_interval: 1000
        }, options);
 
        this._open = false;
 
        // We need to queue queries on a db connection:
        // https://github.com/mapbox/node-sqlite3/issues/304
        // Alternative would be to create a separate connection
        // for each query. The calling application can still do
        // this if required (to achieve more parallelism) by
        // creating many keystores.
        this._queue = queue((task, cb) => {
            if (!this._open) {
                return cb(new Error('not_open'));
            }
            task(cb);
        });
 
        waterfall([
            cb => {
                let db;
                switch (this._options.db_type) {
                case 'sqlite':
                    db = new Database(this._options.db_filename,
                                      this._options.db_mode);
                    db.on('open', err => cb(err, db));
                    this._true = 1;
                    this._false = 0;
                    this._busy_code = 'SQLITE_BUSY';
                    break;
 
                case 'pg':
                    db = new Client(this._options.db);
                    db.connect(err => cb(err, db));
                    this._true = true;
                    this._false = false;
                    this._busy_code = '40001';
                    break;
 
                default:
                    cb(new Error(`invalid database type: ${this._options.db_type}`));
                    break;
                }
            },
 
            (db, cb) => {
                this._open = true;
                this._db = db;
 
                if (this._options.no_changes) {
                    return cb();
                }
 
                this._get(
                    'SELECT id FROM pub_keys ORDER BY id DESC LIMIT 1',
                    [],
                    iferr(cb, r => {
                        if (r !== undefined) {
                            this._last_id = r.id;
                        }
                        db.on('error', this.emit.bind(this, 'error'));
                        this._check();
                        cb();
                    }));
            }
        ], iferr(err => this.close(() => cb(err)), () => cb(null, this)));
    }
 
    _ifopen(cb) {
        return (...args) => !this._open || cb.call(this, ...args);
    }
 
    _check() {
        this._check_timeout = setTimeout(this._ifopen(() => {
            this._queue.push(this._ifopen(cb => {
                let sql = 'SELECT id, uri, deleted FROM pub_keys';
                let args = [];
                if (this._last_id !== undefined) {
                    sql += ' WHERE id > $1';
                    args.push(this._last_id);
                }
                sql += ' ORDER BY id';
                this._all(
                    sql,
                    args,
                    iferr(cb, r => {
                        /* jshint expr: true */
                        this._options.verbose && console.log('database change', r);
                        for (let { id, uri, deleted } of r) {
                            this.emit('change', uri, id.toString(), deleted === this._true);
                            this._last_id = id;
                        }
                        cb();
                    }));
            }), this._busy(iferr(this.emit.bind(this, 'error'),
                                 this._ifopen(this._check)),
                           this._ifopen(this._check)));
        }), this._options.check_interval);
    }
 
    close(cb) {
        this._queue.push(cb => {
            waterfall([
                cb => {
                    clearTimeout(this._check_timeout);
                    cb();
                },
                cb => {
                    switch (this._options.db_type) {
                    case 'sqlite':
                        this._db.close(cb);
                        break;
 
                    case 'pg':
                        this._db.end(cb);
                        break;
                    }
                },
                cb => {
                    this._open = false;
                    cb();
                }
            ], cb);
        }, cb);
    }
 
    get_pub_key_by_uri(uri, cb) {
        this._queue.push(cb => {
            this._get(
                'SELECT pub_key, issuer_id, id, deleted FROM pub_keys WHERE uri = $1 ORDER BY id DESC LIMIT 1;',
                [uri],
                iferr(cb, r => {
                    if ((r === undefined) || r.deleted) {
                        return cb(null, null);
                    }
                    cb(null, JSON.parse(r.pub_key), r.issuer_id, r.id.toString());
                }));
        }, this._busy(cb, this.get_pub_key_by_uri.bind(this, uri, cb)));
    }
 
    get_pub_key_by_issuer_id(issuer_id, cb) {
        const b = this._busy(cb, this.get_pub_key_by_issuer_id.bind(this, issuer_id, cb));
        this._in_transaction(b, cb => {
            this._queue.unshift(cb => {
                this._get(
                    'SELECT uri FROM pub_keys WHERE issuer_id = $1;',
                    [issuer_id],
                    iferr(cb, r => {
                        if (r === undefined) {
                            return cb(null, null);
                        }
                        this._get(
                            'SELECT pub_key, issuer_id, id, deleted FROM pub_keys WHERE uri = $1 ORDER BY id DESC LIMIT 1;',
                            [r.uri],
                            iferr(cb, r2 => {
                                if (r2.deleted || (r2.issuer_id !== issuer_id)) {
                                    return cb(null, null);
                                }
                                cb(null, JSON.parse(r2.pub_key), r.uri, r2.id.toString());
                            }));
                    }));
            }, cb);
        });
    }
 
    get_issuer_id(uri, cb) {
        this._queue.push(cb => {
            this._get(
                'SELECT issuer_id, id, deleted FROM pub_keys WHERE uri = $1 ORDER BY id DESC LIMIT 1;',
                [uri],
                iferr(cb, r => {
                    if ((r === undefined) || r.deleted) {
                        return cb(null, null);
                    }
                    cb(null, r.issuer_id, r.id.toString());
                }));
        }, this._busy(cb, this.get_issuer_id.bind(this, uri, cb)));
    }
 
    get_uris(cb) {
        this._queue.push(cb => {
            this._all(
                'SELECT uri FROM (SELECT uri, deleted, row_number() OVER(PARTITION BY uri ORDER BY id DESC) AS rn FROM pub_keys) sub WHERE rn = 1 AND NOT deleted;',
                [],
                iferr(cb, r => {
                    cb(null, r.map(row => row.uri));
                }));
        }, this._busy(cb, this.get_uris.bind(this, cb)));
    }
 
    add_pub_key(uri, pub_key, options, cb) {
        if (typeof options === 'function')
        {
            cb = options;
            options = {};
        }
        options = options || {};
        cb = cb || function () { return undefined; };
        if ((uri === null) || (uri === undefined)) {
            return cb(new Error('invalid_uri'));
        }
        const issuer_id = randomBytes(64).toString('hex');
        const b = this._busy(cb, this.add_pub_key.bind(this, uri, pub_key, cb));
        this._in_transaction(b, cb => {
            this._queue.unshift(cb => {
                this._get(
                    'SELECT deleted FROM pub_keys WHERE uri = $1 ORDER BY id DESC LIMIT 1;',
                    [uri],
                    iferr(cb, r => {
                        if (this._options.no_updates &&
                            !options.allow_update &&
                            (r !== undefined) &&
                            !r.deleted) {
                            const err = new Error('already exists');
                            err.statusCode = 409;
                            err.error = 'conflict';
                            return cb(err);
                        }
                        this._run(
                            'INSERT INTO pub_keys (uri, issuer_id, pub_key, deleted) VALUES ($1, $2, $3, $4)',
                            [uri, issuer_id, JSON.stringify(pub_key), this._false],
                            iferr(cb, () => {
                                this._get(
                                    'SELECT id FROM pub_keys WHERE issuer_id = $1;',
                                    [issuer_id],
                                    iferr(cb, r => {
                                        cb(null, issuer_id, r.id.toString());
                                    }));
                            }));
                    }));
            }, cb);
        });
    }
 
    remove_pub_key(uri, cb) {
        if ((uri === null) || (uri === undefined)) {
            return cb(new Error('invalid_uri'));
        }
        const b = this._busy(cb, this.remove_pub_key.bind(this, uri, cb));
        this._in_transaction(b, cb => {
            this._queue.unshift(cb => {
                this._get(
                    'SELECT deleted FROM pub_keys WHERE uri = $1 ORDER BY id DESC LIMIT 1;',
                    [uri],
                    iferr(cb, r => {
                        if ((r === undefined) || r.deleted) {
                            return cb();
                        }
                        this._run(
                            'INSERT INTO pub_keys (uri, deleted) VALUES ($1, $2)',
                            [uri, this._true],
                            cb);
                    }));
            }, cb);
        });
    }
 
    create(cb) {
        /* jshint expr: true */
        !cb || cb();
    }
 
    destroy(cb) {
        this._queue.push(cb => {
            this._run('DELETE FROM pub_keys', [], cb);
        }, this._busy(iferr(cb, this.close.bind(this, cb)),
                      this.destroy.bind(this, cb)));
    }
 
    replicate(opts, cb) {
        /* jshint expr: true */
        (typeof opts !== 'function') || (cb = opts);
        cb = cb || (() => {});
        if (!this._open) {
            return cb(new Error('not_open'));
        }
        this.emit('replicated', cb => cb());
        cb();
    }
 
    deploy(cb) {
        /* jshint expr: true */
        !cb || cb();
    }
 
    _busy(f, retry, block) {
        return (err, ...args) => {
            if (err && (err.code === this._busy_code)) {
                if (block) {
                    return this._queue.unshift(cb => setTimeout(cb, this._options.busy_wait),
                                               retry);
                }
 
                return setTimeout(retry, this._options.busy_wait);
            }
 
            f(err, ...args);
        };
    }
 
    _end_transaction(cb) {
        let f = (err, ...args) => {
            if (err) {
                return this._queue.unshift(cb => {
                    this._run('ROLLBACK',
                              [],
                              cb);
                }, this._busy(err2 => cb(err2 || err, ...args),
                              f.bind(this, err, ...args),
                              true));
            }
 
            const cb2 = err => cb(err, ...args);
 
            this._queue.unshift(cb => {
                this._run('END TRANSACTION',
                          [],
                          cb);
            }, this._options.db_type === 'sqlite' ?
                this._busy(cb2,
                           f.bind(this, err, ...args),
                           true) :
                cb2);
        };
 
        return f;
    }
 
    _in_transaction(cb, f) {
        let isolation_level;
 
        switch (this._options.db_type) {
        case 'sqlite':
            isolation_level = ''; // SQLite transactions are serializable
            break;
 
        case 'pg':
            isolation_level = 'ISOLATION LEVEL SERIALIZABLE';
            break;
        }
 
        this._queue.push(cb2 =>
            this._run(`BEGIN TRANSACTION ${isolation_level}`, [], cb2),
            iferr(cb, () => f(this._end_transaction(cb))));
    }
 
    // Note: $1, $2 placeholders in SQL statements are PostgreSQL syntax.
    // However, as long as they appear _in order_ (i.e. never $2 before $1)
    // then they work in SQLite too. This is because when $ is used, SQLite
    // binds first parameter in array to first $whatever in the statement,
    // second parameter to second $something etc.
 
    _run(sql, values, cb) {
        switch (this._options.db_type) {
        case 'sqlite':
            this._db.run(sql, ...values, cb);
            break;
 
        case 'pg':
            this._db.query(sql, values, iferr(cb, () => cb()));
            break;
        }
    }
 
    _all(sql, values, cb) {
        switch (this._options.db_type) {
        case 'sqlite':
            this._db.all(sql, ...values, cb);
            break;
 
        case 'pg':
            this._db.query(sql, values, iferr(cb, r => cb(null, r.rows)));
            break;
        }
    }
 
    _get(sql, values, cb) {
        switch (this._options.db_type) {
        case 'sqlite':
            this._db.get(sql, ...values, cb);
            break;
 
        case 'pg':
            this._db.query(sql, values, iferr(cb, r => cb(null, r.rows[0])));
            break;
        }
    }
}
 
module.exports = function (config, cb) {
    new PubKeyStoreSQL(config, cb);
};