@stigmer/server 3.14.1 → 3.15.0

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.
Files changed (116) hide show
  1. package/dist/boot/compose.d.ts +8 -1
  2. package/dist/boot/compose.d.ts.map +1 -1
  3. package/dist/boot/compose.js +98 -12
  4. package/dist/boot/compose.js.map +1 -1
  5. package/dist/domain/apikey/verifier.d.ts +8 -1
  6. package/dist/domain/apikey/verifier.d.ts.map +1 -1
  7. package/dist/domain/apikey/verifier.js +14 -2
  8. package/dist/domain/apikey/verifier.js.map +1 -1
  9. package/dist/domain/identityaccount/constants.d.ts +66 -0
  10. package/dist/domain/identityaccount/constants.d.ts.map +1 -0
  11. package/dist/domain/identityaccount/constants.js +153 -0
  12. package/dist/domain/identityaccount/constants.js.map +1 -0
  13. package/dist/domain/identityaccount/controller.d.ts +34 -0
  14. package/dist/domain/identityaccount/controller.d.ts.map +1 -0
  15. package/dist/domain/identityaccount/controller.js +342 -0
  16. package/dist/domain/identityaccount/controller.js.map +1 -0
  17. package/dist/domain/identityaccount/operator.d.ts +14 -0
  18. package/dist/domain/identityaccount/operator.d.ts.map +1 -0
  19. package/dist/domain/identityaccount/operator.js +67 -0
  20. package/dist/domain/identityaccount/operator.js.map +1 -0
  21. package/dist/domain/identityaccount/provisioning.d.ts +52 -0
  22. package/dist/domain/identityaccount/provisioning.d.ts.map +1 -0
  23. package/dist/domain/identityaccount/provisioning.js +114 -0
  24. package/dist/domain/identityaccount/provisioning.js.map +1 -0
  25. package/dist/domain/identityaccount/resolve.d.ts +36 -0
  26. package/dist/domain/identityaccount/resolve.d.ts.map +1 -0
  27. package/dist/domain/identityaccount/resolve.js +12 -0
  28. package/dist/domain/identityaccount/resolve.js.map +1 -0
  29. package/dist/domain/identityaccount/resource-store.d.ts +4 -0
  30. package/dist/domain/identityaccount/resource-store.d.ts.map +1 -0
  31. package/dist/domain/identityaccount/resource-store.js +131 -0
  32. package/dist/domain/identityaccount/resource-store.js.map +1 -0
  33. package/dist/domain/identityaccount/steps.d.ts +79 -0
  34. package/dist/domain/identityaccount/steps.d.ts.map +1 -0
  35. package/dist/domain/identityaccount/steps.js +291 -0
  36. package/dist/domain/identityaccount/steps.js.map +1 -0
  37. package/dist/domain/identityaccount/store-contract.d.ts +22 -0
  38. package/dist/domain/identityaccount/store-contract.d.ts.map +1 -0
  39. package/dist/domain/identityaccount/store-contract.js +307 -0
  40. package/dist/domain/identityaccount/store-contract.js.map +1 -0
  41. package/dist/domain/identityaccount/store.d.ts +66 -0
  42. package/dist/domain/identityaccount/store.d.ts.map +1 -0
  43. package/dist/domain/identityaccount/store.js +13 -0
  44. package/dist/domain/identityaccount/store.js.map +1 -0
  45. package/dist/extensions/drivers.d.ts +26 -0
  46. package/dist/extensions/drivers.d.ts.map +1 -1
  47. package/dist/extensions/gate-slots.d.ts +16 -1
  48. package/dist/extensions/gate-slots.d.ts.map +1 -1
  49. package/dist/extensions/gate-slots.js +1 -0
  50. package/dist/extensions/gate-slots.js.map +1 -1
  51. package/dist/extensions/identity-federation.d.ts +36 -0
  52. package/dist/extensions/identity-federation.d.ts.map +1 -0
  53. package/dist/extensions/identity-federation.js +2 -0
  54. package/dist/extensions/identity-federation.js.map +1 -0
  55. package/dist/extensions/registry.d.ts +18 -1
  56. package/dist/extensions/registry.d.ts.map +1 -1
  57. package/dist/extensions/registry.js +20 -0
  58. package/dist/extensions/registry.js.map +1 -1
  59. package/dist/identity/oidc-discovery.d.ts +36 -0
  60. package/dist/identity/oidc-discovery.d.ts.map +1 -0
  61. package/dist/identity/oidc-discovery.js +60 -0
  62. package/dist/identity/oidc-discovery.js.map +1 -0
  63. package/dist/identity/oidc-userinfo.d.ts +30 -0
  64. package/dist/identity/oidc-userinfo.d.ts.map +1 -0
  65. package/dist/identity/oidc-userinfo.js +28 -0
  66. package/dist/identity/oidc-userinfo.js.map +1 -0
  67. package/dist/identity/oidc-verifier.d.ts +6 -0
  68. package/dist/identity/oidc-verifier.d.ts.map +1 -1
  69. package/dist/identity/oidc-verifier.js +35 -34
  70. package/dist/identity/oidc-verifier.js.map +1 -1
  71. package/dist/index.d.ts +7 -0
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +3 -0
  74. package/dist/index.js.map +1 -1
  75. package/dist/pipeline/interceptors/auth.d.ts +10 -0
  76. package/dist/pipeline/interceptors/auth.d.ts.map +1 -1
  77. package/dist/pipeline/interceptors/auth.js +9 -1
  78. package/dist/pipeline/interceptors/auth.js.map +1 -1
  79. package/package.json +4 -4
  80. package/src/boot/__tests__/auth-enabled-composition.test.ts +226 -2
  81. package/src/boot/compose.ts +118 -13
  82. package/src/domain/apikey/__tests__/verifier.test.ts +146 -22
  83. package/src/domain/apikey/verifier.ts +24 -2
  84. package/src/domain/identityaccount/__tests__/constants.test.ts +155 -0
  85. package/src/domain/identityaccount/__tests__/identityaccount.test.ts +484 -0
  86. package/src/domain/identityaccount/__tests__/operator.test.ts +180 -0
  87. package/src/domain/identityaccount/__tests__/provisioning.test.ts +281 -0
  88. package/src/domain/identityaccount/__tests__/resolve.test.ts +114 -0
  89. package/src/domain/identityaccount/__tests__/resource-store.test.ts +216 -0
  90. package/src/domain/identityaccount/__tests__/support.ts +58 -0
  91. package/src/domain/identityaccount/constants.ts +178 -0
  92. package/src/domain/identityaccount/controller.ts +667 -0
  93. package/src/domain/identityaccount/operator.ts +94 -0
  94. package/src/domain/identityaccount/provisioning.ts +182 -0
  95. package/src/domain/identityaccount/resolve.ts +52 -0
  96. package/src/domain/identityaccount/resource-store.ts +157 -0
  97. package/src/domain/identityaccount/steps.ts +377 -0
  98. package/src/domain/identityaccount/store-contract.ts +471 -0
  99. package/src/domain/identityaccount/store.ts +70 -0
  100. package/src/extensions/__tests__/identity-account-composed.test.ts +803 -0
  101. package/src/extensions/__tests__/identity-account-points.test.ts +129 -0
  102. package/src/extensions/__tests__/registry.test.ts +4 -0
  103. package/src/extensions/__tests__/tier-truthfulness.test.ts +299 -0
  104. package/src/extensions/drivers.ts +26 -0
  105. package/src/extensions/gate-slots.ts +16 -0
  106. package/src/extensions/identity-federation.ts +58 -0
  107. package/src/extensions/registry.ts +44 -1
  108. package/src/identity/__tests__/oidc-discovery.test.ts +122 -0
  109. package/src/identity/__tests__/oidc-userinfo.test.ts +103 -0
  110. package/src/identity/__tests__/oidc-verifier.test.ts +173 -3
  111. package/src/identity/oidc-discovery.ts +84 -0
  112. package/src/identity/oidc-userinfo.ts +64 -0
  113. package/src/identity/oidc-verifier.ts +42 -45
  114. package/src/index.ts +19 -0
  115. package/src/pipeline/interceptors/auth.ts +13 -1
  116. package/src/pipeline/steps/__tests__/authorize-annotation-completeness.test.ts +184 -0
