/** * Credentials and project discovery for Google Cloud APIs. * * On Cloud Run (and other Google compute), the instance metadata server * hands out OAuth access tokens for the service's identity and knows the * project id. `MetadataServerCredentials` reads tokens from it and keeps * one until shortly before it expires. For local runs, an access token * from `gcloud auth print-access-token` in `GOOGLE_OAUTH_ACCESS_TOKEN` * works through `AccessTokenCredentials`. */ import { getEnv } from 'zena:cli'; import { fetch } from 'zena:fetch'; import { JsonObject, parseJson } from 'zena:json'; import { Duration, Instant, milliseconds, monotonic } from 'zena:time'; import { URL } from 'zena:url'; import { Credentials } from 'protobuf/runtime'; /** The metadata server every Google compute instance can reach. */ let METADATA_ORIGIN = 'http://metadata.google.internal'; /** How long before a token's expiry it is replaced. */ let REFRESH_MARGIN_SECONDS = 60; /** Credentials or a project id could not be obtained. */ export class AuthError extends Error { new(message: String) : super(message); } /** Sends one fixed access token: `Bearer `. */ export final class AccessTokenCredentials implements Credentials { #header: String; new(token: String) : #header = `Bearer ${token}`; async authorization(): Future { return this.#header; } } /** * Access tokens for the instance's service account, from the metadata * server. A token is fetched on first use and replaced a minute before it * expires. `origin` overrides the server, as `GCE_METADATA_HOST` does. */ export final class MetadataServerCredentials implements Credentials { #origin: String; var #header: String | null = null; var #expires: Instant = 0 as Instant; new(origin: String = 'http://metadata.google.internal') : #origin = origin; async authorization(): Future { if (this.#header != null && monotonic() < this.#expires) { return this.#header; } let body = await metadataGet(this.#origin, '/computeMetadata/v1/instance/service-accounts/default/token'); let json = parseJson(body); if (!(json is JsonObject)) { throw new AuthError('the metadata server answered with no token'); } let token = json; var accessToken = ''; if (let (true, value) = token.stringAt('access_token')) { accessToken = value; } else { throw new AuthError('the metadata server answered with no access_token'); } var lifetime = 0; if (let (true, seconds) = token.intAt('expires_in')) { lifetime = seconds; } let header = `Bearer ${accessToken}`; this.#header = header; let usable = if (lifetime > REFRESH_MARGIN_SECONDS) lifetime - REFRESH_MARGIN_SECONDS else 0; this.#expires = monotonic() + milliseconds((usable as i64) * 1000); return header; } } /** * The credentials a program run on Google Cloud should use: * `GOOGLE_OAUTH_ACCESS_TOKEN` when it is set, otherwise the metadata * server, at `GCE_METADATA_HOST` when that is set. */ export function defaultCredentials(): Credentials { let token = getEnv('GOOGLE_OAUTH_ACCESS_TOKEN'); if (token != null && token.length > 0) { return new AccessTokenCredentials(token); } return new MetadataServerCredentials(metadataOrigin()); } /** * The project the program runs in: `GOOGLE_CLOUD_PROJECT` or * `GCLOUD_PROJECT` when set, otherwise the metadata server's answer. */ export async function defaultProjectId(): Future { for (let name in ['GOOGLE_CLOUD_PROJECT', 'GCLOUD_PROJECT']) { let value = getEnv(name); if (value != null && value.length > 0) { return value; } } return await projectIdFrom(metadataOrigin()); } /** The project id the metadata server at `origin` reports. */ export async function projectIdFrom(origin: String): Future { return (await metadataGet(origin, '/computeMetadata/v1/project/project-id')).trim(); } function metadataOrigin(): String { let host = getEnv('GCE_METADATA_HOST'); return if (host != null && host.length > 0) `http://${host}` else METADATA_ORIGIN; } /** GETs `path` from the metadata server at `origin` and returns the body; throws unless it answers 200. */ async function metadataGet(origin: String, path: String): Future { if (URL.parse(origin) == null) { throw new AuthError(`not a URL: ${origin}`); } try { let response = await fetch(`${origin}${path}`, { headers: [('metadata-flavor', 'Google')], }); let status = response.status; let text = await response.text(); if (status != 200) { throw new AuthError(`the metadata server answered ${path} with HTTP ${status}: ${text}`); } return text; } catch (e) { if (e is AuthError) { throw e; } throw new AuthError(`the metadata server at ${origin} could not be reached`); } }