/
token-verifier.spec.ts
243 lines (196 loc) · 8.89 KB
/
token-verifier.spec.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
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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.
*/
'use strict';
import * as _ from 'lodash';
import * as chai from 'chai';
import * as sinon from 'sinon';
import * as mocks from '../../resources/mocks';
import * as nock from 'nock';
import { AppCheckTokenVerifier } from '../../../src/app-check/token-verifier';
import { JwtError, JwtErrorCode, PublicKeySignatureVerifier } from '../../../src/utils/jwt';
const expect = chai.expect;
const ONE_HOUR_IN_SECONDS = 60 * 60;
describe('AppCheckTokenVerifier', () => {
// Stubs used to simulate underlying api calls.
let stubs: sinon.SinonStub[] = [];
let tokenVerifier: AppCheckTokenVerifier;
let clock: sinon.SinonFakeTimers | undefined;
before(() => {
tokenVerifier = new AppCheckTokenVerifier(mocks.app());
});
after(() => {
nock.cleanAll();
});
afterEach(() => {
_.forEach(stubs, (stub) => stub.restore());
stubs = [];
if (clock) {
clock.restore();
clock = undefined;
}
});
describe('verifyJWT()', () => {
let mockedRequests: nock.Scope[] = [];
let stubs: sinon.SinonStub[] = [];
afterEach(() => {
_.forEach(mockedRequests, (mockedRequest) => mockedRequest.done());
mockedRequests = [];
_.forEach(stubs, (stub) => stub.restore());
stubs = [];
});
it('should throw given no App Check token', () => {
expect(() => {
(tokenVerifier as any).verifyToken();
}).to.throw('App check token must be a non-null string');
});
const invalidTokens = [null, NaN, 0, 1, true, false, [], {}, { a: 1 }, _.noop];
invalidTokens.forEach((invalidToken) => {
it('should throw given a non-string App Check token: ' + JSON.stringify(invalidToken), () => {
expect(() => {
tokenVerifier.verifyToken(invalidToken as any);
}).to.throw('App check token must be a non-null string');
});
});
it('should throw given an empty string App Check token', () => {
return tokenVerifier.verifyToken('')
.should.eventually.be.rejectedWith('Decoding App Check token failed');
});
it('should be rejected given an invalid App Check token', () => {
return tokenVerifier.verifyToken('invalid-token')
.should.eventually.be.rejectedWith('Decoding App Check token failed');
});
it('should throw if the token verifier was initialized with no "project_id"', () => {
const tokenVerifierWithNoProjectId = new AppCheckTokenVerifier(mocks.mockCredentialApp());
const expected = 'Must initialize app with a cert credential or set your Firebase project ID as ' +
'the GOOGLE_CLOUD_PROJECT environment variable to verify an App Check token.';
return tokenVerifierWithNoProjectId.verifyToken('app.check.token')
.should.eventually.be.rejectedWith(expected);
});
it('should be rejected given an App Check token with an incorrect algorithm', () => {
const mockAppCheckToken = mocks.generateAppCheckToken({
algorithm: 'PS256',
});
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has incorrect algorithm');
});
const invalidAudiences = [
'incorrectAudience', [], [mocks.projectNumber, mocks.projectId],
['projects/' + mocks.projectNumber, mocks.projectId]
];
invalidAudiences.forEach((invalidAudience) => {
it('should be rejected given an App Check token with an incorrect audience:' +
JSON.stringify(invalidAudience), () => {
const mockAppCheckToken = mocks.generateAppCheckToken({
audience: invalidAudience,
});
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has incorrect "aud" (audience) claim');
});
});
it('should be rejected given an App Check token with an incorrect issuer', () => {
const mockAppCheckToken = mocks.generateAppCheckToken({
issuer: 'incorrectIssuer',
});
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has incorrect "iss" (issuer) claim');
});
it('should be rejected given an App Check token with an empty subject', () => {
const mockAppCheckToken = mocks.generateAppCheckToken({
subject: '',
});
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has an empty string "sub" (subject) claim');
});
it('should be rejected when the verifier throws no maching kid error', () => {
const verifierStub = sinon.stub(PublicKeySignatureVerifier.prototype, 'verify')
.rejects(new JwtError(JwtErrorCode.NO_MATCHING_KID, 'No matching key ID.'));
stubs.push(verifierStub);
const mockAppCheckToken = mocks.generateAppCheckToken({
header: {
kid: 'wrongkid',
},
});
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has "kid" claim which does not ' +
'correspond to a known public key');
});
it('should be rejected when the verifier throws expired token error', () => {
const verifierStub = sinon.stub(PublicKeySignatureVerifier.prototype, 'verify')
.rejects(new JwtError(JwtErrorCode.TOKEN_EXPIRED, 'Expired token.'));
stubs.push(verifierStub);
const mockAppCheckToken = mocks.generateAppCheckToken();
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has expired. ' +
'Get a fresh App Check token from your client app and try again.')
.and.have.property('code', 'app-check/app-check-token-expired');
});
it('should be rejected when the verifier throws invalid signature error.', () => {
const verifierStub = sinon.stub(PublicKeySignatureVerifier.prototype, 'verify')
.rejects(new JwtError(JwtErrorCode.INVALID_SIGNATURE, 'invalid signature.'));
stubs.push(verifierStub);
const mockAppCheckToken = mocks.generateAppCheckToken();
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('The provided App Check token has invalid signature');
});
it('should be rejected when the verifier throws key fetch error.', () => {
const verifierStub = sinon.stub(PublicKeySignatureVerifier.prototype, 'verify')
.rejects(new JwtError(JwtErrorCode.KEY_FETCH_ERROR, 'Error fetching Json Web Keys.'));
stubs.push(verifierStub);
const mockAppCheckToken = mocks.generateAppCheckToken();
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.rejectedWith('Error fetching Json Web Keys.');
});
it('should be fulfilled when the kid is not present in the header (should try all the keys)', () => {
const verifierStub = sinon.stub(PublicKeySignatureVerifier.prototype, 'verify')
.resolves();
stubs.push(verifierStub);
clock = sinon.useFakeTimers(1000);
const mockAppCheckToken = mocks.generateAppCheckToken({
header: {},
});
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.fulfilled.and.deep.equal({
one: 'uno',
two: 'dos',
iat: 1,
exp: ONE_HOUR_IN_SECONDS + 1,
aud: ['projects/' + mocks.projectNumber, 'projects/' + mocks.projectId],
iss: 'https://firebaseappcheck.googleapis.com/' + mocks.projectNumber,
sub: mocks.appId,
app_id: mocks.appId,
});
});
it('should be fulfilled with decoded claims given a valid App Check token', () => {
const verifierStub = sinon.stub(PublicKeySignatureVerifier.prototype, 'verify')
.resolves();
stubs.push(verifierStub);
clock = sinon.useFakeTimers(1000);
const mockAppCheckToken = mocks.generateAppCheckToken();
return tokenVerifier.verifyToken(mockAppCheckToken)
.should.eventually.be.fulfilled.and.deep.equal({
one: 'uno',
two: 'dos',
iat: 1,
exp: ONE_HOUR_IN_SECONDS + 1,
aud: ['projects/' + mocks.projectNumber, 'projects/' + mocks.projectId],
iss: 'https://firebaseappcheck.googleapis.com/' + mocks.projectNumber,
sub: mocks.appId,
app_id: mocks.appId,
});
});
});
});