|
| 1 | +import * as jwt from 'jsonwebtoken'; |
| 2 | +import * as _ from 'lodash'; |
| 3 | +import * as nock from 'nock'; |
| 4 | +import * as mocks from '../fixtures/credential/key.json'; |
| 5 | + |
| 6 | +// MockRequest mocks an https.Request. |
| 7 | +export class MockRequest { |
| 8 | + public method: 'POST' | 'GET' | 'OPTIONS' = 'POST'; |
| 9 | + |
| 10 | + constructor( |
| 11 | + readonly body: any, |
| 12 | + readonly headers: { [name: string]: string } |
| 13 | + ) { |
| 14 | + // This block intentionally left blank. |
| 15 | + } |
| 16 | + |
| 17 | + public header(name: string): string { |
| 18 | + return this.headers[name.toLowerCase()]; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +// Creates a mock request with the given data and content-type. |
| 23 | +export function mockRequest( |
| 24 | + data: any, |
| 25 | + contentType: string = 'application/json', |
| 26 | + context: { |
| 27 | + authorization?: string; |
| 28 | + instanceIdToken?: string; |
| 29 | + } = {} |
| 30 | +) { |
| 31 | + const body: any = {}; |
| 32 | + if (!_.isUndefined(data)) { |
| 33 | + body.data = data; |
| 34 | + } |
| 35 | + |
| 36 | + const headers = { |
| 37 | + 'content-type': contentType, |
| 38 | + authorization: context.authorization, |
| 39 | + 'firebase-instance-id-token': context.instanceIdToken, |
| 40 | + origin: 'example.com', |
| 41 | + }; |
| 42 | + |
| 43 | + return new MockRequest(body, headers); |
| 44 | +} |
| 45 | + |
| 46 | +export const expectedResponseHeaders = { |
| 47 | + 'Access-Control-Allow-Origin': 'example.com', |
| 48 | + Vary: 'Origin', |
| 49 | +}; |
| 50 | + |
| 51 | +/** |
| 52 | + * Mocks out the http request used by the firebase-admin SDK to get the key for |
| 53 | + * verifying an id token. |
| 54 | + */ |
| 55 | +export function mockFetchPublicKeys(): nock.Scope { |
| 56 | + const mockedResponse = { [mocks.key_id]: mocks.public_key }; |
| 57 | + const headers = { |
| 58 | + 'cache-control': 'public, max-age=1, must-revalidate, no-transform', |
| 59 | + }; |
| 60 | + |
| 61 | + return nock('https://www.googleapis.com:443') |
| 62 | + .get('/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com') |
| 63 | + .reply(200, mockedResponse, headers); |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Generates a mocked Firebase ID token. |
| 68 | + */ |
| 69 | +export function generateIdToken(projectId: string): string { |
| 70 | + const claims = {}; |
| 71 | + const options = { |
| 72 | + audience: projectId, |
| 73 | + expiresIn: 60 * 60, // 1 hour in seconds |
| 74 | + issuer: 'https://securetoken.google.com/' + projectId, |
| 75 | + subject: mocks.user_id, |
| 76 | + algorithm: 'RS256', |
| 77 | + header: { |
| 78 | + kid: mocks.key_id, |
| 79 | + }, |
| 80 | + }; |
| 81 | + return jwt.sign(claims, mocks.private_key, options); |
| 82 | +} |
0 commit comments