-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfleetgner-core.test.ts
More file actions
692 lines (605 loc) · 19.7 KB
/
fleetgner-core.test.ts
File metadata and controls
692 lines (605 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { generateSecretKey } from "nostr-tools";
import { createDatabase } from "../src/db/client";
import { createRepositories, type Repositories } from "../src/db/repositories";
import { createFleetgnerMcpServer } from "../src/cvm/server";
import { Keyring } from "../src/keys/keyring";
import { Nip46Gateway } from "../src/nip46/gateway";
import { PolicyRegistry } from "../src/policy/registry";
import { SigningCore, SigningDeniedError } from "../src/signing/core";
function stubExtra(clientPubkey: string) {
return { _meta: { clientPubkey } };
}
async function callRegisteredTool(
server: ReturnType<typeof createFleetgnerMcpServer>,
name: string,
args: Record<string, unknown>,
clientPubkey: string,
): Promise<{ structuredContent: unknown }> {
const tool = (
server as unknown as {
_registeredTools: Record<string, unknown>;
executeToolHandler: (
tool: unknown,
args: Record<string, unknown>,
extra: { _meta: { clientPubkey: string } },
) => Promise<{ structuredContent: unknown }>;
}
)._registeredTools[name];
return await (
server as unknown as {
executeToolHandler: (
tool: unknown,
args: Record<string, unknown>,
extra: { _meta: { clientPubkey: string } },
) => Promise<{ structuredContent: unknown }>;
}
).executeToolHandler(tool, args, stubExtra(clientPubkey));
}
function toHex(bytes: Uint8Array): string {
return Buffer.from(bytes).toString("hex");
}
describe("database repositories", () => {
test("stores grants and policies in normalized tables", () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
repos.users.upsert({
pubkey: "u".repeat(64),
enabled: true,
label: "user",
});
repos.keys.upsert({
pubkey: "k".repeat(64).replace(/k/g, "a"),
secretRef: "key:test:nsec",
enabled: true,
label: "key",
});
repos.grants.upsert({
userPubkey: "u".repeat(64),
keyPubkey: "a".repeat(64),
enabled: true,
});
repos.policies.upsert({
userPubkey: "u".repeat(64),
keyPubkey: "a".repeat(64),
policyKey: "allow_kinds",
enabled: true,
value: "1,30078",
});
repos.policies.upsert({
userPubkey: "u".repeat(64),
keyPubkey: "a".repeat(64),
policyKey: "max_content_length",
enabled: true,
value: "42",
});
const policies = repos.policies.listByGrant("u".repeat(64), "a".repeat(64));
expect(policies).toHaveLength(2);
expect(policies.find((p) => p.policy_key === "allow_kinds")?.value).toBe(
"1,30078",
);
expect(
repos.policies.delete("u".repeat(64), "a".repeat(64), "allow_kinds"),
).not.toBeNull();
db.close();
});
test("deleting grant cascades related policies", () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const userPubkey = "u".repeat(64);
const keyPubkey = "a".repeat(64);
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: "user" });
repos.keys.upsert({
pubkey: keyPubkey,
secretRef: "key:cascade:nsec",
enabled: true,
label: "key",
});
repos.grants.upsert({ userPubkey, keyPubkey, enabled: true });
repos.policies.upsert({
userPubkey,
keyPubkey,
policyKey: "allow_kinds",
enabled: true,
value: "1",
});
repos.policies.upsert({
userPubkey,
keyPubkey,
policyKey: "max_content_length",
enabled: true,
value: "120",
});
expect(repos.policies.listByGrant(userPubkey, keyPubkey)).toHaveLength(2);
expect(repos.grants.delete(userPubkey, keyPubkey)).not.toBeNull();
expect(repos.policies.listByGrant(userPubkey, keyPubkey)).toHaveLength(0);
db.close();
});
test("listEnabledKeyPubkeysByUser returns only enabled grants for enabled keys", () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const userPubkey = "f".repeat(64);
const keyA = "a".repeat(64);
const keyB = "b".repeat(64);
const keyC = "c".repeat(64);
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: keyA,
secretRef: "key:a",
enabled: true,
label: null,
});
repos.keys.upsert({
pubkey: keyB,
secretRef: "key:b",
enabled: false,
label: null,
});
repos.keys.upsert({
pubkey: keyC,
secretRef: "key:c",
enabled: true,
label: null,
});
repos.grants.upsert({ userPubkey, keyPubkey: keyA, enabled: true });
repos.grants.upsert({ userPubkey, keyPubkey: keyB, enabled: true });
repos.grants.upsert({ userPubkey, keyPubkey: keyC, enabled: false });
const keyPubkeys = repos.grants.listEnabledKeyPubkeysByUser(userPubkey);
expect(keyPubkeys).toEqual([keyA]);
db.close();
});
test("policy upsert patch keeps existing value when only enabled changes", () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const userPubkey = "d".repeat(64);
const keyPubkey = "e".repeat(64);
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: keyPubkey,
secretRef: "key:patch:nsec",
enabled: true,
label: null,
});
repos.grants.upsert({ userPubkey, keyPubkey, enabled: true });
repos.policies.upsert({
userPubkey,
keyPubkey,
policyKey: "allow_kinds",
enabled: true,
value: "1,30078",
});
repos.policies.upsert({
userPubkey,
keyPubkey,
policyKey: "allow_kinds",
enabled: false,
});
const policy = repos.policies.get(userPubkey, keyPubkey, "allow_kinds");
expect(policy).not.toBeNull();
expect(policy?.enabled).toBe(0);
expect(policy?.value).toBe("1,30078");
db.close();
});
test("deleting key cascades grants, policies and nip46 connections", () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const userPubkey = "9".repeat(64);
const keyPubkey = "8".repeat(64);
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: keyPubkey,
secretRef: "key:cascade:key-remove",
enabled: true,
label: null,
});
repos.grants.upsert({ userPubkey, keyPubkey, enabled: true });
repos.policies.upsert({
userPubkey,
keyPubkey,
policyKey: "allow_kinds",
enabled: true,
value: "1",
});
repos.nip46Connections.create({
id: "conn-key-remove",
userPubkey,
keyPubkey,
mode: "bunker",
relays: ["wss://relay.example"],
secretHash: "s".repeat(64),
});
expect(repos.grants.get(userPubkey, keyPubkey)).not.toBeNull();
expect(repos.policies.listByGrant(userPubkey, keyPubkey)).toHaveLength(1);
expect(repos.nip46Connections.listByKeyPubkey(keyPubkey)).toHaveLength(1);
expect(repos.keys.delete(keyPubkey)).not.toBeNull();
expect(repos.grants.get(userPubkey, keyPubkey)).toBeNull();
expect(repos.policies.listByGrant(userPubkey, keyPubkey)).toHaveLength(0);
expect(repos.nip46Connections.listByKeyPubkey(keyPubkey)).toHaveLength(0);
db.close();
});
});
describe("keyring", () => {
const keyring = new Keyring();
const createdRefs: string[] = [];
afterEach(async () => {
for (const ref of createdRefs.splice(0)) {
await keyring.deleteSecretByRef(ref);
}
});
test("imports, reads and deletes signing key secret", async () => {
const nsecHex = toHex(generateSecretKey());
const imported = await keyring.importSigningKey(nsecHex);
createdRefs.push(imported.secretRef);
const loaded = await keyring.getSecretByRef(imported.secretRef);
expect(loaded).toBe(imported.nsec);
await keyring.deleteSecretByRef(imported.secretRef);
await expect(keyring.getSecretByRef(imported.secretRef)).rejects.toThrow(
`missing secret for ref: ${imported.secretRef}`,
);
});
test("getOrCreateCommsSecret is stable for same ref", async () => {
const ref = `comms:test:${Date.now()}:${Math.random()}`;
createdRefs.push(ref);
const first = await keyring.getOrCreateCommsSecret(ref);
const second = await keyring.getOrCreateCommsSecret(ref);
expect(first).toBe(second);
expect(first).toHaveLength(64);
});
});
describe("signing core", () => {
let repos: Repositories;
let keyring: Keyring;
let signing: SigningCore;
beforeEach(() => {
const db = createDatabase({ filename: ":memory:" });
repos = createRepositories(db);
keyring = new Keyring();
signing = new SigningCore(repos, keyring, new PolicyRegistry());
});
test("signs when grant and policies allow", async () => {
const callerPubkey = "b".repeat(64);
const imported = await keyring.importSigningKey(toHex(generateSecretKey()));
repos.users.upsert({ pubkey: callerPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: imported.pubkey,
secretRef: imported.secretRef,
enabled: true,
label: null,
});
repos.grants.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
enabled: true,
});
repos.policies.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
policyKey: "allow_kinds",
enabled: true,
value: "1",
});
const signed = await signing.signDraft({
callerPubkey,
channel: "cvm",
draft: {
pubkey: imported.pubkey,
kind: 1,
tags: [],
content: "hello",
},
});
expect(signed.pubkey).toBe(imported.pubkey);
expect(signed.kind).toBe(1);
expect(signed.id).toHaveLength(64);
expect(signed.sig).toHaveLength(128);
await keyring.deleteSecretByRef(imported.secretRef);
});
test("denies signing when policy rejects", async () => {
const callerPubkey = "c".repeat(64);
const imported = await keyring.importSigningKey(toHex(generateSecretKey()));
repos.users.upsert({ pubkey: callerPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: imported.pubkey,
secretRef: imported.secretRef,
enabled: true,
label: null,
});
repos.grants.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
enabled: true,
});
repos.policies.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
policyKey: "deny_kinds",
enabled: true,
value: "1",
});
await expect(
signing.signDraft({
callerPubkey,
channel: "nip46",
draft: {
pubkey: imported.pubkey,
kind: 1,
tags: [],
content: "blocked",
},
}),
).rejects.toBeInstanceOf(SigningDeniedError);
await keyring.deleteSecretByRef(imported.secretRef);
});
test("denies signing when grant exists but is disabled", async () => {
const callerPubkey = "d".repeat(64);
const imported = await keyring.importSigningKey(toHex(generateSecretKey()));
repos.users.upsert({ pubkey: callerPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: imported.pubkey,
secretRef: imported.secretRef,
enabled: true,
label: null,
});
repos.grants.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
enabled: false,
});
await expect(
signing.signDraft({
callerPubkey,
channel: "cvm",
draft: {
pubkey: imported.pubkey,
kind: 1,
tags: [],
content: "blocked-by-disabled-grant",
},
}),
).rejects.toMatchObject({ reason: "grant_not_enabled" });
await keyring.deleteSecretByRef(imported.secretRef);
});
test("disabled denying policy is ignored", async () => {
const callerPubkey = "e".repeat(64);
const imported = await keyring.importSigningKey(toHex(generateSecretKey()));
repos.users.upsert({ pubkey: callerPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: imported.pubkey,
secretRef: imported.secretRef,
enabled: true,
label: null,
});
repos.grants.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
enabled: true,
});
repos.policies.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
policyKey: "deny_kinds",
enabled: false,
value: "1",
});
const signed = await signing.signDraft({
callerPubkey,
channel: "nip46",
draft: {
pubkey: imported.pubkey,
kind: 1,
tags: [],
content: "allowed-because-policy-disabled",
},
});
expect(signed.pubkey).toBe(imported.pubkey);
expect(signed.sig).toHaveLength(128);
await keyring.deleteSecretByRef(imported.secretRef);
});
});
describe("cvm server tool behavior", () => {
test("user_list includes admin self and user labels", async () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const keyring = new Keyring();
const policyRegistry = new PolicyRegistry();
const signingCore = new SigningCore(repos, keyring, policyRegistry);
const adminPubkey = "a".repeat(64);
const userPubkey = "b".repeat(64);
repos.serverConfig.set({
adminPubkey,
commsSecretRef: "comms:test",
relayUrls: ["wss://relay.example"],
});
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: "alice" });
const gatewayStub = {
refreshConnectionsForUser: async () => {},
refreshConnectionsForKey: async () => {},
refreshConnectionsForGrant: async () => {},
stopConnectionsForUser: async () => {},
stopConnectionsForKey: async () => {},
stopAndDeleteConnectionsForGrant: async () => {},
createBunkerUri: async () => "bunker://uri",
addNostrConnectUri: async () => {},
} as unknown as Nip46Gateway;
const server = createFleetgnerMcpServer({
repos,
keyring,
policyRegistry,
signingCore,
nip46Gateway: gatewayStub,
});
const result = await callRegisteredTool(
server,
"user_list",
{},
adminPubkey,
);
const users = (
result.structuredContent as { users: Array<Record<string, unknown>> }
).users;
expect(users).toHaveLength(2);
expect(users[0]).toMatchObject({
pubkey: adminPubkey,
label: "",
isAdmin: true,
});
expect(users[1]).toMatchObject({
pubkey: userPubkey,
label: "alice",
isAdmin: false,
});
db.close();
});
test("grant_set allows creating a restricted zero-policy grant before policies exist", async () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const keyring = new Keyring();
const policyRegistry = new PolicyRegistry();
const signingCore = new SigningCore(repos, keyring, policyRegistry);
const adminPubkey = "c".repeat(64);
const userPubkey = "d".repeat(64);
const keyPubkey = "e".repeat(64);
repos.serverConfig.set({
adminPubkey,
commsSecretRef: "comms:test-2",
relayUrls: ["wss://relay.example"],
});
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: "user" });
repos.keys.upsert({
pubkey: keyPubkey,
secretRef: "key:test-grant",
enabled: true,
label: "key",
});
const gatewayCalls: string[] = [];
const gatewayStub = {
refreshConnectionsForUser: async () => {},
refreshConnectionsForKey: async () => {},
refreshConnectionsForGrant: async (user: string, key: string) => {
gatewayCalls.push(`${user}:${key}`);
},
stopConnectionsForUser: async () => {},
stopConnectionsForKey: async () => {},
stopAndDeleteConnectionsForGrant: async () => {},
createBunkerUri: async () => "bunker://uri",
addNostrConnectUri: async () => {},
} as unknown as Nip46Gateway;
const server = createFleetgnerMcpServer({
repos,
keyring,
policyRegistry,
signingCore,
nip46Gateway: gatewayStub,
});
const result = await callRegisteredTool(
server,
"grant_set",
{ user_pubkey: userPubkey, key_pubkey: keyPubkey },
adminPubkey,
);
expect(result.structuredContent).toMatchObject({
user_pubkey: userPubkey,
key_pubkey: keyPubkey,
grant_enabled: true,
is_unrestricted: false,
});
expect(repos.grants.get(userPubkey, keyPubkey)).toMatchObject({
allow_unrestricted: 0,
enabled: 1,
});
expect(gatewayCalls).toEqual([`${userPubkey}:${keyPubkey}`]);
db.close();
});
test("signing denies a restricted zero-policy grant until a policy is added", async () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const keyring = new Keyring();
const signing = new SigningCore(repos, keyring, new PolicyRegistry());
const callerPubkey = "f".repeat(64);
const imported = await keyring.importSigningKey(toHex(generateSecretKey()));
repos.users.upsert({ pubkey: callerPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: imported.pubkey,
secretRef: imported.secretRef,
enabled: true,
label: null,
});
repos.grants.upsert({
userPubkey: callerPubkey,
keyPubkey: imported.pubkey,
enabled: true,
allowUnrestricted: false,
});
await expect(
signing.signDraft({
callerPubkey,
channel: "cvm",
draft: {
pubkey: imported.pubkey,
kind: 1,
tags: [],
content: "blocked-until-policy-exists",
},
}),
).rejects.toMatchObject({
reason: "grant_not_ready_requires_policy_or_allow_unrestricted",
});
await keyring.deleteSecretByRef(imported.secretRef);
db.close();
});
});
describe("nip46 gateway lifecycle", () => {
test("stopConnectionsForGrant keeps persisted rows and refreshConnectionsForGrant restarts eligible ones", async () => {
const db = createDatabase({ filename: ":memory:" });
const repos = createRepositories(db);
const signingCore = {
signDraft: async () => ({}) as never,
} as unknown as SigningCore;
const commsSigner = {} as ConstructorParameters<typeof Nip46Gateway>[2];
const gateway = new Nip46Gateway(repos, signingCore, commsSigner);
const userPubkey = "1".repeat(64);
const keyPubkey = "2".repeat(64);
repos.users.upsert({ pubkey: userPubkey, enabled: true, label: null });
repos.keys.upsert({
pubkey: keyPubkey,
secretRef: "key:test-gateway",
enabled: true,
label: null,
});
repos.grants.upsert({
userPubkey,
keyPubkey,
enabled: true,
allowUnrestricted: true,
});
repos.nip46Connections.create({
id: "conn-1",
userPubkey,
keyPubkey,
mode: "bunker",
relays: ["wss://relay.example"],
secretHash: "s".repeat(64),
});
const stopCalls: string[] = [];
const startCalls: string[] = [];
(
gateway as unknown as {
providers: Map<string, { stop: () => Promise<void> }>;
}
).providers.set("conn-1", {
stop: async () => {
stopCalls.push("conn-1");
},
});
gateway.startConnection = async (connectionId: string) => {
startCalls.push(connectionId);
return { connectionId, provider: {} as never };
};
await gateway.stopConnectionsForGrant(userPubkey, keyPubkey);
expect(stopCalls).toEqual(["conn-1"]);
expect(repos.nip46Connections.get("conn-1")).not.toBeNull();
await gateway.refreshConnectionsForGrant(userPubkey, keyPubkey);
expect(startCalls).toEqual(["conn-1"]);
db.close();
});
});