@webpieces/gcp-identity 0.4.923 → 0.4.925

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,26 +10,38 @@ tests) every call falls back to a deterministic localhost value so no GCP is nee
10
10
  - `gcpCloudRunDeriver()` — the GCP half of URL resolution: `svcName` → `https://<svc>-<projectNumber>.<region>.run.app`. Install it once at startup with `ClientRegistry.setDeriver(gcpCloudRunDeriver())` and every same-project/same-region peer resolves with no URL table. Off GCP (a CLI, CI) pass the values instead: `gcpCloudRunDeriver(new GcpCloudRunTarget(projectNumber, region))`
11
11
  - `getRuntimeServiceAccountEmail()` — the SA this process runs as
12
12
  - `GcpOidc.mintIdToken(audience)` — Google-signed OIDC ID token (a `dev-oidc.*` token off-GCP)
13
- - `GcpOidc.verifyFromCallers(idToken, callers)` — verify + allow-list the caller SA
13
+ - `GcpOidc.verify(idToken, methods)` — verify the token ONCE against the endpoint's OIDC methods (`oidcSameProject()` and/or `oidcSvcs([...])`); the call passes when any of them admits the caller
14
14
 
15
- Underpins the `oidc(...)` service-to-service credential contract used by
16
- `@webpieces/http-client-node` (RPC) and `@webpieces/cloudtasks-client`, with supplementary
17
- server checks dispatched by `AuthFilter`.
15
+ Underpins the `oidcSameProject()` / `oidcSvcs([...])` service-to-service credential contract used by
16
+ `@webpieces/http-client-node` (RPC) and `@webpieces/cloudtasks-client`, with the server checks
17
+ dispatched by `AuthFilter`.
18
18
 
19
- ## Private Cloud Run: Google enforces invocation access
19
+ ## Private Cloud Run: Google enforces invocation access, the application checks the caller
20
20
 
21
21
  The protected Cloud Run edge verifies the invocation ID token and enforces `roles/run.invoker`
22
- before the container receives it. The annotation primarily tells clients to generate the
23
- correct destination-audience token. A bare `@WpAuth([oidc()])` delegates caller authorization to
24
- that edge; explicit callers add an application allow-list. Real tokens are also checked by the
25
- application verifier, without its own audience constraint.
26
-
27
- Synthetic `dev-oidc.*` tokens support local/in-process tests and are unsigned. The current
28
- application decoder accepts that prefix without checking the runtime; the protected Cloud Run
29
- edge rejects it as an invocation credential. A direct verifier call does not test ingress IAM,
30
- and this verifier must not be treated as standalone protection for public/direct ingress.
22
+ before the container receives it. The descriptor tells clients to generate the correct
23
+ destination-audience token and names the callers the application accepts:
24
+
25
+ - `oidcSameProject()` admits a Google-signed token from a user-managed service account of this
26
+ project (`<name>@<projectId>.iam.gserviceaccount.com`) or from the project's Compute Engine
27
+ default (`<projectNumber>-compute@developer.gserviceaccount.com`). Google service agents, other
28
+ projects and user accounts are refused. Off GCP there is no project, so the check is open.
29
+ - `oidcSvcs([...])` admits exactly the listed accounts: `'self'` is this service's runtime
30
+ account, a bare id is an account of this project, and a full email is taken verbatim, so an
31
+ account of another project can be listed.
32
+
33
+ Real tokens are checked for signature and expiry, without an audience constraint of the verifier's own.
34
+
35
+ Synthetic `dev-oidc.*` tokens support local/in-process tests and are unsigned. `verify` accepts
36
+ that prefix only off GCP, where `mintIdToken` creates it: when `isOnGcp()` is true it refuses
37
+ one (`ok:false`, logged as a warning) before any project or caller check. The protected Cloud Run
38
+ edge also rejects it as an invocation credential. `isOnGcp()` reads `K_SERVICE` /
39
+ `METADATA_SERVER_DETECTION`, so a deployed host that sets neither is treated as off GCP: it still
40
+ accepts a synthetic token, and the `oidcSameProject()` check is open there. Set
41
+ `METADATA_SERVER_DETECTION=assume-present` on such hosts. A direct verifier call does not test
42
+ ingress IAM, and this verifier must not be treated as standalone protection for public/direct ingress.
31
43
  See [the Cloud Run OIDC guide](../../../docs/architecture/cloud-run-oidc.md) for deployment
32
- assumptions, the advisory public-posture check, and separate-header handling.
44
+ assumptions and separate-header handling.
33
45
 
34
46
  **There is exactly ONE service name.** The Cloud Run service name is what you report, what peers
35
47
  call you by, and what goes in every URL — yours and theirs. Nothing strips or adds a prefix: deploy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/gcp-identity",
3
- "version": "0.4.923",
3
+ "version": "0.4.925",
4
4
  "description": "GCP runtime identity: project/region metadata, Cloud Run URLs, OIDC mint/verify",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -23,8 +23,8 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
- "@webpieces/core-context": "0.4.923",
27
- "@webpieces/core-util": "0.4.923",
26
+ "@webpieces/core-context": "0.4.925",
27
+ "@webpieces/core-util": "0.4.925",
28
28
  "google-auth-library": "9.15.1",
29
29
  "gcp-metadata": "6.1.1",
30
30
  "inversify": "7.10.4",
package/src/index.d.ts CHANGED
@@ -5,8 +5,8 @@
5
5
  * all read from the metadata server / ADC at runtime with deterministic localhost
6
6
  * fallbacks off-GCP so local dev and tests never touch GCP.
7
7
  *
8
- * Underpins the oidc(...) service-to-service auth mode (enforced by the framework AuthFilter
9
- * via an app-bound AuthConfig) and the RPC + Cloud Tasks clients.
8
+ * Underpins the OIDC service-to-service auth modes, oidcSameProject() and oidcSvcs([...]) (enforced by http-routing's
9
+ * AuthFilter through DefaultOidcVerifier or an app-bound OidcHook) and the RPC + Cloud Tasks clients.
10
10
  *
11
11
  * URL RESOLUTION lives in core-util's browser-safe `ClientRegistry`, NOT here; this package
12
12
  * contributes only the GCP half of it — {@link gcpCloudRunDeriver}, which an app installs with
package/src/index.js CHANGED
@@ -6,8 +6,8 @@
6
6
  * all read from the metadata server / ADC at runtime with deterministic localhost
7
7
  * fallbacks off-GCP so local dev and tests never touch GCP.
8
8
  *
9
- * Underpins the oidc(...) service-to-service auth mode (enforced by the framework AuthFilter
10
- * via an app-bound AuthConfig) and the RPC + Cloud Tasks clients.
9
+ * Underpins the OIDC service-to-service auth modes, oidcSameProject() and oidcSvcs([...]) (enforced by http-routing's
10
+ * AuthFilter through DefaultOidcVerifier or an app-bound OidcHook) and the RPC + Cloud Tasks clients.
11
11
  *
12
12
  * URL RESOLUTION lives in core-util's browser-safe `ClientRegistry`, NOT here; this package