@@ -0,0 +1,667 @@
1
+ /**
2
+ * IdentityAccount controller (20260911.11) — the identity-account domain
3
+ * served ONCE by @stigmer/server in every edition (the editions program's
4
+ * tier truth: `identity_account` is open-source tier). The behavioural
5
+ * reference is the cloud's iam/account/handlers.ts, whose twelve direct
6
+ * handlers retire against this module; the byte-pinned copy moved with it
7
+ * (constants.ts). The cloud keeps only what differs per edition — its row
8
+ * store as `drivers.identityAccountStore`, the federated arms as
9
+ * `drivers.identityFederation`, the personal organization as a gate on
10
+ * `identity-account-provision:post-persist`.
11
+ *
12
+ * Persistence is the IdentityAccountStore PORT, never the generic Store
13
+ * (steps.ts explains); the storage-free shared steps are reused as they
14
+ * are, so every chain reads onto the inventory unchanged.
15
+ *
16
+ * The ONE create path (`newCreateAccountPath`): the create RPC, the
17
+ * provisioner and the trusted-local operator ensure all run the same
18
+ * chain — DeriveAccountId, CheckDuplicate by subject, BuildNewState,
19
+ * AssignBackendFields, Persist through the port, CreateAuthorizationTuples
20
+ * (the lifecycle driver's SELF arm gives the account its self-owner grant
21
+ * in the cloud) — so no account exists that skipped a step. The create
22
+ * RPC is the cloud#393 gate in front of that path (T01_1_review.md A7):
23
+ * machine / internal / in-process callers only, in every edition. The
24
+ * gate is the RPC's admission rule and deliberately NOT a step in the
25
+ * path, because the provisioner runs the path as the idp-shaped wire user
26
+ * (the account is created by the subject it is for) and the operator
27
+ * ensure runs it as the trusted-local user.
28
+ *
29
+ * Direct handlers (no pipeline): whoAmI (the cloud's two primary-key
30
+ * reads through idpIdOf; NOT_FOUND for the unprovisioned), getByEmail and
31
+ * getByIdpId (lookup FIRST, then authorizeDirect on the FOUND id — the
32
+ * cloud's order; the annotation's `field_path = "value"` would otherwise
33
+ * hand the Authorizer an email as a resource id), getActorInfo, and
34
+ * provisionMyAccount (the provisioner, then the composed post-persist
35
+ * gates; UNAUTHENTICATED with the cloud's copy for a credential naming no
36
+ * subject; UNAVAILABLE with the cloud's copy when userinfo fails).
37
+ *
38
+ * The four federation RPCs refuse UNIMPLEMENTED with the edition reason
39
+ * when no unit composes the capability (never INTERNAL; the organization
40
+ * directory's absent-method shape); present, the controller owns the
41
+ * shared precondition (authorize on the org, ref-with-slug, org match,
42
+ * IdP exists) and dispatches to the arm with the resolved ref.
43
+ *
44
+ * Proven by __tests__/identityaccount.test.ts (the composed trusted-local
45
+ * server), boot/__tests__/auth-enabled-composition.test.ts (the OIDC
46
+ * posture end to end) and identityaccount.conformance.test.ts.
47
+ */
48
+ import { Code, ConnectError } from "@connectrpc/connect";
49
+ import type { ConnectRouter, HandlerContext } from "@connectrpc/connect";
50
+ import type { DescMessage, DescMethod, Message } from "@bufbuild/protobuf";
51
+ import { create } from "@bufbuild/protobuf";
52
+ import type { Empty } from "@bufbuild/protobuf/wkt";
53
+
54
+ import type { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
55
+ import type { ApiResourceReference } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
56
+ import { ApiResourceAuditActorSchema } from "@stigmer/protos/ai/stigmer/commons/apiresource/status_pb";
57
+ import type { ApiResourceAuditActor } from "@stigmer/protos/ai/stigmer/commons/apiresource/status_pb";
58
+ import type { IdentityAccount } from "@stigmer/protos/ai/stigmer/iam/identityaccount/v1/api_pb";
59
+ import { IdentityAccountSchema } from "@stigmer/protos/ai/stigmer/iam/identityaccount/v1/api_pb";
60
+ import { IdentityAccountCommandController } from "@stigmer/protos/ai/stigmer/iam/identityaccount/v1/command_pb";
61
+ import type {
62
+ IdentityAccountEmail,
63
+ IdentityAccountId,
64
+ IdpId,
65
+ } from "@stigmer/protos/ai/stigmer/iam/identityaccount/v1/io_pb";
66
+ import { IdentityAccountQueryController } from "@stigmer/protos/ai/stigmer/iam/identityaccount/v1/query_pb";
67
+
68
+ import type { Logger } from "../../boot/logger.js";
69
+ import type { Authorizer } from "../../extensions/authorizer.js";
70
+ import { stepsForSlot } from "../../extensions/gate-slots.js";
71
+ import type { ResolvedGateSteps } from "../../extensions/gate-slots.js";
72
+ import type { CallerIdentity } from "../../extensions/identity.js";
73
+ import type { IdentityFederation } from "../../extensions/identity-federation.js";
74
+ import type { ResourceAuthorizationLifecycle } from "../../extensions/resource-authorization.js";
75
+ import { internalError, invalidArgumentError } from "../../pipeline/errors.js";
76
+ import { apiResourceKindKey } from "../../pipeline/interceptors/apiresource.js";
77
+ import { callerIdentityOf } from "../../pipeline/interceptors/auth.js";
78
+ import { newPipeline } from "../../pipeline/pipeline.js";
79
+ import { RequestContext } from "../../pipeline/request-context.js";
80
+ import {
81
+ newCleanupIamPoliciesStep,
82
+ newCreateAuthorizationTuplesStep,
83
+ } from "../../pipeline/steps/authorization-tuples.js";
84
+ import {
85
+ authorizeDirect,
86
+ newAuthorizeStep,
87
+ } from "../../pipeline/steps/authorize.js";
88
+ import { newBuildUpdateStateStep } from "../../pipeline/steps/build-update-state.js";
89
+ import { newBuildNewStateStep } from "../../pipeline/steps/defaults.js";
90
+ import { newExtractResourceIdStep } from "../../pipeline/steps/delete.js";
91
+ import { newGuardReservedLabelsStep } from "../../pipeline/steps/guard-reserved-labels.js";
92
+ import { EXISTING_RESOURCE_KEY } from "../../pipeline/steps/load-existing.js";
93
+ import { TARGET_RESOURCE_KEY } from "../../pipeline/steps/load-target.js";
94
+ import { newResolveSlugStep } from "../../pipeline/steps/slug.js";
95
+ import { newValidateProtoStep } from "../../pipeline/steps/validation.js";
96
+ import {
97
+ ACCOUNT_NOT_FOUND_FOR_CALLER_MESSAGE,
98
+ CREATE_IS_INTERNAL_MESSAGE,
99
+ NO_IDP_ID_MESSAGE,
100
+ USERINFO_UNAVAILABLE_PREFIX,
101
+ federationUnimplementedMessage,
102
+ idpIdOf,
103
+ } from "./constants.js";
104
+ import type {
105
+ CreateAccount,
106
+ CreateAccountInput,
107
+ DirectAccountProvisioner,
108
+ } from "./provisioning.js";
109
+ import { UserInfoFetchError } from "./provisioning.js";
110
+ import {
111
+ accountNotFoundError,
112
+ newAssignBackendFieldsStep,
113
+ newCheckDuplicateStep,
114
+ newDefaultAccountNameStep,
115
+ newDeleteAccountStep,
116
+ newDeriveAccountIdStep,
117
+ newGuardImmutableSubjectStep,
118
+ newLoadExistingAccountForDeleteStep,
119
+ newLoadExistingAccountStep,
120
+ newLoadTargetAccountStep,
121
+ newPersistNewAccountStep,
122
+ newPersistUpdatedAccountStep,
123
+ newPreserveBackendFieldsStep,
124
+ } from "./steps.js";
125
+ import type { IdentityAccountStore } from "./store.js";
126
+
127
+ /** What the create path needs — the subset every caller of it composes. */
128
+ export interface CreateAccountPathDeps {
129
+ readonly accounts: IdentityAccountStore;
130
+ readonly logger: Logger;
131
+ /** The composed authorization seam — the Authorize step at position 1 of every chain calls it (DD-007 §3). */
132
+ readonly authorizer: Authorizer;
133
+ /** The composed tuple-lifecycle driver — undefined = the shared steps no-op. */
134
+ readonly authorizationLifecycle: ResourceAuthorizationLifecycle | undefined;
135
+ }
136
+
137
+ export interface IdentityAccountControllerDeps extends CreateAccountPathDeps {
138
+ readonly provisioner: DirectAccountProvisioner;
139
+ /** The composed federation capability — undefined = the four RPCs refuse UNIMPLEMENTED. */
140
+ readonly federation: IdentityFederation | undefined;
141
+ /** The composed slot registrations — this domain's provision slot (Q-IA-9, A10). */
142
+ readonly gateSteps: ResolvedGateSteps;
143
+ }
144
+
145
+ /** Registers both identityaccount services on the router (routes stage). */
146
+ export function registerIdentityAccountServices(
147
+ router: ConnectRouter,
148
+ deps: IdentityAccountControllerDeps,
149
+ ): void {
150
+ router.service(IdentityAccountCommandController, {
151
+ create: (account, ctx) => createRpc(deps, account, ctx),
152
+ update: (account, ctx) => update(deps, account, ctx),
153
+ delete: (id, ctx) => deleteAccount(deps, id, ctx),
154
+ createFederatedAccount: (input, ctx) =>
155
+ federated(
156
+ deps,
157
+ ctx,
158
+ IdentityAccountCommandController.method.createFederatedAccount,
159
+ input,
160
+ (federation, ref, caller) =>
161
+ federation.createFederatedAccount(input, ref, caller),
162
+ ),
163
+ updateFederatedAccount: (input, ctx) =>
164
+ federated(
165
+ deps,
166
+ ctx,
167
+ IdentityAccountCommandController.method.updateFederatedAccount,
168
+ input,
169
+ (federation, ref, caller) =>
170
+ federation.updateFederatedAccount(input, ref, caller),
171
+ ),
172
+ deprovisionFederatedAccount: (input, ctx) =>
173
+ federated(
174
+ deps,
175
+ ctx,
176
+ IdentityAccountCommandController.method.deprovisionFederatedAccount,
177
+ input,
178
+ (federation, ref, caller) =>
179
+ federation.deprovisionFederatedAccount(input, ref, caller),
180
+ ),
181
+ provisionMyAccount: (empty, ctx) => provisionMyAccount(deps, empty, ctx),
182
+ });
183
+ router.service(IdentityAccountQueryController, {
184
+ get: (id, ctx) => get(deps, id, ctx),
185
+ whoAmI: (empty, ctx) => whoAmI(deps, empty, ctx),
186
+ getByEmail: (email, ctx) => getByEmail(deps, email, ctx),
187
+ getByIdpId: (idpId, ctx) => getByIdpId(deps, idpId, ctx),
188
+ getByExternalSub: (lookup, ctx) =>
189
+ federated(
190
+ deps,
191
+ ctx,
192
+ IdentityAccountQueryController.method.getByExternalSub,
193
+ lookup,
194
+ (federation, ref, caller) =>
195
+ federation.getByExternalSub(lookup, ref, caller),
196
+ ),
197
+ getActorInfo: (id, ctx) => getActorInfo(deps, id, ctx),
198
+ });
199
+ }
200
+
201
+ function kindOf(ctx: HandlerContext): ApiResourceKind {
202
+ return ctx.values.get(apiResourceKindKey);
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // The one create path
207
+ // ---------------------------------------------------------------------------
208
+
209
+ /**
210
+ * Runs the create chain AS `caller` and answers the persisted account.
211
+ * `kind` is the service's kind tag for wire calls; the path callers with
212
+ * no HandlerContext (the provisioner, the operator ensure) pass the kind
213
+ * the controller serves.
214
+ */
215
+ async function runCreateChain(
216
+ deps: CreateAccountPathDeps,
217
+ account: IdentityAccount,
218
+ caller: CallerIdentity,
219
+ kind: ApiResourceKind,
220
+ ): Promise<IdentityAccount> {
221
+ const reqCtx = new RequestContext(
222
+ IdentityAccountSchema,
223
+ account,
224
+ caller,
225
+ kind,
226
+ );
227
+ await newPipeline<typeof IdentityAccountSchema>(
228
+ "identityaccount-create",
229
+ deps.logger,
230
+ )
231
+ .addStep(
232
+ newAuthorizeStep(
233
+ IdentityAccountCommandController.method.create,
234
+ deps.authorizer,
235
+ ),
236
+ )
237
+ .addStep(newValidateProtoStep())
238
+ .addStep(newDefaultAccountNameStep())
239
+ .addStep(newResolveSlugStep())
240
+ .addStep(newDeriveAccountIdStep())
241
+ .addStep(newCheckDuplicateStep(deps.accounts))
242
+ .addStep(newBuildNewStateStep())
243
+ .addStep(newGuardReservedLabelsStep(deps.authorizer))
244
+ .addStep(newAssignBackendFieldsStep())
245
+ .addStep(newPersistNewAccountStep(deps.accounts))
246
+ .addStep(
247
+ newCreateAuthorizationTuplesStep(
248
+ deps.authorizationLifecycle,
249
+ deps.logger,
250
+ ),
251
+ )
252
+ .build()
253
+ .execute(reqCtx);
254
+ return reqCtx.newState;
255
+ }
256
+
257
+ /**
258
+ * The create path as its in-process callers see it (provisioning.ts
259
+ * `CreateAccount`): the input becomes the resource envelope the chain
260
+ * expects, tagged with the kind this controller serves.
261
+ */
262
+ export function newCreateAccountPath(
263
+ deps: CreateAccountPathDeps,
264
+ kind: ApiResourceKind,
265
+ ): CreateAccount {
266
+ return (input: CreateAccountInput, caller: CallerIdentity) =>
267
+ runCreateChain(
268
+ deps,
269
+ create(IdentityAccountSchema, {
270
+ apiVersion: "iam.stigmer.ai/v1",
271
+ kind: "IdentityAccount",
272
+ metadata: { name: input.name },
273
+ spec: input.spec,
274
+ }),
275
+ caller,
276
+ kind,
277
+ );
278
+ }
279
+
280
+ /**
281
+ * The create RPC: the cloud#393 gate, then the path AS the caller. FGA
282
+ * cannot gate this RPC (the account being created IS the principal — the
283
+ * bootstrap problem), so the gate is caller class: the platform's own
284
+ * pipelines only.
285
+ */
286
+ function createRpc(
287
+ deps: IdentityAccountControllerDeps,
288
+ account: IdentityAccount,
289
+ ctx: HandlerContext,
290
+ ): Promise<IdentityAccount> {
291
+ const caller = callerIdentityOf(ctx);
292
+ guardInternalRpc(caller);
293
+ return runCreateChain(deps, account, caller, kindOf(ctx));
294
+ }
295
+
296
+ function guardInternalRpc(caller: CallerIdentity): void {
297
+ if (
298
+ caller.callerClass === "machine" ||
299
+ caller.callerClass === "internal" ||
300
+ caller.origin === "in-process"
301
+ ) {
302
+ return;
303
+ }
304
+ throw new ConnectError(CREATE_IS_INTERNAL_MESSAGE, Code.PermissionDenied);
305
+ }
306
+
307
+ // ---------------------------------------------------------------------------
308
+ // Update / Delete
309
+ // ---------------------------------------------------------------------------
310
+
311
+ /**
312
+ * Update: full-envelope replace with the cloud's writable surface (A9) —
313
+ * BuildUpdateState preserves id/slug/org/visibility, GuardImmutableSubject
314
+ * refuses a changed subject, AssignBackendFields preserves the rest of
315
+ * what the backend owns from the existing row.
316
+ */
317
+ async function update(
318
+ deps: IdentityAccountControllerDeps,
319
+ account: IdentityAccount,
320
+ ctx: HandlerContext,
321
+ ): Promise<IdentityAccount> {
322
+ const reqCtx = new RequestContext(
323
+ IdentityAccountSchema,
324
+ account,
325
+ callerIdentityOf(ctx),
326
+ kindOf(ctx),
327
+ );
328
+ await newPipeline<typeof IdentityAccountSchema>(
329
+ "identityaccount-update",
330
+ deps.logger,
331
+ )
332
+ .addStep(
333
+ newAuthorizeStep(
334
+ IdentityAccountCommandController.method.update,
335
+ deps.authorizer,
336
+ ),
337
+ )
338
+ .addStep(newValidateProtoStep())
339
+ .addStep(newLoadExistingAccountStep(deps.accounts))
340
+ .addStep(newGuardImmutableSubjectStep())
341
+ .addStep(newBuildUpdateStateStep())
342
+ .addStep(newPreserveBackendFieldsStep())
343
+ .addStep(newPersistUpdatedAccountStep(deps.accounts))
344
+ .build()
345
+ .execute(reqCtx);
346
+ return reqCtx.newState;
347
+ }
348
+
349
+ /** Delete — answers the pre-delete account (the canonical delete chain over the port). */
350
+ async function deleteAccount(
351
+ deps: IdentityAccountControllerDeps,
352
+ id: IdentityAccountId,
353
+ ctx: HandlerContext,
354
+ ): Promise<IdentityAccount> {
355
+ const reqCtx = new RequestContext(
356
+ IdentityAccountCommandController.method.delete.input,
357
+ id,
358
+ callerIdentityOf(ctx),
359
+ kindOf(ctx),
360
+ );
361
+ await newPipeline<
362
+ typeof IdentityAccountCommandController.method.delete.input
363
+ >("identityaccount-delete", deps.logger)
364
+ .addStep(
365
+ newAuthorizeStep(
366
+ IdentityAccountCommandController.method.delete,
367
+ deps.authorizer,
368
+ ),
369
+ )
370
+ .addStep(newValidateProtoStep())
371
+ .addStep(newExtractResourceIdStep())
372
+ .addStep(newLoadExistingAccountForDeleteStep(deps.accounts))
373
+ .addStep(newDeleteAccountStep(deps.accounts))
374
+ .addStep(
375
+ newCleanupIamPoliciesStep(deps.authorizationLifecycle, deps.logger),
376
+ )
377
+ .build()
378
+ .execute(reqCtx);
379
+
380
+ const deleted = reqCtx.get(EXISTING_RESOURCE_KEY);
381
+ if (deleted === undefined) {
382
+ throw internalError(
383
+ new Error("delete pipeline completed without a loaded resource"),
384
+ "deleted identity account not found in context",
385
+ );
386
+ }
387
+ return deleted as IdentityAccount;
388
+ }
389
+
390
+ // ---------------------------------------------------------------------------
391
+ // Reads
392
+ // ---------------------------------------------------------------------------
393
+
394
+ /** Get — LoadTarget by id through the port; the domain's NOT_FOUND copy. */
395
+ async function get(
396
+ deps: IdentityAccountControllerDeps,
397
+ id: IdentityAccountId,
398
+ ctx: HandlerContext,
399
+ ): Promise<IdentityAccount> {
400
+ return loadTarget(deps, IdentityAccountQueryController.method.get, id, ctx);
401
+ }
402
+
403
+ /** getActorInfo — the contract-shaped actor: id, avatar, "First Last", email. */
404
+ async function getActorInfo(
405
+ deps: IdentityAccountControllerDeps,
406
+ id: IdentityAccountId,
407
+ ctx: HandlerContext,
408
+ ): Promise<ApiResourceAuditActor> {
409
+ const account = await loadTarget(
410
+ deps,
411
+ IdentityAccountQueryController.method.getActorInfo,
412
+ id,
413
+ ctx,
414
+ );
415
+ const firstName = account.spec?.firstName ?? "";
416
+ const lastName = account.spec?.lastName ?? "";
417
+ return create(ApiResourceAuditActorSchema, {
418
+ id: account.metadata?.id ?? "",
419
+ avatar: account.spec?.pictureUrl ?? "",
420
+ displayName: `${firstName} ${lastName}`.trim(),
421
+ email: account.spec?.email ?? "",
422
+ });
423
+ }
424
+
425
+ async function loadTarget(
426
+ deps: IdentityAccountControllerDeps,
427
+ method: DescMethod,
428
+ id: IdentityAccountId,
429
+ ctx: HandlerContext,
430
+ ): Promise<IdentityAccount> {
431
+ const reqCtx = new RequestContext(
432
+ method.input,
433
+ id,
434
+ callerIdentityOf(ctx),
435
+ kindOf(ctx),
436
+ );
437
+ await newPipeline<DescMessage>(
438
+ `identityaccount-${method.localName}`,
439
+ deps.logger,
440
+ )
441
+ .addStep(newAuthorizeStep(method, deps.authorizer))
442
+ .addStep(newValidateProtoStep())
443
+ .addStep(newLoadTargetAccountStep(deps.accounts))
444
+ .build()
445
+ .execute(reqCtx);
446
+ return reqCtx.get(TARGET_RESOURCE_KEY) as IdentityAccount;
447
+ }
448
+
449
+ /**
450
+ * whoAmI — the cloud's lookup verbatim: by the resolved identity, then by
451
+ * the derived id of the caller's subject for a caller whose identity is
452
+ * still idp-shaped (an unprovisioned OIDC subject), then NOT_FOUND with
453
+ * the cloud's copy. Two primary-key reads at most; no scan.
454
+ */
455
+ async function whoAmI(
456
+ deps: IdentityAccountControllerDeps,
457
+ _empty: Empty,
458
+ ctx: HandlerContext,
459
+ ): Promise<IdentityAccount> {
460
+ const caller = callerIdentityOf(ctx);
461
+ let account = await read(
462
+ () => deps.accounts.findById(caller.identityId),
463
+ "failed to load identity account",
464
+ );
465
+ if (account === undefined) {
466
+ account = await read(
467
+ () => deps.accounts.findDirectByIdpId(idpIdOf(caller)),
468
+ "failed to load identity account",
469
+ );
470
+ }
471
+ if (account === undefined) {
472
+ throw new ConnectError(ACCOUNT_NOT_FOUND_FOR_CALLER_MESSAGE, Code.NotFound);
473
+ }
474
+ return account;
475
+ }
476
+
477
+ /** getByEmail — direct accounts only; lookup first, authorize on the FOUND id. */
478
+ async function getByEmail(
479
+ deps: IdentityAccountControllerDeps,
480
+ email: IdentityAccountEmail,
481
+ ctx: HandlerContext,
482
+ ): Promise<IdentityAccount> {
483
+ return lookupThenAuthorize(
484
+ deps,
485
+ IdentityAccountQueryController.method.getByEmail,
486
+ email,
487
+ ctx,
488
+ () => deps.accounts.findDirectByEmail(email.value),
489
+ email.value,
490
+ );
491
+ }
492
+
493
+ /** getByIdpId — any provisioning mode; lookup first, authorize on the FOUND id. */
494
+ async function getByIdpId(
495
+ deps: IdentityAccountControllerDeps,
496
+ idpId: IdpId,
497
+ ctx: HandlerContext,
498
+ ): Promise<IdentityAccount> {
499
+ return lookupThenAuthorize(
500
+ deps,
501
+ IdentityAccountQueryController.method.getByIdpId,
502
+ idpId,
503
+ ctx,
504
+ () => deps.accounts.findByIdpId(idpId.value),
505
+ idpId.value,
506
+ );
507
+ }
508
+
509
+ async function lookupThenAuthorize(
510
+ deps: IdentityAccountControllerDeps,
511
+ method: DescMethod,
512
+ input: IdentityAccountEmail | IdpId,
513
+ ctx: HandlerContext,
514
+ lookup: () => Promise<IdentityAccount | undefined>,
515
+ handle: string,
516
+ ): Promise<IdentityAccount> {
517
+ const account = await read(lookup, "failed to look up identity account");
518
+ if (account === undefined) {
519
+ throw accountNotFoundError(handle);
520
+ }
521
+ await authorizeDirect(method, deps.authorizer, callerIdentityOf(ctx), input, {
522
+ resourceId: account.metadata?.id ?? "",
523
+ });
524
+ return account;
525
+ }
526
+
527
+ // ---------------------------------------------------------------------------
528
+ // Provisioning
529
+ // ---------------------------------------------------------------------------
530
+
531
+ /**
532
+ * provisionMyAccount — the subject from the caller's credential, the
533
+ * provisioner's flow, then the composed post-persist gates (the cloud's
534
+ * personal organization) with the caller RE-STAMPED as the account: the
535
+ * position-1 identity was idp-shaped because no row existed when the
536
+ * verifier ran, and a gate that attributes ownership must name the
537
+ * account, never a principal no later request carries. The gates run on
538
+ * EVERY call, the idempotent early return included — the cloud's step
539
+ * backfills accounts that predate personal organizations there, which is
540
+ * why Q-IA-9 chose a slot over onResourceCreated. Non-transactional in
541
+ * the `org-create:post-persist` sense: a gate failure fails the request,
542
+ * the row survives, the next call heals it.
543
+ */
544
+ async function provisionMyAccount(
545
+ deps: IdentityAccountControllerDeps,
546
+ _empty: Empty,
547
+ ctx: HandlerContext,
548
+ ): Promise<IdentityAccount> {
549
+ const caller = callerIdentityOf(ctx);
550
+ const idpId = idpIdOf(caller);
551
+ if (idpId === "") {
552
+ throw new ConnectError(NO_IDP_ID_MESSAGE, Code.Unauthenticated);
553
+ }
554
+ let account: IdentityAccount;
555
+ try {
556
+ account = await deps.provisioner.provisionDirectAccount(idpId, caller);
557
+ } catch (error) {
558
+ if (error instanceof UserInfoFetchError) {
559
+ throw new ConnectError(
560
+ `${USERINFO_UNAVAILABLE_PREFIX}${error.message}`,
561
+ Code.Unavailable,
562
+ );
563
+ }
564
+ throw error;
565
+ }
566
+ // The ratified provision slot (Q-IA-9; the gate-slots.ts header carries
567
+ // its semantics). Empty in OSS — no pipeline is built for zero steps.
568
+ const gates = stepsForSlot<typeof IdentityAccountSchema>(
569
+ deps.gateSteps,
570
+ "identity-account-provision:post-persist",
571
+ );
572
+ if (gates.length > 0) {
573
+ const asAccount: CallerIdentity = {
574
+ ...caller,
575
+ identityId: account.metadata?.id ?? "",
576
+ };
577
+ const reqCtx = new RequestContext(
578
+ IdentityAccountSchema,
579
+ account,
580
+ asAccount,
581
+ kindOf(ctx),
582
+ );
583
+ const pipeline = newPipeline<typeof IdentityAccountSchema>(
584
+ "identityaccount-provision-post-persist",
585
+ deps.logger,
586
+ );
587
+ for (const step of gates) {
588
+ pipeline.addStep(step);
589
+ }
590
+ await pipeline.build().execute(reqCtx);
591
+ }
592
+ return account;
593
+ }
594
+
595
+ // ---------------------------------------------------------------------------
596
+ // Federation
597
+ // ---------------------------------------------------------------------------
598
+
599
+ /**
600
+ * The four federated RPCs' shared shape: refuse UNIMPLEMENTED when no
601
+ * unit composes the capability; otherwise the cloud's precondition arms
602
+ * verbatim — ref-with-slug required, org match, authorize on the org, IdP
603
+ * exists — then the unit's arm with the resolved ref.
604
+ */
605
+ interface FederatedInput extends Message {
606
+ readonly org: string;
607
+ readonly identityProviderRef?: ApiResourceReference;
608
+ }
609
+
610
+ async function federated<Input extends FederatedInput>(
611
+ deps: IdentityAccountControllerDeps,
612
+ ctx: HandlerContext,
613
+ method: DescMethod,
614
+ input: Input,
615
+ arm: (
616
+ federation: IdentityFederation,
617
+ ref: ApiResourceReference,
618
+ caller: CallerIdentity,
619
+ ) => Promise<IdentityAccount>,
620
+ ): Promise<IdentityAccount> {
621
+ const federation = deps.federation;
622
+ if (federation === undefined) {
623
+ throw new ConnectError(
624
+ federationUnimplementedMessage(
625
+ `${method.parent.typeName}.${method.localName}`,
626
+ ),
627
+ Code.Unimplemented,
628
+ );
629
+ }
630
+ const caller = callerIdentityOf(ctx);
631
+ const org = input.org;
632
+ const ref = input.identityProviderRef;
633
+ if (ref === undefined || ref.slug === "") {
634
+ throw invalidArgumentError(
635
+ "identity_provider_ref with a valid slug is required",
636
+ );
637
+ }
638
+ if (ref.org !== "" && ref.org !== org) {
639
+ throw invalidArgumentError(
640
+ `identity_provider_ref.org '${ref.org}' does not match input org '${org}'`,
641
+ );
642
+ }
643
+ // The annotation's target is the org (`field_path = "org"`); resolved
644
+ // from the input exactly as the pipeline step would.
645
+ await authorizeDirect(method, deps.authorizer, caller, input);
646
+ const refOrg = ref.org !== "" ? ref.org : org;
647
+ if (!(await federation.providerExists(refOrg, ref.slug))) {
648
+ throw new ConnectError(
649
+ `IdentityProvider '${refOrg}/${ref.slug}' not found`,
650
+ Code.NotFound,
651
+ );
652
+ }
653
+ ref.org = refOrg;
654
+ return arm(federation, ref, caller);
655
+ }
656
+
657
+ /** A direct handler's store read: a fault is INTERNAL with a static message, never "not found". */
658
+ async function read<T>(
659
+ operation: () => Promise<T>,
660
+ message: string,
661
+ ): Promise<T> {
662
+ try {
663
+ return await operation();
664
+ } catch (error) {
665
+ throw internalError(error, message);
666
+ }
667
+ }