@intentius/chant-lexicon-gcp 0.124.34 → 0.124.35

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gcp-iam.d.ts","sourceRoot":"","sources":["../../../src/op/activities/gcp-iam.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAW,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAExE,iDAAiD;AACjD,MAAM,WAAW,mBAAmB;IAClC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACvF,SAAS,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1E,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,UAAU,OAAO;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,SAAS,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC3E;AAED,UAAU,MAAM;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAC;CACtB;AAED,mDAAmD;AACnD,MAAM,WAAW,SAAS;IACxB,8CAA8C;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK;QAAE,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;IAC/E,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK;QAAE,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,OAAO,CAAA;KAAE,CAAC;CAC/F;AAED,gHAAgH;AAChH,eAAO,MAAM,gBAAgB,+BAA+B,CAAC;AAqB7D;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,IAAI,EAAE,mBAAmB,EACzB,OAAO,EAAE,MAAM,EACf,QAAQ,GAAE,SAAS,WAAW,EAAO,EACrC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,SAAS,GAAG,SAAS,CAgDvB;AAYD,uFAAuF;AACvF,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAElF;AAED,8FAA8F;AAC9F,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,mBAAmB,GAAG,MAAM,CAY5E;AAED,kGAAkG;AAClG,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,mBAAmB,GAAG,MAAM,CAS/E;AAkED,eAAO,MAAM,qBAAqB,EAAE,cA8CnC,CAAC"}
@@ -0,0 +1,215 @@
1
+ /** The default host this mapper reports; a target's own host replaces it when there is no endpoint override. */
2
+ export const IAM_DEFAULT_HOST = "https://iam.googleapis.com";
3
+ const enc = encodeURIComponent;
4
+ function region(env = process.env) {
5
+ return env.GCP_REGION || "us-central1";
6
+ }
7
+ /** A `:getIamPolicy` / `:setIamPolicy` pair on a REST resource path (the Google API convention). */
8
+ function verbTarget(host, version, path, getMethod) {
9
+ return {
10
+ host,
11
+ path,
12
+ get: (base) => getMethod === "GET"
13
+ ? { method: "GET", url: `${base}/${version}/${path}:getIamPolicy?options.requestedPolicyVersion=3` }
14
+ : { method: "POST", url: `${base}/${version}/${path}:getIamPolicy`, body: { options: { requestedPolicyVersion: 3 } } },
15
+ set: (base, policy) => ({ method: "POST", url: `${base}/${version}/${path}:setIamPolicy`, body: { policy } }),
16
+ };
17
+ }
18
+ /**
19
+ * Resolve `resourceRef` to the target's policy endpoints, or undefined for a
20
+ * target chant cannot reach. `manifest` is the rest of the applied manifest, so
21
+ * a RunService named by `name` takes its region from its own spec. Pure.
22
+ */
23
+ export function iamTarget(spec, project, manifest = [], env = process.env) {
24
+ const ref = spec.resourceRef ?? {};
25
+ const external = typeof ref.external === "string" && ref.external !== "" ? ref.external : undefined;
26
+ const name = typeof ref.name === "string" && ref.name !== "" ? ref.name : undefined;
27
+ switch (ref.kind) {
28
+ case "Project": {
29
+ const id = external ? external.replace(/^projects\//, "") : (name ?? project);
30
+ return verbTarget("https://cloudresourcemanager.googleapis.com", "v1", `projects/${enc(id)}`, "POST");
31
+ }
32
+ case "RunService": {
33
+ if (external)
34
+ return verbTarget("https://run.googleapis.com", "v2", external, "GET");
35
+ if (!name)
36
+ return undefined;
37
+ const declared = manifest.find((r) => r.kind === "RunService" && r.metadata?.name === name);
38
+ const location = declared?.spec?.location;
39
+ const loc = typeof location === "string" ? location : (spec.location ?? region(env));
40
+ return verbTarget("https://run.googleapis.com", "v2", `projects/${enc(project)}/locations/${enc(loc)}/services/${enc(name)}`, "GET");
41
+ }
42
+ case "IAMServiceAccount": {
43
+ if (external?.startsWith("projects/"))
44
+ return verbTarget(IAM_DEFAULT_HOST, "v1", external, "POST");
45
+ const email = external ?? (name ? `${name}@${project}.iam.gserviceaccount.com` : undefined);
46
+ if (!email)
47
+ return undefined;
48
+ return verbTarget(IAM_DEFAULT_HOST, "v1", `projects/${enc(project)}/serviceAccounts/${email}`, "POST");
49
+ }
50
+ case "PubSubTopic":
51
+ case "PubSubSubscription": {
52
+ const collection = ref.kind === "PubSubTopic" ? "topics" : "subscriptions";
53
+ const path = external ?? (name ? `projects/${enc(project)}/${collection}/${enc(name)}` : undefined);
54
+ return path ? verbTarget("https://pubsub.googleapis.com", "v1", path, "GET") : undefined;
55
+ }
56
+ case "SecretManagerSecret": {
57
+ const path = external ?? (name ? `projects/${enc(project)}/secrets/${enc(name)}` : undefined);
58
+ return path ? verbTarget("https://secretmanager.googleapis.com", "v1", path, "GET") : undefined;
59
+ }
60
+ case "StorageBucket": {
61
+ const bucket = external ? external.replace(/^(gs:\/\/|projects\/_\/buckets\/)/, "") : name;
62
+ if (!bucket)
63
+ return undefined;
64
+ // GCS has its own IAM shape: GET and PUT on `b/<bucket>/iam`, with the policy as the body.
65
+ const url = (base) => `${base}/storage/v1/b/${enc(bucket)}/iam`;
66
+ return {
67
+ host: "https://storage.googleapis.com",
68
+ path: `b/${bucket}`,
69
+ get: (base) => ({ method: "GET", url: `${url(base)}?optionsRequestedPolicyVersion=3` }),
70
+ set: (base, policy) => ({ method: "PUT", url: url(base), body: policy }),
71
+ };
72
+ }
73
+ default:
74
+ return undefined;
75
+ }
76
+ }
77
+ function sameCondition(a, b) {
78
+ if (!a && !b)
79
+ return true;
80
+ if (!a || !b)
81
+ return false;
82
+ return (a.expression ?? "") === (b.expression ?? "") && (a.title ?? "") === (b.title ?? "");
83
+ }
84
+ function findBinding(policy, spec) {
85
+ return policy.bindings?.find((b) => b.role === spec.role && sameCondition(b.condition, spec.condition));
86
+ }
87
+ /** True when the policy grants the spec's member in its role (and condition). Pure. */
88
+ export function policyHasMember(policy, spec) {
89
+ return findBinding(policy, spec)?.members?.includes(spec.member ?? "") ?? false;
90
+ }
91
+ /** The policy with the spec's member added to its binding, every other binding kept. Pure. */
92
+ export function withMember(policy, spec) {
93
+ const member = spec.member;
94
+ const bindings = (policy.bindings ?? []).map((b) => ({ ...b, members: [...(b.members ?? [])] }));
95
+ const existing = bindings.find((b) => b.role === spec.role && sameCondition(b.condition, spec.condition));
96
+ if (existing) {
97
+ if (!existing.members.includes(member))
98
+ existing.members.push(member);
99
+ }
100
+ else {
101
+ bindings.push({ role: spec.role, members: [member], ...(spec.condition ? { condition: spec.condition } : {}) });
102
+ }
103
+ // A conditional binding needs policy version 3; otherwise keep what was read.
104
+ const version = spec.condition || bindings.some((b) => b.condition) ? 3 : policy.version;
105
+ return { ...policy, bindings, ...(version !== undefined ? { version } : {}) };
106
+ }
107
+ /** The policy with the spec's member removed; a binding left with no members is dropped. Pure. */
108
+ export function withoutMember(policy, spec) {
109
+ const bindings = (policy.bindings ?? [])
110
+ .map((b) => b.role === spec.role && sameCondition(b.condition, spec.condition)
111
+ ? { ...b, members: (b.members ?? []).filter((m) => m !== spec.member) }
112
+ : b)
113
+ .filter((b) => (b.members ?? []).length > 0);
114
+ return { ...policy, bindings };
115
+ }
116
+ function specOf(resource) {
117
+ const spec = (resource.spec ?? {});
118
+ const name = resource.metadata?.name ?? "?";
119
+ if (!spec.member)
120
+ throw new Error(`IAMPolicyMember ${name} has no spec.member`);
121
+ if (!spec.role)
122
+ throw new Error(`IAMPolicyMember ${name} has no spec.role`);
123
+ return spec;
124
+ }
125
+ function targetOf(resource, ctx, env) {
126
+ const target = iamTarget(specOf(resource), ctx.project, ctx.manifest, env);
127
+ if (!target) {
128
+ const ref = resource.spec?.resourceRef;
129
+ throw new Error(`IAMPolicyMember ${resource.metadata?.name ?? "?"}: no IAM policy endpoint for resourceRef kind ${ref?.kind ?? "(none)"}`);
130
+ }
131
+ // No endpoint override: each target's own service host. An override (floci-gcp) serves every service.
132
+ const base = ctx.base === IAM_DEFAULT_HOST ? target.host : ctx.base;
133
+ return { target, base };
134
+ }
135
+ async function readPolicy(target, base, http, signal) {
136
+ const req = target.get(base);
137
+ const res = await http(req.method, req.url, req.body, signal);
138
+ if (res.status >= 300)
139
+ return res;
140
+ let policy;
141
+ try {
142
+ policy = JSON.parse(res.text);
143
+ }
144
+ catch {
145
+ policy = {};
146
+ }
147
+ return { ...res, policy };
148
+ }
149
+ /** How many times a write that loses an `etag` race (409, or 412 on GCS) is retried. */
150
+ const ETAG_ATTEMPTS = 3;
151
+ async function writeWith(resource, ctx, http, signal, change) {
152
+ const spec = specOf(resource);
153
+ const { target, base } = targetOf(resource, ctx);
154
+ const name = resource.metadata?.name ?? "?";
155
+ for (let attempt = 1;; attempt++) {
156
+ const read = await readPolicy(target, base, http, signal);
157
+ if (!read.policy)
158
+ throw new Error(`IAMPolicyMember ${name}: reading the policy of ${target.path} failed (${read.status}): ${read.text}`);
159
+ const next = change(read.policy, spec);
160
+ if (!next)
161
+ return false;
162
+ const req = target.set(base, next);
163
+ const res = await http(req.method, req.url, req.body, signal);
164
+ if (res.status < 300)
165
+ return true;
166
+ if ((res.status === 409 || res.status === 412) && attempt < ETAG_ATTEMPTS)
167
+ continue;
168
+ throw new Error(`IAMPolicyMember ${name}: writing the policy of ${target.path} failed (${res.status}): ${res.text}`);
169
+ }
170
+ }
171
+ export const iamPolicyMemberMapper = {
172
+ kind: "IAMPolicyMember",
173
+ defaultHost: IAM_DEFAULT_HOST,
174
+ accepts(resource, ctx) {
175
+ return iamTarget((resource.spec ?? {}), ctx.project, ctx.manifest) !== undefined;
176
+ },
177
+ plan(resource, ctx) {
178
+ // Only the read is a single URL here; apply and delete go through `custom`.
179
+ const { target, base } = targetOf(resource, ctx);
180
+ const get = target.get(base);
181
+ return { getUrl: get.url, create: { method: "POST", url: get.url, body: get.body ?? {} } };
182
+ },
183
+ custom: {
184
+ async apply(resource, ctx, http, signal) {
185
+ const created = await writeWith(resource, ctx, http, signal, (policy, spec) => policyHasMember(policy, spec) ? undefined : withMember(policy, spec));
186
+ return { created, updated: false };
187
+ },
188
+ async delete(resource, ctx, http, signal) {
189
+ return writeWith(resource, ctx, http, signal, (policy, spec) => policyHasMember(policy, spec) ? withoutMember(policy, spec) : undefined);
190
+ },
191
+ async read(resource, ctx, http, signal) {
192
+ const spec = specOf(resource);
193
+ const { target, base } = targetOf(resource, ctx);
194
+ const read = await readPolicy(target, base, http, signal);
195
+ if (!read.policy)
196
+ return read;
197
+ // The binding member is the resource: absent from the policy reads as absent.
198
+ if (!policyHasMember(read.policy, spec))
199
+ return { status: 404, text: `${spec.member} has no ${spec.role} on ${target.path}` };
200
+ const binding = findBinding(read.policy, spec);
201
+ return {
202
+ status: 200,
203
+ // `resourceRef` is the declared one: the policy read is that target's, so the binding is on it.
204
+ text: JSON.stringify({
205
+ member: spec.member,
206
+ role: spec.role,
207
+ resource: target.path,
208
+ ...(spec.resourceRef ? { resourceRef: spec.resourceRef } : {}),
209
+ ...(binding?.condition ? { condition: binding.condition } : {}),
210
+ ...(read.policy.etag ? { etag: read.policy.etag } : {}),
211
+ }),
212
+ };
213
+ },
214
+ },
215
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-gcp",
3
- "version": "0.124.34",
3
+ "version": "0.124.35",
4
4
  "description": "Google Cloud lexicon for chant — declarative IaC in TypeScript",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -76,6 +76,6 @@
76
76
  "typescript": "^5.9.3"
77
77
  },
78
78
  "peerDependencies": {
79
- "@intentius/chant": "^0.124.34"
79
+ "@intentius/chant": "^0.124.35"
80
80
  }
81
81
  }