13
13
  * contributes only the GCP half of it — {@link gcpCloudRunDeriver}, which an app installs with
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/cloud/gcp-identity/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uCAA4D;AAAnD,mGAAA,OAAO,OAAA;AAAE,iHAAA,qBAAqB,OAAA;AACvC,+BAOgB;AANZ,sGAAA,cAAc,OAAA;AACd,oGAAA,YAAY,OAAA;AACZ,iGAAA,SAAS,OAAA;AACT,qHAAA,6BAA6B,OAAA;AAC7B,0GAAA,kBAAkB,OAAA;AAClB,mHAAA,2BAA2B,OAAA;AAE/B,2DAA6E;AAApE,wHAAA,kBAAkB,OAAA;AAAE,uHAAA,iBAAiB,OAAA;AAC9C,+BAAmD;AAA1C,+FAAA,OAAO,OAAA;AAAE,wGAAA,gBAAgB,OAAA","sourcesContent":["/**\n * @webpieces/gcp-identity\n *\n * GCP runtime identity (Node-only). Metadata, Cloud Run URLs, and OIDC mint/verify,\n * all read from the metadata server / ADC at runtime with deterministic localhost\n * fallbacks off-GCP so local dev and tests never touch GCP.\n *\n * Underpins the oidc(...) service-to-service auth mode (enforced by the framework AuthFilter\n * via an app-bound AuthConfig) and the RPC + Cloud Tasks clients.\n *\n * URL RESOLUTION lives in core-util's browser-safe `ClientRegistry`, NOT here; this package\n * contributes only the GCP half of it — {@link gcpCloudRunDeriver}, which an app installs with\n * `ClientRegistry.setDeriver(...)` at startup. That is the seam that lets a non-GCP deployment use\n * `templateDeriver` (or plain mappings) and never pull gcp-metadata onto the URL path.\n */\n\nexport { isOnGcp, resetMetadataForTests } from './metadata';\nexport {\n getServiceName,\n getProjectId,\n getRegion,\n getRuntimeServiceAccountEmail,\n getSelfCloudRunUrl,\n LOCAL_SERVICE_ACCOUNT_EMAIL,\n} from './urls';\nexport { gcpCloudRunDeriver, GcpCloudRunTarget } from './gcpCloudRunDeriver';\nexport { GcpOidc, OidcVerifyResult } from './oidc';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/cloud/gcp-identity/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,uCAA4D;AAAnD,mGAAA,OAAO,OAAA;AAAE,iHAAA,qBAAqB,OAAA;AACvC,+BAOgB;AANZ,sGAAA,cAAc,OAAA;AACd,oGAAA,YAAY,OAAA;AACZ,iGAAA,SAAS,OAAA;AACT,qHAAA,6BAA6B,OAAA;AAC7B,0GAAA,kBAAkB,OAAA;AAClB,mHAAA,2BAA2B,OAAA;AAE/B,2DAA6E;AAApE,wHAAA,kBAAkB,OAAA;AAAE,uHAAA,iBAAiB,OAAA;AAC9C,+BAAmD;AAA1C,+FAAA,OAAO,OAAA;AAAE,wGAAA,gBAAgB,OAAA","sourcesContent":["/**\n * @webpieces/gcp-identity\n *\n * GCP runtime identity (Node-only). Metadata, Cloud Run URLs, and OIDC mint/verify,\n * all read from the metadata server / ADC at runtime with deterministic localhost\n * fallbacks off-GCP so local dev and tests never touch GCP.\n *\n * Underpins the OIDC service-to-service auth modes, oidcSameProject() and oidcSvcs([...]) (enforced by http-routing's\n * AuthFilter through DefaultOidcVerifier or an app-bound OidcHook) and the RPC + Cloud Tasks clients.\n *\n * URL RESOLUTION lives in core-util's browser-safe `ClientRegistry`, NOT here; this package\n * contributes only the GCP half of it — {@link gcpCloudRunDeriver}, which an app installs with\n * `ClientRegistry.setDeriver(...)` at startup. That is the seam that lets a non-GCP deployment use\n * `templateDeriver` (or plain mappings) and never pull gcp-metadata onto the URL path.\n */\n\nexport { isOnGcp, resetMetadataForTests } from './metadata';\nexport {\n getServiceName,\n getProjectId,\n getRegion,\n getRuntimeServiceAccountEmail,\n getSelfCloudRunUrl,\n LOCAL_SERVICE_ACCOUNT_EMAIL,\n} from './urls';\nexport { gcpCloudRunDeriver, GcpCloudRunTarget } from './gcpCloudRunDeriver';\nexport { GcpOidc, OidcVerifyResult } from './oidc';\n"]}
package/src/metadata.d.ts CHANGED
@@ -2,6 +2,10 @@
2
2
  * True when running on GCP Cloud Run. Gated on `K_SERVICE` (set by Cloud Run) so local dev does NO
3
3
  * metadata network probe. For non-Cloud-Run GCP (GCE / Cloud Functions, which don't set `K_SERVICE`),
4
4
  * set `METADATA_SERVER_DETECTION=assume-present` to force on-GCP behavior.
5
+ *
6
+ * This is also a security gate. While it is false, GcpOidc accepts an unsigned `dev-oidc.*` token
7
+ * and the `oidcSameProject()` check is open (there is no project to compare against). A deployed host that
8
+ * sets neither variable therefore gets both, so it must set `METADATA_SERVER_DETECTION=assume-present`.
5
9
  */
6
10
  export declare function isOnGcp(): Promise<boolean>;
7
11
  /** GCP project id (e.g. 'my-project'). Only call when isOnGcp() is true. */
package/src/metadata.js CHANGED
@@ -17,7 +17,8 @@ const gcpMetadata = tslib_1.__importStar(require("gcp-metadata"));
17
17
  * `isOnGcp()` is decided from the `K_SERVICE` env var (which Cloud Run always sets),
18
18
  * NOT a metadata network probe — so local dev never blocks on the ~3s
19
19
  * `gcpMetadata.isAvailable()` timeout. Every caller (project id, region, Cloud Run URL
20
- * resolution, OIDC minting, Cloud Tasks) short-circuits through this one gate.
20
+ * resolution, OIDC minting, dev-token and same-project verification, Cloud Tasks) short-circuits
21
+ * through this one gate.
21
22
  */
22
23
  let cachedOnGcp;
23
24
  let cachedProjectId;
@@ -28,6 +29,10 @@ let cachedSaEmail;
28
29
  * True when running on GCP Cloud Run. Gated on `K_SERVICE` (set by Cloud Run) so local dev does NO
