-
Notifications
You must be signed in to change notification settings - Fork 303
/
BlobSharedKeyAuthenticator.ts
319 lines (288 loc) · 11.6 KB
/
BlobSharedKeyAuthenticator.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
import IAccountDataStore from "../../common/IAccountDataStore";
import ILogger from "../../common/ILogger";
import { computeHMACSHA256, getURLQueries } from "../../common/utils/utils";
import BlobStorageContext from "../context/BlobStorageContext";
import StorageErrorFactory from "../errors/StorageErrorFactory";
import Context from "../generated/Context";
import IRequest from "../generated/IRequest";
import { HeaderConstants } from "../utils/constants";
import IAuthenticator from "./IAuthenticator";
export default class BlobSharedKeyAuthenticator implements IAuthenticator {
public constructor(
private readonly dataStore: IAccountDataStore,
private readonly logger: ILogger
) {}
public async validate(
req: IRequest,
context: Context
): Promise<boolean | undefined> {
const blobContext = new BlobStorageContext(context);
const account = blobContext.account!;
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Start validation against account shared key authentication.`,
blobContext.contextId
);
const authHeaderValue = req.getHeader(HeaderConstants.AUTHORIZATION);
if (authHeaderValue === undefined) {
this.logger.info(
// tslint:disable-next-line:max-line-length
`BlobSharedKeyAuthenticator:validate() Request doesn't include valid authentication header. Skip shared key authentication.`,
blobContext.contextId
);
return undefined;
}
// TODO: Make following async
const accountProperties = this.dataStore.getAccount(account);
if (accountProperties === undefined) {
this.logger.error(
`BlobSharedKeyAuthenticator:validate() Invalid storage account ${account}.`,
blobContext.contextId
);
throw StorageErrorFactory.getInvalidOperation(
blobContext.contextId!,
"Invalid storage account."
);
}
const stringToSign: string =
[
req.getMethod().toUpperCase(),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_ENCODING),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_LANGUAGE),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_LENGTH),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_MD5),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_TYPE),
this.getHeaderValueToSign(req, HeaderConstants.DATE),
this.getHeaderValueToSign(req, HeaderConstants.IF_MODIFIED_SINCE),
this.getHeaderValueToSign(req, HeaderConstants.IF_MATCH),
this.getHeaderValueToSign(req, HeaderConstants.IF_NONE_MATCH),
this.getHeaderValueToSign(req, HeaderConstants.IF_UNMODIFIED_SINCE),
this.getHeaderValueToSign(req, HeaderConstants.RANGE)
].join("\n") +
"\n" +
this.getCanonicalizedHeadersString(req) +
this.getCanonicalizedResourceString(
req,
account,
blobContext.authenticationPath
);
this.logger.info(
`BlobSharedKeyAuthenticator:validate() [STRING TO SIGN]:${JSON.stringify(
stringToSign
)}`,
blobContext.contextId
);
const signature1 = computeHMACSHA256(stringToSign, accountProperties.key1);
const authValue1 = `SharedKey ${account}:${signature1}`;
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Calculated authentication header based on key1: ${authValue1}`,
blobContext.contextId
);
if (authHeaderValue === authValue1) {
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Signature 1 matched.`,
blobContext.contextId
);
return true;
}
if (accountProperties.key2) {
const signature2 = computeHMACSHA256(
stringToSign,
accountProperties.key2
);
const authValue2 = `SharedKey ${account}:${signature2}`;
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Calculated authentication header based on key2: ${authValue2}`,
blobContext.contextId
);
if (authHeaderValue === authValue2) {
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Signature 2 matched.`,
blobContext.contextId
);
return true;
}
}
if (context.context.isSecondary && blobContext.authenticationPath?.indexOf(account) === 1)
{
// JS/.net Track2 SDK will generate stringToSign from IP style Uri with "-secondary" in authenticationPath, so will also compare signature with this kind stringToSign
const stringToSign_secondary: string =
[
req.getMethod().toUpperCase(),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_ENCODING),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_LANGUAGE),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_LENGTH),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_MD5),
this.getHeaderValueToSign(req, HeaderConstants.CONTENT_TYPE),
this.getHeaderValueToSign(req, HeaderConstants.DATE),
this.getHeaderValueToSign(req, HeaderConstants.IF_MODIFIED_SINCE),
this.getHeaderValueToSign(req, HeaderConstants.IF_MATCH),
this.getHeaderValueToSign(req, HeaderConstants.IF_NONE_MATCH),
this.getHeaderValueToSign(req, HeaderConstants.IF_UNMODIFIED_SINCE),
this.getHeaderValueToSign(req, HeaderConstants.RANGE)
].join("\n") +
"\n" +
this.getCanonicalizedHeadersString(req) +
this.getCanonicalizedResourceString(
req,
account,
// The authenticationPath looks like "/devstoreaccount1/container", add "-secondary" after account name to "/devstoreaccount1-secondary/container"
blobContext.authenticationPath?.replace(account, account + "-secondary")
);
this.logger.info(
`BlobSharedKeyAuthenticator:validate() [STRING TO SIGN_secondary]:${JSON.stringify(
stringToSign_secondary
)}`,
blobContext.contextId
);
const signature1_secondary= computeHMACSHA256(stringToSign_secondary, accountProperties.key1);
const authValue1_secondary = `SharedKey ${account}:${signature1_secondary}`;
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Calculated authentication header based on key1 and stringToSign with "-secondary": ${authValue1_secondary}`,
blobContext.contextId
);
if (authHeaderValue === authValue1_secondary) {
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Signature 1_secondary matched.`,
blobContext.contextId
);
return true;
}
if (accountProperties.key2) {
const signature2_secondary = computeHMACSHA256(
stringToSign_secondary,
accountProperties.key2
);
const authValue2_secondary = `SharedKey ${account}:${signature2_secondary}`;
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Calculated authentication header based on key2: ${authValue2_secondary}`,
blobContext.contextId
);
if (authHeaderValue === authValue2_secondary) {
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Signature 2_secondary matched.`,
blobContext.contextId
);
return true;
}
}
}
// this.logger.info(`[URL]:${req.getUrl()}`);
// this.logger.info(`[HEADERS]:${req.getHeaders().toString()}`);
// this.logger.info(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
this.logger.info(
`BlobSharedKeyAuthenticator:validate() Validation failed.`,
blobContext.contextId
);
return false;
}
/**
* Retrieve header value according to shared key sign rules.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key
*
* @private
* @param {WebResource} request
* @param {string} headerName
* @returns {string}
* @memberof SharedKeyCredentialPolicy
*/
private getHeaderValueToSign(request: IRequest, headerName: string): string {
const value = request.getHeader(headerName);
if (!value) {
return "";
}
// When using version 2015-02-21 or later, if Content-Length is zero, then
// set the Content-Length part of the StringToSign to an empty string.
// https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key
if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") {
return "";
}
return value;
}
/**
* To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
* 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
* 2. Convert each HTTP header name to lowercase.
* 3. Sort the headers lexicographically by header name, in ascending order.
* Each header may appear only once in the string.
* 4. Replace any linear whitespace in the header value with a single space.
* 5. Trim any whitespace around the colon in the header.
* 6. Finally, append a new-line character to each canonicalized header in the resulting list.
* Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
*
* @private
* @param {IRequest} request
* @returns {string}
* @memberof SharedKeyCredentialPolicy
*/
private getCanonicalizedHeadersString(request: IRequest): string {
const headers: { value: string; name: string }[] = [];
const headersObject = request.getHeaders();
for (const name in headersObject) {
if (headersObject.hasOwnProperty(name)) {
const value = headersObject[name];
if (value === undefined) {
headers.push({ name, value: "" });
} else if (typeof value === "string") {
headers.push({ name, value });
} else {
headers.push({ name, value: value.join(",") });
}
}
}
const headersArray = headers.filter((value) => {
return value.name
.toLowerCase()
.startsWith(HeaderConstants.PREFIX_FOR_STORAGE);
});
headersArray.sort((a, b): number => {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
let canonicalizedHeadersStringToSign: string = "";
headersArray.forEach((header) => {
canonicalizedHeadersStringToSign += `${header.name
.toLowerCase()
.trimRight()}:${header.value.trimLeft()}\n`;
});
return canonicalizedHeadersStringToSign;
}
/**
* Retrieves canonicalized resource string.
*
* @private
* @param {IRequest} request
* @returns {string}
* @memberof SharedKeyCredentialPolicy
*/
private getCanonicalizedResourceString(
request: IRequest,
account: string,
authenticationPath?: string
): string {
let path = request.getPath() || "/";
// For secondary account, we use account name (without "-secondary") for the path
if (authenticationPath !== undefined) {
path = authenticationPath;
}
let canonicalizedResourceString: string = "";
canonicalizedResourceString += `/${account}${path}`;
const queries = getURLQueries(request.getUrl());
const lowercaseQueries: { [key: string]: string } = {};
if (queries) {
const queryKeys: string[] = [];
for (const key in queries) {
if (queries.hasOwnProperty(key)) {
const lowercaseKey = key.toLowerCase();
lowercaseQueries[lowercaseKey] = queries[key];
queryKeys.push(lowercaseKey);
}
}
queryKeys.sort();
for (const key of queryKeys) {
canonicalizedResourceString += `\n${key}:${decodeURIComponent(
lowercaseQueries[key]
)}`;
}
}
return canonicalizedResourceString;
}
}