lib6/encryption/encryption-profile.js
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { newError } from '../error';
import { int } from '../integer';
import { stringify } from '../json';
/**
* An encryption profile that enables Envelope Encryption for Neo4j Property Encryption.
*
* @since 6.3.0
* @experimental Part of the Client-Side Encrytion preview feature
*/
export class EnvelopeEncryptionProfile {
/**
*
* @param {Object} config - Configurations
* @param {string} config.name - Name of the profile, must be the same on all drivers used to access the encrypted data.
* @param {KeyEncapsulationService} config.encapsulationService - Encapsulation service used to encapsulate and dencapsulate keys. The driver ships with {@link LocalKeyEncapsulationService}, other implementations can be found as separate packages.
* @param {EncapsulatedKeyRecordRepository} config.keyRepository - Implementation of the {@link EncapsulatedKeyRecordRepository} interface, must be implemented so that the driver can access your key repository.
* @param {number} config.keyCacheTTL - How How long in milliseconds to keep a retrieved encapsulated keys cached by Id - defaults to 15 minutes
* @param {number} config.keyCacheMaxSize - How many items to keep in the key cache before pruning the oldest, setting to 0 will disable the cache - defaults to 100
* @param {number} config.keyAliasIndexTTL - How How long in milliseconds to keep the mapping of alias to key cached - defaults to 15 seconds
* @param {number} config.keyAliasIndexMaxSize - How many items to keep in the alias cache before pruning the oldest, setting to 0 will disable the index - defaults to 100
*/
constructor(config) {
var _a, _b, _c, _d;
this.name = config.name;
this.encapsulationService = config.encapsulationService;
this.keyRepository = config.keyRepository;
this._keyCacheEnabled = config.keyCacheMaxSize !== 0;
this._keyCacheTTL = (_a = config.keyCacheTTL) !== null && _a !== void 0 ? _a : 15 * 60 * 1000;
this._keyCacheMaxSize = (_b = config.keyCacheMaxSize) !== null && _b !== void 0 ? _b : 100;
this._keyCache = new Map();
if (this._keyCacheEnabled) {
this._keyAliasIndexEnabled = config.keyAliasIndexMaxSize !== 0;
}
else {
this._keyAliasIndexEnabled = false;
}
this._keyAliasIndexTTL = (_c = config.keyAliasIndexTTL) !== null && _c !== void 0 ? _c : 15 * 1000;
this._keyAliasIndexMaxSize = (_d = config.keyAliasIndexMaxSize) !== null && _d !== void 0 ? _d : 100;
this._aliasIndex = new Map();
this.type = 'ENVELOPE';
this.version = int(1);
}
/**
* @private
*/
findKey(options) {
return __awaiter(this, void 0, void 0, function* () {
let key;
if (typeof options === 'string') {
key = yield this._findById(options);
}
else if (options.id != null) {
key = yield this._findById(options.id);
}
else if (options.alias != null) {
key = yield this._findByAlias(options.alias);
}
else {
throw newError(`invalid key options: ${stringify(options)}`);
}
return key;
});
}
/**
* @private
*/
saveKey(alias, encapsulation, metadata) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield this.keyRepository.create(alias, encapsulation, metadata);
}
catch (e) {
throw newError('Call to EncapsulatedKeyRepository.create threw error, see cause', '50N42', e);
}
});
}
/**
* @private
*/
_findById(id) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
if (this._keyCacheEnabled) {
const entry = this._keyCache.get(id);
if (entry != null) {
if (new Date().getTime() - ((_a = entry === null || entry === void 0 ? void 0 : entry.retrieved.getTime()) !== null && _a !== void 0 ? _a : 0) < ((_b = this._keyCacheTTL) !== null && _b !== void 0 ? _b : 0)) {
return entry === null || entry === void 0 ? void 0 : entry.entry;
}
else {
this._keyCache.delete(id);
}
}
}
let key;
try {
key = yield this.keyRepository.findById(id);
}
catch (e) {
throw newError('Call to EncapsulatedKeyRepository.findById threw error, see cause', '50N42', e);
}
if (key == null) {
return undefined;
}
this._keyCache.set(id, { entry: key, retrieved: new Date() });
this._pruneCache(this._keyCache, this._keyCacheMaxSize);
return key;
});
}
/**
* @private
*/
_findByAlias(alias) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
if (this._keyAliasIndexEnabled) {
const entry = this._aliasIndex.get(alias);
if (entry != null) {
if (new Date().getTime() - ((_a = entry === null || entry === void 0 ? void 0 : entry.retrieved.getTime()) !== null && _a !== void 0 ? _a : 0) < ((_b = this._keyAliasIndexTTL) !== null && _b !== void 0 ? _b : 0)) {
return yield this._findById(entry === null || entry === void 0 ? void 0 : entry.entry);
}
else {
this._aliasIndex.delete(alias);
}
}
}
let key;
try {
key = yield this.keyRepository.findByAlias(alias);
}
catch (e) {
throw newError('Call to EncapsulatedKeyRepository.findByAlias threw error, see cause', '50N42', e);
}
if (key == null) {
return undefined;
}
this._aliasIndex.set(alias, { entry: key.id(), retrieved: new Date() });
this._keyCache.set(key.id(), { entry: key, retrieved: new Date() });
this._pruneCache(this._aliasIndex, this._keyAliasIndexMaxSize);
this._pruneCache(this._keyCache, this._keyCacheMaxSize);
return key;
});
}
/**
* @private
*/
_pruneCache(cache, maxSize) {
if (cache.size > maxSize) {
const entries = Array.from(cache.entries());
entries.sort((a, b) => a[1].retrieved.getTime() - b[1].retrieved.getTime());
let i = 0;
while (cache.size > maxSize) {
cache.delete(entries[i][0]);
i++;
}
}
}
}