forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amp-access-server-jwt.js
354 lines (316 loc) · 10.4 KB
/
amp-access-server-jwt.js
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
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* 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 {AccessClientAdapter} from './amp-access-client';
import {JwtHelper} from './jwt';
import {Services} from '../../../src/services';
import {
assertHttpsUrl,
isProxyOrigin,
removeFragment,
serializeQueryString,
} from '../../../src/url';
import {dev, user, userAssert} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {escapeCssSelectorIdent} from '../../../src/css';
import {fetchDocument} from '../../../src/document-fetcher';
import {getMode} from '../../../src/mode';
import {isArray} from '../../../src/types';
import {isExperimentOn} from '../../../src/experiments';
/** @const {string} */
const TAG = 'amp-access-server-jwt';
/** @const {number} */
const AUTHORIZATION_TIMEOUT = 3000;
/** @const {string} */
const AMP_AUD = 'ampproject.org';
/**
* This class implements server-side authorization protocol with JWT. In this
* approach only immediately visible sections are downloaded. For authorization,
* the client calls the authorization endpoint, which returns a signed JWT
* token with `amp_authdata` field. The client calls CDN with this JWT token,
* and CDN returns back the authorized content fragments.
*
* The approximate diagram looks like this:
*
* Initial GET
* ||
* || [Limited document: fragments requiring
* || authorization are exlcuded]
* ||
* \/
* Authorize request to Publisher
* ||
* || [Authorization response as JWT]
* ||
* \/
* Authorize request to CDN w/JWT
* ||
* || [Authorized fragments]
* ||
* \/
* Merge authorized fragments
* ||
* ||
* \/
* Apply authorization response
*
* @implements {./amp-access-source.AccessTypeAdapterDef}
*/
export class AccessServerJwtAdapter {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!JsonObject} configJson
* @param {!./amp-access-source.AccessTypeAdapterContextDef} context
*/
constructor(ampdoc, configJson, context) {
/** @const */
this.ampdoc = ampdoc;
/** @const @private {!./amp-access-source.AccessTypeAdapterContextDef} */
this.context_ = context;
/** @private @const */
this.clientAdapter_ = new AccessClientAdapter(ampdoc, configJson, context);
/** @private @const {!../../../src/service/viewer-impl.Viewer} */
this.viewer_ = Services.viewerForDoc(ampdoc);
/** @const @private {!../../../src/service/xhr-impl.Xhr} */
this.xhr_ = Services.xhrFor(ampdoc.win);
/** @const @private {!../../../src/service/timer-impl.Timer} */
this.timer_ = Services.timerFor(ampdoc.win);
/** @const @private {!../../../src/service/vsync-impl.Vsync} */
this.vsync_ = Services.vsyncFor(ampdoc.win);
const stateElement = ampdoc.getRootNode().querySelector(
'meta[name="i-amphtml-access-state"]');
/** @private @const {?string} */
this.serverState_ = stateElement ?
stateElement.getAttribute('content') : null;
const isInExperiment = isExperimentOn(ampdoc.win, 'amp-access-server-jwt');
/** @private @const {boolean} */
this.isProxyOrigin_ = isProxyOrigin(ampdoc.win.location) || isInExperiment;
const serviceUrlOverride = isInExperiment ?
this.viewer_.getParam('serverAccessService') : null;
/** @private @const {string} */
this.serviceUrl_ = serviceUrlOverride ||
removeFragment(ampdoc.win.location.href);
/** @const @private {?string} */
this.key_ = configJson['publicKey'] || null;
/** @const @private {?string} */
this.keyUrl_ = configJson['publicKeyUrl'] || null;
userAssert(this.key_ || this.keyUrl_,
'"publicKey" or "publicKeyUrl" must be specified');
if (this.keyUrl_) {
assertHttpsUrl(this.keyUrl_, '"publicKeyUrl"');
}
if (this.key_ && this.keyUrl_) {
// TODO(dvoytenko): Remove "publicKey" option eventually.
user().warn(TAG,
'Both "publicKey" and "publicKeyUrl" specified. ' +
'The "publicKeyUrl" will be ignored.');
}
/** @private @const {!JwtHelper} */
this.jwtHelper_ = new JwtHelper(ampdoc.win);
}
/** @override */
getConfig() {
return {
'client': this.clientAdapter_.getConfig(),
'proxy': this.isProxyOrigin_,
'serverState': this.serverState_,
'publicKey': this.key_,
'publicKeyUrl': this.keyUrl_,
};
}
/** @override */
isAuthorizationEnabled() {
return true;
}
/** @override */
authorize() {
dev().fine(TAG, 'Start authorization with ',
this.isProxyOrigin_ ? 'proxy' : 'non-proxy',
this.serverState_,
this.clientAdapter_.getAuthorizationUrl());
if (!this.isProxyOrigin_ || !this.serverState_) {
return this.authorizeOnClient_();
}
return this.authorizeOnServer_();
}
/** @override */
isPingbackEnabled() {
return this.clientAdapter_.isPingbackEnabled();
}
/** @override */
pingback() {
return this.clientAdapter_.pingback();
}
/** @override */
postAction() {
// Nothing to do.
}
/**
* @return {!Promise<{encoded:string, jwt:!JsonObject}>}
* @private
*/
fetchJwt_() {
const urlPromise = this.context_.buildUrl(
this.clientAdapter_.getAuthorizationUrl(),
/* useAuthData */ false);
let jwtPromise = urlPromise.then(url => {
dev().fine(TAG, 'Authorization URL: ', url);
return this.timer_.timeoutPromise(
AUTHORIZATION_TIMEOUT,
this.xhr_.fetchText(url, {
credentials: 'include',
}));
}).then(resp => {
return resp.text();
}).then(encoded => {
const jwt = this.jwtHelper_.decode(encoded);
userAssert(jwt['amp_authdata'],
'"amp_authdata" must be present in JWT');
return {encoded, jwt};
});
if (this.shouldBeValidated_()) {
// Validate JWT in the development mode.
if (this.jwtHelper_.isVerificationSupported()) {
jwtPromise = jwtPromise.then(resp => {
return this.jwtHelper_
.decodeAndVerify(resp.encoded, this.loadKeyPem_())
.then(() => resp);
});
} else {
user().warn(TAG, 'Cannot verify signature on this browser since' +
' it doesn\'t support WebCrypto APIs');
}
jwtPromise = jwtPromise.then(resp => {
this.validateJwt_(resp.jwt);
return resp;
});
}
return jwtPromise.catch(reason => {
throw user().createError('JWT fetch or validation failed: ', reason);
});
}
/**
* @return {!Promise<string>}
* @private
*/
loadKeyPem_() {
if (this.key_) {
return Promise.resolve(this.key_);
}
return this.xhr_.fetchText(dev().assertString(this.keyUrl_))
.then(res => res.text());
}
/**
* @return {boolean}
* @private
*/
shouldBeValidated_() {
return getMode().development;
}
/**
* @param {!JsonObject} jwt
* @private
*/
validateJwt_(jwt) {
const now = Date.now();
// exp: expiration time.
const exp = jwt['exp'];
userAssert(exp, '"exp" field must be specified');
userAssert(parseFloat(exp) * 1000 > now,
'token has expired: %s', exp);
// aud: audience.
const aud = jwt['aud'];
userAssert(aud, '"aud" field must be specified');
let audForAmp = false;
if (isArray(aud)) {
for (let i = 0; i < aud.length; i++) {
if (aud[i] == AMP_AUD) {
audForAmp = true;
break;
}
}
} else {
audForAmp = (aud == AMP_AUD);
}
userAssert(audForAmp, '"aud" must be "%s": %s', AMP_AUD, aud);
}
/**
* @return {!Promise<!JsonObject>}
* @private
*/
authorizeOnClient_() {
dev().fine(TAG, 'Proceed via client protocol via ',
this.clientAdapter_.getAuthorizationUrl());
return this.fetchJwt_().then(resp => {
return resp.jwt['amp_authdata'];
});
}
/**
* @return {!Promise<!JsonObject>}
* @private
*/
authorizeOnServer_() {
dev().fine(TAG, 'Proceed via server protocol');
return this.fetchJwt_().then(resp => {
const {encoded, jwt} = resp;
const accessData = jwt['amp_authdata'];
const request = serializeQueryString(dict({
'url': removeFragment(this.ampdoc.win.location.href),
'state': this.serverState_,
'jwt': encoded,
}));
dev().fine(TAG, 'Authorization request: ', this.serviceUrl_, request);
dev().fine(TAG, '- access data: ', accessData);
// Note that `application/x-www-form-urlencoded` is used to avoid
// CORS preflight request.
return this.timer_.timeoutPromise(
AUTHORIZATION_TIMEOUT,
fetchDocument(this.ampdoc.win, this.serviceUrl_, {
method: 'POST',
body: request,
headers: dict({
'Content-Type': 'application/x-www-form-urlencoded',
}),
requireAmpResponseSourceOrigin: false,
})).then(response => {
dev().fine(TAG, 'Authorization response: ', response);
return this.replaceSections_(response);
}).then(() => accessData);
});
}
/**
* @param {!Document} doc
* @return {!Promise}
*/
replaceSections_(doc) {
const sections = doc.querySelectorAll('[i-amphtml-access-id]');
dev().fine(TAG, '- access sections: ', sections);
return this.vsync_.mutatePromise(() => {
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const sectionId = section.getAttribute('i-amphtml-access-id');
const target = this.ampdoc.getRootNode().querySelector(
`[i-amphtml-access-id="${escapeCssSelectorIdent(sectionId)}"]`);
if (!target) {
dev().warn(TAG, 'Section not found: ', sectionId);
continue;
}
target.parentElement.replaceChild(
this.ampdoc.win.document.importNode(section, /* deep */ true),
target);
}
});
}
}