Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/encryption/key-provider.ts
2500 views
1
/**
2
* Copyright (c) 2020 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { injectable, inject } from "inversify";
8
9
export interface KeyMetadata {
10
name: string;
11
version: number;
12
}
13
14
export interface Key {
15
metadata: KeyMetadata;
16
material: Buffer;
17
}
18
19
export const KeyProvider = Symbol("KeyProvider");
20
export interface KeyProvider {
21
getPrimaryKey(): Key;
22
getKeyFor(metadata: KeyMetadata): Key;
23
}
24
25
export type KeyConfig = KeyMetadata & {
26
/** base64 encoded */
27
material: string;
28
primary?: boolean;
29
};
30
31
export const KeyProviderConfig = Symbol("KeyProviderConfig");
32
export interface KeyProviderConfig {
33
keys: KeyConfig[];
34
}
35
36
@injectable()
37
export class KeyProviderImpl implements KeyProvider {
38
static loadKeyConfigFromJsonString(configStr: string): KeyConfig[] {
39
const keys = (JSON.parse(configStr) || []) as KeyConfig[];
40
if (!Array.isArray(keys) || keys.length < 0 || 1 !== keys.reduce((p, k) => (k.primary ? p + 1 : p), 0)) {
41
throw new Error("Invalid key config!");
42
}
43
return keys;
44
}
45
46
constructor(@inject(KeyProviderConfig) protected readonly config: KeyProviderConfig) {}
47
48
protected get keys() {
49
return this.config.keys;
50
}
51
52
getPrimaryKey(): Key {
53
const primaryKey = this.keys.find((key) => !!key.primary);
54
if (!primaryKey) {
55
throw new Error("No primary encryption key found!");
56
}
57
return this.configToKey(primaryKey);
58
}
59
60
getKeyFor(metadata: KeyMetadata): Key {
61
const key = this.keys.find((k) => k.name === metadata.name && k.version === metadata.version);
62
if (!key) {
63
throw new Error(`No key found for metadata ${metadata.name}/${metadata.version}`);
64
}
65
return this.configToKey(key);
66
}
67
68
protected configToKey(config: KeyConfig): Key {
69
return {
70
metadata: {
71
name: config.name,
72
version: config.version,
73
},
74
material: Buffer.from(config.material, "base64"),
75
};
76
}
77
}
78
79