@@ -22,7 +22,11 @@
22
22
  *
23
23
  * Coverage is exactly the applier's dispatch table (`MAPPERS`) — StorageBucket,
24
24
  * PubSubTopic, PubSubSubscription, SecretManagerSecret, IAMServiceAccount,
25
- * RunService. The kubectl path could fetch any CNRM kind the cluster knew
25
+ * RunService, IAMPolicyMember and the Cloud Run load balancer kinds
26
+ * (ComputeAddress, ComputeRegionNetworkEndpointGroup, ComputeBackendService,
27
+ * ComputeURLMap, ComputeTargetHTTPProxy, ComputeForwardingRule; #4233). An
28
+ * IAMPolicyMember is read through its target's policy and is present when the
29
+ * policy grants its member the role. The kubectl path could fetch any CNRM kind the cluster knew
26
30
  * about, so this is narrower on paper. It is not narrower in practice for
27
31
  * anything chant can act on: a kind with no mapper cannot be applied either, so
28
32
  * observing it produced a live tree nothing could ever reconcile against.
@@ -44,11 +48,14 @@ export interface GcpReadClientOptions {
44
48
  http?: GcpReadHttp;
45
49
  }
46
50
 
47
- /** Injectable HTTP client — mirrors the applier's `GcpHttp`. */
48
- export type GcpReadHttp = (method: string, url: string) => Promise<{ status: number; text: string }>;
51
+ /** Injectable HTTP client — mirrors the applier's `GcpHttp`. A body is sent only for a POST read (`:getIamPolicy`). */
52
+ export type GcpReadHttp = (method: string, url: string, body?: unknown) => Promise<{ status: number; text: string }>;
49
53
 
50
- const defaultHttp: GcpReadHttp = async (method, url) => {
51
- const res = await fetch(url, { method });
54
+ const defaultHttp: GcpReadHttp = async (method, url, body) => {
55
+ const res = await fetch(url, {
56
+ method,
57
+ ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
58
+ });
52
59
  return { status: res.status, text: await res.text() };
53
60
  };
54
61
 
@@ -100,21 +107,33 @@ export async function getResource(
100
107
  spec: (declared?.spec as Record<string, unknown> | undefined) ?? declared ?? {},
101
108
  };
102
109
 
103
- let getUrl: string;
104
- try {
105
- getUrl = mapper.plan(resource, { base, project: client.project }).getUrl;
106
- } catch (err) {
107
- // A mapper that cannot plan from the declared spec cannot produce a URL, so
108
- // there is nothing to read — a hole, never an absence.
109
- throw new GcpReadError(`could not build a read URL for ${kind}/${name}: ${err instanceof Error ? err.message : String(err)}`);
110
+ const ctx = { base, project: client.project };
111
+ if (mapper.accepts && !mapper.accepts(resource, ctx)) {
112
+ throw new GcpReadError(`no REST read for ${kind}/${name}: its target has no endpoint chant can read`);
110
113
  }
111
114
 
112
115
  const http = client.http ?? defaultHttp;
113
116
  let res: { status: number; text: string };
114
- try {
115
- res = await http("GET", getUrl);
116
- } catch (err) {
117
- throw new GcpReadError(err instanceof Error ? err.message : String(err));
117
+ if (mapper.custom) {
118
+ try {
119
+ res = await mapper.custom.read(resource, ctx, (method, url, body) => http(method, url, body));
120
+ } catch (err) {
121
+ throw new GcpReadError(`could not read ${kind}/${name}: ${err instanceof Error ? err.message : String(err)}`);
122
+ }
123
+ } else {
124
+ let getUrl: string;
125
+ try {
126
+ getUrl = mapper.plan(resource, ctx).getUrl;
127
+ } catch (err) {
128
+ // A mapper that cannot plan from the declared spec cannot produce a URL, so
129
+ // there is nothing to read — a hole, never an absence.
130
+ throw new GcpReadError(`could not build a read URL for ${kind}/${name}: ${err instanceof Error ? err.message : String(err)}`);
131
+ }
132
+ try {
133
+ res = await http("GET", getUrl);
134
+ } catch (err) {
135
+ throw new GcpReadError(err instanceof Error ? err.message : String(err));
136
+ }
118
137
  }
119
138
 
120
139
  if (res.status === 404) throw new GcpReadError(`${kind}/${name} not found`, 404);
@@ -34,6 +34,8 @@ export interface CloudRunServiceProps {
34
34
  publicAccess?: boolean;
35
35
  /** Environment variables. */
36
36
  env?: Array<{ name: string; value: string }>;
37
+ /** Service account the service runs as: an email, or the account id of an IAMServiceAccount in the project. */
38
+ serviceAccount?: string;
37
39
  /** Additional labels. */
38
40
  labels?: Record<string, string>;
39
41
  /** Namespace for all resources. */
@@ -75,6 +77,7 @@ export const CloudRunServiceComposite = Composite((props: CloudRunServiceProps)
75
77
  maxInstanceCount = 100,
76
78
  publicAccess = false,
77
79
  env,
80
+ serviceAccount,
78
81
  labels: extraLabels = {},
79
82
  namespace,
80
83
  defaults: defs,
@@ -112,6 +115,9 @@ export const CloudRunServiceComposite = Composite((props: CloudRunServiceProps)
112
115
  maxInstanceCount,
113
116
  },
114
117
  containers,
118
+ ...(serviceAccount && {
119
+ serviceAccountRef: serviceAccount.includes("@") ? { external: serviceAccount } : { name: serviceAccount },
120
+ }),
115
121
  },
116
122
  }, defs?.service));
117
123
 
@@ -83,6 +83,13 @@ describe("CloudRunServiceComposite", () => {
83
83
  expect(result.service).toBeDefined();
84
84
  });
85
85
 
86
+ test("serviceAccount sets serviceAccountRef: an account id by name, an email as external (#4240)", () => {
87
+ const byName = CloudRunServiceComposite({ name: "api", image: "i", serviceAccount: "run-sa" });
88
+ expect((p(byName.service).template as Record<string, unknown>).serviceAccountRef).toEqual({ name: "run-sa" });
89
+ const byEmail = CloudRunServiceComposite({ name: "api", image: "i", serviceAccount: "x@o.iam.gserviceaccount.com" });
90
+ expect((p(byEmail.service).template as Record<string, unknown>).serviceAccountRef).toEqual({ external: "x@o.iam.gserviceaccount.com" });
91
+ });
92
+
86
93
  test("sets projectRef and location, which the RunService CRD requires", () => {
87
94
  const result = CloudRunServiceComposite({
88
95
  name: "api",
@@ -124,6 +124,21 @@ describe("toCnrmTree — each REST shape in the declared vocabulary (#1210)", ()
124
124
  expect(tree).toEqual({ metadata: { name: "t" }, messageRetentionDuration: "86400s" });
125
125
  });
126
126
 
127
+ test("run service: the v2 serviceAccount email maps back to the declared serviceAccountRef (#4240)", () => {
128
+ const same = toCnrmTree(
129
+ "RunService",
130
+ { name: "projects/my-project/locations/us-central1/services/web", template: { serviceAccount: "run-sa@my-project.iam.gserviceaccount.com" } },
131
+ ctx,
132
+ ) as { template: Record<string, unknown> };
133
+ expect(same.template).toEqual({ serviceAccountRef: { name: "run-sa" } });
134
+ const other = toCnrmTree(
135
+ "RunService",
136
+ { name: "projects/my-project/locations/us-central1/services/web", template: { serviceAccount: "x@other.iam.gserviceaccount.com" } },
137
+ ctx,
138
+ ) as { template: Record<string, unknown> };
139
+ expect(other.template).toEqual({ serviceAccountRef: { external: "x@other.iam.gserviceaccount.com" } });
140
+ });
141
+
127
142
  test("bucket: GCS's iamConfiguration and lifecycle map onto the CNRM field names", () => {
128
143
  const tree = toCnrmTree(
129
144
  "StorageBucket",
@@ -235,7 +250,7 @@ describe("observeResourcesDeepGcp — over REST (#1209)", () => {
235
250
  });
236
251
 
237
252
  test("a kind the applier cannot write is unsupported-kind, and is never queried", async () => {
238
- const out = await observe(entities([["e", "GCP::Compute::Address", { metadata: { name: "a" } }]]));
253
+ const out = await observe(entities([["e", "GCP::Compute::Network", { metadata: { name: "n" } }]]));
239
254
  expect(out.unobserved?.e?.reason).toBe("unsupported-kind");
240
255
  expect(fetchMock).not.toHaveBeenCalled();
241
256
  });
@@ -182,9 +182,133 @@ const CNRM_REFINERS: Record<string, (tree: CnrmTree, ctx: RefineContext) => void
182
182
  // name. The declared side writes it as `location`.
183
183
  const m = ctx.restName ? /\/locations\/([^/]+)\//.exec(ctx.restName) : null;
184
184
  if (m) tree.location = m[1];
185
+ // #4240: v2 returns the account as an email; the declared side writes a
186
+ // `serviceAccountRef`, `name` for an account in the project.
187
+ const template = tree.template as Record<string, unknown> | undefined;
188
+ if (template && typeof template.serviceAccount === "string") {
189
+ const email = template.serviceAccount;
190
+ const suffix = `@${ctx.project}.iam.gserviceaccount.com`;
191
+ template.serviceAccountRef = email.endsWith(suffix) ? { name: email.slice(0, -suffix.length) } : { external: email };
192
+ delete template.serviceAccount;
193
+ }
194
+ },
195
+ // #4233: the inverse of gcp-compute.ts's body builders. Compute returns refs
196
+ // as full URLs and a region as a URL; CNRM writes `*Ref: { name }` and a
197
+ // bare `location` (`"global"` when the resource has no region).
198
+ IAMPolicyMember(tree) {
199
+ delete tree.etag;
200
+ delete tree.resource;
201
+ },
202
+ ComputeAddress(tree) {
203
+ computeLocation(tree);
204
+ },
205
+ ComputeRegionNetworkEndpointGroup(tree) {
206
+ if (typeof tree.region === "string") tree.region = lastSegment(tree.region);
207
+ const cloudRun = tree.cloudRun as Record<string, unknown> | undefined;
208
+ if (cloudRun && typeof cloudRun.service === "string") {
209
+ cloudRun.serviceRef = { name: cloudRun.service };
210
+ delete cloudRun.service;
211
+ }
212
+ },
213
+ ComputeBackendService(tree) {
214
+ computeLocation(tree);
215
+ if (tree.enableCDN !== undefined) {
216
+ tree.enableCdn = tree.enableCDN;
217
+ delete tree.enableCDN;
218
+ }
219
+ const draining = tree.connectionDraining as { drainingTimeoutSec?: unknown } | undefined;
220
+ if (draining) {
221
+ if (draining.drainingTimeoutSec !== undefined) tree.connectionDrainingTimeoutSec = draining.drainingTimeoutSec;
222
+ delete tree.connectionDraining;
223
+ }
224
+ if (Array.isArray(tree.backends)) {
225
+ tree.backend = (tree.backends as Array<Record<string, unknown>>).map((b) => {
226
+ const { group, ...rest } = b;
227
+ return { ...rest, ...(typeof group === "string" ? { group: refOf(group) } : {}) };
228
+ });
229
+ delete tree.backends;
230
+ }
231
+ if (Array.isArray(tree.healthChecks)) {
232
+ tree.healthChecks = (tree.healthChecks as unknown[]).map((h) => (typeof h === "string" ? { healthCheckRef: { name: lastSegment(h) } } : h));
233
+ }
234
+ if (typeof tree.securityPolicy === "string") {
235
+ tree.securityPolicyRef = { name: lastSegment(tree.securityPolicy) };
236
+ delete tree.securityPolicy;
237
+ }
238
+ },
239
+ ComputeURLMap(tree) {
240
+ computeLocation(tree);
241
+ if (typeof tree.defaultService === "string") tree.defaultService = refOf(tree.defaultService);
242
+ if (Array.isArray(tree.hostRules)) {
243
+ tree.hostRule = tree.hostRules;
244
+ delete tree.hostRules;
245
+ }
246
+ if (Array.isArray(tree.pathMatchers)) {
247
+ tree.pathMatcher = (tree.pathMatchers as Array<Record<string, unknown>>).map((m) => {
248
+ const { defaultService, pathRules, ...rest } = m;
249
+ return {
250
+ ...rest,
251
+ ...(typeof defaultService === "string" ? { defaultService: refOf(defaultService) } : {}),
252
+ ...(Array.isArray(pathRules)
253
+ ? {
254
+ pathRule: (pathRules as Array<Record<string, unknown>>).map(({ service, ...r }) => ({
255
+ ...r,
256
+ ...(typeof service === "string" ? { service: refOf(service) } : {}),
257
+ })),
258
+ }
259
+ : {}),
260
+ };
261
+ });
262
+ delete tree.pathMatchers;
263
+ }
264
+ },
265
+ ComputeTargetHTTPProxy(tree) {
266
+ computeLocation(tree);
267
+ if (typeof tree.urlMap === "string") {
268
+ tree.urlMapRef = { name: lastSegment(tree.urlMap) };
269
+ delete tree.urlMap;
270
+ }
185
271
  },
272
+ ComputeForwardingRule(tree) {
273
+ computeLocation(tree);
274
+ if (tree.IPProtocol !== undefined) {
275
+ tree.ipProtocol = tree.IPProtocol;
276
+ delete tree.IPProtocol;
277
+ }
278
+ if (typeof tree.target === "string") tree.target = refOf(tree.target);
279
+ if (typeof tree.backendService === "string") {
280
+ tree.backendServiceRef = { name: lastSegment(tree.backendService) };
281
+ delete tree.backendService;
282
+ }
283
+ },
284
+ };
285
+
286
+ function lastSegment(url: string): string {
287
+ return url.slice(url.lastIndexOf("/") + 1);
288
+ }
289
+
290
+ /** Compute's `region` URL as CNRM's `location`; no region means a global resource. */
291
+ function computeLocation(tree: CnrmTree): void {
292
+ tree.location = typeof tree.region === "string" ? lastSegment(tree.region) : "global";
293
+ delete tree.region;
294
+ }
295
+
296
+ /** The `*Ref` a compute URL names, by its collection (`.../backendServices/web` -> `{ backendServiceRef: { name: "web" } }`). */
297
+ const REF_KEY_BY_COLLECTION: Record<string, string> = {
298
+ networkEndpointGroups: "networkEndpointGroupRef",
299
+ backendServices: "backendServiceRef",
300
+ backendBuckets: "backendBucketRef",
301
+ targetHttpProxies: "targetHTTPProxyRef",
302
+ targetHttpsProxies: "targetHTTPSProxyRef",
303
+ instanceGroups: "instanceGroupRef",
186
304
  };
187
305
 
306
+ function refOf(url: string): unknown {
307
+ const parts = url.split("/");
308
+ const key = REF_KEY_BY_COLLECTION[parts[parts.length - 2] ?? ""];
309
+ return key ? { [key]: { name: parts[parts.length - 1] } } : url;
310
+ }
311
+
188
312
  /**
189
313
  * A REST payload as a CNRM-shaped property tree, in the declared side's
190
314
  * vocabulary. The generic reshape runs first, then the full resource path is
@@ -80,7 +80,7 @@ describe("gcp describeResources — direct REST (#1209)", () => {
80
80
 
81
81
  test("a kind the applier has no mapper for is unsupported-kind, not absent", async () => {
82
82
  const out = await read(
83
- makeEntities([{ name: "e", entityType: "GCP::Compute::Address", props: { metadata: { name: "addr" } } }]),
83
+ makeEntities([{ name: "e", entityType: "GCP::Compute::Network", props: { metadata: { name: "net" } } }]),
84
84
  );
85
85
  expect(out.unobserved?.e?.reason).toBe("unsupported-kind");
86
86
  expect(fetchMock).not.toHaveBeenCalled();
@@ -5,6 +5,7 @@ import {
5
5
  bucketInsertBody,
6
6
  pubSubTopicBody,
7
7
  cloudRunServiceBody,
8
+ serviceAccountEmail,
8
9
  resolveGcpProject,
9
10
  resolveGcpEndpoint,
10
11
  applyResource,
@@ -118,6 +119,13 @@ describe("mappers build correct plans (#706)", () => {
118
119
 
119
120
  test("registry keys match each mapper's kind", () => {
120
121
  expect(Object.keys(MAPPERS).sort()).toEqual([
122
+ "ComputeAddress",
123
+ "ComputeBackendService",
124
+ "ComputeForwardingRule",
125
+ "ComputeRegionNetworkEndpointGroup",
126
+ "ComputeTargetHTTPProxy",
127
+ "ComputeURLMap",
128
+ "IAMPolicyMember",
121
129
  "IAMServiceAccount",
122
130
  "PubSubSubscription",
123
131
  "PubSubTopic",
@@ -136,6 +144,35 @@ describe("Cloud Run mapper + LRO (#706)", () => {
136
144
  });
137
145
  });
138
146
 
147
+ test("cloudRunServiceBody sends serviceAccountRef as template.serviceAccount (#4240)", () => {
148
+ const withRef = (ref: Record<string, string>) => ({
149
+ ...RUN_SERVICE,
150
+ spec: { ...(RUN_SERVICE.spec as object), template: { containers: [{ image: "gcr.io/x/hello" }], serviceAccountRef: ref } },
151
+ });
152
+ expect(cloudRunServiceBody(withRef({ name: "run-sa" }), "p")).toEqual({
153
+ template: { containers: [{ image: "gcr.io/x/hello" }], serviceAccount: "run-sa@p.iam.gserviceaccount.com" },
154
+ });
155
+ expect(cloudRunServiceBody(withRef({ external: "x@other.iam.gserviceaccount.com" }), "p")).toEqual({
156
+ template: { containers: [{ image: "gcr.io/x/hello" }], serviceAccount: "x@other.iam.gserviceaccount.com" },
157
+ });
158
+ });
159
+
160
+ test("serviceAccountEmail: external as given or from a path, name in the project", () => {
161
+ expect(serviceAccountEmail({ external: "projects/o/serviceAccounts/x@o.iam.gserviceaccount.com" })).toBe("x@o.iam.gserviceaccount.com");
162
+ expect(serviceAccountEmail({ name: "run-sa" }, "p")).toBe("run-sa@p.iam.gserviceaccount.com");
163
+ expect(serviceAccountEmail(undefined, "p")).toBeUndefined();
164
+ expect(() => serviceAccountEmail({ name: "run-sa" })).toThrow(/needs a project/);
165
+ });
166
+
167
+ test("RunService plan sends the service account email on create and update", () => {
168
+ const resource = {
169
+ ...RUN_SERVICE,
170
+ spec: { ...(RUN_SERVICE.spec as object), template: { containers: [{ image: "i" }], serviceAccountRef: { name: "run-sa" } } },
171
+ };
172
+ const plan = cloudRunServiceMapper.plan(resource, { base: "http://x", project: "p" });
173
+ expect((plan.create.body as { template: { serviceAccount: string } }).template.serviceAccount).toBe("run-sa@p.iam.gserviceaccount.com");
174
+ });
175
+
139
176
  test("RunService plan → POST v2 services?serviceId, async operation present", () => {
140
177
  const plan = cloudRunServiceMapper.plan(RUN_SERVICE, { base: "http://x", project: "p" });
141
178
  expect(plan.getUrl).toBe("http://x/v2/projects/p/locations/us-central1/services/hello-svc");