From 8dfaab1af03bcadf7bad60d903180fcebb189e13 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 18 Sep 2018 12:48:58 +0100 Subject: [PATCH] fix: validate createKey params properly (#26) License: MIT Signed-off-by: Alan Shaw --- src/keychain.js | 12 ++++++++++++ test/keychain.spec.js | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/keychain.js b/src/keychain.js index da94ab2..a9619fd 100644 --- a/src/keychain.js +++ b/src/keychain.js @@ -6,6 +6,8 @@ const deepmerge = require('lodash/merge') const crypto = require('libp2p-crypto') const DS = require('interface-datastore') const pull = require('pull-stream') +const isString = require('lodash/isString') +const isSafeInteger = require('lodash/isSafeInteger') const CMS = require('./cms') const keyPrefix = '/pkcs8/' @@ -30,6 +32,7 @@ const defaultOptions = { function validateKeyName (name) { if (!name) return false + if (!isString(name)) return false return name === sanitize(name.trim()) } @@ -182,6 +185,15 @@ class Keychain { if (!validateKeyName(name) || name === 'self') { return _error(callback, `Invalid key name '${name}'`) } + + if (!isString(type)) { + return _error(callback, `Invalid key type '${type}'`) + } + + if (!isSafeInteger(size)) { + return _error(callback, `Invalid key size '${size}'`) + } + const dsname = DsName(name) self.store.has(dsname, (err, exists) => { if (err) return _error(callback, err) diff --git a/test/keychain.spec.js b/test/keychain.spec.js index ae78cb1..ed6f1a8 100644 --- a/test/keychain.spec.js +++ b/test/keychain.spec.js @@ -117,6 +117,30 @@ module.exports = (datastore1, datastore2) => { }) }) + it('should validate name is string', (done) => { + ks.createKey(5, 'rsa', 2048, (err) => { + expect(err).to.exist() + expect(err.message).to.contain('Invalid key name') + done() + }) + }) + + it('should validate type is string', (done) => { + ks.createKey('TEST' + Date.now(), null, 2048, (err) => { + expect(err).to.exist() + expect(err.message).to.contain('Invalid key type') + done() + }) + }) + + it('should validate size is integer', (done) => { + ks.createKey('TEST' + Date.now(), 'rsa', 'string', (err) => { + expect(err).to.exist() + expect(err.message).to.contain('Invalid key size') + done() + }) + }) + describe('implements NIST SP 800-131A', () => { it('disallows RSA length < 2048', (done) => { ks.createKey('bad-nist-rsa', 'rsa', 1024, (err) => {