@kya-os/mcp-i-runtime 1.2.2 → 1.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/proof/generator.d.ts +7 -1
- package/dist/proof/generator.d.ts.map +1 -1
- package/dist/proof/generator.js +10 -1
- package/dist/proof/generator.js.map +1 -1
- package/dist/runtime/base.d.ts +3 -0
- package/dist/runtime/base.d.ts.map +1 -1
- package/dist/runtime/base.js +12 -4
- package/dist/runtime/base.js.map +1 -1
- package/dist/services/proof-verifier.d.ts +29 -12
- package/dist/services/proof-verifier.d.ts.map +1 -1
- package/dist/services/proof-verifier.js +50 -17
- package/dist/services/proof-verifier.js.map +1 -1
- package/package.json +4 -4
- package/src/__tests__/runtime/native-holder-enforcement.test.ts +107 -0
- package/src/__tests__/runtime/tool-protection-enforcement.test.ts +19 -36
- package/src/__tests__/utils/tool-protection-runtime.ts +25 -0
- package/src/proof/__tests__/proof-generator.test.ts +65 -0
- package/src/proof/generator.ts +12 -1
- package/src/runtime/base.ts +18 -4
- package/src/services/__tests__/proof-verifier.test.ts +182 -0
- package/src/services/__tests__/storage.service.test.ts +21 -16
- package/src/services/proof-verifier.ts +52 -17
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kya-os/mcp-i-runtime",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.5",
|
|
4
4
|
"description": "Shared product-runtime layer for the MCP-I framework (Node + Cloudflare adapters). Protocol types/values live in @kya-os/mcp (DIF).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Dylan Hobbs",
|
|
@@ -59,10 +59,10 @@
|
|
|
59
59
|
"prepublishOnly": "npm run build && node ../create-mcpi-app/scripts/validate-no-workspace.js"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@kya-os/contracts": "^1.
|
|
63
|
-
"@kya-os/mcp": "1.
|
|
62
|
+
"@kya-os/contracts": "^1.12.1",
|
|
63
|
+
"@kya-os/mcp": "1.15.0",
|
|
64
64
|
"jose": "^5.6.3",
|
|
65
|
-
"json-canonicalize": "
|
|
65
|
+
"json-canonicalize": "2.0.0",
|
|
66
66
|
"zod": "^3.25.67"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, vi } from "vitest";
|
|
2
|
+
import type { MCPIRuntimeBase } from "../../runtime/base";
|
|
3
|
+
import { createToolProtectionRuntime } from "../utils/tool-protection-runtime";
|
|
4
|
+
import { DelegationRequiredError } from "../../types/tool-protection";
|
|
5
|
+
|
|
6
|
+
describe("native holder tool enforcement", () => {
|
|
7
|
+
let runtime: MCPIRuntimeBase;
|
|
8
|
+
let mockToolProtectionService: {
|
|
9
|
+
checkToolProtection: ReturnType<typeof vi.fn>;
|
|
10
|
+
};
|
|
11
|
+
let mockAccessControlService: { verifyDelegation: ReturnType<typeof vi.fn> };
|
|
12
|
+
const mockHandler = vi.fn().mockResolvedValue({ result: "success" });
|
|
13
|
+
const session = {
|
|
14
|
+
id: "session123",
|
|
15
|
+
audience: "https://client.example.com",
|
|
16
|
+
nonce: "test-nonce",
|
|
17
|
+
};
|
|
18
|
+
beforeEach(async () => {
|
|
19
|
+
vi.clearAllMocks();
|
|
20
|
+
({ runtime, mockToolProtectionService, mockAccessControlService } =
|
|
21
|
+
await createToolProtectionRuntime());
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it.each([true, false])(
|
|
25
|
+
"uses the proved invoker and rejects a foreign verified grant (matching=%s)",
|
|
26
|
+
async (matching) => {
|
|
27
|
+
mockToolProtectionService.checkToolProtection.mockResolvedValue({
|
|
28
|
+
requiresDelegation: true,
|
|
29
|
+
requiredScopes: ["files:write"],
|
|
30
|
+
});
|
|
31
|
+
const holder = "did:web:native-agent.example";
|
|
32
|
+
mockAccessControlService.verifyDelegation.mockResolvedValue({
|
|
33
|
+
success: true,
|
|
34
|
+
data: {
|
|
35
|
+
valid: true,
|
|
36
|
+
credential: {
|
|
37
|
+
agent_did: matching ? holder : "did:key:zmock123",
|
|
38
|
+
scopes: ["files:write"],
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
const call = runtime.processToolCall("protectedTool", {}, mockHandler, {
|
|
43
|
+
...session,
|
|
44
|
+
agentDid: holder,
|
|
45
|
+
verifiedInvokerDid: holder,
|
|
46
|
+
delegationToken: "delegation-for-native-holder",
|
|
47
|
+
});
|
|
48
|
+
if (matching) {
|
|
49
|
+
await expect(call).resolves.toEqual({ result: "success" });
|
|
50
|
+
expect(mockHandler).toHaveBeenCalledTimes(1);
|
|
51
|
+
} else {
|
|
52
|
+
await expect(call).rejects.toThrow(DelegationRequiredError);
|
|
53
|
+
expect(mockHandler).not.toHaveBeenCalled();
|
|
54
|
+
}
|
|
55
|
+
expect(mockAccessControlService.verifyDelegation).toHaveBeenCalledWith(
|
|
56
|
+
expect.objectContaining({ agent_did: holder }),
|
|
57
|
+
expect.any(Object)
|
|
58
|
+
);
|
|
59
|
+
// Configuration belongs to the serving deployment, while authority names
|
|
60
|
+
// the invoker. Response signing must still use the serving identity.
|
|
61
|
+
expect(
|
|
62
|
+
mockToolProtectionService.checkToolProtection
|
|
63
|
+
).toHaveBeenCalledWith("protectedTool", "did:key:zmock123");
|
|
64
|
+
expect((await runtime.getIdentity()).did).toBe("did:key:zmock123");
|
|
65
|
+
}
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
it("does not promote a handshake agent label to a proved invoker", async () => {
|
|
69
|
+
mockToolProtectionService.checkToolProtection.mockResolvedValue({
|
|
70
|
+
requiresDelegation: true,
|
|
71
|
+
requiredScopes: ["files:write"],
|
|
72
|
+
});
|
|
73
|
+
mockAccessControlService.verifyDelegation.mockResolvedValue({
|
|
74
|
+
success: true,
|
|
75
|
+
data: { valid: true },
|
|
76
|
+
});
|
|
77
|
+
await runtime.processToolCall("protectedTool", {}, mockHandler, {
|
|
78
|
+
...session,
|
|
79
|
+
agentDid: "did:web:unproved.example",
|
|
80
|
+
delegationToken: "runtime-grant",
|
|
81
|
+
});
|
|
82
|
+
expect(mockAccessControlService.verifyDelegation).toHaveBeenCalledWith(
|
|
83
|
+
expect.objectContaining({ agent_did: "did:key:zmock123" }),
|
|
84
|
+
expect.any(Object)
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("keeps the proved holder in the existing consent challenge when authority is missing", async () => {
|
|
89
|
+
mockToolProtectionService.checkToolProtection.mockResolvedValue({
|
|
90
|
+
requiresDelegation: true,
|
|
91
|
+
requiredScopes: ["files:write"],
|
|
92
|
+
});
|
|
93
|
+
const holder = "did:web:native-agent.example";
|
|
94
|
+
const failure = await runtime
|
|
95
|
+
.processToolCall("protectedTool", {}, mockHandler, {
|
|
96
|
+
...session,
|
|
97
|
+
agentDid: holder,
|
|
98
|
+
verifiedInvokerDid: holder,
|
|
99
|
+
})
|
|
100
|
+
.catch((error: unknown) => error);
|
|
101
|
+
expect(failure).toBeInstanceOf(DelegationRequiredError);
|
|
102
|
+
const url = new URL((failure as DelegationRequiredError).consentUrl!);
|
|
103
|
+
expect(url.searchParams.get("agent_did")).toBe(holder);
|
|
104
|
+
expect(url.searchParams.get("scopes")).toBe("files:write");
|
|
105
|
+
expect(mockHandler).not.toHaveBeenCalled();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -7,14 +7,13 @@
|
|
|
7
7
|
import { describe, it, expect, beforeEach, vi } from "vitest";
|
|
8
8
|
import { MCPIRuntimeBase } from "../../runtime/base";
|
|
9
9
|
import { ProviderRuntimeConfig } from "../../config";
|
|
10
|
-
import {
|
|
10
|
+
import { createToolProtectionRuntime } from "../utils/tool-protection-runtime";
|
|
11
11
|
import { DelegationRequiredError } from "../../types/tool-protection";
|
|
12
12
|
import type { VerifyDelegationAPIResponse } from "@kya-os/contracts/agentshield-api";
|
|
13
13
|
|
|
14
14
|
describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
|
|
15
15
|
let runtime: MCPIRuntimeBase;
|
|
16
16
|
let config: ProviderRuntimeConfig;
|
|
17
|
-
let mockProviders: ReturnType<typeof createMockProviders>;
|
|
18
17
|
let mockToolProtectionService: {
|
|
19
18
|
checkToolProtection: ReturnType<typeof vi.fn>;
|
|
20
19
|
};
|
|
@@ -24,31 +23,8 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
|
|
|
24
23
|
|
|
25
24
|
beforeEach(async () => {
|
|
26
25
|
vi.clearAllMocks();
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
// Create mock tool protection service
|
|
30
|
-
mockToolProtectionService = {
|
|
31
|
-
checkToolProtection: vi.fn(),
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
// Create mock access control service
|
|
35
|
-
mockAccessControlService = {
|
|
36
|
-
verifyDelegation: vi.fn(),
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
config = {
|
|
40
|
-
...mockProviders,
|
|
41
|
-
environment: "development",
|
|
42
|
-
session: {
|
|
43
|
-
timestampSkewSeconds: 120,
|
|
44
|
-
ttlMinutes: 30,
|
|
45
|
-
},
|
|
46
|
-
toolProtectionService: mockToolProtectionService as any,
|
|
47
|
-
};
|
|
48
|
-
runtime = new MCPIRuntimeBase(config);
|
|
49
|
-
// Inject mock access control service
|
|
50
|
-
(runtime as any).accessControlService = mockAccessControlService as any;
|
|
51
|
-
await runtime.initialize();
|
|
26
|
+
({ runtime, config, mockToolProtectionService, mockAccessControlService } =
|
|
27
|
+
await createToolProtectionRuntime());
|
|
52
28
|
});
|
|
53
29
|
|
|
54
30
|
describe("processToolCall with tool protection", () => {
|
|
@@ -315,12 +291,14 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
|
|
|
315
291
|
delegationToken: "valid-delegation-token",
|
|
316
292
|
};
|
|
317
293
|
|
|
318
|
-
await expect(
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
294
|
+
await expect(
|
|
295
|
+
runtime.processToolCall(
|
|
296
|
+
"protectedTool",
|
|
297
|
+
{ arg: "value" },
|
|
298
|
+
mockHandler,
|
|
299
|
+
sessionWithDelegation
|
|
300
|
+
)
|
|
301
|
+
).rejects.toThrow(DelegationRequiredError);
|
|
324
302
|
|
|
325
303
|
expect(mockHandler).not.toHaveBeenCalled();
|
|
326
304
|
});
|
|
@@ -577,7 +555,8 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
|
|
|
577
555
|
);
|
|
578
556
|
|
|
579
557
|
// Verify that user_did was NOT included (backward compatibility)
|
|
580
|
-
const verifyCall =
|
|
558
|
+
const verifyCall =
|
|
559
|
+
mockAccessControlService.verifyDelegation.mock.calls[0][0];
|
|
581
560
|
expect(verifyCall.user_did).toBeUndefined();
|
|
582
561
|
});
|
|
583
562
|
});
|
|
@@ -751,7 +730,9 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
|
|
|
751
730
|
|
|
752
731
|
it("should label tool execution as a diagnostic", async () => {
|
|
753
732
|
mockToolProtectionService.checkToolProtection.mockResolvedValue(null);
|
|
754
|
-
const diagnostic = vi
|
|
733
|
+
const diagnostic = vi
|
|
734
|
+
.spyOn(console, "error")
|
|
735
|
+
.mockImplementation(() => {});
|
|
755
736
|
|
|
756
737
|
await runtime.processToolCall(
|
|
757
738
|
"testTool",
|
|
@@ -803,7 +784,9 @@ describe("MCPIRuntimeBase - Tool Protection Enforcement", () => {
|
|
|
803
784
|
});
|
|
804
785
|
|
|
805
786
|
it("should suppress diagnostic tool output in production", async () => {
|
|
806
|
-
const diagnostic = vi
|
|
787
|
+
const diagnostic = vi
|
|
788
|
+
.spyOn(console, "error")
|
|
789
|
+
.mockImplementation(() => {});
|
|
807
790
|
const productionConfig = {
|
|
808
791
|
...config,
|
|
809
792
|
environment: "production" as const,
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { vi } from "vitest";
|
|
2
|
+
import { MCPIRuntimeBase } from "../../runtime/base";
|
|
3
|
+
import type { ProviderRuntimeConfig } from "../../config";
|
|
4
|
+
import { createMockProviders } from "./mock-providers";
|
|
5
|
+
|
|
6
|
+
/** Shared initialized runtime for delegation enforcement tests. */
|
|
7
|
+
export async function createToolProtectionRuntime() {
|
|
8
|
+
const mockToolProtectionService = { checkToolProtection: vi.fn() };
|
|
9
|
+
const mockAccessControlService = { verifyDelegation: vi.fn() };
|
|
10
|
+
const config: ProviderRuntimeConfig = {
|
|
11
|
+
...createMockProviders(),
|
|
12
|
+
environment: "development",
|
|
13
|
+
session: { timestampSkewSeconds: 120, ttlMinutes: 30 },
|
|
14
|
+
toolProtectionService: mockToolProtectionService as any,
|
|
15
|
+
};
|
|
16
|
+
const runtime = new MCPIRuntimeBase(config);
|
|
17
|
+
(runtime as any).accessControlService = mockAccessControlService;
|
|
18
|
+
await runtime.initialize();
|
|
19
|
+
return {
|
|
20
|
+
runtime,
|
|
21
|
+
config,
|
|
22
|
+
mockToolProtectionService,
|
|
23
|
+
mockAccessControlService,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -272,6 +272,71 @@ describe("ProofGenerator", () => {
|
|
|
272
272
|
|
|
273
273
|
expect(payload.clientDid).toBe("did:key:zClientPayload");
|
|
274
274
|
});
|
|
275
|
+
|
|
276
|
+
it("encodes did, kid, and audience as literal payload fields, since verifiers check those exact property names, not the JWT-standard sub/iss/aud aliases", async () => {
|
|
277
|
+
const request: ToolRequest = {
|
|
278
|
+
method: "test-tool",
|
|
279
|
+
params: { input: "hello" },
|
|
280
|
+
};
|
|
281
|
+
const response: ToolResponse = { data: { output: "world" } };
|
|
282
|
+
|
|
283
|
+
const proof = await proofGenerator.generateProof(
|
|
284
|
+
request,
|
|
285
|
+
response,
|
|
286
|
+
mockSession
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
const payload = JSON.parse(
|
|
290
|
+
Buffer.from(proof.jws.split(".")[1], "base64url").toString()
|
|
291
|
+
) as { did?: string; kid?: string; audience?: string };
|
|
292
|
+
|
|
293
|
+
expect(payload.did).toBe(mockIdentity.did);
|
|
294
|
+
expect(payload.kid).toBe(mockIdentity.kid);
|
|
295
|
+
expect(payload.audience).toBe(mockSession.audience);
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
it("omits toolName and outcome from the JWS payload when not provided", async () => {
|
|
299
|
+
const request: ToolRequest = {
|
|
300
|
+
method: "test-tool",
|
|
301
|
+
params: { input: "hello" },
|
|
302
|
+
};
|
|
303
|
+
const response: ToolResponse = { data: { output: "world" } };
|
|
304
|
+
|
|
305
|
+
const proof = await proofGenerator.generateProof(
|
|
306
|
+
request,
|
|
307
|
+
response,
|
|
308
|
+
mockSession
|
|
309
|
+
);
|
|
310
|
+
|
|
311
|
+
const payload = JSON.parse(
|
|
312
|
+
Buffer.from(proof.jws.split(".")[1], "base64url").toString()
|
|
313
|
+
) as Record<string, unknown>;
|
|
314
|
+
|
|
315
|
+
expect(payload).not.toHaveProperty("toolName");
|
|
316
|
+
expect(payload).not.toHaveProperty("outcome");
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it("encodes toolName as a literal payload field, and renames submissionOutcome to the literal payload key outcome, since know-that-ai's verifier checks those exact property names", async () => {
|
|
320
|
+
const request: ToolRequest = {
|
|
321
|
+
method: "test-tool",
|
|
322
|
+
params: { input: "hello" },
|
|
323
|
+
};
|
|
324
|
+
const response: ToolResponse = { data: { output: "world" } };
|
|
325
|
+
|
|
326
|
+
const proof = await proofGenerator.generateProof(
|
|
327
|
+
request,
|
|
328
|
+
response,
|
|
329
|
+
mockSession,
|
|
330
|
+
{ toolName: "get_weather", submissionOutcome: "success" }
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
const payload = JSON.parse(
|
|
334
|
+
Buffer.from(proof.jws.split(".")[1], "base64url").toString()
|
|
335
|
+
) as { toolName?: string; outcome?: string };
|
|
336
|
+
|
|
337
|
+
expect(payload.toolName).toBe("get_weather");
|
|
338
|
+
expect(payload.outcome).toBe("success");
|
|
339
|
+
});
|
|
275
340
|
});
|
|
276
341
|
|
|
277
342
|
describe("Proof Verification", () => {
|
package/src/proof/generator.ts
CHANGED
|
@@ -57,6 +57,8 @@ export interface ProofOptions {
|
|
|
57
57
|
scopeId?: string;
|
|
58
58
|
delegationRef?: string;
|
|
59
59
|
clientDid?: string;
|
|
60
|
+
toolName?: string;
|
|
61
|
+
submissionOutcome?: "success" | "failure" | "denied";
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
/**
|
|
@@ -144,7 +146,11 @@ export class ProofGenerator {
|
|
|
144
146
|
* Generate Ed25519 JWS in compact format (header.payload.signature).
|
|
145
147
|
* Requirement: 5.3
|
|
146
148
|
*
|
|
147
|
-
*
|
|
149
|
+
* Includes both the JWT-standard claims (aud, sub, iss) and the literal
|
|
150
|
+
* did/kid/audience field names verifiers check for -- a verifier that
|
|
151
|
+
* compares payload fields against proof metadata by exact property name
|
|
152
|
+
* (did, kid, nonce, ts, audience) would otherwise see them all as
|
|
153
|
+
* undefined, since none of the JWT-standard aliases match those names.
|
|
148
154
|
*/
|
|
149
155
|
private async generateJWS(meta: ProofMeta): Promise<string> {
|
|
150
156
|
try {
|
|
@@ -155,6 +161,9 @@ export class ProofGenerator {
|
|
|
155
161
|
aud: meta.audience,
|
|
156
162
|
sub: meta.did,
|
|
157
163
|
iss: meta.did,
|
|
164
|
+
did: meta.did,
|
|
165
|
+
kid: this.identity.kid,
|
|
166
|
+
audience: meta.audience,
|
|
158
167
|
requestHash: meta.requestHash,
|
|
159
168
|
responseHash: meta.responseHash,
|
|
160
169
|
ts: meta.ts,
|
|
@@ -163,6 +172,8 @@ export class ProofGenerator {
|
|
|
163
172
|
...(meta.scopeId && { scopeId: meta.scopeId }),
|
|
164
173
|
...(meta.delegationRef && { delegationRef: meta.delegationRef }),
|
|
165
174
|
...(meta.clientDid && { clientDid: meta.clientDid }),
|
|
175
|
+
...(meta.toolName && { toolName: meta.toolName }),
|
|
176
|
+
...(meta.submissionOutcome && { outcome: meta.submissionOutcome }),
|
|
166
177
|
};
|
|
167
178
|
|
|
168
179
|
const jwt = await new SignJWT(payload)
|
package/src/runtime/base.ts
CHANGED
|
@@ -98,6 +98,9 @@ interface RuntimeSessionContext {
|
|
|
98
98
|
clientDid?: string;
|
|
99
99
|
userDid?: string;
|
|
100
100
|
agentDid?: string;
|
|
101
|
+
/** Trusted adapter fact from verification of THIS request's holder proof.
|
|
102
|
+
* Never populate from JSON params, decoded credentials, or handshake labels. */
|
|
103
|
+
verifiedInvokerDid?: string;
|
|
101
104
|
serverDid?: string;
|
|
102
105
|
nonce?: string;
|
|
103
106
|
delegationToken?: string;
|
|
@@ -715,7 +718,7 @@ export class MCPIRuntimeBase {
|
|
|
715
718
|
|
|
716
719
|
// Build verification request
|
|
717
720
|
const verifyRequest: VerifyDelegationRequest = {
|
|
718
|
-
agent_did: identity.did,
|
|
721
|
+
agent_did: session?.verifiedInvokerDid ?? identity.did,
|
|
719
722
|
scopes: protection.requiredScopes,
|
|
720
723
|
};
|
|
721
724
|
|
|
@@ -760,11 +763,22 @@ export class MCPIRuntimeBase {
|
|
|
760
763
|
credentialJwt: consentProof || undefined,
|
|
761
764
|
});
|
|
762
765
|
|
|
763
|
-
//
|
|
764
|
-
|
|
766
|
+
// A native admission binds this exact request to a holder. Recheck
|
|
767
|
+
// the returned authority rather than accepting a valid response for
|
|
768
|
+
// another principal or a weaker scope set from a stale adapter.
|
|
769
|
+
const nativeBindingMismatch =
|
|
770
|
+
session?.verifiedInvokerDid !== undefined &&
|
|
771
|
+
(verificationResult.data.credential?.agent_did !==
|
|
772
|
+
session.verifiedInvokerDid ||
|
|
773
|
+
!protection.requiredScopes.every((scope) =>
|
|
774
|
+
verificationResult.data.credential?.scopes?.includes(scope)
|
|
775
|
+
));
|
|
776
|
+
if (!verificationResult.data.valid || nativeBindingMismatch) {
|
|
765
777
|
// Delegation verification failed
|
|
766
778
|
const reason =
|
|
767
|
-
|
|
779
|
+
(nativeBindingMismatch
|
|
780
|
+
? "Native holder or scope binding mismatch"
|
|
781
|
+
: verificationResult.data.reason) ||
|
|
768
782
|
"Delegation token invalid or expired";
|
|
769
783
|
const errorDetails = verificationResult.data.error;
|
|
770
784
|
|
|
@@ -22,6 +22,10 @@ import {
|
|
|
22
22
|
ProofVerificationError,
|
|
23
23
|
PROOF_VERIFICATION_ERROR_CODES,
|
|
24
24
|
} from '../errors.js';
|
|
25
|
+
import { ProofGenerator } from '../../proof/generator.js';
|
|
26
|
+
// Cross-package relative import for a real Node crypto provider in tests —
|
|
27
|
+
// same pattern already used by proof/__tests__/proof-generator.test.ts.
|
|
28
|
+
import { NodeCryptoProvider } from '../../../../mcp-i/src/providers/node-providers';
|
|
25
29
|
|
|
26
30
|
describe('ProofVerifier Security', () => {
|
|
27
31
|
let proofVerifier: ProofVerifier;
|
|
@@ -256,6 +260,69 @@ describe('ProofVerifier Security', () => {
|
|
|
256
260
|
expect(canonical1).toBe(canonical2);
|
|
257
261
|
});
|
|
258
262
|
|
|
263
|
+
it('omits toolName and outcome from the reconstructed payload when meta carries neither', () => {
|
|
264
|
+
const meta = {
|
|
265
|
+
did: 'did:test',
|
|
266
|
+
kid: 'kid',
|
|
267
|
+
ts: 123,
|
|
268
|
+
nonce: 'nonce',
|
|
269
|
+
audience: 'aud',
|
|
270
|
+
sessionId: 'session',
|
|
271
|
+
requestHash: 'sha256:' + 'a'.repeat(64),
|
|
272
|
+
responseHash: 'sha256:' + 'b'.repeat(64),
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
const canonical = JSON.parse(proofVerifier.buildCanonicalPayload(meta));
|
|
276
|
+
|
|
277
|
+
expect(canonical).not.toHaveProperty('toolName');
|
|
278
|
+
expect(canonical).not.toHaveProperty('outcome');
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
it('reconstructs the same fields a real ProofGenerator actually signs — regression guard for generator/verifier payload drift', async () => {
|
|
282
|
+
const cryptoProvider = new NodeCryptoProvider();
|
|
283
|
+
const keyPair = await cryptoProvider.generateKeyPair();
|
|
284
|
+
const identity = {
|
|
285
|
+
did: 'did:web:example.com:agents:sync-test',
|
|
286
|
+
kid: 'did:web:example.com:agents:sync-test#key-1',
|
|
287
|
+
privateKey: keyPair.privateKey,
|
|
288
|
+
publicKey: keyPair.publicKey,
|
|
289
|
+
};
|
|
290
|
+
const generator = new ProofGenerator(identity, cryptoProvider);
|
|
291
|
+
|
|
292
|
+
const proof = await generator.generateProof(
|
|
293
|
+
{ method: 'test-tool', params: { input: 'hello' } },
|
|
294
|
+
{ data: { output: 'world' } },
|
|
295
|
+
{
|
|
296
|
+
sessionId: 'sess-sync-test',
|
|
297
|
+
audience: 'did:web:business.example',
|
|
298
|
+
nonce: 'nonce-sync-test',
|
|
299
|
+
timestamp: Math.floor(Date.now() / 1000),
|
|
300
|
+
createdAt: Math.floor(Date.now() / 1000),
|
|
301
|
+
lastActivity: Math.floor(Date.now() / 1000),
|
|
302
|
+
ttlMinutes: 30,
|
|
303
|
+
identityState: 'anonymous',
|
|
304
|
+
} as never,
|
|
305
|
+
{ toolName: 'test-tool', submissionOutcome: 'success' }
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
const actualPayload = JSON.parse(
|
|
309
|
+
Buffer.from(proof.jws.split('.')[1]!, 'base64url').toString('utf8')
|
|
310
|
+
);
|
|
311
|
+
const reconstructedPayload = JSON.parse(
|
|
312
|
+
proofVerifier.buildCanonicalPayload(proof.meta)
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
// Field-level equality (not byte/order equality — canonicalization
|
|
316
|
+
// sorts keys, which the signed JWS payload does not). If the
|
|
317
|
+
// reconstruction ever drifts from what generator.ts actually signs,
|
|
318
|
+
// this fails long before it reaches a live 403. Covers toolName and
|
|
319
|
+
// the submissionOutcome -> outcome rename too, since those are the
|
|
320
|
+
// two newest fields most likely to drift out of lockstep.
|
|
321
|
+
expect(reconstructedPayload).toEqual(actualPayload);
|
|
322
|
+
expect(reconstructedPayload.toolName).toBe('test-tool');
|
|
323
|
+
expect(reconstructedPayload.outcome).toBe('success');
|
|
324
|
+
});
|
|
325
|
+
|
|
259
326
|
it('should handle detached JWS reconstruction', async () => {
|
|
260
327
|
const header = { alg: 'EdDSA', kid: 'did:key:z123#key-1' };
|
|
261
328
|
const headerB64 = btoa(JSON.stringify(header))
|
|
@@ -419,6 +486,121 @@ describe('ProofVerifier Security', () => {
|
|
|
419
486
|
});
|
|
420
487
|
});
|
|
421
488
|
|
|
489
|
+
describe('End-to-end verifyProof() with real crypto — regression guard for DIF payload drift', () => {
|
|
490
|
+
// Uses a REAL NodeCryptoProvider (unlike the mocked cryptoProvider used
|
|
491
|
+
// elsewhere in this file, whose verify() always returns true and so
|
|
492
|
+
// could never catch a signature mismatch). This is the only way to
|
|
493
|
+
// prove verifyProof() itself -- not just buildCanonicalPayload() --
|
|
494
|
+
// still accepts a proof signed with the literal did/kid/audience/
|
|
495
|
+
// toolName/outcome fields once the DIF-delegated verifier is involved.
|
|
496
|
+
function makeRealVerifier() {
|
|
497
|
+
const cryptoProvider = new NodeCryptoProvider();
|
|
498
|
+
const clockProvider: ClockProvider = {
|
|
499
|
+
now: () => Date.now(),
|
|
500
|
+
isWithinSkew: () => true,
|
|
501
|
+
hasExpired: () => false,
|
|
502
|
+
calculateExpiry: (ttlSeconds: number) => Date.now() + ttlSeconds * 1000,
|
|
503
|
+
format: (d: number) => new Date(d).toISOString(),
|
|
504
|
+
};
|
|
505
|
+
const nonceCacheProvider: NonceCacheProvider = {
|
|
506
|
+
has: async () => false,
|
|
507
|
+
add: async () => {},
|
|
508
|
+
cleanup: async () => {},
|
|
509
|
+
destroy: async () => {},
|
|
510
|
+
};
|
|
511
|
+
const fetchProvider: FetchProvider = {
|
|
512
|
+
resolveDID: async () => null,
|
|
513
|
+
fetchStatusList: async () => null,
|
|
514
|
+
fetchDelegationChain: async () => null,
|
|
515
|
+
fetch: async () => {
|
|
516
|
+
throw new Error('not used');
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
const verifier = new ProofVerifier({
|
|
520
|
+
cryptoProvider,
|
|
521
|
+
clockProvider,
|
|
522
|
+
nonceCacheProvider,
|
|
523
|
+
fetchProvider,
|
|
524
|
+
});
|
|
525
|
+
return { cryptoProvider, verifier };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function toJwk(publicKeyBase64: string, kid: string): Ed25519JWK {
|
|
529
|
+
const bytes = Buffer.from(publicKeyBase64, 'base64');
|
|
530
|
+
const x = bytes
|
|
531
|
+
.toString('base64')
|
|
532
|
+
.replace(/\+/g, '-')
|
|
533
|
+
.replace(/\//g, '_')
|
|
534
|
+
.replace(/=/g, '');
|
|
535
|
+
return { kty: 'OKP', crv: 'Ed25519', x, kid };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
it('accepts a proof signed with the literal did/kid/audience/toolName/outcome fields', async () => {
|
|
539
|
+
const { cryptoProvider, verifier } = makeRealVerifier();
|
|
540
|
+
const keyPair = await cryptoProvider.generateKeyPair();
|
|
541
|
+
const identity = {
|
|
542
|
+
did: 'did:web:example.com:agents:e2e-test',
|
|
543
|
+
kid: 'did:web:example.com:agents:e2e-test#key-1',
|
|
544
|
+
privateKey: keyPair.privateKey,
|
|
545
|
+
publicKey: keyPair.publicKey,
|
|
546
|
+
};
|
|
547
|
+
const generator = new ProofGenerator(identity, cryptoProvider);
|
|
548
|
+
|
|
549
|
+
const proof = await generator.generateProof(
|
|
550
|
+
{ method: 'test-tool', params: { input: 'hello' } },
|
|
551
|
+
{ data: { output: 'world' } },
|
|
552
|
+
{
|
|
553
|
+
sessionId: 'sess-e2e-test',
|
|
554
|
+
audience: 'did:web:business.example',
|
|
555
|
+
nonce: 'nonce-e2e-test',
|
|
556
|
+
timestamp: Math.floor(Date.now() / 1000),
|
|
557
|
+
createdAt: Math.floor(Date.now() / 1000),
|
|
558
|
+
lastActivity: Math.floor(Date.now() / 1000),
|
|
559
|
+
ttlMinutes: 30,
|
|
560
|
+
identityState: 'anonymous',
|
|
561
|
+
} as never,
|
|
562
|
+
{ toolName: 'get_weather', submissionOutcome: 'success' }
|
|
563
|
+
);
|
|
564
|
+
|
|
565
|
+
const publicKeyJwk = toJwk(identity.publicKey, identity.kid);
|
|
566
|
+
const result = await verifier.verifyProof(proof, publicKeyJwk);
|
|
567
|
+
|
|
568
|
+
expect(result.valid).toBe(true);
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
it('also accepts a proof signed WITHOUT toolName/outcome (PR651-era fields only)', async () => {
|
|
572
|
+
const { cryptoProvider, verifier } = makeRealVerifier();
|
|
573
|
+
const keyPair = await cryptoProvider.generateKeyPair();
|
|
574
|
+
const identity = {
|
|
575
|
+
did: 'did:web:example.com:agents:e2e-test-2',
|
|
576
|
+
kid: 'did:web:example.com:agents:e2e-test-2#key-1',
|
|
577
|
+
privateKey: keyPair.privateKey,
|
|
578
|
+
publicKey: keyPair.publicKey,
|
|
579
|
+
};
|
|
580
|
+
const generator = new ProofGenerator(identity, cryptoProvider);
|
|
581
|
+
|
|
582
|
+
const proof = await generator.generateProof(
|
|
583
|
+
{ method: 'test-tool', params: { input: 'hello' } },
|
|
584
|
+
{ data: { output: 'world' } },
|
|
585
|
+
{
|
|
586
|
+
sessionId: 'sess-e2e-test-2',
|
|
587
|
+
audience: 'did:web:business.example',
|
|
588
|
+
nonce: 'nonce-e2e-test-2',
|
|
589
|
+
timestamp: Math.floor(Date.now() / 1000),
|
|
590
|
+
createdAt: Math.floor(Date.now() / 1000),
|
|
591
|
+
lastActivity: Math.floor(Date.now() / 1000),
|
|
592
|
+
ttlMinutes: 30,
|
|
593
|
+
identityState: 'anonymous',
|
|
594
|
+
} as never
|
|
595
|
+
);
|
|
596
|
+
|
|
597
|
+
const publicKeyJwk = toJwk(identity.publicKey, identity.kid);
|
|
598
|
+
const result = await verifier.verifyProof(proof, publicKeyJwk);
|
|
599
|
+
|
|
600
|
+
expect(result.valid).toBe(true);
|
|
601
|
+
});
|
|
602
|
+
});
|
|
603
|
+
|
|
422
604
|
describe('fetchPublicKeyFromDID', () => {
|
|
423
605
|
it('should fetch public key from DID document', async () => {
|
|
424
606
|
const jwk = await proofVerifier.fetchPublicKeyFromDID('did:key:z123', 'key-1');
|
|
@@ -6,6 +6,23 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { describe, it, expect, vi } from 'vitest';
|
|
9
|
+
|
|
10
|
+
// Hoist-safe redis mock (vitest hoists vi.mock above the imports, so the
|
|
11
|
+
// client must come from vi.hoisted). The nested vi.mock this replaces was
|
|
12
|
+
// hoisted here anyway; vitest >=4.1.10 rejects the misleading placement.
|
|
13
|
+
const mockRedisClient = vi.hoisted(() => ({
|
|
14
|
+
connect: vi.fn().mockResolvedValue(undefined),
|
|
15
|
+
ping: vi.fn().mockResolvedValue('PONG'),
|
|
16
|
+
get: vi.fn(),
|
|
17
|
+
set: vi.fn(),
|
|
18
|
+
setEx: vi.fn(),
|
|
19
|
+
del: vi.fn(),
|
|
20
|
+
exists: vi.fn(),
|
|
21
|
+
keys: vi.fn().mockResolvedValue([]),
|
|
22
|
+
}));
|
|
23
|
+
vi.mock('redis', () => ({
|
|
24
|
+
createClient: vi.fn().mockReturnValue(mockRedisClient),
|
|
25
|
+
}));
|
|
9
26
|
import {
|
|
10
27
|
createStorageProviders,
|
|
11
28
|
StorageKeyHelpers,
|
|
@@ -43,22 +60,6 @@ describe('StorageService', () => {
|
|
|
43
60
|
});
|
|
44
61
|
|
|
45
62
|
it('should prefer Redis over KV when both are configured', async () => {
|
|
46
|
-
const mockRedisClient = {
|
|
47
|
-
connect: vi.fn().mockResolvedValue(undefined),
|
|
48
|
-
ping: vi.fn().mockResolvedValue('PONG'),
|
|
49
|
-
get: vi.fn(),
|
|
50
|
-
set: vi.fn(),
|
|
51
|
-
setEx: vi.fn(),
|
|
52
|
-
del: vi.fn(),
|
|
53
|
-
exists: vi.fn(),
|
|
54
|
-
keys: vi.fn().mockResolvedValue([]),
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
// Mock redis import
|
|
58
|
-
vi.mock('redis', () => ({
|
|
59
|
-
createClient: vi.fn().mockReturnValue(mockRedisClient),
|
|
60
|
-
}));
|
|
61
|
-
|
|
62
63
|
const config: StorageServiceConfig = {
|
|
63
64
|
redisUrl: 'redis://localhost:6379',
|
|
64
65
|
kvNamespace: {
|
|
@@ -81,6 +82,10 @@ describe('StorageService', () => {
|
|
|
81
82
|
});
|
|
82
83
|
|
|
83
84
|
it('should fall back to memory when Redis connection fails', async () => {
|
|
85
|
+
// The module-level redis mock connects successfully by default; this
|
|
86
|
+
// case needs the connection itself to fail.
|
|
87
|
+
mockRedisClient.connect.mockRejectedValueOnce(new Error('connection refused'));
|
|
88
|
+
mockRedisClient.ping.mockRejectedValueOnce(new Error('connection refused'));
|
|
84
89
|
const config: StorageServiceConfig = {
|
|
85
90
|
redisUrl: 'redis://invalid:6379',
|
|
86
91
|
fallbackToMemory: true,
|