@stigmer/server 3.21.0 → 3.22.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 (185) hide show
  1. package/dist/authorization/evaluator.d.ts +7 -1
  2. package/dist/authorization/evaluator.d.ts.map +1 -1
  3. package/dist/authorization/evaluator.js.map +1 -1
  4. package/dist/authorization/list-read-scope.d.ts.map +1 -1
  5. package/dist/authorization/list-read-scope.js +19 -11
  6. package/dist/authorization/list-read-scope.js.map +1 -1
  7. package/dist/authorization/model/organization.d.ts.map +1 -1
  8. package/dist/authorization/model/organization.js +2 -0
  9. package/dist/authorization/model/organization.js.map +1 -1
  10. package/dist/domain/agent/controller.d.ts.map +1 -1
  11. package/dist/domain/agent/controller.js +2 -0
  12. package/dist/domain/agent/controller.js.map +1 -1
  13. package/dist/domain/agentchannel/controller.d.ts.map +1 -1
  14. package/dist/domain/agentchannel/controller.js +6 -1
  15. package/dist/domain/agentchannel/controller.js.map +1 -1
  16. package/dist/domain/agentchannel/steps.d.ts +19 -0
  17. package/dist/domain/agentchannel/steps.d.ts.map +1 -1
  18. package/dist/domain/agentchannel/steps.js +32 -0
  19. package/dist/domain/agentchannel/steps.js.map +1 -1
  20. package/dist/domain/agentinstance/controller.d.ts +5 -5
  21. package/dist/domain/agentinstance/controller.d.ts.map +1 -1
  22. package/dist/domain/agentinstance/controller.js +6 -1
  23. package/dist/domain/agentinstance/controller.js.map +1 -1
  24. package/dist/domain/agentinstance/steps.d.ts +43 -8
  25. package/dist/domain/agentinstance/steps.d.ts.map +1 -1
  26. package/dist/domain/agentinstance/steps.js +71 -8
  27. package/dist/domain/agentinstance/steps.js.map +1 -1
  28. package/dist/domain/agentshare/controller.d.ts.map +1 -1
  29. package/dist/domain/agentshare/controller.js +7 -1
  30. package/dist/domain/agentshare/controller.js.map +1 -1
  31. package/dist/domain/agentshare/steps.d.ts +58 -0
  32. package/dist/domain/agentshare/steps.d.ts.map +1 -1
  33. package/dist/domain/agentshare/steps.js +109 -4
  34. package/dist/domain/agentshare/steps.js.map +1 -1
  35. package/dist/domain/artifact/controller.js +21 -25
  36. package/dist/domain/artifact/controller.js.map +1 -1
  37. package/dist/domain/channelapp/controller.d.ts.map +1 -1
  38. package/dist/domain/channelapp/controller.js +2 -0
  39. package/dist/domain/channelapp/controller.js.map +1 -1
  40. package/dist/domain/environment/controller.d.ts.map +1 -1
  41. package/dist/domain/environment/controller.js +2 -0
  42. package/dist/domain/environment/controller.js.map +1 -1
  43. package/dist/domain/executioncontext/controller.d.ts.map +1 -1
  44. package/dist/domain/executioncontext/controller.js +2 -0
  45. package/dist/domain/executioncontext/controller.js.map +1 -1
  46. package/dist/domain/executioncontext/steps.d.ts.map +1 -1
  47. package/dist/domain/executioncontext/steps.js +2 -1
  48. package/dist/domain/executioncontext/steps.js.map +1 -1
  49. package/dist/domain/mcpserver/connect.d.ts.map +1 -1
  50. package/dist/domain/mcpserver/connect.js +8 -7
  51. package/dist/domain/mcpserver/connect.js.map +1 -1
  52. package/dist/domain/mcpserver/controller.d.ts.map +1 -1
  53. package/dist/domain/mcpserver/controller.js +2 -0
  54. package/dist/domain/mcpserver/controller.js.map +1 -1
  55. package/dist/domain/mcpserver/start-connect.d.ts.map +1 -1
  56. package/dist/domain/mcpserver/start-connect.js +8 -7
  57. package/dist/domain/mcpserver/start-connect.js.map +1 -1
  58. package/dist/domain/memory/controller.d.ts.map +1 -1
  59. package/dist/domain/memory/controller.js +6 -1
  60. package/dist/domain/memory/controller.js.map +1 -1
  61. package/dist/domain/memory/steps.d.ts +23 -0
  62. package/dist/domain/memory/steps.d.ts.map +1 -1
  63. package/dist/domain/memory/steps.js +35 -0
  64. package/dist/domain/memory/steps.js.map +1 -1
  65. package/dist/domain/oauthapp/controller.d.ts.map +1 -1
  66. package/dist/domain/oauthapp/controller.js +2 -0
  67. package/dist/domain/oauthapp/controller.js.map +1 -1
  68. package/dist/domain/plugin/controller.d.ts.map +1 -1
  69. package/dist/domain/plugin/controller.js +5 -24
  70. package/dist/domain/plugin/controller.js.map +1 -1
  71. package/dist/domain/schedule/controller.d.ts.map +1 -1
  72. package/dist/domain/schedule/controller.js +7 -1
  73. package/dist/domain/schedule/controller.js.map +1 -1
  74. package/dist/domain/schedule/steps.d.ts +19 -0
  75. package/dist/domain/schedule/steps.d.ts.map +1 -1
  76. package/dist/domain/schedule/steps.js +32 -0
  77. package/dist/domain/schedule/steps.js.map +1 -1
  78. package/dist/domain/session/steps.d.ts +8 -9
  79. package/dist/domain/session/steps.d.ts.map +1 -1
  80. package/dist/domain/session/steps.js +17 -21
  81. package/dist/domain/session/steps.js.map +1 -1
  82. package/dist/domain/skill/controller.d.ts.map +1 -1
  83. package/dist/domain/skill/controller.js +8 -17
  84. package/dist/domain/skill/controller.js.map +1 -1
  85. package/dist/domain/workflow/controller.d.ts.map +1 -1
  86. package/dist/domain/workflow/controller.js +30 -107
  87. package/dist/domain/workflow/controller.js.map +1 -1
  88. package/dist/domain/workflow/version-resolution.d.ts +5 -0
  89. package/dist/domain/workflow/version-resolution.d.ts.map +1 -0
  90. package/dist/domain/workflow/version-resolution.js +113 -0
  91. package/dist/domain/workflow/version-resolution.js.map +1 -0
  92. package/dist/domain/workflowinstance/controller.d.ts.map +1 -1
  93. package/dist/domain/workflowinstance/controller.js +6 -1
  94. package/dist/domain/workflowinstance/controller.js.map +1 -1
  95. package/dist/domain/workflowinstance/steps.d.ts +20 -0
  96. package/dist/domain/workflowinstance/steps.d.ts.map +1 -1
  97. package/dist/domain/workflowinstance/steps.js +39 -0
  98. package/dist/domain/workflowinstance/steps.js.map +1 -1
  99. package/dist/extensions/identity.d.ts +19 -0
  100. package/dist/extensions/identity.d.ts.map +1 -1
  101. package/dist/extensions/identity.js +22 -3
  102. package/dist/extensions/identity.js.map +1 -1
  103. package/dist/extensions/list-read-scope.d.ts +41 -7
  104. package/dist/extensions/list-read-scope.d.ts.map +1 -1
  105. package/dist/extensions/list-read-scope.js +13 -2
  106. package/dist/extensions/list-read-scope.js.map +1 -1
  107. package/dist/pipeline/steps/authorize-resolved-target.d.ts +88 -0
  108. package/dist/pipeline/steps/authorize-resolved-target.d.ts.map +1 -0
  109. package/dist/pipeline/steps/authorize-resolved-target.js +36 -0
  110. package/dist/pipeline/steps/authorize-resolved-target.js.map +1 -0
  111. package/dist/pipeline/steps/authorize.d.ts +27 -0
  112. package/dist/pipeline/steps/authorize.d.ts.map +1 -1
  113. package/dist/pipeline/steps/authorize.js +49 -10
  114. package/dist/pipeline/steps/authorize.js.map +1 -1
  115. package/dist/pipeline/steps/guard-memory-capture.d.ts.map +1 -1
  116. package/dist/pipeline/steps/guard-memory-capture.js +2 -1
  117. package/dist/pipeline/steps/guard-memory-capture.js.map +1 -1
  118. package/dist/pipeline/steps/guard-reserved-labels.d.ts.map +1 -1
  119. package/dist/pipeline/steps/guard-reserved-labels.js +6 -7
  120. package/dist/pipeline/steps/guard-reserved-labels.js.map +1 -1
  121. package/dist/pipeline/steps/helpers.d.ts +9 -5
  122. package/dist/pipeline/steps/helpers.d.ts.map +1 -1
  123. package/dist/pipeline/steps/helpers.js +11 -15
  124. package/dist/pipeline/steps/helpers.js.map +1 -1
  125. package/dist/pipeline/steps/version-history.d.ts +11 -0
  126. package/dist/pipeline/steps/version-history.d.ts.map +1 -1
  127. package/dist/pipeline/steps/version-history.js +26 -0
  128. package/dist/pipeline/steps/version-history.js.map +1 -1
  129. package/package.json +6 -6
  130. package/src/authorization/__tests__/list-read-scope.test.ts +23 -12
  131. package/src/authorization/__tests__/skip-lane-inventory.test.ts +160 -0
  132. package/src/authorization/__tests__/wire-permissions.test.ts +5 -5
  133. package/src/authorization/evaluator.ts +7 -0
  134. package/src/authorization/list-read-scope.ts +22 -11
  135. package/src/authorization/model/__tests__/registry.test.ts +2 -0
  136. package/src/authorization/model/organization.ts +2 -0
  137. package/src/domain/agent/controller.ts +10 -0
  138. package/src/domain/agentchannel/__tests__/create-authorization.test.ts +58 -0
  139. package/src/domain/agentchannel/controller.ts +19 -0
  140. package/src/domain/agentchannel/steps.ts +40 -0
  141. package/src/domain/agentinstance/__tests__/create-authorization.composed.test.ts +243 -0
  142. package/src/domain/agentinstance/__tests__/create-authorization.test.ts +144 -0
  143. package/src/domain/agentinstance/controller.ts +24 -5
  144. package/src/domain/agentinstance/steps.ts +82 -8
  145. package/src/domain/agentshare/__tests__/create-authorization.test.ts +86 -0
  146. package/src/domain/agentshare/__tests__/member-audience.test.ts +113 -0
  147. package/src/domain/agentshare/controller.ts +21 -0
  148. package/src/domain/agentshare/steps.ts +181 -15
  149. package/src/domain/artifact/controller.ts +18 -22
  150. package/src/domain/channelapp/controller.ts +10 -0
  151. package/src/domain/environment/controller.ts +10 -0
  152. package/src/domain/executioncontext/__tests__/executioncontext.test.ts +1 -0
  153. package/src/domain/executioncontext/controller.ts +10 -0
  154. package/src/domain/executioncontext/steps.ts +2 -1
  155. package/src/domain/mcpserver/connect.ts +11 -10
  156. package/src/domain/mcpserver/controller.ts +13 -1
  157. package/src/domain/mcpserver/start-connect.ts +17 -11
  158. package/src/domain/memory/__tests__/create-authorization.test.ts +59 -0
  159. package/src/domain/memory/controller.ts +11 -0
  160. package/src/domain/memory/steps.ts +41 -0
  161. package/src/domain/oauthapp/controller.ts +10 -0
  162. package/src/domain/plugin/controller.ts +22 -36
  163. package/src/domain/schedule/__tests__/create-authorization.test.ts +58 -0
  164. package/src/domain/schedule/controller.ts +20 -0
  165. package/src/domain/schedule/steps.ts +45 -2
  166. package/src/domain/session/steps.ts +24 -32
  167. package/src/domain/skill/controller.ts +24 -23
  168. package/src/domain/workflow/controller.ts +58 -145
  169. package/src/domain/workflow/version-resolution.ts +166 -0
  170. package/src/domain/workflowinstance/__tests__/create-authorization.test.ts +109 -0
  171. package/src/domain/workflowinstance/controller.ts +19 -0
  172. package/src/domain/workflowinstance/steps.ts +49 -1
  173. package/src/extensions/__tests__/composed-support.ts +38 -4
  174. package/src/extensions/__tests__/identity.test.ts +44 -1
  175. package/src/extensions/__tests__/list-read-scope-composed.test.ts +87 -1
  176. package/src/extensions/__tests__/list-read-scope.test.ts +63 -0
  177. package/src/extensions/identity.ts +23 -5
  178. package/src/extensions/list-read-scope.ts +47 -7
  179. package/src/pipeline/steps/__tests__/authorize-resolved-target.test.ts +285 -0
  180. package/src/pipeline/steps/authorize-resolved-target.ts +129 -0
  181. package/src/pipeline/steps/authorize.ts +70 -13
  182. package/src/pipeline/steps/guard-memory-capture.ts +2 -1
  183. package/src/pipeline/steps/guard-reserved-labels.ts +6 -9
  184. package/src/pipeline/steps/helpers.ts +11 -15
  185. package/src/pipeline/steps/version-history.ts +34 -0
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Pins the AuthorizeResolvedTarget step's contract: a thin shell around the
3
+ * shared evaluation over the questions a PURE resolver names. Every target
4
+ * reaches the Authorizer as exactly the three fields of a check (never the
5
+ * copy); the questions are asked in the resolver's order and the first
6
+ * refusal answers; an empty list asks nothing; a throwing resolver surfaces
7
+ * as the chain's Internal, never as an admitted request; deny carries the
8
+ * target's copy, not-found the load-first NOT_FOUND, unavailable INTERNAL;
9
+ * the `internal` class alone skips, and a propagated in-process caller does
10
+ * not (that arm is a resolver's to model, never the step's). The step runs
11
+ * under the shared name by default and under a caller-supplied frozen name
12
+ * for the lanes that predate it.
13
+ *
14
+ * Also pins `loadedTargetAsMethod`: the reads' resolver asks the sibling
15
+ * `get` annotation about the LOADED row's id — the `get`'s kind,
16
+ * permission and byte-pinned copy, the loader's id — and is a no-op when
17
+ * that `get` is itself a skip, so a read by reference is never stricter
18
+ * than the read by id and never laxer. A missing loaded row is a thrown
19
+ * invariant, not an empty answer.
20
+ */
21
+ import { describe, expect, it } from "vitest";
22
+ import { create } from "@bufbuild/protobuf";
23
+ import { Code, ConnectError } from "@connectrpc/connect";
24
+
25
+ import { AgentSchema } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
26
+ import { AgentQueryController } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/query_pb";
27
+ import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
28
+ import { ApiResourceReferenceSchema } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
29
+ import { IamPermission } from "@stigmer/protos/ai/stigmer/iam/v1/enum_pb";
30
+
31
+ import type {
32
+ Authorizer,
33
+ AuthzCheck,
34
+ AuthzDecision,
35
+ } from "../../../extensions/authorizer.js";
36
+ import { testCallerIdentity } from "../../__tests__/support.js";
37
+ import { RequestContext } from "../../request-context.js";
38
+ import {
39
+ AUTHORIZATION_UNAVAILABLE_MESSAGE,
40
+ type AuthorizationTarget,
41
+ } from "../authorize.js";
42
+ import {
43
+ AUTHORIZE_RESOLVED_TARGET_STEP,
44
+ loadedTargetAsMethod,
45
+ newAuthorizeResolvedTargetStep,
46
+ } from "../authorize-resolved-target.js";
47
+ import { TARGET_RESOURCE_KEY } from "../load-target.js";
48
+
49
+ function fakeAuthorizer(decide: (check: AuthzCheck) => AuthzDecision): {
50
+ authorizer: Authorizer;
51
+ checks: AuthzCheck[];
52
+ } {
53
+ const checks: AuthzCheck[] = [];
54
+ return {
55
+ checks,
56
+ authorizer: {
57
+ authorize(_caller, check) {
58
+ checks.push(check);
59
+ return Promise.resolve(decide(check));
60
+ },
61
+ },
62
+ };
63
+ }
64
+
65
+ const allow = (): AuthzDecision => ({ kind: "allow" });
66
+
67
+ async function captureError(
68
+ run: () => void | Promise<void>,
69
+ ): Promise<ConnectError> {
70
+ try {
71
+ await run();
72
+ } catch (error) {
73
+ return ConnectError.from(error);
74
+ }
75
+ throw new Error("expected the step to reject");
76
+ }
77
+
78
+ const ORG_QUESTION: AuthorizationTarget = {
79
+ permission: IamPermission.can_create_agent_instance,
80
+ resourceKind: ApiResourceKind.organization,
81
+ resourceId: "acme",
82
+ deniedMessage: "unauthorized to create agent instance in this organization",
83
+ };
84
+
85
+ const PARENT_QUESTION: AuthorizationTarget = {
86
+ permission: IamPermission.can_create_instance,
87
+ resourceKind: ApiResourceKind.agent,
88
+ resourceId: "agt_01parent",
89
+ deniedMessage: "You don't have permission to create instances of this agent",
90
+ };
91
+
92
+ function agentCtx(caller = testCallerIdentity()) {
93
+ return new RequestContext(
94
+ AgentSchema,
95
+ create(AgentSchema, { metadata: { name: "a", org: "acme" } }),
96
+ caller,
97
+ ApiResourceKind.agent,
98
+ );
99
+ }
100
+
101
+ describe("AuthorizeResolvedTarget — the step shell", () => {
102
+ it("runs under the shared name by default and under a frozen name when a folded lane supplies one", () => {
103
+ const { authorizer } = fakeAuthorizer(allow);
104
+ expect(newAuthorizeResolvedTargetStep(authorizer, () => []).name).toBe(
105
+ AUTHORIZE_RESOLVED_TARGET_STEP,
106
+ );
107
+ expect(
108
+ newAuthorizeResolvedTargetStep(
109
+ authorizer,
110
+ () => [],
111
+ "AuthorizeResolvedPlugin",
112
+ ).name,
113
+ ).toBe("AuthorizeResolvedPlugin");
114
+ });
115
+
116
+ it("asks nothing when the resolver answers an empty list", async () => {
117
+ const { authorizer, checks } = fakeAuthorizer(() => ({
118
+ kind: "deny",
119
+ reason: "would have refused",
120
+ }));
121
+ await newAuthorizeResolvedTargetStep(authorizer, () => []).execute(
122
+ agentCtx(),
123
+ );
124
+ expect(checks).toEqual([]);
125
+ });
126
+
127
+ it("asks each question in the resolver's order, as a bare check without the copy", async () => {
128
+ const { authorizer, checks } = fakeAuthorizer(allow);
129
+ await newAuthorizeResolvedTargetStep(authorizer, () => [
130
+ ORG_QUESTION,
131
+ PARENT_QUESTION,
132
+ ]).execute(agentCtx());
133
+ expect(checks).toEqual([
134
+ {
135
+ permission: IamPermission.can_create_agent_instance,
136
+ resourceKind: ApiResourceKind.organization,
137
+ resourceId: "acme",
138
+ },
139
+ {
140
+ permission: IamPermission.can_create_instance,
141
+ resourceKind: ApiResourceKind.agent,
142
+ resourceId: "agt_01parent",
143
+ },
144
+ ]);
145
+ });
146
+
147
+ it("the first refusal answers, with THAT question's copy, and later questions are never asked", async () => {
148
+ const { authorizer, checks } = fakeAuthorizer((check) =>
149
+ check.resourceKind === ApiResourceKind.organization
150
+ ? { kind: "deny", reason: "" }
151
+ : allow(),
152
+ );
153
+ const error = await captureError(() =>
154
+ newAuthorizeResolvedTargetStep(authorizer, () => [
155
+ ORG_QUESTION,
156
+ PARENT_QUESTION,
157
+ ]).execute(agentCtx()),
158
+ );
159
+ expect(error.code).toBe(Code.PermissionDenied);
160
+ expect(error.rawMessage).toBe(ORG_QUESTION.deniedMessage);
161
+ expect(checks).toHaveLength(1);
162
+ });
163
+
164
+ it("not-found answers the load-first NOT_FOUND for the target", async () => {
165
+ const { authorizer } = fakeAuthorizer(() => ({ kind: "not-found" }));
166
+ const error = await captureError(() =>
167
+ newAuthorizeResolvedTargetStep(authorizer, () => [
168
+ PARENT_QUESTION,
169
+ ]).execute(agentCtx()),
170
+ );
171
+ expect(error.code).toBe(Code.NotFound);
172
+ expect(error.rawMessage).toContain("agt_01parent");
173
+ });
174
+
175
+ it("unavailable is INTERNAL with the sanitized copy", async () => {
176
+ const { authorizer } = fakeAuthorizer(() => ({
177
+ kind: "unavailable",
178
+ cause: new Error("backend down"),
179
+ }));
180
+ const error = await captureError(() =>
181
+ newAuthorizeResolvedTargetStep(authorizer, () => [
182
+ PARENT_QUESTION,
183
+ ]).execute(agentCtx()),
184
+ );
185
+ expect(error.code).toBe(Code.Internal);
186
+ expect(error.rawMessage).toBe(AUTHORIZATION_UNAVAILABLE_MESSAGE);
187
+ });
188
+
189
+ it("a resolver that throws surfaces its error; a broken chain invariant never admits the request", async () => {
190
+ const { authorizer, checks } = fakeAuthorizer(allow);
191
+ await expect(
192
+ newAuthorizeResolvedTargetStep(authorizer, () => {
193
+ throw new Error("parent not found in context");
194
+ }).execute(agentCtx()),
195
+ ).rejects.toThrow("parent not found in context");
196
+ expect(checks).toEqual([]);
197
+ });
198
+
199
+ it("the internal class alone skips; a propagated in-process caller is still asked", async () => {
200
+ const denying = fakeAuthorizer(() => ({ kind: "deny", reason: "" }));
201
+ await newAuthorizeResolvedTargetStep(denying.authorizer, () => [
202
+ PARENT_QUESTION,
203
+ ]).execute(agentCtx(testCallerIdentity({ callerClass: "internal" })));
204
+ expect(denying.checks).toEqual([]);
205
+
206
+ const error = await captureError(() =>
207
+ newAuthorizeResolvedTargetStep(denying.authorizer, () => [
208
+ PARENT_QUESTION,
209
+ ]).execute(
210
+ agentCtx(
211
+ testCallerIdentity({ callerClass: "user", origin: "in-process" }),
212
+ ),
213
+ ),
214
+ );
215
+ expect(error.code).toBe(Code.PermissionDenied);
216
+ });
217
+ });
218
+
219
+ function referenceCtx(loaded?: unknown) {
220
+ const ctx = new RequestContext(
221
+ ApiResourceReferenceSchema,
222
+ create(ApiResourceReferenceSchema, { org: "acme", slug: "helper" }),
223
+ testCallerIdentity(),
224
+ ApiResourceKind.agent,
225
+ );
226
+ if (loaded !== undefined) {
227
+ ctx.set(TARGET_RESOURCE_KEY, loaded);
228
+ }
229
+ return ctx;
230
+ }
231
+
232
+ describe("loadedTargetAsMethod — a read by reference asks what its get asks", () => {
233
+ it("names the get annotation's kind, permission and copy on the LOADED row's id", async () => {
234
+ const { authorizer, checks } = fakeAuthorizer(() => ({
235
+ kind: "deny",
236
+ reason: "",
237
+ }));
238
+ const loaded = create(AgentSchema, {
239
+ metadata: { id: "agt_01loaded", name: "helper", org: "acme" },
240
+ });
241
+ const error = await captureError(() =>
242
+ newAuthorizeResolvedTargetStep(
243
+ authorizer,
244
+ loadedTargetAsMethod(AgentQueryController.method.get),
245
+ ).execute(referenceCtx(loaded)),
246
+ );
247
+ expect(checks).toEqual([
248
+ {
249
+ permission: IamPermission.can_view,
250
+ resourceKind: ApiResourceKind.agent,
251
+ resourceId: "agt_01loaded",
252
+ },
253
+ ]);
254
+ expect(error.code).toBe(Code.PermissionDenied);
255
+ expect(error.rawMessage).toBe("unauthorized to get agent");
256
+ });
257
+
258
+ it("is a no-op when the method it is keyed on is itself a skip — never stricter than the annotation it mirrors", async () => {
259
+ // Keyed on a skip descriptor (the reference RPC's own), the resolver
260
+ // answers nothing: the annotation, not the step, owns the skip arms.
261
+ const { authorizer, checks } = fakeAuthorizer(() => ({
262
+ kind: "deny",
263
+ reason: "",
264
+ }));
265
+ const loaded = create(AgentSchema, {
266
+ metadata: { id: "agt_01loaded", name: "helper", org: "acme" },
267
+ });
268
+ await newAuthorizeResolvedTargetStep(
269
+ authorizer,
270
+ loadedTargetAsMethod(AgentQueryController.method.getByReference),
271
+ ).execute(referenceCtx(loaded));
272
+ expect(checks).toEqual([]);
273
+ });
274
+
275
+ it("a missing loaded row is a thrown invariant, never an empty answer", async () => {
276
+ const { authorizer, checks } = fakeAuthorizer(allow);
277
+ await expect(
278
+ newAuthorizeResolvedTargetStep(
279
+ authorizer,
280
+ loadedTargetAsMethod(AgentQueryController.method.get),
281
+ ).execute(referenceCtx()),
282
+ ).rejects.toThrow(TARGET_RESOURCE_KEY);
283
+ expect(checks).toEqual([]);
284
+ });
285
+ });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * AuthorizeResolvedTarget — the ONE mid-chain authorization step: the
3
+ * question a lane can only ask once its chain has loaded something the
4
+ * position-1 annotation could not key on.
5
+ *
6
+ * The `Authorize` step resolves its target from the REQUEST (a field path
7
+ * over the input), so it cannot serve two shapes of lane, and both are
8
+ * `is_skip_authorization` on the wire for that reason alone:
9
+ *
10
+ * - a read by reference: the request carries an org and a slug, the
11
+ * target is the row the loader finds, and the question is exactly the
12
+ * one the kind's `get` asks by id — `can_view` on that row, with the
13
+ * `get` annotation's byte-pinned copy. `loadedTargetAsMethod(get)` is
14
+ * that resolver: it reads the row under TARGET_RESOURCE_KEY and asks the
15
+ * sibling `get` descriptor's annotation about its id, so the two lanes
16
+ * cannot drift (one annotation owns the permission and the copy; a
17
+ * `get` that is itself a skip makes the reference read a skip too).
18
+ * - a parent-gated create: the request names a parent (an agent to
19
+ * schedule, share, channel-bind or instantiate; a workflow to
20
+ * instantiate), the domain's resolve step loads and stashes it, and the
21
+ * question is the caller's standing on that parent (or on the row's
22
+ * organization), with the copy the lane has always answered.
23
+ *
24
+ * The step owns nothing but the position and the evaluation: a PURE
25
+ * resolver over the request context names the questions (kind, id,
26
+ * permission, copy), in the order the lane asks them; the first refusal
27
+ * answers. The evaluation is `authorizeTarget` (authorize.ts): allow
28
+ * proceeds, deny is PERMISSION_DENIED with the copy, not-found is NOT_FOUND
29
+ * as the load-first chain would answer, unavailable is INTERNAL, and the
30
+ * `internal` class alone is exempt — the annotation's skip arms do not
31
+ * apply, because the caller IS the enforcement the annotation opted out of.
32
+ *
33
+ * Two contracts a resolver keeps. It returns an EMPTY list only for an arm
34
+ * the lane has modelled as "nothing to ask" (a default instance the server
35
+ * composed for the run's human, whose access already follows the parent);
36
+ * an absent stash, a parent the chain guaranteed and did not deliver, is a
37
+ * chain invariant broken and the resolver THROWS, so a mis-ordered chain
38
+ * fails loudly instead of silently reopening the lane. And it names the
39
+ * questions in the anti-probing order: the organization's bar before the
40
+ * parent's where both are asked, so an outsider learns nothing about the
41
+ * parent's grants from which copy came back.
42
+ *
43
+ * Position: immediately after the step that loads what the resolver reads,
44
+ * before the duplicate check, before any engine or store side effect, and
45
+ * before any step whose refusal would reveal the loaded row (a same-org
46
+ * rule that names the parent's organization, an enrichment that reads the
47
+ * row's connections).
48
+ *
49
+ * The step's name is the shared vocabulary for every NEW lane. The lanes
50
+ * that carried a hand-written copy of this body before it existed keep
51
+ * their frozen names through `stepName` — the version ladder's own
52
+ * precedent (LoadSkillByReference and LoadPluginByReference are one
53
+ * factory) — because a step name is never renamed.
54
+ *
55
+ * Sibling: `AuthorizeRunTarget` runs the same evaluation over the record
56
+ * being built (`ctx.newState`) and carries the run-gate doctrine an
57
+ * edition's lane admission keys on; this step reads what the chain LOADED
58
+ * and carries no doctrine of its own.
59
+ */
60
+ import type { DescMessage, DescMethod, Message } from "@bufbuild/protobuf";
61
+
62
+ import type { ApiResourceReferenceSchema } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
63
+
64
+ import type { Authorizer } from "../../extensions/authorizer.js";
65
+ import type { PipelineStep } from "../pipeline.js";
66
+ import type { RequestContext } from "../request-context.js";
67
+ import { metadataOf } from "./shapes.js";
68
+ import { TARGET_RESOURCE_KEY } from "./load-target.js";
69
+ import {
70
+ authorizeTarget,
71
+ resolveAnnotatedCheck,
72
+ type AuthorizationTarget,
73
+ } from "./authorize.js";
74
+
75
+ /** The step's shared name; a folded lane passes its own frozen name instead. */
76
+ export const AUTHORIZE_RESOLVED_TARGET_STEP = "AuthorizeResolvedTarget";
77
+
78
+ /**
79
+ * Names the questions a lane asks, in order, over the request context after
80
+ * its chain has loaded the target. Pure: no store, no clock, no side effect.
81
+ * Empty means the lane has nothing to ask on this request; an invariant the
82
+ * chain broke (an absent stash) is a throw, never an empty list.
83
+ */
84
+ export type ResolvedTargetResolver<Desc extends DescMessage> = (
85
+ ctx: RequestContext<Desc>,
86
+ ) => ReadonlyArray<AuthorizationTarget>;
87
+
88
+ export function newAuthorizeResolvedTargetStep<Desc extends DescMessage>(
89
+ authorizer: Authorizer,
90
+ resolve: ResolvedTargetResolver<Desc>,
91
+ stepName: string = AUTHORIZE_RESOLVED_TARGET_STEP,
92
+ ): PipelineStep<Desc> {
93
+ return {
94
+ name: stepName,
95
+ async execute(ctx: RequestContext<Desc>): Promise<void> {
96
+ for (const target of resolve(ctx)) {
97
+ await authorizeTarget(authorizer, ctx.callerIdentity, target);
98
+ }
99
+ },
100
+ };
101
+ }
102
+
103
+ /** The request shape every `getByReference` lane runs on. */
104
+ export type GetByReferenceDesc = typeof ApiResourceReferenceSchema;
105
+
106
+ /**
107
+ * The reads' resolver: the row the loader stashed under TARGET_RESOURCE_KEY,
108
+ * authorized exactly as `get` would authorize it by id. The `get`
109
+ * descriptor's annotation supplies the kind, the permission and the copy;
110
+ * the loaded row's id is the target override (a reference has no `value`
111
+ * field for the annotation's path to read). A `get` that is public, skip
112
+ * or unannotated makes this a no-op — the reference read is never stricter
113
+ * than the read by id, and never laxer.
114
+ */
115
+ export function loadedTargetAsMethod(
116
+ get: DescMethod,
117
+ ): ResolvedTargetResolver<GetByReferenceDesc> {
118
+ return (ctx) => {
119
+ const loaded = ctx.get(TARGET_RESOURCE_KEY) as Message | undefined;
120
+ const id = loaded === undefined ? undefined : metadataOf(loaded)?.id;
121
+ if (id === undefined) {
122
+ throw new Error(
123
+ `${AUTHORIZE_RESOLVED_TARGET_STEP}: no loaded target with metadata under ${TARGET_RESOURCE_KEY}; the loader must run first`,
124
+ );
125
+ }
126
+ const target = resolveAnnotatedCheck(get, ctx.input, { resourceId: id });
127
+ return target === undefined ? [] : [target];
128
+ };
129
+ }
@@ -56,6 +56,14 @@
56
56
  * names no kind because the target is the loaded row's resource). The
57
57
  * annotation keeps owning the permission, the copy and the skip arms in
58
58
  * both shapes; only the target is the handler's.
59
+ *
60
+ * The annotation read itself is one pure function, `resolveAnnotatedCheck`,
61
+ * so a third entry shape needs no third copy of it: the resolved-target
62
+ * step (authorize-resolved-target.ts) authorizes a row a chain LOADED as
63
+ * a sibling method's annotation would — a read by reference asks exactly
64
+ * what its `get` asks, target override and all — and every lane whose
65
+ * position-1 annotation is a skip because the target is not in the request
66
+ * answers its question there, with the same four arms.
59
67
  */
60
68
  import { Code, ConnectError } from "@connectrpc/connect";
61
69
  import type { DescMethod, DescMessage, Message } from "@bufbuild/protobuf";
@@ -137,6 +145,49 @@ export interface AuthorizeTargetOverride {
137
145
  readonly resourceId: string;
138
146
  }
139
147
 
148
+ /**
149
+ * One question for the Authorizer together with the lane's deny copy: the
150
+ * unit `authorizeResolvedResource` consumes, whether the annotation named
151
+ * it (`resolveAnnotatedCheck`) or a chain's own resolver did (the run gate,
152
+ * the resolved-target step).
153
+ */
154
+ export interface AuthorizationTarget extends AuthzCheck {
155
+ readonly deniedMessage: string;
156
+ }
157
+
158
+ /**
159
+ * The annotation's answer for one method: the target it names for this
160
+ * request, or `undefined` when it names none — `is_public`,
161
+ * `is_skip_authorization`, or no config at all. Pure over the descriptor
162
+ * and the request; the `internal` exemption is the evaluation's, not the
163
+ * annotation's, so it is not applied here. Exported so a chain step can
164
+ * authorize a loaded row exactly as a SIBLING method's annotation would
165
+ * (a read by reference asks what its `get` asks) without a second copy of
166
+ * the skip arms or the field-path resolution.
167
+ */
168
+ export function resolveAnnotatedCheck(
169
+ method: DescMethod,
170
+ input: Message,
171
+ override?: AuthorizeTargetOverride,
172
+ ): AuthorizationTarget | undefined {
173
+ if (
174
+ getOption(method, is_public) ||
175
+ getOption(method, is_skip_authorization)
176
+ ) {
177
+ return undefined;
178
+ }
179
+ if (!hasOption(method, rpcAuthorizationConfig)) {
180
+ return undefined;
181
+ }
182
+ const config = getOption(method, rpcAuthorizationConfig);
183
+ return {
184
+ permission: config.permission,
185
+ resourceKind: override?.resourceKind ?? resolveResourceKind(input, config),
186
+ resourceId: override?.resourceId ?? resolveResourceId(input, config),
187
+ deniedMessage: config.errorMsg,
188
+ };
189
+ }
190
+
140
191
  /**
141
192
  * The Authorize evaluation for direct handlers: identical skip arms,
142
193
  * target resolution, and decision-to-wire mapping as the pipeline step
@@ -153,27 +204,33 @@ export async function authorizeDirect(
153
204
  if (identity.callerClass === "internal") {
154
205
  return;
155
206
  }
156
- if (
157
- getOption(method, is_public) ||
158
- getOption(method, is_skip_authorization)
159
- ) {
160
- return;
161
- }
162
- if (!hasOption(method, rpcAuthorizationConfig)) {
207
+ const target = resolveAnnotatedCheck(method, input, override);
208
+ if (target === undefined) {
163
209
  return;
164
210
  }
165
- const config = getOption(method, rpcAuthorizationConfig);
211
+ return authorizeTarget(authorizer, identity, target);
212
+ }
166
213
 
214
+ /**
215
+ * `authorizeResolvedResource` over an AuthorizationTarget: the check the
216
+ * Authorizer sees carries exactly the three fields of an AuthzCheck, never
217
+ * the copy, so a recording Authorizer (a test's, a driver's audit line)
218
+ * observes the question and nothing else.
219
+ */
220
+ export function authorizeTarget(
221
+ authorizer: Authorizer,
222
+ identity: CallerIdentity,
223
+ target: AuthorizationTarget,
224
+ ): Promise<void> {
167
225
  return authorizeResolvedResource(
168
226
  authorizer,
169
227
  identity,
170
228
  {
171
- permission: config.permission,
172
- resourceKind:
173
- override?.resourceKind ?? resolveResourceKind(input, config),
174
- resourceId: override?.resourceId ?? resolveResourceId(input, config),
229
+ permission: target.permission,
230
+ resourceKind: target.resourceKind,
231
+ resourceId: target.resourceId,
175
232
  },
176
- config.errorMsg,
233
+ target.deniedMessage,
177
234
  );
178
235
  }
179
236
 
@@ -37,6 +37,7 @@
37
37
  import type { DescMessage } from "@bufbuild/protobuf";
38
38
  import { Code, ConnectError } from "@connectrpc/connect";
39
39
 
40
+ import { isServerComposedRequest } from "../../extensions/identity.js";
40
41
  import type { PipelineStep } from "../pipeline.js";
41
42
  import type { RequestContext } from "../request-context.js";
42
43
  import type { RunnerCredentialProvider } from "../../runnerauth/runner-credential-provider.js";
@@ -61,7 +62,7 @@ export function newGuardMemoryCaptureStep<Desc extends DescMessage>(
61
62
  name: "GuardMemoryCapture",
62
63
  async execute(ctx: RequestContext<Desc>): Promise<void> {
63
64
  const caller = ctx.callerIdentity;
64
- if (caller.callerClass === "internal" || caller.origin === "in-process") {
65
+ if (isServerComposedRequest(caller)) {
65
66
  // Server-composed traversals are not capture requests from a
66
67
  // credential; the entry-point request already passed the gate.
67
68
  return;
@@ -55,6 +55,7 @@ import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/
55
55
  import { IamPermission } from "@stigmer/protos/ai/stigmer/iam/v1/enum_pb";
56
56
 
57
57
  import type { Authorizer } from "../../extensions/authorizer.js";
58
+ import { isServerComposedRequest } from "../../extensions/identity.js";
58
59
  import { internalError } from "../errors.js";
59
60
  import type { PipelineStep } from "../pipeline.js";
60
61
  import type { RequestContext } from "../request-context.js";
@@ -117,15 +118,11 @@ export function newGuardReservedLabelsStep<Desc extends DescMessage>(
117
118
  return {
118
119
  name: "GuardReservedLabels",
119
120
  async execute(ctx: RequestContext<Desc>): Promise<void> {
120
- if (
121
- ctx.callerIdentity.callerClass === "internal" ||
122
- ctx.callerIdentity.origin === "in-process"
123
- ) {
124
- // Server-composed request (the Java isInProcessCall arm,
125
- // cloud#386): the trust decision was made by the service code
126
- // that built it — default-instance factories stamp reserved
127
- // labels by design, even when the call propagates the user's
128
- // identity for attribution (ruling R5).
121
+ if (isServerComposedRequest(ctx.callerIdentity)) {
122
+ // The Java isInProcessCall arm (cloud#386): the trust decision was
123
+ // made by the service code that built the request — default-instance
124
+ // factories stamp reserved labels by design, even when the call
125
+ // propagates the user's identity for attribution (ruling R5).
129
126
  return;
130
127
  }
131
128
  const state = stateOf(ctx);
@@ -8,7 +8,6 @@ import type { DescMessage, MessageShape } from "@bufbuild/protobuf";
8
8
  import type { Timestamp } from "@bufbuild/protobuf/wkt";
9
9
 
10
10
  import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
11
- import { AuthorizationScopeType } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/authorization_config_pb";
12
11
 
13
12
  import type { Store } from "../../store/interface.js";
14
13
  import { getKindMeta } from "../apiresource-meta.js";
@@ -85,11 +84,15 @@ export async function findResourceByLabelAndOrg<Desc extends DescMessage>(
85
84
  }
86
85
 
87
86
  /**
88
- * Rejects a getByReference lookup that omits org for an org-scoped kind —
89
- * Go RequireOrgForReference. For AUTHORIZATION_SCOPE_TYPE_ORGANIZATION
90
- * kinds a slug is unique only WITHIN an org; resolving an org-less
91
- * reference globally would cross tenant boundaries. The message matches
92
- * the cloud edition verbatim (cross-edition error contract).
87
+ * Rejects a getByReference lookup that omits org — Go RequireOrgForReference,
88
+ * widened to every kind that has a reference lane. A slug is unique only
89
+ * WITHIN an org, so an org-less reference resolves globally and the first
90
+ * match wins: for an org-scoped kind that crosses tenant boundaries, and
91
+ * for an owner-only kind (the execution context) it let a caller name a
92
+ * slug and receive whichever organization's row matched first. Every kind
93
+ * with a reference lane is served per organization, so the rule is the
94
+ * same for all of them. The message matches the cloud edition verbatim
95
+ * (cross-edition error contract); the kind name comes from kind_meta.
93
96
  *
94
97
  * Belongs at the getByReference boundary only — the low-level slug finders
95
98
  * are legitimately called with a relative (possibly empty) org by internal
@@ -102,23 +105,16 @@ export function requireOrgForReference(
102
105
  if (org !== "") {
103
106
  return;
104
107
  }
105
- let scopeType: AuthorizationScopeType | undefined;
106
108
  let kindName: string;
107
109
  try {
108
- const meta = getKindMeta(kind);
109
- scopeType = meta.authorization?.scopeType;
110
- kindName = meta.name;
110
+ kindName = getKindMeta(kind).name;
111
111
  } catch (error) {
112
112
  throw internalError(
113
113
  error,
114
114
  "failed to resolve kind metadata for reference org check",
115
115
  );
116
116
  }
117
- // protobuf-es strips the shared enum prefix: proto
118
- // AUTHORIZATION_SCOPE_TYPE_ORGANIZATION generates as ORGANIZATION.
119
- if (scopeType === AuthorizationScopeType.ORGANIZATION) {
120
- throw invalidArgumentError(`org is required for ${kindName} lookup`);
121
- }
117
+ throw invalidArgumentError(`org is required for ${kindName} lookup`);
122
118
  }
123
119
 
124
120
  // The two list-step helpers below are duplicated per package in Go (each
@@ -31,6 +31,7 @@ import type { DescMessage, Message, MessageShape } from "@bufbuild/protobuf";
31
31
 
32
32
  import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
33
33
  import type { ApiResourceReferenceSchema } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
34
+ import { IamPermission } from "@stigmer/protos/ai/stigmer/iam/v1/enum_pb";
34
35
 
35
36
  import {
36
37
  internalError,
@@ -42,6 +43,7 @@ import type { RequestContext } from "../request-context.js";
42
43
  import { AuditNotFoundError } from "../../store/interface.js";
43
44
  import type { Store } from "../../store/interface.js";
44
45
  import { findResourceBySlug, requireOrgForReference } from "./helpers.js";
46
+ import type { ResolvedTargetResolver } from "./authorize-resolved-target.js";
45
47
  import { TARGET_RESOURCE_KEY } from "./load-target.js";
46
48
  import { metadataOf } from "./shapes.js";
47
49
 
@@ -192,6 +194,38 @@ export const LIST_VERSIONS_RESOURCE_ID_KEY = "listVersionsResourceId";
192
194
  export const LIST_VERSIONS_HEAD_HASH_KEY = "listVersionsHeadHash";
193
195
  export const LIST_VERSIONS_RESPONSE_KEY = "listVersionsResponse";
194
196
 
197
+ /**
198
+ * The ListVersions lanes' authorization question, for the
199
+ * AuthorizeResolvedTarget step placed after the slug resolver: `can_view`
200
+ * on the resolved head's id (the version history of a row is readable by
201
+ * whoever may read the row), with the lane's byte-pinned copy. The id key
202
+ * is the resolver's own — the shared resolver stashes under
203
+ * LIST_VERSIONS_RESOURCE_ID_KEY; a domain resolver with its own key names
204
+ * it. An id the chain did not stash is a broken invariant and throws.
205
+ */
206
+ export function versionHistoryTarget<Desc extends DescMessage>(
207
+ kind: ApiResourceKind,
208
+ deniedMessage: string,
209
+ idKey: string = LIST_VERSIONS_RESOURCE_ID_KEY,
210
+ ): ResolvedTargetResolver<Desc> {
211
+ return (ctx) => {
212
+ const resourceId = ctx.get(idKey);
213
+ if (typeof resourceId !== "string" || resourceId === "") {
214
+ throw new Error(
215
+ `ListVersions: no resolved resource id under ${idKey}; the slug resolver must run first`,
216
+ );
217
+ }
218
+ return [
219
+ {
220
+ permission: IamPermission.can_view,
221
+ resourceKind: kind,
222
+ resourceId,
223
+ deniedMessage,
224
+ },
225
+ ];
226
+ };
227
+ }
228
+
195
229
  /** The fields every ListVersions input carries; the binding reads them off its own message. */
196
230
  export interface ListVersionsInputShape {
197
231
  readonly org: string;