Repository navigation
Add support for Build Envvars and Secrets #11266
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
e39e372
Support build-time env vars and secrets for Cloud Run
falahat 6666aa1
Make the build env tests easier to read
falahat 663a82a
Merge branch 'bapi_local_builds' into bapi_build_env
falahat e83ea5c
Merge branch 'bapi_local_builds' into bapi_build_env
falahat b014a4f
Merge branch 'bapi_local_builds' into bapi_build_env
falahat 99519f9
Merge branch 'bapi_local_builds' into bapi_build_env
falahat a292c19
Merge branch 'bapi_local_builds' into bapi_build_env
falahat de55cf2
Merge branch 'bapi_local_builds' into bapi_build_env
falahat cea325c
Use App Hosting's secret format for build secrets
falahat 24171b5
Rename plainValues to nonSecretValues
falahat fa68a23
Merge branch 'bapi_local_builds' into bapi_build_env
falahat c84fca1
Accept numbers and booleans in the build env annotation, like apphost…
falahat b4b4cb3
Check for secrets with isSecretRef instead of typeof string
falahat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import { expect } from "chai"; | ||
| import * as runv2 from "../../gcp/runv2"; | ||
| import { | ||
| BUILD_ENV_ANNOTATION, | ||
| getBuildEnv, | ||
| nonSecretValues, | ||
| secretNames, | ||
| toLocalBuildEnv, | ||
| } from "./buildEnv"; | ||
|
|
||
| describe("run buildEnv", () => { | ||
| const web = { name: "projects/my-project/locations/us-central1/services/web" } as runv2.Service; | ||
| /** The web service, with this build env annotation. */ | ||
| const withAnnotation = (value: string): runv2.Service => ({ | ||
| ...web, | ||
| annotations: { [BUILD_ENV_ANNOTATION]: value }, | ||
| }); | ||
|
|
||
| describe("getBuildEnv", () => { | ||
| it("returns {} without a service or annotation", () => { | ||
| expect(getBuildEnv(undefined)).to.deep.equal({}); | ||
| expect(getBuildEnv({ ...web, annotations: { team: "frontend" } })).to.deep.equal({}); | ||
| }); | ||
|
|
||
| it("parses a plain map like Cloud Run's buildConfig.environmentVariables", () => { | ||
| const env = { API_URL: "https://api.example.com", BASE_PATH: "" }; | ||
| expect(getBuildEnv(withAnnotation(JSON.stringify(env)))).to.deep.equal(env); | ||
| }); | ||
|
|
||
| it("parses secrets written the way apphosting.yaml writes them", () => { | ||
| const env = { | ||
| API_URL: "https://api.example.com", | ||
| NPM_TOKEN: { secret: "npm-token" }, | ||
| SENTRY_AUTH_TOKEN: { secret: "sentry-auth-token@2" }, | ||
| GITHUB_TOKEN: { secret: "projects/shared-secrets/secrets/github-token/versions/3" }, | ||
| }; | ||
| expect(getBuildEnv(withAnnotation(JSON.stringify(env)))).to.deep.equal(env); | ||
| }); | ||
|
|
||
| it("rejects invalid JSON and non-objects", () => { | ||
| expect(() => getBuildEnv(withAnnotation("API_URL=https://api.example.com"))).to.throw( | ||
| `Invalid ${BUILD_ENV_ANNOTATION} annotation on projects/my-project/locations/us-central1/services/web: it isn't valid JSON.`, | ||
| ); | ||
| for (const value of ["[]", "null", '"https://api.example.com"', "1"]) { | ||
| expect(() => getBuildEnv(withAnnotation(value))).to.throw("it must be a JSON object."); | ||
| } | ||
| }); | ||
|
|
||
| it("converts numbers and booleans to strings, as apphosting.yaml does", () => { | ||
| const annotation = | ||
| '{"NEXT_TELEMETRY_DISABLED": 1, "CI": true, "DEBUG": false, "RATIO": 1.50}'; | ||
| expect(getBuildEnv(withAnnotation(annotation))).to.deep.equal({ | ||
| NEXT_TELEMETRY_DISABLED: "1", | ||
| CI: "true", | ||
| DEBUG: "false", | ||
| // JSON doesn't keep how a number was written. | ||
| RATIO: "1.5", | ||
| }); | ||
| }); | ||
|
|
||
| it("rejects invalid values", () => { | ||
| const invalid = [ | ||
| null, | ||
| ["npm-token"], | ||
| {}, | ||
| { secret: 1 }, | ||
| // The version goes in the secret string, e.g. "npm-token@3". | ||
| { secret: "npm-token", version: "3" }, | ||
| ]; | ||
| for (const value of invalid) { | ||
| expect(() => getBuildEnv(withAnnotation(JSON.stringify({ NPM_TOKEN: value })))).to.throw( | ||
| 'NPM_TOKEN must be a string, number, boolean, or {"secret": "<secret name>"}.', | ||
| ); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| it("splits secrets from plain values", () => { | ||
| const env = { | ||
| API_URL: "https://api.example.com", | ||
| NPM_TOKEN: { secret: "npm-token" }, | ||
| SENTRY_AUTH_TOKEN: { secret: "sentry-auth-token@2" }, | ||
| }; | ||
| expect(secretNames(env)).to.deep.equal(["NPM_TOKEN", "SENTRY_AUTH_TOKEN"]); | ||
| expect(nonSecretValues(env)).to.deep.equal({ API_URL: "https://api.example.com" }); | ||
| }); | ||
|
|
||
| it("converts to local build env, available only to the build, with secrets unchanged", () => { | ||
| expect( | ||
| toLocalBuildEnv({ | ||
| API_URL: "https://api.example.com", | ||
| NPM_TOKEN: { secret: "npm-token" }, | ||
| GITHUB_TOKEN: { secret: "projects/shared-secrets/secrets/github-token/versions/3" }, | ||
| }), | ||
| ).to.deep.equal({ | ||
| API_URL: { value: "https://api.example.com", availability: ["BUILD"] }, | ||
| NPM_TOKEN: { secret: "npm-token", availability: ["BUILD"] }, | ||
| GITHUB_TOKEN: { | ||
| secret: "projects/shared-secrets/secrets/github-token/versions/3", | ||
| availability: ["BUILD"], | ||
| }, | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import { FirebaseError } from "../../error"; | ||
| import * as runv2 from "../../gcp/runv2"; | ||
| import { EnvMap } from "../../apphosting/yaml"; | ||
|
|
||
| /** | ||
| * Prototype: build-time env vars and secrets, stored on the Cloud Run service as a JSON object. | ||
| * Each value is a string, a number or boolean (which becomes a string, as in apphosting.yaml), or a | ||
| * Secret Manager secret written the way apphosting.yaml writes one: {"secret": "<name>"}, | ||
| * {"secret": "<name>@<version>"}, or {"secret": "<full resource name>"}. | ||
| * For example: | ||
| * { | ||
| * "API_URL": "https://api.example.com", | ||
| * "NEXT_TELEMETRY_DISABLED": 1, | ||
| * "NPM_TOKEN": {"secret": "npm-token"}, | ||
| * "SENTRY_AUTH_TOKEN": {"secret": "sentry-auth-token@2"}, | ||
| * "GITHUB_TOKEN": {"secret": "projects/shared-secrets/secrets/github-token/versions/3"} | ||
| * } | ||
| * The annotation only names secrets. Their values stay in Secret Manager. | ||
| */ | ||
| export const BUILD_ENV_ANNOTATION = | ||
| "firebase.google.com/buildConfig.environmentVariablesAndSecrets"; | ||
|
|
||
| /** | ||
| * A Secret Manager secret, in App Hosting's format. A version is optional and defaults to the | ||
| * latest. Local builds read the secret with App Hosting's loadSecret, which checks the format. | ||
| */ | ||
| export interface SecretRef { | ||
| secret: string; | ||
| } | ||
|
|
||
| export type BuildEnv = Record<string, string | SecretRef>; | ||
|
|
||
| /** | ||
| * Reads and validates the service's build environment. Returns {} if it has none. Numbers and | ||
| * booleans come back as strings, since env vars are strings. | ||
| */ | ||
| export function getBuildEnv(service: runv2.Service | undefined): BuildEnv { | ||
| const raw = service?.annotations?.[BUILD_ENV_ANNOTATION]; | ||
| if (!service || !raw) { | ||
| return {}; | ||
| } | ||
| const invalid = (reason: string): FirebaseError => | ||
| new FirebaseError(`Invalid ${BUILD_ENV_ANNOTATION} annotation on ${service.name}: ${reason}`); | ||
| let parsed: unknown; | ||
| try { | ||
| parsed = JSON.parse(raw); | ||
| } catch { | ||
| throw invalid("it isn't valid JSON."); | ||
| } | ||
| if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { | ||
| throw invalid("it must be a JSON object."); | ||
| } | ||
| const env: BuildEnv = {}; | ||
| for (const [name, value] of Object.entries(parsed)) { | ||
|
falahat marked this conversation as resolved.
|
||
| if (typeof value === "string" || isSecretRef(value)) { | ||
| env[name] = value; | ||
| } else if (typeof value === "number" || typeof value === "boolean") { | ||
| // apphosting.yaml takes unquoted numbers and booleans too. JSON doesn't keep how a number was | ||
| // written, so 1.50 becomes "1.5". Quote a value to keep it exactly as written. | ||
| env[name] = String(value); | ||
| } else { | ||
| throw invalid(`${name} must be a string, number, boolean, or {"secret": "<secret name>"}.`); | ||
| } | ||
| } | ||
| return env; | ||
| } | ||
|
|
||
| /** Whether a value is {"secret": "<secret name>"}, with no other fields. */ | ||
| function isSecretRef(value: unknown): value is SecretRef { | ||
| const ref = value as Partial<SecretRef> | null; | ||
| return ( | ||
| typeof ref === "object" && | ||
| ref !== null && | ||
| Object.keys(ref).length === 1 && | ||
| typeof ref.secret === "string" | ||
| ); | ||
| } | ||
|
|
||
| /** Names of the variables that are secrets. */ | ||
| export function secretNames(env: BuildEnv): string[] { | ||
| return Object.entries(env) | ||
| .filter(([, value]) => isSecretRef(value)) | ||
| .map(([name]) => name); | ||
| } | ||
|
|
||
| /** | ||
| * The env vars that aren't secrets, with their values. Secrets are left out entirely, so the result | ||
| * never names a secret or holds a secret's value. | ||
| */ | ||
| export function nonSecretValues(env: BuildEnv): Record<string, string> { | ||
| const values: Record<string, string> = {}; | ||
| for (const [name, value] of Object.entries(env)) { | ||
| if (!isSecretRef(value)) { | ||
| values[name] = value; | ||
| } | ||
| } | ||
| return values; | ||
| } | ||
|
|
||
| /** | ||
| * Converts the build environment to the form local builds take. Secrets pass through unchanged: | ||
| * the local build reads them with your credentials. | ||
| */ | ||
| export function toLocalBuildEnv(env: BuildEnv): EnvMap { | ||
| const result: EnvMap = {}; | ||
| for (const [name, value] of Object.entries(env)) { | ||
| if (isSecretRef(value)) { | ||
| result[name] = { secret: value.secret, availability: ["BUILD"] }; | ||
| } else { | ||
| result[name] = { value, availability: ["BUILD"] }; | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.