-
Notifications
You must be signed in to change notification settings - Fork 388
/
Copy pathjwtaccess.ts
252 lines (231 loc) Β· 6.98 KB
/
jwtaccess.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
// Copyright 2015 Google LLC
//
// 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.
import * as jws from 'jws';
import * as LRU from 'lru-cache';
import * as stream from 'stream';
import {JWTInput} from './credentials';
import {Headers} from './oauth2client';
const DEFAULT_HEADER: jws.Header = {
alg: 'RS256',
typ: 'JWT',
};
export interface Claims {
[index: string]: string;
}
export class JWTAccess {
email?: string | null;
key?: string | null;
keyId?: string | null;
projectId?: string;
eagerRefreshThresholdMillis: number;
private cache = new LRU<string, {expiration: number; headers: Headers}>({
max: 500,
maxAge: 60 * 60 * 1000,
});
/**
* JWTAccess service account credentials.
*
* Create a new access token by using the credential to create a new JWT token
* that's recognized as the access token.
*
* @param email the service account email address.
* @param key the private key that will be used to sign the token.
* @param keyId the ID of the private key used to sign the token.
*/
constructor(
email?: string | null,
key?: string | null,
keyId?: string | null,
eagerRefreshThresholdMillis?: number
) {
this.email = email;
this.key = key;
this.keyId = keyId;
this.eagerRefreshThresholdMillis =
eagerRefreshThresholdMillis ?? 5 * 60 * 1000;
}
/**
* Ensures that we're caching a key appropriately, giving precedence to scopes vs. url
*
* @param url The URI being authorized.
* @param scopes The scope or scopes being authorized
* @returns A string that returns the cached key.
*/
getCachedKey(url?: string, scopes?: string | string[]): string {
let cacheKey = url;
if (scopes && Array.isArray(scopes) && scopes.length) {
cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;
} else if (typeof scopes === 'string') {
cacheKey = url ? `${url}_${scopes}` : scopes;
}
if (!cacheKey) {
throw Error('Scopes or url must be provided');
}
return cacheKey;
}
/**
* Get a non-expired access token, after refreshing if necessary.
*
* @param url The URI being authorized.
* @param additionalClaims An object with a set of additional claims to
* include in the payload.
* @returns An object that includes the authorization header.
*/
getRequestHeaders(
url?: string,
additionalClaims?: Claims,
scopes?: string | string[]
): Headers {
// Return cached authorization headers, unless we are within
// eagerRefreshThresholdMillis ms of them expiring:
const key = this.getCachedKey(url, scopes);
const cachedToken = this.cache.get(key);
const now = Date.now();
if (
cachedToken &&
cachedToken.expiration - now > this.eagerRefreshThresholdMillis
) {
return cachedToken.headers;
}
const iat = Math.floor(Date.now() / 1000);
const exp = JWTAccess.getExpirationTime(iat);
let defaultClaims;
// Turn scopes into space-separated string
if (Array.isArray(scopes)) {
scopes = scopes.join(' ');
}
// If scopes are specified, sign with scopes
if (scopes) {
defaultClaims = {
iss: this.email,
sub: this.email,
scope: scopes,
exp,
iat,
};
} else {
defaultClaims = {
iss: this.email,
sub: this.email,
aud: url,
exp,
iat,
};
}
// if additionalClaims are provided, ensure they do not collide with
// other required claims.
if (additionalClaims) {
for (const claim in defaultClaims) {
if (additionalClaims[claim]) {
throw new Error(
`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`
);
}
}
}
const header = this.keyId
? {...DEFAULT_HEADER, kid: this.keyId}
: DEFAULT_HEADER;
const payload = Object.assign(defaultClaims, additionalClaims);
// Sign the jwt and add it to the cache
const signedJWT = jws.sign({header, payload, secret: this.key});
const headers = {Authorization: `Bearer ${signedJWT}`};
this.cache.set(key, {
expiration: exp * 1000,
headers,
});
return headers;
}
/**
* Returns an expiration time for the JWT token.
*
* @param iat The issued at time for the JWT.
* @returns An expiration time for the JWT.
*/
private static getExpirationTime(iat: number): number {
const exp = iat + 3600; // 3600 seconds = 1 hour
return exp;
}
/**
* Create a JWTAccess credentials instance using the given input options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void {
if (!json) {
throw new Error(
'Must pass in a JSON object containing the service account auth settings.'
);
}
if (!json.client_email) {
throw new Error(
'The incoming JSON object does not contain a client_email field'
);
}
if (!json.private_key) {
throw new Error(
'The incoming JSON object does not contain a private_key field'
);
}
// Extract the relevant information from the json key file.
this.email = json.client_email;
this.key = json.private_key;
this.keyId = json.private_key_id;
this.projectId = json.project_id;
}
/**
* Create a JWTAccess credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(
inputStream: stream.Readable,
callback: (err?: Error) => void
): void;
fromStream(
inputStream: stream.Readable,
callback?: (err?: Error) => void
): void | Promise<void> {
if (callback) {
this.fromStreamAsync(inputStream).then(() => callback(), callback);
} else {
return this.fromStreamAsync(inputStream);
}
}
private fromStreamAsync(inputStream: stream.Readable): Promise<void> {
return new Promise((resolve, reject) => {
if (!inputStream) {
reject(
new Error(
'Must pass in a stream containing the service account auth settings.'
)
);
}
let s = '';
inputStream
.setEncoding('utf8')
.on('data', chunk => (s += chunk))
.on('error', reject)
.on('end', () => {
try {
const data = JSON.parse(s);
this.fromJSON(data);
resolve();
} catch (err) {
reject(err);
}
});
});
}
}