@kya-os/mcp-i-runtime 1.2.0 → 1.2.2

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,293 @@
1
+ /**
2
+ * Tests for auth-type-satisfies
3
+ *
4
+ * Covers the strict-normalized-equality decision (locked 2026-07-29) for the
5
+ * consent-approve auth-gate security fix:
6
+ * - the demonstrated bug case (a `none` delegation must not satisfy a typed
7
+ * requirement)
8
+ * - happy-path equality across all canonical types
9
+ * - deprecated-alias folding (`oauth` -> `oauth2`, `credential` ->
10
+ * `verifiable_credential`)
11
+ * - non-interchangeability of distinct typed requirements
12
+ * - nullish/fail-safe handling on both sides
13
+ * - a full cross-product table across all 10 canonical authorization types
14
+ * (`AUTHORIZATION_TYPES`, contracts/src/tool-protection/index.ts ~88-106),
15
+ * checked against an independently-defined normalization oracle (not the
16
+ * implementation under test) so the table isn't tautological.
17
+ */
18
+
19
+ import { describe, it, expect } from "vitest";
20
+ import {
21
+ authTypeSatisfies,
22
+ normalizeAuthType,
23
+ isUnsatisfiableAuthType,
24
+ MINTABLE_AUTH_TYPES,
25
+ } from "../auth-type-satisfies";
26
+
27
+ describe("normalizeAuthType", () => {
28
+ it("returns undefined for undefined", () => {
29
+ expect(normalizeAuthType(undefined)).toBeUndefined();
30
+ });
31
+
32
+ it("returns undefined for null", () => {
33
+ expect(normalizeAuthType(null)).toBeUndefined();
34
+ });
35
+
36
+ it("returns undefined for an empty/whitespace-only string", () => {
37
+ expect(normalizeAuthType("")).toBeUndefined();
38
+ expect(normalizeAuthType(" ")).toBeUndefined();
39
+ });
40
+
41
+ it("folds the deprecated 'oauth' alias to 'oauth2'", () => {
42
+ expect(normalizeAuthType("oauth")).toBe("oauth2");
43
+ });
44
+
45
+ it("folds the deprecated 'credential' alias to 'verifiable_credential'", () => {
46
+ expect(normalizeAuthType("credential")).toBe("verifiable_credential");
47
+ });
48
+
49
+ it("leaves canonical types unchanged", () => {
50
+ expect(normalizeAuthType("oauth2")).toBe("oauth2");
51
+ expect(normalizeAuthType("password")).toBe("password");
52
+ expect(normalizeAuthType("mdl")).toBe("mdl");
53
+ expect(normalizeAuthType("idv")).toBe("idv");
54
+ expect(normalizeAuthType("verifiable_credential")).toBe(
55
+ "verifiable_credential"
56
+ );
57
+ expect(normalizeAuthType("webauthn")).toBe("webauthn");
58
+ expect(normalizeAuthType("siwe")).toBe("siwe");
59
+ expect(normalizeAuthType("apikey")).toBe("apikey");
60
+ expect(normalizeAuthType("none")).toBe("none");
61
+ });
62
+
63
+ it("trims and lowercases defensively", () => {
64
+ expect(normalizeAuthType(" Password ")).toBe("password");
65
+ expect(normalizeAuthType("OAUTH")).toBe("oauth2");
66
+ });
67
+ });
68
+
69
+ describe("authTypeSatisfies", () => {
70
+ describe("the bug case: a 'none' delegation must not satisfy a typed requirement", () => {
71
+ it('("none", "password") -> false', () => {
72
+ expect(authTypeSatisfies("none", "password")).toBe(false);
73
+ });
74
+
75
+ it('("none", "oauth2") -> false', () => {
76
+ expect(authTypeSatisfies("none", "oauth2")).toBe(false);
77
+ });
78
+ });
79
+
80
+ describe("happy pairs (strict equality)", () => {
81
+ it('("password", "password") -> true', () => {
82
+ expect(authTypeSatisfies("password", "password")).toBe(true);
83
+ });
84
+
85
+ it('("oauth2", "oauth2") -> true', () => {
86
+ expect(authTypeSatisfies("oauth2", "oauth2")).toBe(true);
87
+ });
88
+
89
+ it('("none", "none") -> true', () => {
90
+ expect(authTypeSatisfies("none", "none")).toBe(true);
91
+ });
92
+
93
+ it('("apikey", "apikey") -> true', () => {
94
+ expect(authTypeSatisfies("apikey", "apikey")).toBe(true);
95
+ });
96
+
97
+ it('("mdl", "mdl") -> true', () => {
98
+ expect(authTypeSatisfies("mdl", "mdl")).toBe(true);
99
+ });
100
+
101
+ it('("idv", "idv") -> true', () => {
102
+ expect(authTypeSatisfies("idv", "idv")).toBe(true);
103
+ });
104
+
105
+ it('("webauthn", "webauthn") -> true', () => {
106
+ expect(authTypeSatisfies("webauthn", "webauthn")).toBe(true);
107
+ });
108
+
109
+ it('("siwe", "siwe") -> true', () => {
110
+ expect(authTypeSatisfies("siwe", "siwe")).toBe(true);
111
+ });
112
+
113
+ it('("verifiable_credential", "verifiable_credential") -> true', () => {
114
+ expect(
115
+ authTypeSatisfies("verifiable_credential", "verifiable_credential")
116
+ ).toBe(true);
117
+ });
118
+ });
119
+
120
+ describe("alias folding", () => {
121
+ it('("oauth", "oauth2") -> true', () => {
122
+ expect(authTypeSatisfies("oauth", "oauth2")).toBe(true);
123
+ });
124
+
125
+ it('("oauth2", "oauth") -> true', () => {
126
+ expect(authTypeSatisfies("oauth2", "oauth")).toBe(true);
127
+ });
128
+
129
+ it('("oauth", "oauth") -> true', () => {
130
+ expect(authTypeSatisfies("oauth", "oauth")).toBe(true);
131
+ });
132
+
133
+ it('("credential", "verifiable_credential") -> true', () => {
134
+ expect(authTypeSatisfies("credential", "verifiable_credential")).toBe(
135
+ true
136
+ );
137
+ });
138
+
139
+ it('("verifiable_credential", "credential") -> true', () => {
140
+ expect(authTypeSatisfies("verifiable_credential", "credential")).toBe(
141
+ true
142
+ );
143
+ });
144
+
145
+ it('("credential", "credential") -> true', () => {
146
+ expect(authTypeSatisfies("credential", "credential")).toBe(true);
147
+ });
148
+ });
149
+
150
+ describe("non-interchangeable types (no stronger-satisfies-weaker lattice)", () => {
151
+ it('("oauth2", "password") -> false', () => {
152
+ expect(authTypeSatisfies("oauth2", "password")).toBe(false);
153
+ });
154
+
155
+ it('("password", "oauth2") -> false', () => {
156
+ expect(authTypeSatisfies("password", "oauth2")).toBe(false);
157
+ });
158
+
159
+ it('("verifiable_credential", "password") -> false', () => {
160
+ expect(authTypeSatisfies("verifiable_credential", "password")).toBe(
161
+ false
162
+ );
163
+ });
164
+
165
+ it('("password", "none") -> false (typed delegation does not satisfy a none-gated tool either)', () => {
166
+ expect(authTypeSatisfies("password", "none")).toBe(false);
167
+ });
168
+
169
+ it('("apikey", "webauthn") -> false', () => {
170
+ expect(authTypeSatisfies("apikey", "webauthn")).toBe(false);
171
+ });
172
+ });
173
+
174
+ describe("nullish / fail-safe handling", () => {
175
+ it('(undefined, "password") -> false', () => {
176
+ expect(authTypeSatisfies(undefined, "password")).toBe(false);
177
+ });
178
+
179
+ it('(null, "password") -> false', () => {
180
+ expect(authTypeSatisfies(null, "password")).toBe(false);
181
+ });
182
+
183
+ it('("password", undefined) -> false (documented rule: no requirement is not auto-satisfied)', () => {
184
+ expect(authTypeSatisfies("password", undefined)).toBe(false);
185
+ });
186
+
187
+ it('("password", null) -> false', () => {
188
+ expect(authTypeSatisfies("password", null)).toBe(false);
189
+ });
190
+
191
+ it("(undefined, undefined) -> false", () => {
192
+ expect(authTypeSatisfies(undefined, undefined)).toBe(false);
193
+ });
194
+
195
+ it('("", "password") -> false (empty string normalizes to undefined)', () => {
196
+ expect(authTypeSatisfies("", "password")).toBe(false);
197
+ });
198
+
199
+ it('("none", undefined) -> false', () => {
200
+ expect(authTypeSatisfies("none", undefined)).toBe(false);
201
+ });
202
+ });
203
+
204
+ describe("full cross-product table across all 10 canonical types", () => {
205
+ // Independent normalization oracle (deliberately NOT importing
206
+ // normalizeAuthType) so this table verifies authTypeSatisfies's
207
+ // behavior rather than merely restating its own implementation.
208
+ const CANONICAL_NORMALIZED: Record<string, string> = {
209
+ oauth: "oauth2",
210
+ oauth2: "oauth2",
211
+ password: "password",
212
+ mdl: "mdl",
213
+ idv: "idv",
214
+ verifiable_credential: "verifiable_credential",
215
+ webauthn: "webauthn",
216
+ siwe: "siwe",
217
+ apikey: "apikey",
218
+ none: "none",
219
+ };
220
+
221
+ const ALL_TYPES = Object.keys(CANONICAL_NORMALIZED);
222
+
223
+ for (const delegationType of ALL_TYPES) {
224
+ for (const requiredType of ALL_TYPES) {
225
+ const expected =
226
+ CANONICAL_NORMALIZED[delegationType] ===
227
+ CANONICAL_NORMALIZED[requiredType];
228
+
229
+ it(`("${delegationType}", "${requiredType}") -> ${expected}`, () => {
230
+ expect(authTypeSatisfies(delegationType, requiredType)).toBe(
231
+ expected
232
+ );
233
+ });
234
+ }
235
+ }
236
+ });
237
+ });
238
+
239
+ describe("isUnsatisfiableAuthType", () => {
240
+ // Diagnostic predicate only — it must never influence an authorization
241
+ // decision. It exists so the enforcement gates can distinguish "re-auth
242
+ // fixes this" from "no mint can ever satisfy this, you are in a loop".
243
+
244
+ it("is false for the types a mint can actually produce", () => {
245
+ expect(isUnsatisfiableAuthType("password")).toBe(false);
246
+ expect(isUnsatisfiableAuthType("oauth2")).toBe(false);
247
+ expect(isUnsatisfiableAuthType("none")).toBe(false);
248
+ });
249
+
250
+ it("folds deprecated aliases before deciding", () => {
251
+ // `oauth` normalizes to `oauth2`, which IS mintable — so this must not be
252
+ // reported as unsatisfiable.
253
+ expect(isUnsatisfiableAuthType("oauth")).toBe(false);
254
+ // `credential` normalizes to `verifiable_credential`, which is NOT.
255
+ expect(isUnsatisfiableAuthType("credential")).toBe(true);
256
+ });
257
+
258
+ it("is true for declarable-but-never-minted types", () => {
259
+ for (const type of [
260
+ "mdl",
261
+ "idv",
262
+ "verifiable_credential",
263
+ "webauthn",
264
+ "siwe",
265
+ ]) {
266
+ expect(isUnsatisfiableAuthType(type)).toBe(true);
267
+ }
268
+ });
269
+
270
+ it("is true for apikey as a bare string, which is safe because api-key tools never reach this gate", () => {
271
+ // Documented explicitly so a future reader does not "fix" this: api-key
272
+ // tools are resolved by a separate vault branch that returns before the
273
+ // delegation gate, so the predicate is never consulted for them.
274
+ expect(isUnsatisfiableAuthType("apikey")).toBe(true);
275
+ });
276
+
277
+ it("is false for nullish/empty input — no requirement is not an unsatisfiable requirement", () => {
278
+ expect(isUnsatisfiableAuthType(undefined)).toBe(false);
279
+ expect(isUnsatisfiableAuthType(null)).toBe(false);
280
+ expect(isUnsatisfiableAuthType("")).toBe(false);
281
+ expect(isUnsatisfiableAuthType(" ")).toBe(false);
282
+ });
283
+
284
+ it("agrees with authTypeSatisfies: nothing mintable can satisfy an unsatisfiable requirement", () => {
285
+ // The property that makes the diagnostic true rather than a guess.
286
+ for (const required of ["mdl", "idv", "verifiable_credential", "webauthn", "siwe"]) {
287
+ expect(isUnsatisfiableAuthType(required)).toBe(true);
288
+ for (const minted of MINTABLE_AUTH_TYPES) {
289
+ expect(authTypeSatisfies(minted, required)).toBe(false);
290
+ }
291
+ }
292
+ });
293
+ });
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Tests for ToolContextBuilder — delegation auth-type enforcement (Task B3)
3
+ *
4
+ * Security fix: consent-approve auth-gate (2026-07-29). These tests cover the
5
+ * delegation-only fallback in `buildContext` (the OAuth path), asserting that a
6
+ * delegation only authorizes a tool when its OWN authorization type satisfies
7
+ * the tool's required type.
8
+ *
9
+ * They exercise the exact enforcement gap that the demonstrated exploit rode:
10
+ * an anonymous consent-only (`none`) delegation must NOT satisfy an
11
+ * OAuth-gated tool. A legacy stored record with no persisted authorization type
12
+ * (undefined) is likewise rejected (fail-safe → re-challenge).
13
+ *
14
+ * The gate is reached only when no IDP token is stored but a delegation IS
15
+ * present, so every case here mocks `resolveTokenDataFromDid` → null.
16
+ */
17
+
18
+ import { describe, it, expect, vi, beforeEach } from "vitest";
19
+ import { ToolContextBuilder } from "../tool-context-builder";
20
+ import type { IdpTokenResolver } from "../../identity/idp-token-resolver";
21
+ import type { OAuthConfigService } from "../oauth-config.service";
22
+ import type { ProviderResolver } from "../provider-resolver";
23
+ import type { ToolProtection } from "../../types/tool-protection";
24
+ import { OAuthRequiredError } from "../../types/oauth-required-error";
25
+
26
+ describe("ToolContextBuilder — delegation auth-type enforcement (B3)", () => {
27
+ let mockTokenResolver: IdpTokenResolver;
28
+ let mockConfigService: OAuthConfigService;
29
+ let mockProviderResolver: ProviderResolver;
30
+ let builder: ToolContextBuilder;
31
+
32
+ // OAuth-gated tool: resolveProvider is mocked, so the concrete provider is
33
+ // irrelevant — only the required authorization.type drives the gate.
34
+ const oauthTool: ToolProtection = {
35
+ requiresDelegation: true,
36
+ requiredScopes: ["read:user"],
37
+ authorization: { type: "oauth2", provider: "github" },
38
+ };
39
+
40
+ // Legacy OAuth tool: no explicit authorization.type, provider resolved from
41
+ // the deprecated oauthProvider field. The gate falls back to "oauth2".
42
+ const legacyOauthTool: ToolProtection = {
43
+ requiresDelegation: true,
44
+ requiredScopes: ["read:user"],
45
+ oauthProvider: "github",
46
+ };
47
+
48
+ beforeEach(() => {
49
+ mockTokenResolver = {
50
+ // No stored IDP token → force the delegation-only fallback path.
51
+ resolveTokenDataFromDid: vi.fn().mockResolvedValue(null),
52
+ } as unknown as IdpTokenResolver;
53
+
54
+ mockConfigService = {
55
+ getOAuthConfig: vi.fn(),
56
+ } as unknown as OAuthConfigService;
57
+
58
+ mockProviderResolver = {
59
+ resolveProvider: vi.fn().mockResolvedValue("github"),
60
+ } as unknown as ProviderResolver;
61
+
62
+ builder = new ToolContextBuilder({
63
+ tokenResolver: mockTokenResolver,
64
+ configService: mockConfigService,
65
+ providerResolver: mockProviderResolver,
66
+ projectId: "proj-123",
67
+ });
68
+ });
69
+
70
+ it("REJECTS a `none`-type delegation for an oauth-gated tool (the exploit)", async () => {
71
+ await expect(
72
+ builder.buildContext(
73
+ "gated-tool",
74
+ "did:key:z6MkUser",
75
+ "session-123",
76
+ "delegation-token-anon",
77
+ oauthTool,
78
+ "none" // anonymous consent-only delegation
79
+ )
80
+ ).rejects.toThrow(OAuthRequiredError);
81
+ });
82
+
83
+ it("REJECTS a `password`-type delegation for an oauth-gated tool (cross-type)", async () => {
84
+ await expect(
85
+ builder.buildContext(
86
+ "gated-tool",
87
+ "did:key:z6MkUser",
88
+ "session-123",
89
+ "delegation-token-pw",
90
+ oauthTool,
91
+ "password"
92
+ )
93
+ ).rejects.toThrow(OAuthRequiredError);
94
+ });
95
+
96
+ it("REJECTS an undefined-type (legacy record) delegation for a typed tool", async () => {
97
+ await expect(
98
+ builder.buildContext(
99
+ "gated-tool",
100
+ "did:key:z6MkUser",
101
+ "session-123",
102
+ "delegation-token-legacy",
103
+ oauthTool,
104
+ undefined // predates persisting authorizationType → fail-safe
105
+ )
106
+ ).rejects.toThrow(OAuthRequiredError);
107
+ });
108
+
109
+ it("ACCEPTS an `oauth2`-type delegation for an oauth2-gated tool (happy path)", async () => {
110
+ const result = await builder.buildContext(
111
+ "gated-tool",
112
+ "did:key:z6MkUser",
113
+ "session-123",
114
+ "delegation-token-oauth",
115
+ oauthTool,
116
+ "oauth2"
117
+ );
118
+
119
+ expect(result).toBeDefined();
120
+ expect(result!.delegationToken).toBe("delegation-token-oauth");
121
+ expect(result!.provider).toBe("github");
122
+ expect(result!.userDid).toBe("did:key:z6MkUser");
123
+ });
124
+
125
+ it("ACCEPTS an `oauth` (deprecated alias) delegation for an oauth2-gated tool", async () => {
126
+ const result = await builder.buildContext(
127
+ "gated-tool",
128
+ "did:key:z6MkUser",
129
+ "session-123",
130
+ "delegation-token-oauth-alias",
131
+ oauthTool,
132
+ "oauth" // normalizes to oauth2
133
+ );
134
+
135
+ expect(result).toBeDefined();
136
+ expect(result!.delegationToken).toBe("delegation-token-oauth-alias");
137
+ });
138
+
139
+ it("ACCEPTS an `oauth2` delegation for a legacy oauthProvider-only tool (fallback)", async () => {
140
+ // authorization.type is absent → gate falls back to "oauth2"; a genuine
141
+ // OAuth delegation must still authorize such tools (no regression).
142
+ const result = await builder.buildContext(
143
+ "gated-tool",
144
+ "did:key:z6MkUser",
145
+ "session-123",
146
+ "delegation-token-oauth",
147
+ legacyOauthTool,
148
+ "oauth2"
149
+ );
150
+
151
+ expect(result).toBeDefined();
152
+ expect(result!.delegationToken).toBe("delegation-token-oauth");
153
+ });
154
+
155
+ it("REJECTS a `none` delegation for a legacy oauthProvider-only tool", async () => {
156
+ await expect(
157
+ builder.buildContext(
158
+ "gated-tool",
159
+ "did:key:z6MkUser",
160
+ "session-123",
161
+ "delegation-token-anon",
162
+ legacyOauthTool,
163
+ "none"
164
+ )
165
+ ).rejects.toThrow(OAuthRequiredError);
166
+ });
167
+
168
+ describe("unsatisfiable-requirement diagnostic", () => {
169
+ // A tool whose required type no mint can produce re-challenges forever.
170
+ // The gate cannot fix that (strict equality is the locked decision), but it
171
+ // must SAY so — otherwise the operator sees an inexplicable auth loop.
172
+
173
+ const mdlTool: ToolProtection = {
174
+ requiresDelegation: true,
175
+ requiredScopes: ["read:user"],
176
+ authorization: { type: "mdl" } as ToolProtection["authorization"],
177
+ };
178
+
179
+ function buildWithLogger(logger: (msg: string, data?: unknown) => void) {
180
+ return new ToolContextBuilder({
181
+ tokenResolver: mockTokenResolver,
182
+ configService: mockConfigService,
183
+ providerResolver: mockProviderResolver,
184
+ projectId: "proj-123",
185
+ logger,
186
+ });
187
+ }
188
+
189
+ it("logs a MISCONFIGURATION line when the required type can never be minted", async () => {
190
+ const lines: string[] = [];
191
+ const builderWithLog = buildWithLogger((msg) => lines.push(msg));
192
+
193
+ await expect(
194
+ builderWithLog.buildContext(
195
+ "gated-tool",
196
+ "did:key:z6MkUser",
197
+ "session-123",
198
+ "delegation-token-oauth",
199
+ mdlTool,
200
+ "oauth2"
201
+ )
202
+ ).rejects.toThrow(OAuthRequiredError);
203
+
204
+ expect(lines.some((l) => l.includes("MISCONFIGURATION"))).toBe(true);
205
+ });
206
+
207
+ it("does NOT log it for an ordinary mismatch that re-authenticating can fix", async () => {
208
+ const lines: string[] = [];
209
+ const builderWithLog = buildWithLogger((msg) => lines.push(msg));
210
+
211
+ // oauth2-gated tool presented a `none` delegation: a real mismatch, but
212
+ // the user CAN resolve it by authenticating via OAuth.
213
+ await expect(
214
+ builderWithLog.buildContext(
215
+ "gated-tool",
216
+ "did:key:z6MkUser",
217
+ "session-123",
218
+ "delegation-token-anon",
219
+ oauthTool,
220
+ "none"
221
+ )
222
+ ).rejects.toThrow(OAuthRequiredError);
223
+
224
+ expect(lines.some((l) => l.includes("MISCONFIGURATION"))).toBe(false);
225
+ });
226
+
227
+ it("still REJECTS — the diagnostic must not relax the decision", async () => {
228
+ // Guards against a future "unsatisfiable, so let it through" "fix",
229
+ // which would reopen the bypass the gate exists to close.
230
+ await expect(
231
+ buildWithLogger(() => {}).buildContext(
232
+ "gated-tool",
233
+ "did:key:z6MkUser",
234
+ "session-123",
235
+ "delegation-token-oauth",
236
+ mdlTool,
237
+ "oauth2"
238
+ )
239
+ ).rejects.toThrow(OAuthRequiredError);
240
+ });
241
+ });
242
+ });