29
30
  * metadata network probe. For non-Cloud-Run GCP (GCE / Cloud Functions, which don't set `K_SERVICE`),
30
31
  * set `METADATA_SERVER_DETECTION=assume-present` to force on-GCP behavior.
32
+ *
33
+ * This is also a security gate. While it is false, GcpOidc accepts an unsigned `dev-oidc.*` token
34
+ * and the `oidcSameProject()` check is open (there is no project to compare against). A deployed host that
35
+ * sets neither variable therefore gets both, so it must set `METADATA_SERVER_DETECTION=assume-present`.
31
36
  */
32
37
  function isOnGcp() {
33
38
  if (!cachedOnGcp) {
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../packages/cloud/gcp-identity/src/metadata.ts"],"names":[],"mappings":";;AAyBA,0BAQC;AAUD,sCAKC;AAGD,oDAKC;AAGD,gCAQC;AAGD,wEAKC;AAOD,sDAMC;;AAxFD,kEAA4C;AAE5C;;;;;;;;;;GAUG;AAEH,IAAI,WAAyC,CAAC;AAC9C,IAAI,eAA4C,CAAC;AACjD,IAAI,sBAAmD,CAAC;AACxD,IAAI,YAAyC,CAAC;AAC9C,IAAI,aAA0C,CAAC;AAE/C;;;;GAIG;AACH,SAAgB,OAAO;IACnB,IAAI,CAAC,WAAW,EAAE,CAAC;QACf,MAAM,KAAK,GACP,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,SAAS;YACtC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,KAAK,gBAAgB,CAAC;QAClE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,WAAW,CAAC;AACvB,CAAC;AAED,oFAAoF;AACpF,wEAAwE;AACxE,iGAAiG;AACjG,SAAS,QAAQ,CAAC,KAAc;IAC5B,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC;AAED,4EAA4E;AAC5E,SAAgB,aAAa;IACzB,IAAI,CAAC,eAAe,EAAE,CAAC;QACnB,eAAe,GAAG,WAAW,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvE,CAAC;IACD,OAAO,eAAe,CAAC;AAC3B,CAAC;AAED,yDAAyD;AACzD,SAAgB,oBAAoB;IAChC,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC1B,sBAAsB,GAAG,WAAW,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtF,CAAC;IACD,OAAO,sBAAsB,CAAC;AAClC,CAAC;AAED,4FAA4F;AAC5F,SAAgB,UAAU;IACtB,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,YAAY,GAAG,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,GAAW,EAAE,EAAE;YAC9E,MAAM,GAAG,GAAG,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;YACjC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;QACnD,CAAC,CAAC,CAAC;IACP,CAAC;IACD,OAAO,YAAY,CAAC;AACxB,CAAC;AAED,sDAAsD;AACtD,SAAgB,8BAA8B;IAC1C,IAAI,CAAC,aAAa,EAAE,CAAC;QACjB,aAAa,GAAG,WAAW,CAAC,QAAQ,CAAC,gCAAgC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,aAAa,CAAC;AACzB,CAAC;AAED;;;GAGG;AACH,yIAAyI;AACzI,SAAgB,qBAAqB;IACjC,WAAW,GAAG,SAAS,CAAC;IACxB,eAAe,GAAG,SAAS,CAAC;IAC5B,sBAAsB,GAAG,SAAS,CAAC;IACnC,YAAY,GAAG,SAAS,CAAC;IACzB,aAAa,GAAG,SAAS,CAAC;AAC9B,CAAC","sourcesContent":["import * as gcpMetadata from 'gcp-metadata';\n\n/**\n * Cached reads of the GCP metadata server. Every value is fetched at most once per\n * process (the metadata server is stable for the life of the instance). Off-GCP\n * `isOnGcp()` is false and the callers fall back to localhost values, so nothing\n * here is ever reached in local dev / tests.\n *\n * `isOnGcp()` is decided from the `K_SERVICE` env var (which Cloud Run always sets),\n * NOT a metadata network probe — so local dev never blocks on the ~3s\n * `gcpMetadata.isAvailable()` timeout. Every caller (project id, region, Cloud Run URL\n * resolution, OIDC minting, Cloud Tasks) short-circuits through this one gate.\n */\n\nlet cachedOnGcp: Promise<boolean> | undefined;\nlet cachedProjectId: Promise<string> | undefined;\nlet cachedNumericProjectId: Promise<string> | undefined;\nlet cachedRegion: Promise<string> | undefined;\nlet cachedSaEmail: Promise<string> | undefined;\n\n/**\n * True when running on GCP Cloud Run. Gated on `K_SERVICE` (set by Cloud Run) so local dev does NO\n * metadata network probe. For non-Cloud-Run GCP (GCE / Cloud Functions, which don't set `K_SERVICE`),\n * set `METADATA_SERVER_DETECTION=assume-present` to force on-GCP behavior.\n */\nexport function isOnGcp(): Promise<boolean> {\n if (!cachedOnGcp) {\n const onGcp =\n process.env['K_SERVICE'] !== undefined ||\n process.env['METADATA_SERVER_DETECTION'] === 'assume-present';\n cachedOnGcp = Promise.resolve(onGcp);\n }\n return cachedOnGcp;\n}\n\n// gcp-metadata returns loosely-typed values; coerce every metadata read to a string\n// through this one helper so the rest of the file stays strongly typed.\n// webpieces-disable no-any-unknown -- single coercion point for gcp-metadata's loose return type\nfunction asString(value: unknown): string {\n return String(value);\n}\n\n/** GCP project id (e.g. 'my-project'). Only call when isOnGcp() is true. */\nexport function readProjectId(): Promise<string> {\n if (!cachedProjectId) {\n cachedProjectId = gcpMetadata.project('project-id').then(asString);\n }\n return cachedProjectId;\n}\n\n/** Numeric project id (used to build Cloud Run URLs). */\nexport function readNumericProjectId(): Promise<string> {\n if (!cachedNumericProjectId) {\n cachedNumericProjectId = gcpMetadata.project('numeric-project-id').then(asString);\n }\n return cachedNumericProjectId;\n}\n\n/** Cloud Run region (e.g. 'us-central1'), parsed from 'projects/<num>/regions/<region>'. */\nexport function readRegion(): Promise<string> {\n if (!cachedRegion) {\n cachedRegion = gcpMetadata.instance('region').then(asString).then((raw: string) => {\n const idx = raw.lastIndexOf('/');\n return idx >= 0 ? raw.substring(idx + 1) : raw;\n });\n }\n return cachedRegion;\n}\n\n/** The service-account email this process runs as. */\nexport function readRuntimeServiceAccountEmail(): Promise<string> {\n if (!cachedSaEmail) {\n cachedSaEmail = gcpMetadata.instance('service-accounts/default/email').then(asString);\n }\n return cachedSaEmail;\n}\n\n/**\n * Drop every memoized value. FOR TESTS ONLY — the caches above are module-scope and would otherwise\n * pin the FIRST spec's `K_SERVICE` / metadata answers for the whole file.\n */\n// webpieces-disable no-function-outside-class -- resets this module's own module-scope memo cells; every sibling here is a free function\nexport function resetMetadataForTests(): void {\n cachedOnGcp = undefined;\n cachedProjectId = undefined;\n cachedNumericProjectId = undefined;\n cachedRegion = undefined;\n cachedSaEmail = undefined;\n}\n"]}
1
+ {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../packages/cloud/gcp-identity/src/metadata.ts"],"names":[],"mappings":";;AA8BA,0BAQC;AAUD,sCAKC;AAGD,oDAKC;AAGD,gCAQC;AAGD,wEAKC;AAOD,sDAMC;;AA7FD,kEAA4C;AAE5C;;;;;;;;;;;GAWG;AAEH,IAAI,WAAyC,CAAC;AAC9C,IAAI,eAA4C,CAAC;AACjD,IAAI,sBAAmD,CAAC;AACxD,IAAI,YAAyC,CAAC;AAC9C,IAAI,aAA0C,CAAC;AAE/C;;;;;;;;GAQG;AACH,SAAgB,OAAO;IACnB,IAAI,CAAC,WAAW,EAAE,CAAC;QACf,MAAM,KAAK,GACP,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,SAAS;YACtC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,KAAK,gBAAgB,CAAC;QAClE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,WAAW,CAAC;AACvB,CAAC;AAED,oFAAoF;AACpF,wEAAwE;AACxE,iGAAiG;AACjG,SAAS,QAAQ,CAAC,KAAc;IAC5B,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC;AAED,4EAA4E;AAC5E,SAAgB,aAAa;IACzB,IAAI,CAAC,eAAe,EAAE,CAAC;QACnB,eAAe,GAAG,WAAW,CAAC,OAAO,CAAC,YAAY,CAAC,CA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\n\n/**\n * Cached reads of the GCP metadata server. Every value is fetched at most once per\n * process (the metadata server is stable for the life of the instance). Off-GCP\n * `isOnGcp()` is false and the callers fall back to localhost values, so nothing\n * here is ever reached in local dev / tests.\n *\n * `isOnGcp()` is decided from the `K_SERVICE` env var (which Cloud Run always sets),\n * NOT a metadata network probe — so local dev never blocks on the ~3s\n * `gcpMetadata.isAvailable()` timeout. Every caller (project id, region, Cloud Run URL\n * resolution, OIDC minting, dev-token and same-project verification, Cloud Tasks) short-circuits\n * through this one gate.\n */\n\nlet cachedOnGcp: Promise<boolean> | undefined;\nlet cachedProjectId: Promise<string> | undefined;\nlet cachedNumericProjectId: Promise<string> | undefined;\nlet cachedRegion: Promise<string> | undefined;\nlet cachedSaEmail: Promise<string> | undefined;\n\n/**\n * True when running on GCP Cloud Run. Gated on `K_SERVICE` (set by Cloud Run) so local dev does NO\n * metadata network probe. For non-Cloud-Run GCP (GCE / Cloud Functions, which don't set `K_SERVICE`),\n * set `METADATA_SERVER_DETECTION=assume-present` to force on-GCP behavior.\n *\n * This is also a security gate. While it is false, GcpOidc accepts an unsigned `dev-oidc.*` token\n * and the `oidcSameProject()` check is open (there is no project to compare against). A deployed host that\n * sets neither variable therefore gets both, so it must set `METADATA_SERVER_DETECTION=assume-present`.\n */\nexport function isOnGcp(): Promise<boolean> {\n if (!cachedOnGcp) {\n const onGcp =\n process.env['K_SERVICE'] !== undefined ||\n process.env['METADATA_SERVER_DETECTION'] === 'assume-present';\n cachedOnGcp = Promise.resolve(onGcp);\n }\n return cachedOnGcp;\n}\n\n// gcp-metadata returns loosely-typed values; coerce every metadata read to a string\n// through this one helper so the rest of the file stays strongly typed.\n// webpieces-disable no-any-unknown -- single coercion point for gcp-metadata's loose return type\nfunction asString(value: unknown): string {\n return String(value);\n}\n\n/** GCP project id (e.g. 'my-project'). Only call when isOnGcp() is true. */\nexport function readProjectId(): Promise<string> {\n if (!cachedProjectId) {\n cachedProjectId = gcpMetadata.project('project-id').then(asString);\n }\n return cachedProjectId;\n}\n\n/** Numeric project id (used to build Cloud Run URLs). */\nexport function readNumericProjectId(): Promise<string> {\n if (!cachedNumericProjectId) {\n cachedNumericProjectId = gcpMetadata.project('numeric-project-id').then(asString);\n }\n return cachedNumericProjectId;\n}\n\n/** Cloud Run region (e.g. 'us-central1'), parsed from 'projects/<num>/regions/<region>'. */\nexport function readRegion(): Promise<string> {\n if (!cachedRegion) {\n cachedRegion = gcpMetadata.instance('region').then(asString).then((raw: string) => {\n const idx = raw.lastIndexOf('/');\n return idx >= 0 ? raw.substring(idx + 1) : raw;\n });\n }\n return cachedRegion;\n}\n\n/** The service-account email this process runs as. */\nexport function readRuntimeServiceAccountEmail(): Promise<string> {\n if (!cachedSaEmail) {\n cachedSaEmail = gcpMetadata.instance('service-accounts/default/email').then(asString);\n }\n return cachedSaEmail;\n}\n\n/**\n * Drop every memoized value. FOR TESTS ONLY — the caches above are module-scope and would otherwise\n * pin the FIRST spec's `K_SERVICE` / metadata answers for the whole file.\n */\n// webpieces-disable no-function-outside-class -- resets this module's own module-scope memo cells; every sibling here is a free function\nexport function resetMetadataForTests(): void {\n cachedOnGcp = undefined;\n cachedProjectId = undefined;\n cachedNumericProjectId = undefined;\n cachedRegion = undefined;\n cachedSaEmail = undefined;\n}\n"]}
package/src/oidc.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- /** Outcome of verifying an inbound OIDC token against an allow-list of callers. */
1
+ import { OidcAuthMethods } from '@webpieces/core-util';
2
+ /** Outcome of verifying an inbound OIDC token against an endpoint's caller scope. */
2
3
  export declare class OidcVerifyResult {
3
4
  /** True when the token is valid AND its caller SA is allowed. */
4
5
  ok: boolean;
@@ -10,45 +11,62 @@ export declare class OidcVerifyResult {
10
11
  }
11
12
  /**
12
13
  * GcpOidc - Google OIDC service-to-service tokens: MINT an outbound token as this service's runtime
13
- * SA, and VERIFY an inbound token against a caller allow-list. Injected by type (@provideSingleton /
14
- * inject-by-type) into the RPC + Cloud Tasks clients (mint) and the framework auth verifier (verify),
15
- * so no DI-managed code calls gcp-identity as a free function.
14
+ * SA, and VERIFY an inbound token against the OIDC methods its endpoint declares
15
+ * (`oidcSameProject()` and/or `oidcSvcs([...])`, see {@link verify}). Injected by type
16
+ * (@provideSingleton / inject-by-type) into the RPC + Cloud Tasks clients (mint) and the framework
17
+ * auth verifier (verify), so no DI-managed code calls gcp-identity as a free function.
18
+ *
19
+ * Verify has one rule for the unsigned `dev-oidc.*` token: it is accepted only OFF GCP, where
20
+ * {@link mintIdToken} creates it. On GCP it is refused before any caller check.
16
21
  *
17
22
  * Holds the reusable google-auth-library clients as instance state (one per process, since this is a
18
- * framework singleton) plus the "warned about public posture once" flag.
23
+ * framework singleton).
19
24
  */
20
25
  export declare class GcpOidc {
21
26
  private readonly auth;
22
27
  private readonly verifier;
23
- private publicPostureChecked;
24
28
  /**
25
29
  * Mint a Google-signed OIDC ID token for `audience` (the callee's base URL), as this service's
26
- * runtime SA. Off-GCP returns a self-describing `dev-oidc.*` token that {@link verifyFromCallers}
27
- * accepts locally.
30
+ * runtime SA. Off-GCP returns a self-describing, unsigned `dev-oidc.*` token instead, and
31
+ * {@link verify} accepts one under the same condition: off GCP only. On GCP it refuses a dev
32
+ * token, so mint and verify agree on where a dev token is legitimate.
28
33
  */
29
34
  mintIdToken(audience: string): Promise<string>;
30
35
  /**
31
- * Verify an inbound OIDC token and require its caller SA to be in the allow-list. Audience is
32
- * deliberately NOT gated (mirrors the platform's cross-service model — the callee's own `aud`
33
- * passes). Never throws — an invalid token or a disallowed caller comes back as `ok:false` so
34
- * callers map it to a 401 without a try/catch.
36
+ * Verify an inbound OIDC token against the endpoint's OIDC methods: the signature is checked ONCE,
37
+ * and the call is admitted when ANY method admits the caller's email. Never throws for a bad token
38
+ * or a disallowed caller, so callers map `ok:false` to a 401 without a try/catch. Audience is
39
+ * deliberately NOT gated (mirrors the platform's cross-service model: the callee's own `aud` passes).
35
40
  *
36
- * `callers` entries resolve as: 'self' → this service's runtime SA; a bare id →
37
- * `<id>@<project>.iam.gserviceaccount.com`; anything containing '@' → verbatim.
41
+ * - `oidcSameProject()`: the caller must be a service account of THIS GCP project, either
42
+ * user-managed (`<name>@<projectId>.iam.gserviceaccount.com`) or the project's Compute Engine
43
+ * default (`<projectNumber>-compute@developer.gserviceaccount.com`). Google service agents
44
+ * (`service-<number>@gcp-sa-*.iam.gserviceaccount.com` and the other Google-owned domains) are
45
+ * NOT this project's accounts and are refused, as is a user account. Off GCP there is no project
46
+ * to compare against, so this check is OPEN.
47
+ * - `oidcSvcs([...])`: the caller must be one of `callers`, which may belong to other projects.
48
+ * Entries resolve as: 'self' → this service's runtime SA; a bare id →
49
+ * `<id>@<project>.iam.gserviceaccount.com`; anything containing '@' → verbatim.
38
50
  */
39
- verifyFromCallers(idToken: string, callers: string[]): Promise<OidcVerifyResult>;
51
+ verify(idToken: string, methods: OidcAuthMethods): Promise<OidcVerifyResult>;
40
52
  /**
41
- * @WpAuth([oidc()]) (trust-the-edge) is only secure when the Cloud Run service is PRIVATE — the edge
42
- * enforces run.invoker. If it is actually PUBLIC, warn LOUDLY (once): we still admit only
43
- * Google-signed callers, but the edge is not filtering WHO. Never fails — this is advisory.
53
+ * Why `method` does not admit `email`, or undefined when it does. One branch per scope, then a
54
+ * `never` tail: a scope added to OidcAuthMethod without a branch here stops compiling, and a scope
55
+ * that reaches this method around the type (a cast, plain JS) is refused instead of falling through
56
+ * to admitted. That refusal names the scope only, never the token or the email.
44
57
  */
45
- private warnIfPublicOnce;
58
+ private refusalOf;
59
+ /** Off GCP there is no project to compare against, so the same-project check is open there. */
60
+ private admitsSameProject;
61
+ private listedRefusal;
46
62
  /**
47
- * True when THIS Cloud Run service grants run.invoker to allUsers/allAuthenticatedUsers (public).
48
- * Reads the service's OWN IAM policy via the Run Admin API (needs run.services.getIamPolicy on the
49
- * runtime SA). On any failure we cannot tell → false (no false alarm).
63
+ * True when `email` is a service account OF this project. Only two shapes qualify: a user-managed
64
+ * account under `<projectId>.iam.gserviceaccount.com`, and this project number's Compute Engine
65
+ * default account. Matching the WHOLE domain (not a prefix or suffix of it) is what keeps service
66
+ * agents out: they live under Google-owned domains such as `gcp-sa-pubsub.iam.gserviceaccount.com`
67
+ * even when their name carries this project's number. Only called on GCP.
50
68
  */
51
- private isServicePublic;
69
+ private isThisProjectsServiceAccount;
52
70
  private makeDevToken;
53
71
  private extractVerifiedEmail;
54
72
  /**
package/src/oidc.js CHANGED
@@ -12,10 +12,23 @@ const log = core_util_1.LogManager.getLogger('gcp-identity-oidc');
12
12
  /**
13
13
  * Prefix marking a deterministic local (off-GCP) OIDC token. Real Google-signed
14
14
  * tokens never start with this, so verify can tell them apart. This is what keeps
15
- * the oidc(...) code path fully exercised in tests without any GCP round-trip.
15
+ * the OIDC (`oidcSameProject()` / `oidcSvcs(...)`) code path fully exercised in tests
16
+ * without any GCP round-trip.
17
+ * The token is UNSIGNED, so verify accepts it only where mint creates it: off GCP.
16
18
  */
17
19
  const DEV_TOKEN_PREFIX = 'dev-oidc.';
18
- /** Outcome of verifying an inbound OIDC token against an allow-list of callers. */
20
+ /** Why a token proved no caller email, in every case but the one below. */
21
+ const NO_VERIFIED_EMAIL = 'token invalid or missing email claim';
22
+ /**
23
+ * Why a dev token is refused on GCP. The caller does not see it: DefaultOidcVerifier throws it inside an
24
+ * ApiUnauthorizedError, and ApiErrorBoundary / ApiErrorCodec.publicMessage disclose only an
25
+ * ApiEndUserError's own message, so the caller gets the generic 401 text. The operator sees it twice:
26
+ * in the thrown error's message, which LogApiCall records on the server's resp-FAIL line, and in the
27
+ * warn line below. It names the rule and the cure, never the token or the email it claims.
28
+ */
29
+ const DEV_TOKEN_ON_GCP = 'dev-oidc token refused on GCP: dev tokens are unsigned and accepted only off GCP, where ' +
30
+ 'mintIdToken creates them; send a Google-signed ID token';
31
+ /** Outcome of verifying an inbound OIDC token against an endpoint's caller scope. */
19
32
  class OidcVerifyResult {
20
33
  /** True when the token is valid AND its caller SA is allowed. */
21
34
  ok;
@@ -32,21 +45,25 @@ class OidcVerifyResult {
32
45
  exports.OidcVerifyResult = OidcVerifyResult;
33
46
  /**
34
47
  * GcpOidc - Google OIDC service-to-service tokens: MINT an outbound token as this service's runtime
35
- * SA, and VERIFY an inbound token against a caller allow-list. Injected by type (@provideSingleton /
36
- * inject-by-type) into the RPC + Cloud Tasks clients (mint) and the framework auth verifier (verify),
37
- * so no DI-managed code calls gcp-identity as a free function.
48
+ * SA, and VERIFY an inbound token against the OIDC methods its endpoint declares
49
+ * (`oidcSameProject()` and/or `oidcSvcs([...])`, see {@link verify}). Injected by type
50
+ * (@provideSingleton / inject-by-type) into the RPC + Cloud Tasks clients (mint) and the framework
51
+ * auth verifier (verify), so no DI-managed code calls gcp-identity as a free function.
52
+ *
53
+ * Verify has one rule for the unsigned `dev-oidc.*` token: it is accepted only OFF GCP, where
54
+ * {@link mintIdToken} creates it. On GCP it is refused before any caller check.
38
55
  *
39
56
  * Holds the reusable google-auth-library clients as instance state (one per process, since this is a
40
- * framework singleton) plus the "warned about public posture once" flag.
57
+ * framework singleton).
41
58
  */
42
59
  let GcpOidc = class GcpOidc {
43
60
  auth = new google_auth_library_1.GoogleAuth();
44
61
  verifier = new google_auth_library_1.OAuth2Client();
45
- publicPostureChecked = false;
46
62
  /**
47
63
  * Mint a Google-signed OIDC ID token for `audience` (the callee's base URL), as this service's
48
- * runtime SA. Off-GCP returns a self-describing `dev-oidc.*` token that {@link verifyFromCallers}
49
- * accepts locally.
64
+ * runtime SA. Off-GCP returns a self-describing, unsigned `dev-oidc.*` token instead, and
65
+ * {@link verify} accepts one under the same condition: off GCP only. On GCP it refuses a dev
66
+ * token, so mint and verify agree on where a dev token is legitimate.
50
67
  */
51
68
  async mintIdToken(audience) {
52
69
  if (!(await (0, metadata_1.isOnGcp)())) {
@@ -57,74 +74,86 @@ let GcpOidc = class GcpOidc {
57
74
  return client.idTokenProvider.fetchIdToken(audience);
58
75
  }
59
76
  /**
60
- * Verify an inbound OIDC token and require its caller SA to be in the allow-list. Audience is
61
- * deliberately NOT gated (mirrors the platform's cross-service model — the callee's own `aud`
62
- * passes). Never throws — an invalid token or a disallowed caller comes back as `ok:false` so
63
- * callers map it to a 401 without a try/catch.
77
+ * Verify an inbound OIDC token against the endpoint's OIDC methods: the signature is checked ONCE,
78
+ * and the call is admitted when ANY method admits the caller's email. Never throws for a bad token
79
+ * or a disallowed caller, so callers map `ok:false` to a 401 without a try/catch. Audience is
80
+ * deliberately NOT gated (mirrors the platform's cross-service model: the callee's own `aud` passes).
64
81
  *
65
- * `callers` entries resolve as: 'self' → this service's runtime SA; a bare id →
66
- * `<id>@<project>.iam.gserviceaccount.com`; anything containing '@' → verbatim.
82
+ * - `oidcSameProject()`: the caller must be a service account of THIS GCP project, either
83
+ * user-managed (`<name>@<projectId>.iam.gserviceaccount.com`) or the project's Compute Engine
84
+ * default (`<projectNumber>-compute@developer.gserviceaccount.com`). Google service agents
85
+ * (`service-<number>@gcp-sa-*.iam.gserviceaccount.com` and the other Google-owned domains) are
86
+ * NOT this project's accounts and are refused, as is a user account. Off GCP there is no project
87
+ * to compare against, so this check is OPEN.
88
+ * - `oidcSvcs([...])`: the caller must be one of `callers`, which may belong to other projects.
89
+ * Entries resolve as: 'self' → this service's runtime SA; a bare id →
90
+ * `<id>@<project>.iam.gserviceaccount.com`; anything containing '@' → verbatim.
67
91
  */
68
- async verifyFromCallers(idToken, callers) {
69
- const email = await this.extractVerifiedEmail(idToken);
92
+ async verify(idToken, methods) {
93
+ const verified = await this.extractVerifiedEmail(idToken);
94
+ const email = verified.email;
70
95
  if (!email) {
71
- return new OidcVerifyResult(false, undefined, 'token invalid or missing email claim');
96
+ return new OidcVerifyResult(false, undefined, verified.reasonIfNone);
72
97
  }
73
- // EMPTY allow-list = TRUST THE EDGE: accept any genuine Google-signed OIDC caller, because a
74
- // PRIVATE Cloud Run service's edge already gated WHO via run.invoker IAM (managed in terraform,
75
- // one source of truth). Warn loudly (once) if the service is actually PUBLIC — then the edge is
76
- // NOT filtering callers and this is insecure. Non-empty list = explicit app-level allow-list.
77
- if (callers.length === 0) {
78
- await this.warnIfPublicOnce();
79
- return new OidcVerifyResult(true, email);
80
- }
81
- const allowed = await this.resolveCallers(callers);
82
- if (!allowed.includes(email)) {
83
- return new OidcVerifyResult(false, email, `caller '${email}' is not in the allow-list [${allowed.join(', ')}]`);
98
+ const refusals = [];
99
+ for (const method of methods) {
100
+ const refusal = await this.refusalOf(email, method);
101
+ if (refusal === undefined) {
102
+ return new OidcVerifyResult(true, email);
103
+ }
104
+ refusals.push(refusal);
84
105
  }
85
- return new OidcVerifyResult(true, email);
106
+ return new OidcVerifyResult(false, email, refusals.join('; '));
86
107
  }
87
108
  /**
88
- * @WpAuth([oidc()]) (trust-the-edge) is only secure when the Cloud Run service is PRIVATE — the edge
89
- * enforces run.invoker. If it is actually PUBLIC, warn LOUDLY (once): we still admit only
90
- * Google-signed callers, but the edge is not filtering WHO. Never fails — this is advisory.
109
+ * Why `method` does not admit `email`, or undefined when it does. One branch per scope, then a
110
+ * `never` tail: a scope added to OidcAuthMethod without a branch here stops compiling, and a scope
111
+ * that reaches this method around the type (a cast, plain JS) is refused instead of falling through
112
+ * to admitted. That refusal names the scope only, never the token or the email.
91
113
  */
92
- async warnIfPublicOnce() {
93
- if (this.publicPostureChecked) {
94
- return;
114
+ async refusalOf(email, method) {
115
+ switch (method.callerScope) {
116
+ case 'same-project':
117
+ return (await this.admitsSameProject(email))
118
+ ? undefined
119
+ : `caller '${email}' is not a service account of this GCP project`;
120
+ case 'services':
121
+ return this.listedRefusal(email, method.callers);
122
+ default: {
123
+ const unhandled = method;
124
+ return `unknown OIDC callerScope '${String(unhandled.callerScope)}'`;
125
+ }
95
126
  }
96
- this.publicPostureChecked = true; // attempt at most once, even if the check itself errors
127
+ }
128
+ /** Off GCP there is no project to compare against, so the same-project check is open there. */
129
+ async admitsSameProject(email) {
97
130
  if (!(await (0, metadata_1.isOnGcp)())) {
98
- return; // off-GCP: there is no Cloud Run edge; public/private does not apply.
99
- }
100
- if (await this.isServicePublic()) {
101
- log.error('This endpoint is currently public but marked oidc(...) which requires the service to be ' +
102
- 'private. You are currently running in a very insecure mode; however, we are only allowing ' +
103
- 'google-signed callers in. The edge will validate callers are allowed in (make the Cloud Run ' +
104
- 'service private — remove the allUsers run.invoker binding) to reduce your attack surface.');
131
+ return true;
105
132
  }
133
+ return this.isThisProjectsServiceAccount(email);
134
+ }
135
+ async listedRefusal(email, callers) {
136
+ const allowed = await this.resolveCallers(callers);
137
+ return allowed.includes(email)
138
+ ? undefined
139
+ : `caller '${email}' is not in the allow-list [${allowed.join(', ')}]`;
106
140
  }
107
141
  /**
108
- * True when THIS Cloud Run service grants run.invoker to allUsers/allAuthenticatedUsers (public).
109
- * Reads the service's OWN IAM policy via the Run Admin API (needs run.services.getIamPolicy on the
110
- * runtime SA). On any failure we cannot tell → false (no false alarm).
142
+ * True when `email` is a service account OF this project. Only two shapes qualify: a user-managed
143
+ * account under `<projectId>.iam.gserviceaccount.com`, and this project number's Compute Engine
144
+ * default account. Matching the WHOLE domain (not a prefix or suffix of it) is what keeps service
145
+ * agents out: they live under Google-owned domains such as `gcp-sa-pubsub.iam.gserviceaccount.com`
146
+ * even when their name carries this project's number. Only called on GCP.
111
147
  */
112
- async isServicePublic() {
113
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a failed self-IAM read just means "posture unknown" → no warning
114
- try {
115
- const [project, region] = await Promise.all([(0, urls_1.getProjectId)(), (0, urls_1.getRegion)()]);
116
- const service = process.env['K_SERVICE'] ?? '';
117
- const url = `https://run.googleapis.com/v2/projects/${project}/locations/${region}/services/${service}:getIamPolicy`;
118
- const client = await this.auth.getClient();
119
- const res = await client.request({ url: url });
120
- return (res.data.bindings ?? []).some((binding) => binding.role === 'roles/run.invoker' &&
121
- (binding.members ?? []).some((m) => m === 'allUsers' || m === 'allAuthenticatedUsers'));
122
- }
123
- catch (err) {
124
- const error = (0, core_util_2.toError)(err);
125
- log.debug(`Could not read own Cloud Run IAM policy (need run.services.getIamPolicy): ${error.message}`);
148
+ async isThisProjectsServiceAccount(email) {
149
+ const projectId = await (0, metadata_1.readProjectId)();
150
+ const projectNumber = await (0, metadata_1.readNumericProjectId)();
151
+ const at = email.lastIndexOf('@');
152
+ if (at <= 0) {
126
153
  return false;
127
154
  }
155
+ return (email.substring(at + 1) === `${projectId}.iam.gserviceaccount.com` ||
156
+ email === `${projectNumber}-compute@developer.gserviceaccount.com`);
128
157
  }
129
158
  makeDevToken(email, audience) {
130
159
  const payload = JSON.stringify({ email: email, aud: audience });
@@ -132,13 +161,21 @@ let GcpOidc = class GcpOidc {
132
161
  }
133
162
  async extractVerifiedEmail(idToken) {
134
163
  if (idToken.startsWith(DEV_TOKEN_PREFIX)) {
135
- return this.decodeDevTokenEmail(idToken);
164
+ if (await (0, metadata_1.isOnGcp)()) {
165
+ // Mint creates a dev token only OFF GCP, so verify accepts one only there. On GCP it is
166
+ // just unsigned text, so refuse it BEFORE decoding, whatever email it claims.
167
+ log.warn('Refusing a dev-oidc token, because isOnGcp() is true (K_SERVICE is set, or ' +
168
+ 'METADATA_SERVER_DETECTION=assume-present): ' +
169
+ DEV_TOKEN_ON_GCP);
170
+ return new VerifiedEmail(undefined, DEV_TOKEN_ON_GCP);
171
+ }
172
+ return new VerifiedEmail(this.decodeDevTokenEmail(idToken), NO_VERIFIED_EMAIL);
136
173
  }
137
174
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a genuinely unverifiable token is unauthenticated (→ undefined → 401); infra failures are re-thrown below
138
175
  try {
139
176
  const ticket = await this.verifier.verifyIdToken({ idToken: idToken });
140
177
  const payload = ticket.getPayload();
141
- return payload?.email ?? undefined;
178
+ return new VerifiedEmail(payload?.email ?? undefined, NO_VERIFIED_EMAIL);
142
179
  }
143
180
  catch (err) {
144
181
  const error = (0, core_util_2.toError)(err);
@@ -150,7 +187,7 @@ let GcpOidc = class GcpOidc {
150
187
  }
151
188
  // Bad signature / expired / malformed token → genuinely unauthenticated → 401 upstream.
152
189
  log.debug(`OIDC token rejected (unauthenticated): ${error.message}`);
153
- return undefined;
190
+ return new VerifiedEmail(undefined, NO_VERIFIED_EMAIL);
154
191
  }
155
192
  }
156
193
  /**
@@ -197,6 +234,15 @@ exports.GcpOidc = GcpOidc;
197
234
  exports.GcpOidc = GcpOidc = tslib_1.__decorate([
198
235
  (0, core_context_1.provideFrameworkSingleton)()
199
236
  ], GcpOidc);
237
+ /** The caller email a token proved, or `undefined` and the reason it proved none. */
238
+ class VerifiedEmail {
239
+ email;
240
+ reasonIfNone;
241
+ constructor(email, reasonIfNone) {
242
+ this.email = email;
243
+ this.reasonIfNone = reasonIfNone;
244
+ }
245
+ }
200
246
  /** Shape of the decoded dev-oidc token payload. */
201
247
  class DevTokenPayload {
202
248
  email;
package/src/oidc.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"oidc.js","sourceRoot":"","sources":["../../../../../packages/cloud/gcp-identity/src/oidc.ts"],"names":[],"mappings":";;;;AAAA,6DAA+D;AAC/D,0DAAoE;AACpE,oDAAkD;AAClD,oDAA+C;AAC/C,yCAAqC;AACrC,iCAAgF;AAEhF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;AAEtD;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,WAAW,CAAC;AAErC,mFAAmF;AACnF,MAAa,gBAAgB;IACzB,iEAAiE;IACjE,EAAE,CAAU;IACZ,mDAAmD;IACnD,KAAK,CAAU;IACf,kEAAkE;IAClE,MAAM,CAAU;IAEhB,YAAY,EAAW,EAAE,KAAc,EAAE,MAAe;QACpD,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAbD,4CAaC;AAED;;;;;;;;GAQG;AAEI,IAAM,OAAO,GAAb,MAAM,OAAO;IACC,IAAI,GAAG,IA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QACrB,CAAC;IACL,CAAC;IAEO,KAAK,CAAC,cAAc,CAAC,OAAiB;QAC1C,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAc,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACpF,CAAC;IAEO,KAAK,CAAC,aAAa,CAAC,MAAc;QACtC,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;YACpB,OAAO,IAAA,oCAA6B,GAAE,CAAC;QAC3C,CAAC;QACD,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YACvB,OAAO,MAAM,CAAC;QAClB,CAAC;QACD,MAAM,SAAS,GAAG,MAAM,IAAA,mBAAY,GAAE,CAAC;QACvC,OAAO,GAAG,MAAM,IAAI,SAAS,0BAA0B,CAAC;IAC5D,CAAC;CACJ,CAAA;AA/KY,0BAAO;kBAAP,OAAO;IADnB,IAAA,wCAAyB,GAAE;GACf,OAAO,CA+KnB;AAWD,mDAAmD;AACnD,MAAM,eAAe;IACjB,KAAK,CAAU;IACf,GAAG,CAAU;CAChB","sourcesContent":["import { GoogleAuth, OAuth2Client } from 'google-auth-library';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { toError } from '@webpieces/core-util';\nimport { isOnGcp } from './metadata';\nimport { getProjectId, getRegion, getRuntimeServiceAccountEmail } from './urls';\n\nconst log = LogManager.getLogger('gcp-identity-oidc');\n\n/**\n * Prefix marking a deterministic local (off-GCP) OIDC token. Real Google-signed\n * tokens never start with this, so verify can tell them apart. This is what keeps\n * the oidc(...) code path fully exercised in tests without any GCP round-trip.\n */\nconst DEV_TOKEN_PREFIX = 'dev-oidc.';\n\n/** Outcome of verifying an inbound OIDC token against an allow-list of callers. */\nexport class OidcVerifyResult {\n /** True when the token is valid AND its caller SA is allowed. */\n ok: boolean;\n /** The verified caller email (present when ok). */\n email?: string;\n /** Human-readable reason when not ok (for logs / 401 message). */\n reason?: string;\n\n constructor(ok: boolean, email?: string, reason?: string) {\n this.ok = ok;\n this.email = email;\n this.reason = reason;\n }\n}\n\n/**\n * GcpOidc - Google OIDC service-to-service tokens: MINT an outbound token as this service's runtime\n * SA, and VERIFY an inbound token against a caller allow-list. Injected by type (@provideSingleton /\n * inject-by-type) into the RPC + Cloud Tasks clients (mint) and the framework auth verifier (verify),\n * so no DI-managed code calls gcp-identity as a free function.\n *\n * Holds the reusable google-auth-library clients as instance state (one per process, since this is a\n * framework singleton) plus the \"warned about public posture once\" flag.\n */\n@provideFrameworkSingleton()\nexport class GcpOidc {\n private readonly auth = new GoogleAuth();\n private readonly verifier = new OAuth2Client();\n private publicPostureChecked = false;\n\n /**\n * Mint a Google-signed OIDC ID token for `audience` (the callee's base URL), as this service's\n * runtime SA. Off-GCP returns a self-describing `dev-oidc.*` token that {@link verifyFromCallers}\n * accepts locally.\n */\n async mintIdToken(audience: string): Promise<string> {\n if (!(await isOnGcp())) {\n const email = await getRuntimeServiceAccountEmail();\n return this.makeDevToken(email, audience);\n }\n const client = await this.auth.getIdTokenClient(audience);\n return client.idTokenProvider.fetchIdToken(audience);\n }\n\n /**\n * Verify an inbound OIDC token and require its caller SA to be in the allow-list. Audience is\n * deliberately NOT gated (mirrors the platform's cross-service model — the callee's own `aud`\n * passes). Never throws — an invalid token or a disallowed caller comes back as `ok:false` so\n * callers map it to a 401 without a try/catch.\n *\n * `callers` entries resolve as: 'self' → this service's runtime SA; a bare id →\n * `<id>@<project>.iam.gserviceaccount.com`; anything containing '@' → verbatim.\n */\n async verifyFromCallers(idToken: string, callers: string[]): Promise<OidcVerifyResult> {\n const email = await this.extractVerifiedEmail(idToken);\n if (!email) {\n return new OidcVerifyResult(false, undefined, 'token invalid or missing email claim');\n }\n // EMPTY allow-list = TRUST THE EDGE: accept any genuine Google-signed OIDC caller, because a\n // PRIVATE Cloud Run service's edge already gated WHO via run.invoker IAM (managed in terraform,\n // one source of truth). Warn loudly (once) if the service is actually PUBLIC — then the edge is\n // NOT filtering callers and this is insecure. Non-empty list = explicit app-level allow-list.\n if (callers.length === 0) {\n await this.warnIfPublicOnce();\n return new OidcVerifyResult(true, email);\n }\n const allowed = await this.resolveCallers(callers);\n if (!allowed.includes(email)) {\n return new OidcVerifyResult(\n false,\n email,\n `caller '${email}' is not in the allow-list [${allowed.join(', ')}]`,\n );\n }\n return new OidcVerifyResult(true, email);\n }\n\n /**\n * @WpAuth([oidc()]) (trust-the-edge) is only secure when the Cloud Run service is PRIVATE — the edge\n * enforces run.invoker. If it is actually PUBLIC, warn LOUDLY (once): we still admit only\n * Google-signed callers, but the edge is not filtering WHO. Never fails — this is advisory.\n */\n private async warnIfPublicOnce(): Promise<void> {\n if (this.publicPostureChecked) {\n return;\n }\n this.publicPostureChecked = true; // attempt at most once, even if the check itself errors\n if (!(await isOnGcp())) {\n return; // off-GCP: there is no Cloud Run edge; public/private does not apply.\n }\n if (await this.isServicePublic()) {\n log.error(\n 'This endpoint is currently public but marked oidc(...) which requires the service to be ' +\n 'private. You are currently running in a very insecure mode; however, we are only allowing ' +\n 'google-signed callers in. The edge will validate callers are allowed in (make the Cloud Run ' +\n 'service private — remove the allUsers run.invoker binding) to reduce your attack surface.',\n );\n }\n }\n\n /**\n * True when THIS Cloud Run service grants run.invoker to allUsers/allAuthenticatedUsers (public).\n * Reads the service's OWN IAM policy via the Run Admin API (needs run.services.getIamPolicy on the\n * runtime SA). On any failure we cannot tell → false (no false alarm).\n */\n private async isServicePublic(): Promise<boolean> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a failed self-IAM read just means \"posture unknown\" → no warning\n try {\n const [project, region] = await Promise.all([getProjectId(), getRegion()]);\n const service = process.env['K_SERVICE'] ?? '';\n const url = `https://run.googleapis.com/v2/projects/${project}/locations/${region}/services/${service}:getIamPolicy`;\n const client = await this.auth.getClient();\n const res = await client.request<IamPolicy>({ url: url });\n return (res.data.bindings ?? []).some(\n (binding: IamBinding) =>\n binding.role === 'roles/run.invoker' &&\n (binding.members ?? []).some(\n (m: string) => m === 'allUsers' || m === 'allAuthenticatedUsers',\n ),\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.debug(\n `Could not read own Cloud Run IAM policy (need run.services.getIamPolicy): ${error.message}`,\n );\n return false;\n }\n }\n\n private makeDevToken(email: string, audience: string): string {\n const payload = JSON.stringify({ email: email, aud: audience });\n return DEV_TOKEN_PREFIX + Buffer.from(payload, 'utf8').toString('base64url');\n }\n\n private async extractVerifiedEmail(idToken: string): Promise<string | undefined> {\n if (idToken.startsWith(DEV_TOKEN_PREFIX)) {\n return this.decodeDevTokenEmail(idToken);\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a genuinely unverifiable token is unauthenticated (→ undefined → 401); infra failures are re-thrown below\n try {\n const ticket = await this.verifier.verifyIdToken({ idToken: idToken });\n const payload = ticket.getPayload();\n return payload?.email ?? undefined;\n } catch (err: unknown) {\n const error = toError(err);\n if (this.isInfrastructureError(error)) {\n // A network/system failure fetching Google's certs (or a bug) is NOT an auth failure.\n // Do NOT mask it as a 401 — re-throw so it surfaces as a 5xx (alertable / retryable)\n // instead of looking like a caller sent a bad token.\n throw error;\n }\n // Bad signature / expired / malformed token → genuinely unauthenticated → 401 upstream.\n log.debug(`OIDC token rejected (unauthenticated): ${error.message}`);\n return undefined;\n }\n }\n\n /**\n * True when an error thrown while verifying a token is INFRASTRUCTURE (network/system), not a bad\n * token — e.g. the metadata/cert fetch failed. These must NOT be swallowed as a 401 (that would\n * both mislead the caller and hide real outages/bugs behind a client-error status).\n */\n private isInfrastructureError(error: Error): boolean {\n const code = (error as ErrorWithCode).code;\n const networkCodes = ['ENOTFOUND', 'ETIMEDOUT', 'ECONNREFUSED', 'ECONNRESET', 'EAI_AGAIN'];\n return (\n (code !== undefined && networkCodes.includes(code)) ||\n error.name === 'GaxiosError' ||\n error.name === 'FetchError'\n );\n }\n\n private decodeDevTokenEmail(idToken: string): string | undefined {\n const encoded = idToken.substring(DEV_TOKEN_PREFIX.length);\n const json = Buffer.from(encoded, 'base64url').toString('utf8');\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a malformed dev token is just unauthenticated → undefined\n try {\n const parsed = JSON.parse(json) as DevTokenPayload;\n return parsed.email ?? undefined;\n } catch (err: unknown) {\n const error = toError(err);\n log.debug(`dev-oidc token decode failed: ${error.message}`);\n return undefined;\n }\n }\n\n private async resolveCallers(callers: string[]): Promise<string[]> {\n return Promise.all(callers.map((caller: string) => this.resolveCaller(caller)));\n }\n\n private async resolveCaller(caller: string): Promise<string> {\n if (caller === 'self') {\n return getRuntimeServiceAccountEmail();\n }\n if (caller.includes('@')) {\n return caller;\n }\n const projectId = await getProjectId();\n return `${caller}@${projectId}.iam.gserviceaccount.com`;\n }\n}\n\n/** Minimal shape of a Cloud Run getIamPolicy response. */\ninterface IamBinding {\n role: string;\n members?: string[];\n}\ninterface IamPolicy {\n bindings?: IamBinding[];\n}\n\n/** Shape of the decoded dev-oidc token payload. */\nclass DevTokenPayload {\n email!: string;\n aud!: string;\n}\n\n/** A thrown error carrying an optional Node/system error code (e.g. 'ETIMEDOUT'). */\ninterface ErrorWithCode {\n code?: string;\n}\n"]}
1
+ {"version":3,"file":"oidc.js","sourceRoot":"","sources":["../../../../../packages/cloud/gcp-identity/src/oidc.ts"],"names":[],"mappings":";;;;AAAA,6DAA+D;AAC/D,0DAAoE;AACpE,oDAAgG;AAChG,oDAA+C;AAC/C,yCAA0E;AAC1E,iCAAqE;AAErE,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;AAEtD;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAG,WAAW,CAAC;AAErC,2EAA2E;AAC3E,MAAM,iBAAiB,GAAG,sCAAsC,CAAC;AAEjE;;;;;;GAMG;AACH,MAAM,gBAAgB,GAClB,0FAA0F;IAC1F,yDAAyD,CAAC;AAE9D,qFAAqF;AACrF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7LY,0BAAO;kBAAP,OAAO;IADnB,IAAA,wCAAyB,GAAE;GACf,OAAO,CA6LnB;AAED,qFAAqF;AACrF,MAAM,aAAa;IAEF;IACA;IAFb,YACa,KAAyB,EACzB,YAAoB;QADpB,UAAK,GAAL,KAAK,CAAoB;QACzB,iBAAY,GAAZ,YAAY,CAAQ;IAC9B,CAAC;CACP;AAED,mDAAmD;AACnD,MAAM,eAAe;IACjB,KAAK,CAAU;IACf,GAAG,CAAU;CAChB","sourcesContent":["import { GoogleAuth, OAuth2Client } from 'google-auth-library';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { LogManager, OidcAuthMethod, OidcAuthMethods, OidcCallers } from '@webpieces/core-util';\nimport { toError } from '@webpieces/core-util';\nimport { isOnGcp, readNumericProjectId, readProjectId } from './metadata';\nimport { getProjectId, getRuntimeServiceAccountEmail } from './urls';\n\nconst log = LogManager.getLogger('gcp-identity-oidc');\n\n/**\n * Prefix marking a deterministic local (off-GCP) OIDC token. Real Google-signed\n * tokens never start with this, so verify can tell them apart. This is what keeps\n * the OIDC (`oidcSameProject()` / `oidcSvcs(...)`) code path fully exercised in tests\n * without any GCP round-trip.\n * The token is UNSIGNED, so verify accepts it only where mint creates it: off GCP.\n */\nconst DEV_TOKEN_PREFIX = 'dev-oidc.';\n\n/** Why a token proved no caller email, in every case but the one below. */\nconst NO_VERIFIED_EMAIL = 'token invalid or missing email claim';\n\n/**\n * Why a dev token is refused on GCP. The caller does not see it: DefaultOidcVerifier throws it inside an\n * ApiUnauthorizedError, and ApiErrorBoundary / ApiErrorCodec.publicMessage disclose only an\n * ApiEndUserError's own message, so the caller gets the generic 401 text. The operator sees it twice:\n * in the thrown error's message, which LogApiCall records on the server's resp-FAIL line, and in the\n * warn line below. It names the rule and the cure, never the token or the email it claims.\n */\nconst DEV_TOKEN_ON_GCP =\n 'dev-oidc token refused on GCP: dev tokens are unsigned and accepted only off GCP, where ' +\n 'mintIdToken creates them; send a Google-signed ID token';\n\n/** Outcome of verifying an inbound OIDC token against an endpoint's caller scope. */\nexport class OidcVerifyResult {\n /** True when the token is valid AND its caller SA is allowed. */\n ok: boolean;\n /** The verified caller email (present when ok). */\n email?: string;\n /** Human-readable reason when not ok (for logs / 401 message). */\n reason?: string;\n\n constructor(ok: boolean, email?: string, reason?: string) {\n this.ok = ok;\n this.email = email;\n this.reason = reason;\n }\n}\n\n/**\n * GcpOidc - Google OIDC service-to-service tokens: MINT an outbound token as this service's runtime\n * SA, and VERIFY an inbound token against the OIDC methods its endpoint declares\n * (`oidcSameProject()` and/or `oidcSvcs([...])`, see {@link verify}). Injected by type\n * (@provideSingleton / inject-by-type) into the RPC + Cloud Tasks clients (mint) and the framework\n * auth verifier (verify), so no DI-managed code calls gcp-identity as a free function.\n *\n * Verify has one rule for the unsigned `dev-oidc.*` token: it is accepted only OFF GCP, where\n * {@link mintIdToken} creates it. On GCP it is refused before any caller check.\n *\n * Holds the reusable google-auth-library clients as instance state (one per process, since this is a\n * framework singleton).\n */\n@provideFrameworkSingleton()\nexport class GcpOidc {\n private readonly auth = new GoogleAuth();\n private readonly verifier = new OAuth2Client();\n\n /**\n * Mint a Google-signed OIDC ID token for `audience` (the callee's base URL), as this service's\n * runtime SA. Off-GCP returns a self-describing, unsigned `dev-oidc.*` token instead, and\n * {@link verify} accepts one under the same condition: off GCP only. On GCP it refuses a dev\n * token, so mint and verify agree on where a dev token is legitimate.\n */\n async mintIdToken(audience: string): Promise<string> {\n if (!(await isOnGcp())) {\n const email = await getRuntimeServiceAccountEmail();\n return this.makeDevToken(email, audience);\n }\n const client = await this.auth.getIdTokenClient(audience);\n return client.idTokenProvider.fetchIdToken(audience);\n }\n\n /**\n * Verify an inbound OIDC token against the endpoint's OIDC methods: the signature is checked ONCE,\n * and the call is admitted when ANY method admits the caller's email. Never throws for a bad token\n * or a disallowed caller, so callers map `ok:false` to a 401 without a try/catch. Audience is\n * deliberately NOT gated (mirrors the platform's cross-service model: the callee's own `aud` passes).\n *\n * - `oidcSameProject()`: the caller must be a service account of THIS GCP project, either\n * user-managed (`<name>@<projectId>.iam.gserviceaccount.com`) or the project's Compute Engine\n * default (`<projectNumber>-compute@developer.gserviceaccount.com`). Google service agents\n * (`service-<number>@gcp-sa-*.iam.gserviceaccount.com` and the other Google-owned domains) are\n * NOT this project's accounts and are refused, as is a user account. Off GCP there is no project\n * to compare against, so this check is OPEN.\n * - `oidcSvcs([...])`: the caller must be one of `callers`, which may belong to other projects.\n * Entries resolve as: 'self' → this service's runtime SA; a bare id →\n * `<id>@<project>.iam.gserviceaccount.com`; anything containing '@' → verbatim.\n */\n async verify(idToken: string, methods: OidcAuthMethods): Promise<OidcVerifyResult> {\n const verified = await this.extractVerifiedEmail(idToken);\n const email = verified.email;\n if (!email) {\n return new OidcVerifyResult(false, undefined, verified.reasonIfNone);\n }\n const refusals: string[] = [];\n for (const method of methods) {\n const refusal = await this.refusalOf(email, method);\n if (refusal === undefined) {\n return new OidcVerifyResult(true, email);\n }\n refusals.push(refusal);\n }\n return new OidcVerifyResult(false, email, refusals.join('; '));\n }\n\n /**\n * Why `method` does not admit `email`, or undefined when it does. One branch per scope, then a\n * `never` tail: a scope added to OidcAuthMethod without a branch here stops compiling, and a scope\n * that reaches this method around the type (a cast, plain JS) is refused instead of falling through\n * to admitted. That refusal names the scope only, never the token or the email.\n */\n private async refusalOf(email: string, method: OidcAuthMethod): Promise<string | undefined> {\n switch (method.callerScope) {\n case 'same-project':\n return (await this.admitsSameProject(email))\n ? undefined\n : `caller '${email}' is not a service account of this GCP project`;\n case 'services':\n return this.listedRefusal(email, method.callers);\n default: {\n const unhandled: never = method;\n return `unknown OIDC callerScope '${String((unhandled as OidcAuthMethod).callerScope)}'`;\n }\n }\n }\n\n /** Off GCP there is no project to compare against, so the same-project check is open there. */\n private async admitsSameProject(email: string): Promise<boolean> {\n if (!(await isOnGcp())) {\n return true;\n }\n return this.isThisProjectsServiceAccount(email);\n }\n\n private async listedRefusal(email: string, callers: OidcCallers): Promise<string | undefined> {\n const allowed = await this.resolveCallers(callers);\n return allowed.includes(email)\n ? undefined\n : `caller '${email}' is not in the allow-list [${allowed.join(', ')}]`;\n }\n\n /**\n * True when `email` is a service account OF this project. Only two shapes qualify: a user-managed\n * account under `<projectId>.iam.gserviceaccount.com`, and this project number's Compute Engine\n * default account. Matching the WHOLE domain (not a prefix or suffix of it) is what keeps service\n * agents out: they live under Google-owned domains such as `gcp-sa-pubsub.iam.gserviceaccount.com`\n * even when their name carries this project's number. Only called on GCP.\n */\n private async isThisProjectsServiceAccount(email: string): Promise<boolean> {\n const projectId = await readProjectId();\n const projectNumber = await readNumericProjectId();\n const at = email.lastIndexOf('@');\n if (at <= 0) {\n return false;\n }\n return (\n email.substring(at + 1) === `${projectId}.iam.gserviceaccount.com` ||\n email === `${projectNumber}-compute@developer.gserviceaccount.com`\n );\n }\n\n private makeDevToken(email: string, audience: string): string {\n const payload = JSON.stringify({ email: email, aud: audience });\n return DEV_TOKEN_PREFIX + Buffer.from(payload, 'utf8').toString('base64url');\n }\n\n private async extractVerifiedEmail(idToken: string): Promise<VerifiedEmail> {\n if (idToken.startsWith(DEV_TOKEN_PREFIX)) {\n if (await isOnGcp()) {\n // Mint creates a dev token only OFF GCP, so verify accepts one only there. On GCP it is\n // just unsigned text, so refuse it BEFORE decoding, whatever email it claims.\n log.warn(\n 'Refusing a dev-oidc token, because isOnGcp() is true (K_SERVICE is set, or ' +\n 'METADATA_SERVER_DETECTION=assume-present): ' +\n DEV_TOKEN_ON_GCP,\n );\n return new VerifiedEmail(undefined, DEV_TOKEN_ON_GCP);\n }\n return new VerifiedEmail(this.decodeDevTokenEmail(idToken), NO_VERIFIED_EMAIL);\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a genuinely unverifiable token is unauthenticated (→ undefined → 401); infra failures are re-thrown below\n try {\n const ticket = await this.verifier.verifyIdToken({ idToken: idToken });\n const payload = ticket.getPayload();\n return new VerifiedEmail(payload?.email ?? undefined, NO_VERIFIED_EMAIL);\n } catch (err: unknown) {\n const error = toError(err);\n if (this.isInfrastructureError(error)) {\n // A network/system failure fetching Google's certs (or a bug) is NOT an auth failure.\n // Do NOT mask it as a 401 — re-throw so it surfaces as a 5xx (alertable / retryable)\n // instead of looking like a caller sent a bad token.\n throw error;\n }\n // Bad signature / expired / malformed token → genuinely unauthenticated → 401 upstream.\n log.debug(`OIDC token rejected (unauthenticated): ${error.message}`);\n return new VerifiedEmail(undefined, NO_VERIFIED_EMAIL);\n }\n }\n\n /**\n * True when an error thrown while verifying a token is INFRASTRUCTURE (network/system), not a bad\n * token — e.g. the metadata/cert fetch failed. These must NOT be swallowed as a 401 (that would\n * both mislead the caller and hide real outages/bugs behind a client-error status).\n */\n private isInfrastructureError(error: Error): boolean {\n const code = (error as ErrorWithCode).code;\n const networkCodes = ['ENOTFOUND', 'ETIMEDOUT', 'ECONNREFUSED', 'ECONNRESET', 'EAI_AGAIN'];\n return (\n (code !== undefined && networkCodes.includes(code)) ||\n error.name === 'GaxiosError' ||\n error.name === 'FetchError'\n );\n }\n\n private decodeDevTokenEmail(idToken: string): string | undefined {\n const encoded = idToken.substring(DEV_TOKEN_PREFIX.length);\n const json = Buffer.from(encoded, 'base64url').toString('utf8');\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a malformed dev token is just unauthenticated → undefined\n try {\n const parsed = JSON.parse(json) as DevTokenPayload;\n return parsed.email ?? undefined;\n } catch (err: unknown) {\n const error = toError(err);\n log.debug(`dev-oidc token decode failed: ${error.message}`);\n return undefined;\n }\n }\n\n private async resolveCallers(callers: readonly string[]): Promise<string[]> {\n return Promise.all(callers.map((caller: string) => this.resolveCaller(caller)));\n }\n\n private async resolveCaller(caller: string): Promise<string> {\n if (caller === 'self') {\n return getRuntimeServiceAccountEmail();\n }\n if (caller.includes('@')) {\n return caller;\n }\n const projectId = await getProjectId();\n return `${caller}@${projectId}.iam.gserviceaccount.com`;\n }\n}\n\n/** The caller email a token proved, or `undefined` and the reason it proved none. */\nclass VerifiedEmail {\n constructor(\n readonly email: string | undefined,\n readonly reasonIfNone: string,\n ) {}\n}\n\n/** Shape of the decoded dev-oidc token payload. */\nclass DevTokenPayload {\n email!: string;\n aud!: string;\n}\n\n/** A thrown error carrying an optional Node/system error code (e.g. 'ETIMEDOUT'). */\ninterface ErrorWithCode {\n code?: string;\n}\n"]}