@sanoma-ai/connector-gcp 0.1.4 → 0.11.21

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
@@ -1,100 +1,78 @@
1
1
  # @sanoma-ai/connector-gcp
2
2
 
3
- Google Cloud KMS and IAM provisioning through the pinned `hashicorp/google` **8.7.0** OpenTofu provider and isolated [bridge sessions](../../packages/bridge/README.md). This connector provisions infrastructure; it does not store credentials or supply the managed Cloud runtime's identity broker ([D1, #492](https://github.com/Sanoma-AI/sanoma/issues/492)).
3
+ Google Cloud KMS, IAM and Cloud Run provisioning through the pinned `hashicorp/google` **8.7.0** OpenTofu provider and isolated [bridge sessions](../../packages/sanoma/bridge/README.md). This connector provisions infrastructure; it does not store credentials or supply the managed Cloud runtime's identity broker ([D1, #492](https://github.com/Sanoma-AI/sanoma/issues/492)).
4
4
 
5
5
  The Google Cloud logo is the [official homepage asset](https://www.gstatic.com/cgc/google-cloud-logo-fullcolor.svg). Provider schema provenance and its verified download pin are recorded in `testdata/`; the provider binary is downloaded separately by the bridge.
6
6
 
7
7
  ## Resource types
8
8
 
9
- | Constructor | Provider resource | Purpose |
10
- | ------------------------------ | -------------------------------------------- | -------------------------------------------------------- |
11
- | `gcp.keyRing` | `google_kms_key_ring` | KMS key ring in a project/location. |
12
- | `gcp.cryptoKey` | `google_kms_crypto_key` | Symmetric encryption key and rotation settings. |
13
- | `gcp.keyIamMember` | `google_kms_crypto_key_iam_member` | One member's role on one key. |
14
- | `gcp.serviceAccount` | `google_service_account` | Service account, without a private key. |
15
- | `gcp.serviceAccountIamMember` | `google_service_account_iam_member` | One member's role on a service account. |
16
- | `gcp.workloadIdentityPool` | `google_iam_workload_identity_pool` | Workload identity pool. |
17
- | `gcp.workloadIdentityProvider` | `google_iam_workload_identity_pool_provider` | OIDC issuer, claim mapping and explicit trust condition. |
9
+ | Constructor | Provider resource | Identity (import ID) |
10
+ | ------------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------------- |
11
+ | `gcp.keyRing` | `google_kms_key_ring` | `projects/<project>/locations/<location>/keyRings/<name>` |
12
+ | `gcp.cryptoKey` | `google_kms_crypto_key` | `<key_ring>/cryptoKeys/<name>` |
13
+ | `gcp.keyIamMember` | `google_kms_crypto_key_iam_member` | `<crypto_key_id> <role> <member> [condition title]` |
14
+ | `gcp.serviceAccount` | `google_service_account` | `projects/<project>/serviceAccounts/<account_id>@<project>.iam.gserviceaccount.com` |
15
+ | `gcp.serviceAccountIamMember` | `google_service_account_iam_member` | `<service_account_id> <role> <member> [condition title]` |
16
+ | `gcp.workloadIdentityPool` | `google_iam_workload_identity_pool` | `projects/<project>/locations/global/workloadIdentityPools/<pool>` |
17
+ | `gcp.workloadIdentityProvider` | `google_iam_workload_identity_pool_provider` | `projects/<project>/locations/global/workloadIdentityPools/<pool>/providers/<provider>` |
18
+ | `gcp.customRole` | `google_project_iam_custom_role` | `projects/<project>/roles/<role_id>` |
19
+ | `gcp.auditConfig` | `google_project_iam_audit_config` | `<project> <service>` |
20
+ | `gcp.cloudRunService` | `google_cloud_run_v2_service` | `projects/<project>/locations/<location>/services/<name>` |
21
+ | `gcp.cloudRunServiceIamMember` | `google_cloud_run_v2_service_iam_member` | `<name> <role> <member> [condition title]` |
18
22
 
19
- The resource schemas are generated from the recorded provider schema; field names retain Google's provider spelling. Each type exposes read/import/plan and the apply workflow's create/update/delete operations. KMS key-ring/key deletion is refused, key replacement is refused during update, and key configuration uses `deletion_policy: "PREVENT"`. Retiring a key requires a separate retention procedure covering every encrypted value and recoverable backup. The driver refuses a desired purpose other than `ENCRYPT_DECRYPT` or an algorithm other than `GOOGLE_SYMMETRIC_ENCRYPTION`; signing and asymmetric keys are outside this connector’s scope.
23
+ The resource schemas are generated from the recorded provider schema; field names retain Google's provider spelling. Each type exposes read/import/plan and the apply workflow's create/update/delete operations.
24
+
25
+ Each declaration is named by its provider import ID, built from its declared fields, so `project` (and `location` where the ID has one) must be declared: a declaration without them is refused rather than defaulted. A first apply imports each unbound declaration by that ID. When Google already has the object, apply binds it instead of creating a second one; the ID is the provider's state `id` for every type except the three IAM member types and the audit config, whose binding IDs are their import IDs. A Cloud Run service's IAM member names the service by its full resource name, which a reference to a declared `gcp.cloudRunService` gives. KMS key-ring/key deletion is refused, key replacement is refused during update, and key configuration uses `deletion_policy: "PREVENT"`. Retiring a key requires a separate retention procedure covering every encrypted value and recoverable backup. The driver refuses a desired purpose other than `ENCRYPT_DECRYPT` or an algorithm other than `GOOGLE_SYMMETRIC_ENCRYPTION`; signing and asymmetric keys are outside this connector’s scope.
20
26
 
21
27
  ## Deployment identity
22
28
 
23
- `gcpWithIdentities` binds each named connection ID to trusted deployment configuration. Use the configured connector in `defineConfig`; the exported bare `gcp` has no live identity mapping.
29
+ A live call provisions as one identity, declared in code with `gcpWithIdentity`: the project, its number, the provisioning service account, the workload identity provider's audience and the [provisioning identity service](../../packages/sanoma/workflows/CLOUD-IDENTITY.md#provisioning-identity-from-a-non-google-host)'s `/identity` endpoint. None of these is secret. The one secret is the provisioning bearer that the identity service enrolled for this control plane. It is the connection's stored credential, entered on the Google Cloud connector page like an API key, and never an environment variable.
24
30
 
25
31
  ```ts
26
- // sanoma.config.ts: trusted deployment composition, never workflow input
32
+ // sanoma.config.ts
27
33
  import { defineConfig, defineConnection } from "sanoma";
28
- import { gcpWithIdentities } from "@sanoma-ai/connector-gcp";
29
-
30
- const gcp = gcpWithIdentities({
31
- "gcp/provisioning": {
32
- project: "example-company",
33
- projectNumber: "123456789012",
34
- serviceAccount: "provisioner@example-company.iam.gserviceaccount.com",
35
- credentialsFile: "/run/sanoma/gcp-wif.json",
36
- },
34
+ import { secret } from "sanoma/resources";
35
+ import { gcpWithIdentity } from "@sanoma-ai/connector-gcp";
36
+
37
+ const gcp = gcpWithIdentity({
38
+ project: "example-company",
39
+ projectNumber: "123456789012",
40
+ serviceAccount: "provisioner@example-company.iam.gserviceaccount.com",
41
+ audience:
42
+ "//iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/provision/providers/google",
43
+ issuer: "https://provisioning.example.test/identity",
37
44
  });
38
45
  const provisioning = defineConnection(gcp, {
39
46
  name: "provisioning",
40
47
  method: "workloadIdentity",
48
+ credentials: secret("GCP_PROVISIONING_AUTH"),
41
49
  account: "provisioner@example-company.iam.gserviceaccount.com/example-company/123456789012",
42
50
  });
43
51
 
44
52
  export default defineConfig({ connectors: [gcp], connections: [provisioning] });
45
53
  ```
46
54
 
47
- The mapping contains a file **path**, not its contents. Deliver the file through the trusted deployment environment; keep its contents and source tokens out of code, resource inputs, fixtures, logs and the secret-entry form. Treat this configuration and its file as security-sensitive even though no service-account private key is involved. Connect/verify the named account through the normal connection lifecycle; a declaration alone is not a verified binding.
48
-
49
- Only explicit `external_account` OIDC federation configuration is accepted. It must use Google's STS endpoint, a JWT subject token and impersonation of the exact configured service account. Service-account key files, executable sources, AWS environment sources and ambient ADC fallback are refused. A successful token exchange and impersonation verify the selected identity; a configured email alone is not proof. Verification returns the account identity and an empty scope list, not the access token or an attestation of individual IAM grants. Google IAM remains authoritative for permissions.
50
-
51
- The provider receives that explicit federation configuration inside a fresh session for each authorized operation. The driver checks project IDs/numbers in resource identifiers and fields against the selected deployment. The provisioning account's Google IAM grants must also limit its authority: application-side checks do not replace IAM isolation. Give provisioning and company runtime different service accounts and roles; a company runtime must not inherit the provisioning account's IAM administration permissions.
55
+ The identity's facts live on the connector rather than in the stored bundle, so changing the project, account, audience or issuer is a reviewed code change. The connection's `account` pins the service account, project and number: verification returns that account, and a binding made for another one is refused as `wrong_account` until it is connected again. All of a config's GCP connections share the one declared identity; each can hold its own bearer. A declaration's `project` is that project's ID, never its number. The exported bare `gcp` declares no identity: use it for workflows, resources and sandbox runs, where every live verification and call is refused.
52
56
 
53
- ### Provisioning service on a non-Google host
54
-
55
- Use the separate [provisioning identity service](../../packages/workflows/CLOUD-IDENTITY.md#provisioning-identity-from-a-non-google-host) when the control plane has no native Google identity:
56
-
57
- ```ts
58
- import { gcpProvisioningIdentity, gcpWithIdentities } from "@sanoma-ai/connector-gcp";
59
-
60
- const gcp = gcpWithIdentities({
61
- "gcp/provisioning": gcpProvisioningIdentity({
62
- project: "example-company",
63
- projectNumber: "123456789012",
64
- serviceAccount: "provisioner@example-company.iam.gserviceaccount.com",
65
- audience:
66
- "//iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/provision/providers/google",
67
- issuer: "https://provisioning.example.test/identity",
68
- credential: async () => process.env.SANOMA_PROVISIONING_CREDENTIAL ?? "",
69
- }),
70
- });
71
- ```
57
+ **Connect** on the connector page takes the bearer (43 base64url characters) and verifies it before saving. Verification asks the issuer for one Google OIDC token, exchanges it at Google STS for the declared audience and impersonates the declared service account. Success proves the bearer is enrolled and trusted for exactly that account. The connection stores only `{ bearer }`; **Replace credentials** stores a new one, which the next call uses.
72
58
 
73
- This is trusted deployment composition. The host supplies that explicit secret binding; there is no implicit environment fallback. `gcpProvisioningIdentity` generates an HTTPS URL-source configuration in memory, fixes Google STS and the target impersonation URL, and requests ten-minute access tokens. The named account must still be verified normally.
59
+ Each authorized call reads its bundle through `authenticationCredentials` inside that call, builds the external-account configuration in memory and gives it to a fresh provider session. The configuration fixes Google STS, a JWT subject token from the issuer URL and impersonation of the declared account for ten-minute access tokens. It cannot express a service-account key, an executable or file source, or ambient ADC, and nothing falls back to another identity. Failures are sanitized: no SDK message, cause or token crosses the boundary. Verification returns the account and an empty scope list, not the access token or an attestation of individual IAM grants. Google IAM remains authoritative for permissions.
74
60
 
75
- The callback is read for each verification and provider operation. A running provider session holds its starting bootstrap header while it renews from the URL, so bootstrap rotation needs enough overlap for active operations to finish. Stopping enrollment does not invalidate already issued Google OIDC tokens, which last up to one hour: remove federation/impersonation trust as part of incident revocation. Runtime identities use the separate company broker and never receive this provisioning bootstrap.
61
+ The driver also checks project IDs and numbers in resource identifiers and fields against the declared identity. Those checks do not replace IAM isolation: grant the provisioning account only what its declarations need, and give company runtimes different service accounts and roles.
76
62
 
77
- For another trusted deployment integration, `GcpIdentity.credentials` can return external-account JSON asynchronously instead of `credentialsFile`. Configure exactly one source. Callback/file/SDK failures are sanitized and never fall back to another identity. Do not call this callback from a workflow or serialize its output into durable state.
63
+ A running provider session holds the bearer it started with while it renews from the issuer, so a replaced bearer needs enough overlap for active operations to finish before the old enrollment is retired. Stopping an enrollment does not invalidate Google OIDC tokens already issued, which last up to one hour: remove federation or impersonation trust as part of incident revocation. Company runtimes use the separate runtime broker and never receive the provisioning bearer.
78
64
 
79
65
  ### First administrator setup
80
66
 
81
- An administrator must first establish the project, billing, required APIs, provisioning service account and initial federation trust using an existing authorized administration path. This connector has no project, billing or API-enablement resource. Grant the provisioning account only the KMS/IAM administration needed for its intended declarations, and grant the approved federated principal service-account impersonation access. Once that trust works, Sanoma can manage subsequent resources or import existing ones. See [Google's deployment-pipeline WIF setup](https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines).
82
-
83
- For GitHub Actions, bind trust to numeric `repository_owner_id` and `repository_id`, which survive name reuse safely. Map `google.subject` and any attributes used in principal bindings. Set an explicit provider condition; do not trust every repository under the shared GitHub issuer. Google describes these numeric claims in its [attribute-mapping guidance](https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines#define_an_attribute_mapping).
84
-
85
- Restrict branch, workflow and environment as well. For example, a policy for a production provisioning job can require all of these claims (replace every example with the intended deployment):
86
-
87
- ```text
88
- assertion.repository_owner_id == '1234567' &&
89
- assertion.repository_id == '7654321' &&
90
- assertion.ref == 'refs/heads/main' &&
91
- assertion.workflow_ref == 'example/company/.github/workflows/provision.yml@refs/heads/main' &&
92
- assertion.environment == 'production'
93
- ```
67
+ Sanoma cannot provision the trust it provisions through, so an administrator sets up the first identity by hand, with an existing authorized administration path:
94
68
 
95
- The job must use that protected environment and request OIDC with `id-token: write`. Review the actual claims for the workflow; reusable workflows also expose `job_workflow_ref`. Protect changes to the trusted workflow and environment. See [GitHub's OIDC claims and permissions](https://docs.github.com/en/actions/reference/security/oidc). The connector requires a nonempty OIDC trust condition; it does not infer or enforce this particular GitHub policy for you.
69
+ 1. Create the project, enable billing and the IAM, IAM Credentials, STS, KMS and Cloud Run APIs. This connector has no project, billing or API-enablement resource ([#698](https://github.com/Sanoma-AI/sanoma/issues/698)).
70
+ 2. Create the three service accounts the [provisioning identity service](../../packages/sanoma/workflows/CLOUD-IDENTITY.md#provisioning-identity-from-a-non-google-host) separates: the issuer's attached account, the source account it mints OIDC tokens for, and the provisioning account. Grant the issuer `iam.serviceAccounts.getOpenIdToken` on the source account only.
71
+ 3. Create the workload identity pool and an OIDC provider for issuer `https://accounts.google.com`, mapping `google.subject` from `assertion.sub` with a condition on the source account's numeric `uniqueId` and the audience. Grant that principal `roles/iam.workloadIdentityUser` on the provisioning account. Grant the provisioning account only the KMS and IAM administration its declarations need.
72
+ 4. Install the enrollment and audit schemas, deploy the identity service in `provisioning` mode, and enroll the control plane's first bearer: `createDeploymentCredential()` from `sanoma/workflows/cloud-identity` returns `{ credential, hash }`; insert the hash with administrative authority and keep the credential only until the next step. An operation for this enrollment and its rotation is [#701](https://github.com/Sanoma-AI/sanoma/issues/701).
73
+ 5. Paste the credential into **Connect** on the Google Cloud connector page for the `provisioning` connection.
96
74
 
97
- The subject-token source must remain renewable for the full provisioning operation. A file holding one expiring JWT is not a long-lived identity service. Provide a source that refreshes its token or a supported refreshable URL source; both the Node verifier and provider process must be able to read it. Test renewal through expiry in the target environment. A GitHub job's identity belongs to that job, not to a subsequently hosted company runtime; runtime renewal remains D1's separate boundary.
75
+ Once that trust works, declare these objects in a data file and let apply manage them: a first apply binds the existing ones by their import IDs instead of creating them again. The connector requires a nonempty OIDC trust condition on every `workloadIdentityProvider`; it does not infer the right condition for you.
98
76
 
99
77
  ## Authoring resources
100
78
 
@@ -123,7 +101,7 @@ Grant runtime encrypt/decrypt access with `keyIamMember` on the specific key. Ke
123
101
 
124
102
  ### IAM member IDs
125
103
 
126
- For `keyIamMember` and `serviceAccountIamMember`, the public operation result's `id` is the provider's import identifier:
104
+ For `keyIamMember`, `serviceAccountIamMember` and `cloudRunServiceIamMember`, the public operation result's `id` is the provider's import identifier:
127
105
 
128
106
  ```text
129
107
  resource_name role member [condition_title]
@@ -131,18 +109,18 @@ resource_name role member [condition_title]
131
109
 
132
110
  Pass that returned `id` unchanged to a subsequent read, including when no saved provider state is available. Sanoma derives it from the structured parent resource, role, member and optional condition title. Custom role paths and `principal://` members retain their slashes. The provider's native `state.id` remains unchanged; its slash-delimited representation is not the import identifier. See the pinned provider's [IAM member import implementation](https://github.com/hashicorp/terraform-provider-google/blob/v8.7.0/google/tpgiamresource/resource_iam_member.go).
133
111
 
134
- Google 8.7.0 reports an absent IAM member as an import error after reading its parent's policy. For these two IAM types, Sanoma recognizes only that specific missing-binding diagnostic as absence: reads return `gone: true`, provisioning can read before creating a grant, and deleting an already absent grant is idempotent. Permission failures, ambiguous conditions and other diagnostics remain sanitized errors.
112
+ Google 8.7.0 reports an absent IAM member as an import error after reading its parent's policy. For these three IAM types, Sanoma recognizes only that specific missing-binding diagnostic as absence: reads return `gone: true`, provisioning can read before creating a grant, and deleting an already absent grant is idempotent. Permission failures, ambiguous conditions and other diagnostics remain sanitized errors.
135
113
 
136
114
  ## Testing and current evidence
137
115
 
138
- `fakeGcp` is the bridge's in-memory resource fake; it is not Google IAM or a federation server. Authentication tests use synthetic STS/IAM responses and temporary token/config files, including separate account sources, denied impersonation, rejected key/executable configs and sanitized failures. Driver tests use a provider state double to check concurrent session separation, project/account refusals, symmetric-key and retention guards, OIDC condition requirements, sanitized failures and the fake. The recorded schema/pin in `testdata/` establishes the generated provider contract, not a successful cloud deployment.
116
+ `fakeGcp` is the bridge's in-memory resource fake; it is not Google IAM or a federation server. Authentication tests use a synthetic issuer, STS and IAM: verification of a stored bearer, a replaced bearer on the next verification, missing or malformed bundles, unenrolled bearers, denied impersonation, rejected identity facts and sanitized failures. Driver tests use a provider state double to check concurrent session separation, project/account refusals, symmetric-key and retention guards, OIDC condition requirements, sanitized failures and the fake. The recorded schema/pin in `testdata/` establishes the generated provider contract, not a successful cloud deployment.
139
117
 
140
- The [isolated live run](https://github.com/Sanoma-AI/sanoma/actions/runs/41164779676) passed on `e43fb77c1e05d51838687d4574b2678218983386` in project `sanoma-513217`: GitHub OIDC → WIF → scoped provisioning account, denied impersonation of another existing account, real Google-provider key create/read/update, rotation-period update and key-deletion refusal. One provider session remained active for 660 seconds and fetched a fresh OIDC subject token after its ten-minute impersonated token expired. Trust was restricted to numeric repository/owner IDs, branch, workflow and the exact reviewed commit. This proves that provisioning path; it does not establish live CRUD for all seven resource types or a company runtime's identity.
118
+ The [isolated live run](https://github.com/Sanoma-AI/sanoma/actions/runs/41164779676) passed on `e43fb77c1e05d51838687d4574b2678218983386` in project `sanoma-513217`: GitHub OIDC → WIF → scoped provisioning account, denied impersonation of another existing account, real Google-provider key create/read/update, rotation-period update and key-deletion refusal. One provider session remained active for 660 seconds and fetched a fresh OIDC subject token after its ten-minute impersonated token expired. Trust was restricted to numeric repository/owner IDs, branch, workflow and the exact reviewed commit. This proves that provisioning path; it does not establish live CRUD for every resource type or a company runtime's identity. That run used a GitHub Actions OIDC source, which the connector no longer accepts: the identity service's issuer is now the only subject-token source, and a live run through it is still to be recorded.
141
119
 
142
120
  A later published-package workflow under [#532](https://github.com/Sanoma-AI/sanoma/issues/532) created a key ring, service account, crypto key and both IAM member types, then exposed a failure when reading an IAM member by its returned ID. The connector now derives importable public IDs while preserving native provider state. Synthetic regression coverage checks custom roles, `principal://` members, optional conditions and reads by returned ID without saved state. A successful live rerun of the full provisioning graph remains pending.
143
121
 
144
122
  The next published run passed those ID reads, then stopped while importing a grant that did not exist. A separate live read reproduced the provider's missing-binding diagnostic. The corrected unpublished driver then passed live absent-member reads and idempotent deletion for both IAM types against the existing disposable resources. A published rerun of the full provisioning graph remains pending.
145
123
 
146
- The manual `gcp-live.yml` workflow accepts project ID/number, provisioner and denied-account emails, disposable key-ring name and WIF audience as inputs. Administrators must enable billing/APIs, establish narrowly scoped federation and ring permissions, and restrict trust to the intended repository, workflow, ref and reviewed commit before running it. The denied account must exist without an impersonation grant to that federation. No service-account private key is needed. Ordinary CI skips `test/live.test.ts`; only the dedicated workflow enables it. The test creates a synthetic key, so retire all its versions after verification; KMS key/ring metadata remains. Never use a production ring. Provisioning and renewable runtime identity remain separate.
124
+ `test/live.test.ts` is run by hand, never in CI. An administrator sets `SANOMA_GCP_PROVISION_LIVE=1` and the test's own configuration: `SANOMA_GCP_LIVE_PROJECT`, `_PROJECT_NUMBER`, `_PROVISIONER`, `_AUDIENCE`, `_ISSUER` (the deployed identity service's `/identity`), `_BEARER` (an enrolled provisioning bearer), `_OTHER_ACCOUNT` (an existing account the federation must not impersonate) and `_RING` (a disposable key ring). These configure the test, not a deployment. It verifies the bearer, checks denied impersonation, creates, reads and updates a synthetic key through the real provider, and keeps one provider session reading past its ten-minute token. Retire the key's versions afterwards; KMS key and ring metadata remain. Never use a production ring.
147
125
 
148
126
  Run `pnpm vitest run connectors/gcp` and the repository's type/lint/build checks. Regenerate types with `pnpm --filter @sanoma-ai/connector-gcp generate`; update the recorded schema/pins deliberately, and never edit `resources.gen.ts` by hand. Test-map details are in [test/AGENTS.md](test/AGENTS.md).
@@ -1,16 +1,54 @@
1
- import { type AuthenticationContext } from "@sanoma-ai/workflows";
2
- /** Trusted deployment configuration, resolved inside each authorized invocation. */
1
+ import { z } from "zod";
2
+ import { type StoredAuthentication } from "sanoma/workflows";
3
+ /**
4
+ * The provisioning identity, declared in code: who the connection provisions as and where its
5
+ * Google OIDC tokens come from. None of it is secret; the bearer that unlocks the issuer is the
6
+ * connection's stored credential, entered on the connector page.
7
+ */
3
8
  export interface GcpIdentity {
9
+ /** The project the provisioning account works in, by ID. */
4
10
  project: string;
11
+ /** The same project's number: resource names Google returns use either. */
5
12
  projectNumber: string;
13
+ /** The provisioning service account the federated principal impersonates. */
6
14
  serviceAccount: string;
7
- credentialsFile?: string;
8
- /** Reads protected external-account configuration; never a workflow callback or durable result. */
9
- credentials?: () => Promise<string>;
15
+ /** The workload identity provider's full audience. */
16
+ audience: string;
17
+ /** The provisioning identity service's HTTPS `GET /identity` endpoint. */
18
+ issuer: string;
10
19
  }
11
- export type GcpIdentities = Readonly<Record<string, GcpIdentity>>;
12
- export declare function identityFor(identities: GcpIdentities, context?: AuthenticationContext): GcpIdentity;
13
- /** Explicit WIF config only: no ambient ADC fallback, service-account key or executable source. */
14
- export declare function federationCredentials(identity: GcpIdentity): Promise<Record<string, unknown>>;
20
+ /** What the connection stores: the provisioning bearer, never the identity facts. */
21
+ declare const bundle: z.ZodObject<{
22
+ bearer: z.ZodString;
23
+ }, z.core.$strip>;
24
+ /** Refuses facts that could not name one provisioning account and one HTTPS issuer. */
25
+ export declare function checkIdentity(identity: GcpIdentity): GcpIdentity;
26
+ /**
27
+ * The external-account configuration for one invocation: Google's STS, the configured
28
+ * impersonation target and the issuer as a URL source carrying the bearer. Built in memory from
29
+ * declared facts; no ambient ADC, key file or executable source can be expressed.
30
+ */
31
+ export declare function federationCredentials(identity: GcpIdentity, bearer: string): {
32
+ type: string;
33
+ audience: string;
34
+ subject_token_type: string;
35
+ token_url: string;
36
+ service_account_impersonation_url: string;
37
+ service_account_impersonation: {
38
+ token_lifetime_seconds: number;
39
+ };
40
+ credential_source: {
41
+ url: string;
42
+ headers: {
43
+ Authorization: string;
44
+ };
45
+ format: {
46
+ type: string;
47
+ subject_token_field_name: string;
48
+ };
49
+ };
50
+ };
15
51
  export declare const accountOf: (identity: GcpIdentity) => string;
16
- export declare function gcpAuthentication(identities: GcpIdentities): import("@sanoma-ai/workflows").Authentication<import("zod").ZodType<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>;
52
+ /** The `workloadIdentity` method: a stored bearer, verified by federating once as the identity. */
53
+ export declare function gcpAuthentication(identity?: GcpIdentity): StoredAuthentication<typeof bundle>;
54
+ export {};
@@ -1,66 +1,81 @@
1
- import { readFile } from "node:fs/promises";
2
1
  import { GoogleAuth } from "google-auth-library";
3
- import { AuthenticationError, defineAuthentication } from "@sanoma-ai/workflows";
4
- export function identityFor(identities, context) {
5
- const identity = context?.vendor === "gcp" ? identities[context.connectionId] : undefined;
6
- if (!identity ||
7
- !/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(identity.project) ||
8
- !/^[1-9][0-9]+$/.test(identity.projectNumber) ||
9
- !/^[a-z][a-z0-9-]+@[a-z][a-z0-9-]+\.iam\.gserviceaccount\.com$/.test(identity.serviceAccount) ||
10
- !((typeof identity.credentialsFile === "string" && identity.credentialsFile.length > 0 && !identity.credentials) ||
11
- (typeof identity.credentials === "function" && identity.credentialsFile === undefined)))
12
- throw new AuthenticationError("missing");
13
- return identity;
14
- }
15
- /** Explicit WIF config only: no ambient ADC fallback, service-account key or executable source. */
16
- export async function federationCredentials(identity) {
2
+ import { z } from "zod";
3
+ import { AuthenticationError, defineAuthentication } from "sanoma/workflows";
4
+ /** What the connection stores: the provisioning bearer, never the identity facts. */
5
+ const bundle = z.object({
6
+ bearer: z
7
+ .string()
8
+ .regex(/^[A-Za-z0-9_-]{43}$/, "A provisioning bearer is 43 base64url characters")
9
+ .describe("The provisioning bearer the identity service enrolled for this control plane: 43 base64url characters, from the enrollment that minted it"),
10
+ });
11
+ const AUDIENCE = /^\/\/iam\.googleapis\.com\/projects\/[1-9][0-9]+\/locations\/global\/workloadIdentityPools\/[a-z][a-z0-9-]+\/providers\/[a-z][a-z0-9-]+$/;
12
+ /** Refuses facts that could not name one provisioning account and one HTTPS issuer. */
13
+ export function checkIdentity(identity) {
14
+ const { project, projectNumber, serviceAccount, audience, issuer } = identity;
17
15
  try {
18
- // Refuse ambiguous sources even when called outside identityFor. Never fall back on failure.
19
- const text = identity.credentials && identity.credentialsFile === undefined
20
- ? await identity.credentials()
21
- : identity.credentialsFile && !identity.credentials
22
- ? await readFile(identity.credentialsFile, "utf8")
23
- : (() => {
24
- throw new Error();
25
- })();
26
- if (Buffer.byteLength(text) > 65_536)
27
- throw new Error();
28
- const config = JSON.parse(text);
29
- const impersonation = `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${identity.serviceAccount}:generateAccessToken`;
30
- if (config.type !== "external_account" ||
31
- config.token_url !== "https://sts.googleapis.com/v1/token" ||
32
- config.service_account_impersonation_url !== impersonation ||
33
- config.subject_token_type !== "urn:ietf:params:oauth:token-type:jwt" ||
34
- typeof config.audience !== "string" ||
35
- !config.audience.startsWith("//iam.googleapis.com/projects/") ||
36
- !config.credential_source ||
37
- config.credential_source.executable ||
38
- config.credential_source.environment_id)
16
+ const url = new URL(issuer);
17
+ if (!/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(project) ||
18
+ !/^[1-9][0-9]+$/.test(projectNumber) ||
19
+ !/^[a-z][a-z0-9-]+@[a-z][a-z0-9-]+\.iam\.gserviceaccount\.com$/.test(serviceAccount) ||
20
+ !AUDIENCE.test(audience) ||
21
+ url.protocol !== "https:" ||
22
+ url.username ||
23
+ url.password ||
24
+ url.search ||
25
+ url.hash ||
26
+ url.pathname !== "/identity")
39
27
  throw new Error();
40
- return config;
41
28
  }
42
29
  catch {
43
30
  throw new AuthenticationError("rejected");
44
31
  }
32
+ return Object.freeze({ project, projectNumber, serviceAccount, audience, issuer });
33
+ }
34
+ /**
35
+ * The external-account configuration for one invocation: Google's STS, the configured
36
+ * impersonation target and the issuer as a URL source carrying the bearer. Built in memory from
37
+ * declared facts; no ambient ADC, key file or executable source can be expressed.
38
+ */
39
+ export function federationCredentials(identity, bearer) {
40
+ return {
41
+ type: "external_account",
42
+ audience: identity.audience,
43
+ subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
44
+ token_url: "https://sts.googleapis.com/v1/token",
45
+ service_account_impersonation_url: `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${identity.serviceAccount}:generateAccessToken`,
46
+ service_account_impersonation: { token_lifetime_seconds: 600 },
47
+ credential_source: {
48
+ url: identity.issuer,
49
+ headers: { Authorization: `Bearer ${bearer}` },
50
+ format: { type: "json", subject_token_field_name: "idToken" },
51
+ },
52
+ };
45
53
  }
46
54
  export const accountOf = (identity) => `${identity.serviceAccount}/${identity.project}/${identity.projectNumber}`;
47
- export function gcpAuthentication(identities) {
55
+ /** The `workloadIdentity` method: a stored bearer, verified by federating once as the identity. */
56
+ export function gcpAuthentication(identity) {
48
57
  return defineAuthentication({
49
- kind: "workload-identity",
50
- async verify(context) {
51
- const identity = identityFor(identities, context);
52
- const credentials = await federationCredentials(identity);
58
+ kind: "api-key",
59
+ version: 1,
60
+ schema: bundle,
61
+ storage: { writable: false, conditionalWrites: false, maxBytes: 1024 },
62
+ async verify({ bearer }) {
63
+ if (!identity)
64
+ throw new AuthenticationError("missing");
53
65
  try {
54
- // Successful impersonation proves the source may mint for this exact configured account.
55
- // The provider independently refreshes the same source during its operation session.
56
- const auth = new GoogleAuth({ credentials, scopes: ["https://www.googleapis.com/auth/cloud-platform"] });
66
+ // One OIDC token from the issuer, exchanged at STS and used to impersonate the configured
67
+ // account: success proves the bearer is enrolled and trusted for exactly that account.
68
+ const auth = new GoogleAuth({
69
+ credentials: federationCredentials(identity, bearer),
70
+ scopes: ["https://www.googleapis.com/auth/cloud-platform"],
71
+ });
57
72
  if (!(await auth.getAccessToken()))
58
73
  throw new Error();
59
- return { account: accountOf(identity), scopes: [] };
60
74
  }
61
75
  catch {
62
76
  throw new AuthenticationError("unavailable");
63
77
  }
78
+ return { account: accountOf(identity), scopes: [] };
64
79
  },
65
80
  });
66
81
  }
@@ -1 +1 @@
1
- {"version":3,"file":"authentication.js","sourceRoot":"","sources":["../src/authentication.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAA8B,MAAM,sBAAsB,CAAC;AAa7G,MAAM,UAAU,WAAW,CAAC,UAAyB,EAAE,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