/
remoteCryptographyProvider.ts
373 lines (334 loc) · 9.81 KB
/
remoteCryptographyProvider.ts
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
createPipelineFromOptions,
isTokenCredential,
TokenCredential,
signingPolicy
} from "@azure/core-http";
import {
EncryptParameters,
EncryptOptions,
EncryptResult,
KeyWrapAlgorithm,
WrapKeyOptions,
WrapResult,
VerifyOptions,
VerifyResult,
DecryptParameters,
DecryptOptions,
DecryptResult,
UnwrapKeyOptions,
SignOptions,
SignResult
} from "../cryptographyClientModels";
import { challengeBasedAuthenticationPolicy } from "../../../keyvault-common";
import { SDK_VERSION } from "../constants";
import { UnwrapResult } from "../cryptographyClientModels";
import { KeyVaultClient } from "../generated";
import { parseKeyVaultKeyId } from "../identifier";
import {
CryptographyClientOptions,
GetKeyOptions,
KeyVaultKey,
LATEST_API_VERSION
} from "../keysModels";
import { getKeyFromKeyBundle } from "../transformations";
import { createHash } from "./crypto";
import { CryptographyProvider, CryptographyProviderOperation } from "./models";
import { logger } from "../log";
import { createTraceFunction, TracedFunction } from "../../../keyvault-common/src";
const withTrace: TracedFunction = createTraceFunction(
"Azure.KeyVault.Keys.RemoteCryptographyProvider"
);
/**
* The remote cryptography provider is used to run crypto operations against KeyVault.
* @internal
*/
export class RemoteCryptographyProvider implements CryptographyProvider {
constructor(
key: string | KeyVaultKey,
credential: TokenCredential,
pipelineOptions: CryptographyClientOptions = {}
) {
const libInfo = `azsdk-js-keyvault-keys/${SDK_VERSION}`;
const userAgentOptions = pipelineOptions.userAgentOptions;
pipelineOptions.userAgentOptions = {
userAgentPrefix:
userAgentOptions && userAgentOptions.userAgentPrefix
? `${userAgentOptions.userAgentPrefix} ${libInfo}`
: libInfo
};
const authPolicy = isTokenCredential(credential)
? challengeBasedAuthenticationPolicy(credential)
: signingPolicy(credential);
const internalPipelineOptions = {
...pipelineOptions,
loggingOptions: {
logger: logger.info,
allowedHeaderNames: [
"x-ms-keyvault-region",
"x-ms-keyvault-network-info",
"x-ms-keyvault-service-version"
]
}
};
this.client = new KeyVaultClient(
pipelineOptions.serviceVersion || LATEST_API_VERSION,
createPipelineFromOptions(internalPipelineOptions, authPolicy)
);
this.key = key;
let keyId: string;
if (typeof key === "string") {
keyId = key;
} else {
keyId = key.id!;
}
try {
const parsed = parseKeyVaultKeyId(keyId);
if (parsed.name === "") {
throw new Error("Could not find 'name' of key in key URL");
}
if (!parsed.version || parsed.version === "") {
throw new Error("Could not find 'version' of key in key URL");
}
if (!parsed.vaultUrl || parsed.vaultUrl === "") {
throw new Error("Could not find 'vaultUrl' of key in key URL");
}
this.vaultUrl = parsed.vaultUrl;
this.name = parsed.name;
this.version = parsed.version;
} catch (err) {
logger.error(err);
throw new Error(`${keyId} is not a valid Key Vault key ID`);
}
}
// The remote client supports all algorithms and all operations.
isSupported(_algorithm: string, _operation: CryptographyProviderOperation): boolean {
return true;
}
encrypt(
encryptParameters: EncryptParameters,
options: EncryptOptions = {}
): Promise<EncryptResult> {
const { algorithm, plaintext, ...params } = encryptParameters;
const requestOptions = { ...options, ...params };
return withTrace(
"RemoteCryptographyProvider.encrypt",
requestOptions,
async (updatedOptions) => {
const result = await this.client.encrypt(
this.vaultUrl,
this.name,
this.version,
algorithm,
plaintext,
updatedOptions
);
return {
algorithm: encryptParameters.algorithm,
result: result.result!,
keyID: this.getKeyID(),
additionalAuthenticatedData: result.additionalAuthenticatedData,
authenticationTag: result.authenticationTag,
iv: result.iv
};
}
);
}
decrypt(
decryptParameters: DecryptParameters,
options: DecryptOptions = {}
): Promise<DecryptResult> {
const { algorithm, ciphertext, ...params } = decryptParameters;
const requestOptions = { ...options, ...params };
return withTrace(
"RemoteCryptographyProvider.decrypt",
requestOptions,
async (updatedOptions) => {
const result = await this.client.decrypt(
this.vaultUrl,
this.name,
this.version,
algorithm,
ciphertext,
updatedOptions
);
return {
result: result.result!,
keyID: this.getKeyID(),
algorithm
};
}
);
}
wrapKey(
algorithm: KeyWrapAlgorithm,
keyToWrap: Uint8Array,
options: WrapKeyOptions = {}
): Promise<WrapResult> {
return withTrace("RemoteCryptographyProvider.wrapKey", options, async (updatedOptions) => {
const result = await this.client.wrapKey(
this.vaultUrl,
this.name,
this.version,
algorithm,
keyToWrap,
updatedOptions
);
return {
result: result.result!,
algorithm,
keyID: this.getKeyID()
};
});
}
unwrapKey(
algorithm: KeyWrapAlgorithm,
encryptedKey: Uint8Array,
options: UnwrapKeyOptions = {}
): Promise<UnwrapResult> {
return withTrace("RemoteCryptographyProvider.unwrapKey", options, async (updatedOptions) => {
const result = await this.client.unwrapKey(
this.vaultUrl,
this.name,
this.version,
algorithm,
encryptedKey,
updatedOptions
);
return {
result: result.result!,
algorithm,
keyID: this.getKeyID()
};
});
}
sign(algorithm: string, digest: Uint8Array, options: SignOptions = {}): Promise<SignResult> {
return withTrace("RemoteCryptographyProvider.sign", options, async (updatedOptions) => {
const result = await this.client.sign(
this.vaultUrl,
this.name,
this.version,
algorithm,
digest,
updatedOptions
);
return { result: result.result!, algorithm, keyID: this.getKeyID() };
});
}
verifyData(
algorithm: string,
data: Uint8Array,
signature: Uint8Array,
options: VerifyOptions = {}
): Promise<VerifyResult> {
return withTrace("RemoteCryptographyProvider.verifyData", options, async (updatedOptions) => {
const hash = await createHash(algorithm, data);
return this.verify(algorithm, hash, signature, updatedOptions);
});
}
verify(
algorithm: string,
digest: Uint8Array,
signature: Uint8Array,
options: VerifyOptions = {}
): Promise<VerifyResult> {
return withTrace("RemoteCryptographyProvider.verify", options, async (updatedOptions) => {
const response = await this.client.verify(
this.vaultUrl,
this.name,
this.version,
algorithm,
digest,
signature,
updatedOptions
);
return {
result: response.value ? response.value : false,
keyID: this.getKeyID()
};
});
}
signData(algorithm: string, data: Uint8Array, options: SignOptions = {}): Promise<SignResult> {
return withTrace("RemoteCryptographyProvider.signData", options, async (updatedOptions) => {
const digest = await createHash(algorithm, data);
const result = await this.client.sign(
this.vaultUrl,
this.name,
this.version,
algorithm,
digest,
updatedOptions
);
return { result: result.result!, algorithm, keyID: this.getKeyID() };
});
}
/**
* The base URL to the vault.
*/
readonly vaultUrl: string;
/**
* The ID of the key used to perform cryptographic operations for the client.
*/
get keyId(): string | undefined {
return this.getKeyID();
}
/**
* Gets the {@link KeyVaultKey} used for cryptography operations, fetching it
* from KeyVault if necessary.
* @param options - Additional options.
*/
getKey(options: GetKeyOptions = {}): Promise<KeyVaultKey> {
return withTrace("RemoteCryptographyProvider.getKey", options, async (updatedOptions) => {
if (typeof this.key === "string") {
if (!this.name || this.name === "") {
throw new Error("getKey requires a key with a name");
}
const response = await this.client.getKey(
this.vaultUrl,
this.name,
options && options.version ? options.version : this.version ? this.version : "",
updatedOptions
);
this.key = getKeyFromKeyBundle(response);
}
return this.key;
});
}
/**
* @internal
* A reference to the auto-generated KeyVault HTTP client.
*/
private readonly client: KeyVaultClient;
/**
* A reference to the key used for the cryptographic operations.
* Based on what was provided to the CryptographyClient constructor,
* it can be either a string with the URL of a Key Vault Key, or an already parsed {@link KeyVaultKey}.
* @internal
*/
private key: string | KeyVaultKey;
/**
* Name of the key the client represents
* @internal
*/
private name: string;
/**
* Version of the key the client represents
* @internal
*/
private version: string;
/**
* Attempts to retrieve the ID of the key.
* @internal
*/
private getKeyID(): string | undefined {
let kid;
if (typeof this.key !== "string") {
kid = this.key.id;
} else {
kid = this.key;
}
return kid;
}
}