|
| 1 | +import { encodeObjectBase64Url } from './../tests/jwk-utils'; |
| 2 | +import { decodeBase64, encodeBase64Url } from './base64'; |
| 3 | +import { AppErrorCodes, FirebaseAppError } from './errors'; |
| 4 | +import { isNonEmptyString, isNonNullObject } from './validator'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Type representing a Firebase OAuth access token (derived from a Google OAuth2 access token) which |
| 8 | + * can be used to authenticate to Firebase services such as the Realtime Database and Auth. |
| 9 | + */ |
| 10 | +export interface FirebaseAccessToken { |
| 11 | + accessToken: string; |
| 12 | + expirationTime: number; |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * Interface for Google OAuth 2.0 access tokens. |
| 17 | + */ |
| 18 | +export interface GoogleOAuthAccessToken { |
| 19 | + access_token: string; |
| 20 | + expires_in: number; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Interface that provides Google OAuth2 access tokens used to authenticate |
| 25 | + * with Firebase services. |
| 26 | + * |
| 27 | + * In most cases, you will not need to implement this yourself and can instead |
| 28 | + * use the default implementations provided by the `firebase-admin/app` module. |
| 29 | + */ |
| 30 | +export interface Credential { |
| 31 | + /** |
| 32 | + * Returns a Google OAuth2 access token object used to authenticate with |
| 33 | + * Firebase services. |
| 34 | + * |
| 35 | + * @returns A Google OAuth2 access token object. |
| 36 | + */ |
| 37 | + getAccessToken(): Promise<GoogleOAuthAccessToken>; |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Implementation of Credential that uses with emulator. |
| 42 | + */ |
| 43 | +export class EmulatorCredential implements Credential { |
| 44 | + public async getAccessToken(): Promise<GoogleOAuthAccessToken> { |
| 45 | + return { |
| 46 | + access_token: 'owner', |
| 47 | + expires_in: 90 * 3600 * 3600, |
| 48 | + }; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +const GOOGLE_TOKEN_AUDIENCE = 'https://accounts.google.com/o/oauth2/token'; |
| 53 | +const GOOGLE_AUTH_TOKEN_HOST = 'accounts.google.com'; |
| 54 | +const GOOGLE_AUTH_TOKEN_PATH = '/o/oauth2/token'; |
| 55 | + |
| 56 | +/** |
| 57 | + * Implementation of Credential that uses a service account. |
| 58 | + */ |
| 59 | +export class ServiceAccountCredential implements Credential { |
| 60 | + public readonly projectId: string; |
| 61 | + public readonly privateKey: string; |
| 62 | + public readonly clientEmail: string; |
| 63 | + |
| 64 | + /** |
| 65 | + * Creates a new ServiceAccountCredential from the given parameters. |
| 66 | + * |
| 67 | + * @param serviceAccountJson - Service account json content. |
| 68 | + * |
| 69 | + * @constructor |
| 70 | + */ |
| 71 | + constructor(serviceAccountJson: string) { |
| 72 | + const serviceAccount = ServiceAccount.fromJSON(serviceAccountJson); |
| 73 | + this.projectId = serviceAccount.projectId; |
| 74 | + this.privateKey = serviceAccount.privateKey; |
| 75 | + this.clientEmail = serviceAccount.clientEmail; |
| 76 | + } |
| 77 | + |
| 78 | + public async getAccessToken(): Promise<GoogleOAuthAccessToken> { |
| 79 | + const header = encodeObjectBase64Url({ |
| 80 | + alg: 'RS256', |
| 81 | + typ: 'JWT', |
| 82 | + }).replace(/=/g, ''); |
| 83 | + |
| 84 | + const iat = Math.round(Date.now() / 1000); |
| 85 | + const exp = iat + 3600; |
| 86 | + const claim = encodeObjectBase64Url({ |
| 87 | + iss: this.clientEmail, |
| 88 | + scope: ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/identitytoolkit'].join( |
| 89 | + ' ' |
| 90 | + ), |
| 91 | + aud: GOOGLE_TOKEN_AUDIENCE, |
| 92 | + exp, |
| 93 | + iat, |
| 94 | + }).replace(/=/g, ''); |
| 95 | + |
| 96 | + const unsignedContent = `${header}.${claim}`; |
| 97 | + // This method is actually synchronous so we can capture and return the buffer. |
| 98 | + const signature = await this.sign(unsignedContent, this.privateKey); |
| 99 | + const jwt = `${unsignedContent}.${signature}`; |
| 100 | + const body = `grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=${jwt}`; |
| 101 | + const url = `https://${GOOGLE_AUTH_TOKEN_HOST}${GOOGLE_AUTH_TOKEN_PATH}`; |
| 102 | + const res = await fetch(url, { |
| 103 | + method: 'POST', |
| 104 | + headers: { |
| 105 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 106 | + 'Cache-Control': 'no-cache', |
| 107 | + Host: 'oauth2.googleapis.com', |
| 108 | + }, |
| 109 | + body, |
| 110 | + }); |
| 111 | + const json = (await res.json()) as any; |
| 112 | + if (!json.access_token || !json.expires_in) { |
| 113 | + throw new FirebaseAppError( |
| 114 | + AppErrorCodes.INVALID_CREDENTIAL, |
| 115 | + `Unexpected response while fetching access token: ${JSON.stringify(json)}` |
| 116 | + ); |
| 117 | + } |
| 118 | + |
| 119 | + return json; |
| 120 | + } |
| 121 | + |
| 122 | + private async sign(content: string, privateKey: string): Promise<string> { |
| 123 | + const buf = this.str2ab(content); |
| 124 | + const binaryKey = decodeBase64(privateKey); |
| 125 | + const signer = await crypto.subtle.importKey( |
| 126 | + 'pkcs8', |
| 127 | + binaryKey, |
| 128 | + { |
| 129 | + name: 'RSASSA-PKCS1-V1_5', |
| 130 | + hash: { name: 'SHA-256' }, |
| 131 | + }, |
| 132 | + false, |
| 133 | + ['sign'] |
| 134 | + ); |
| 135 | + const binarySignature = await crypto.subtle.sign({ name: 'RSASSA-PKCS1-V1_5' }, signer, buf); |
| 136 | + return encodeBase64Url(binarySignature).replace(/=/g, ''); |
| 137 | + } |
| 138 | + |
| 139 | + private str2ab(str: string): ArrayBuffer { |
| 140 | + const buf = new ArrayBuffer(str.length); |
| 141 | + const bufView = new Uint8Array(buf); |
| 142 | + for (let i = 0, strLen = str.length; i < strLen; i += 1) { |
| 143 | + bufView[i] = str.charCodeAt(i); |
| 144 | + } |
| 145 | + return buf; |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +/** |
| 150 | + * A struct containing the properties necessary to use service account JSON credentials. |
| 151 | + */ |
| 152 | +class ServiceAccount { |
| 153 | + public readonly projectId: string; |
| 154 | + public readonly privateKey: string; |
| 155 | + public readonly clientEmail: string; |
| 156 | + |
| 157 | + public static fromJSON(text: string): ServiceAccount { |
| 158 | + try { |
| 159 | + return new ServiceAccount(JSON.parse(text)); |
| 160 | + } catch (error) { |
| 161 | + // Throw a nicely formed error message if the file contents cannot be parsed |
| 162 | + throw new FirebaseAppError( |
| 163 | + AppErrorCodes.INVALID_CREDENTIAL, |
| 164 | + 'Failed to parse service account json file: ' + error |
| 165 | + ); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + constructor(json: object) { |
| 170 | + if (!isNonNullObject(json)) { |
| 171 | + throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, 'Service account must be an object.'); |
| 172 | + } |
| 173 | + |
| 174 | + copyAttr(this, json, 'projectId', 'project_id'); |
| 175 | + copyAttr(this, json, 'privateKey', 'private_key'); |
| 176 | + copyAttr(this, json, 'clientEmail', 'client_email'); |
| 177 | + |
| 178 | + let errorMessage; |
| 179 | + if (!isNonEmptyString(this.projectId)) { |
| 180 | + errorMessage = 'Service account object must contain a string "project_id" property.'; |
| 181 | + } else if (!isNonEmptyString(this.privateKey)) { |
| 182 | + errorMessage = 'Service account object must contain a string "private_key" property.'; |
| 183 | + } else if (!isNonEmptyString(this.clientEmail)) { |
| 184 | + errorMessage = 'Service account object must contain a string "client_email" property.'; |
| 185 | + } |
| 186 | + |
| 187 | + if (typeof errorMessage !== 'undefined') { |
| 188 | + throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, errorMessage); |
| 189 | + } |
| 190 | + |
| 191 | + this.privateKey = this.privateKey.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''); |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +/** |
| 196 | + * Copies the specified property from one object to another. |
| 197 | + * |
| 198 | + * If no property exists by the given "key", looks for a property identified by "alt", and copies it instead. |
| 199 | + * This can be used to implement behaviors such as "copy property myKey or my_key". |
| 200 | + * |
| 201 | + * @param to - Target object to copy the property into. |
| 202 | + * @param from - Source object to copy the property from. |
| 203 | + * @param key - Name of the property to copy. |
| 204 | + * @param alt - Alternative name of the property to copy. |
| 205 | + */ |
| 206 | +function copyAttr(to: { [key: string]: any }, from: { [key: string]: any }, key: string, alt: string): void { |
| 207 | + const tmp = from[key] || from[alt]; |
| 208 | + if (typeof tmp !== 'undefined') { |
| 209 | + to[key] = tmp; |
| 210 | + } |
| 211 | +} |
0 commit comments