Repository navigation
Expand file tree
/
Copy pathapi.test.mjs
More file actions
852 lines (757 loc) · 40 KB
/
Copy pathapi.test.mjs
File metadata and controls
852 lines (757 loc) · 40 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// In-process tests of the API function against the WAS v0.5 behaviour the
// @interop/was-client (0.93+) relies on. S3 and DynamoDB are faked; every
// request is signed the way the client signs it.
//
// cd test && npm test
// http-client first: @interop/jsonld requires it at load, and the ezcap
// imports below would otherwise reach jsonld before it is initialized.
import "@interop/http-client";
import { test, beforeEach } from "node:test";
import assert from "node:assert/strict";
import { installFakes } from "./fakes.mjs";
import { invoke, seedSpace, seedObject, controllerKey, strangerKey, BASE, asWebvh, mintWebvh, seedWebvhLog, bucketOf, clearWebvhCache } from "./harness.mjs";
import { deriveSpaceId } from "was-lib/webvh.mjs";
import { updateDID, signerFromDidKeySigner, logToJsonlString } from "@interop/did-method-webvh";
import { ZcapClient } from "@interop/ezcap";
import { Ed25519Signature2020 } from "@interop/ed25519-signature";
import { EddsaJcs2022 } from "@interop/ed25519-signature/eddsa-jcs-2022";
import { rootCapabilityId } from "../src/authorizer/zcap.mjs";
const SPACE = "dcc-was-01011f5b-59ea-4e62-880e-d6ad666e361c";
const SPACE_URL = `${BASE}/space/${SPACE}/`;
const PROBLEM = "application/problem+json";
let fakes;
beforeEach(async () => {
fakes = installFakes();
clearWebvhCache();
await seedSpace(fakes, { spaceId: SPACE });
fakes.dynamo.tables["was-coupons"].set("open-sesame", { coupon: { S: "open-sesame" } });
fakes.dynamo.tables["was-coupons"].set("one-shot", { coupon: { S: "one-shot" }, usesRemaining: { N: "1" } });
});
const objectKeys = () => fakes.s3.keys(SPACE);
// --- discovery ---------------------------------------------------------------
test("GET / serves the service description with the service link", async () => {
const res = await invoke({ path: "/", signer: null });
assert.equal(res.status, 200);
assert.equal(res.headers.link, `<${BASE}/>; rel="service"`);
// The one read that may be cached without revalidation: the description
// sets its own short lifetime instead of the no-cache every other read gets
assert.equal(res.headers["cache-control"], "public, max-age=300");
assert.equal(res.json.url, `${BASE}/`);
const entry = res.json.specs["https://w3id.org/pws"][0];
assert.equal(entry.version, "0.5");
assert.equal(entry.spaces, `${BASE}/spaces/`);
assert.ok(entry.features.includes("listing"));
});
test("HEAD / carries the link and no body", async () => {
const res = await invoke({ method: "HEAD", path: "/", signer: null });
assert.equal(res.status, 200);
assert.equal(res.headers.link, `<${BASE}/>; rel="service"`);
assert.equal(res.body, "");
});
test("an unknown path below a resource is a problem+json 404 that still carries the link", async () => {
const res = await invoke({ path: `/space/${SPACE}/c/r/nothing/here`, signer: null });
assert.equal(res.status, 404);
assert.equal(res.headers["content-type"], PROBLEM);
assert.equal(res.json.type, "https://w3id.org/pws#not-found");
assert.ok(res.headers.link);
// Outside every route the gateway answers its own 404.
const outside = await invoke({ path: "/nothing/here", signer: null });
assert.equal(outside.status, 404);
assert.equal(outside.fn, null);
});
// --- spaces repository ---------------------------------------------------------
test("POST /spaces/ provisions a Space for the stated controller", async () => {
const res = await invoke({
method: "POST",
path: "/spaces/",
json: { controller: controllerKey.controller, name: "Home", coupon: "open-sesame" },
});
assert.equal(res.status, 201, JSON.stringify(res.json));
assert.match(res.headers.location, /^http:\/\/localhost:3000\/space\/dcc-was-[0-9a-f-]{36}\/$/);
assert.ok(res.headers.etag);
assert.deepEqual(res.json.type, ["Space"]);
assert.equal(res.json.name, "Home");
assert.equal(res.json.controller, controllerKey.controller);
const id = res.json.id;
assert.ok(fakes.s3.buckets.has(id));
assert.ok(fakes.s3.buckets.get(id).has("meta/space.json"));
const row = fakes.dynamo.tables["was-spaces"].get(`${BASE}/space/${id}`);
assert.equal(row.did.S, controllerKey.controller);
assert.deepEqual(row.type.L, [{ S: "Space" }]);
});
test("POST /spaces/ keeps a typed Space's type array", async () => {
const res = await invoke({
method: "POST",
path: "/spaces/",
json: { controller: controllerKey.controller, type: ["Space", "BatchSpace"], coupon: "one-shot" },
});
assert.equal(res.status, 201);
assert.deepEqual(res.json.type, ["Space", "BatchSpace"]);
// The finite coupon is spent.
const again = await invoke({
method: "POST",
path: "/spaces/",
json: { controller: controllerKey.controller, coupon: "one-shot" },
});
assert.equal(again.status, 403);
});
test("POST /spaces/ refuses a request not signed by the stated controller", async () => {
const res = await invoke({
method: "POST",
path: "/spaces/",
json: { controller: strangerKey.controller, coupon: "open-sesame" },
});
assert.equal(res.status, 400);
assert.equal(res.json.type, "https://w3id.org/pws#invalid-request-body");
});
test("POST /spaces/ validates the body", async () => {
const noController = await invoke({ method: "POST", path: "/spaces/", json: { coupon: "open-sesame" } });
assert.equal(noController.status, 400);
const badType = await invoke({
method: "POST",
path: "/spaces/",
json: { controller: controllerKey.controller, type: ["Other"], coupon: "open-sesame" },
});
assert.equal(badType.status, 400);
const clientId = await invoke({
method: "POST",
path: "/spaces/",
json: { controller: controllerKey.controller, id: "mine", coupon: "open-sesame" },
});
assert.equal(clientId.status, 400);
});
test("GET /spaces/ lists the signer's Spaces and pages them", async () => {
await seedSpace(fakes, { spaceId: "dcc-was-00000000-0000-4000-8000-000000000002", name: "Second" });
await seedSpace(fakes, { spaceId: "dcc-was-00000000-0000-4000-8000-000000000003", controller: strangerKey.controller });
const res = await invoke({ path: "/spaces/" });
assert.equal(res.status, 200);
assert.equal(res.json.totalItems, 2);
assert.deepEqual(res.json.items.map((item) => item.name).sort(), ["Second", "Test Space"]);
assert.ok(res.json.items.every((item) => item.url.endsWith("/") && Array.isArray(item.type)));
const first = await invoke({ path: "/spaces/?limit=1" });
assert.equal(first.json.items.length, 1);
assert.ok(first.json.next.startsWith(`${BASE}/spaces/?cursor=`));
const second = await invoke({ path: first.json.next.slice(BASE.length) });
assert.equal(second.json.items.length, 1);
assert.equal(second.json.next, undefined);
assert.notEqual(first.json.items[0].id, second.json.items[0].id);
});
test("HEAD /spaces/ carries the service link, signed or not", async () => {
const unsigned = await invoke({ method: "HEAD", path: "/spaces/", signer: null });
assert.equal(unsigned.status, 200);
assert.equal(unsigned.headers.link, `<${BASE}/>; rel="service"`);
assert.equal(unsigned.body, "");
const signed = await invoke({ method: "HEAD", path: "/spaces/" });
assert.equal(signed.status, 200);
assert.equal(signed.headers.link, `<${BASE}/>; rel="service"`);
});
test("GET /spaces/ answers an empty list to an unsigned or badly signed caller", async () => {
const unsigned = await invoke({ path: "/spaces/", signer: null });
assert.equal(unsigned.status, 200);
assert.deepEqual(unsigned.json.items, []);
const tampered = await invoke({ path: "/spaces/", tamper: true });
assert.equal(tampered.status, 200);
assert.deepEqual(tampered.json.items, []);
});
// --- space ---------------------------------------------------------------------
test("the bare Space URL redirects to its trailing-slash form", async () => {
const res = await invoke({ path: `/space/${SPACE}` });
assert.equal(res.status, 308);
assert.equal(res.headers.location, SPACE_URL);
});
test("GET /space/{s}/meta returns the Space Metadata with an ETag", async () => {
const res = await invoke({ path: `/space/${SPACE}/meta` });
assert.equal(res.status, 200);
assert.ok(res.headers.etag);
assert.equal(res.headers["cache-control"], "no-cache");
assert.equal(res.json.id, SPACE);
assert.equal(res.json.url, SPACE_URL);
assert.equal(res.json.controller, controllerKey.controller);
assert.deepEqual(res.json.type, ["Space"]);
});
test("PUT /space/{s}/meta renames the Space under If-Match and mirrors the name to the registry", async () => {
const current = await invoke({ path: `/space/${SPACE}/meta` });
const res = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { id: SPACE, name: "Renamed", controller: controllerKey.controller },
headers: { "if-match": current.headers.etag },
});
assert.equal(res.status, 200, JSON.stringify(res.json));
assert.equal(res.json.name, "Renamed");
assert.ok(res.headers.etag && res.headers.etag !== current.headers.etag);
assert.equal(res.headers["cache-control"], "no-store");
assert.equal(fakes.dynamo.tables["was-spaces"].get(`${BASE}/space/${SPACE}`).name.S, "Renamed");
const stale = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { name: "Again", controller: controllerKey.controller },
headers: { "if-match": current.headers.etag },
});
assert.equal(stale.status, 412);
assert.equal(stale.json.type, "https://w3id.org/pws#precondition-failed");
});
test("PUT /space/{s}/meta refuses a controller change and a type change", async () => {
const controller = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { name: "x", controller: strangerKey.controller },
});
assert.equal(controller.status, 400);
assert.equal(controller.json.type, "https://w3id.org/pws#controller-mismatch");
const type = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { name: "x", controller: controllerKey.controller, type: ["Space", "Other"] },
});
assert.equal(type.status, 400);
});
test("unimplemented reserved endpoints answer 405", async () => {
for (const path of [`/space/${SPACE}/linkset`, `/space/${SPACE}/quotas`, `/space/${SPACE}/c/meta/log`, `/space/${SPACE}/c/r/chunks/0`]) {
const res = await invoke({ path });
assert.equal(res.status, 405, path);
}
});
// --- collections -----------------------------------------------------------------
test("POST /space/{s}/ creates a Collection and lists it", async () => {
const res = await invoke({
method: "POST",
path: `/space/${SPACE}/`,
json: { id: "vault", name: "Vault", encryption: { scheme: "edv" } },
});
assert.equal(res.status, 201, JSON.stringify(res.json));
assert.equal(res.headers.location, `${SPACE_URL}vault/`);
assert.ok(res.headers.etag);
assert.equal(res.json.id, "vault");
assert.deepEqual(res.json.type, ["Collection"]);
assert.deepEqual(res.json.encryption, { scheme: "edv" });
assert.equal(res.json.createdBy, controllerKey.controller);
assert.ok(res.json.createdAt);
const list = await invoke({ path: `/space/${SPACE}/` });
assert.equal(list.status, 200);
assert.equal(list.json.url, SPACE_URL);
assert.deepEqual(list.json.items.map((item) => item.id), ["vault"]);
assert.equal(list.json.items[0].url, `${SPACE_URL}vault/`);
assert.equal(list.json.items[0].name, "Vault");
const dup = await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "vault" } });
assert.equal(dup.status, 409);
assert.equal(dup.json.type, "https://w3id.org/pws#id-conflict");
});
test("POST /space/{s}/ assigns an id when none is given, and refuses reserved or malformed ids", async () => {
const assigned = await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { name: "Anon" } });
assert.equal(assigned.status, 201);
assert.match(assigned.json.id, /^[0-9a-f-]{36}$/);
const reserved = await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "meta" } });
assert.equal(reserved.status, 409);
assert.equal(reserved.json.type, "https://w3id.org/pws#reserved-id");
const malformed = await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "a/b" } });
assert.equal(malformed.status, 400);
assert.equal(malformed.json.type, "https://w3id.org/pws#invalid-id");
});
test("the Collection listing includes implicit collections and pages", async () => {
await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "alpha" } });
await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "beta" } });
// Written straight into the bucket by another service, with no metadata.
await seedObject(fakes, SPACE, "collections/logs/log.json", { entries: [] });
const page1 = await invoke({ path: `/space/${SPACE}/?limit=2` });
assert.deepEqual(page1.json.items.map((item) => item.id), ["alpha", "beta"]);
assert.ok(page1.json.next);
const page2 = await invoke({ path: page1.json.next.slice(BASE.length) });
assert.deepEqual(page2.json.items.map((item) => item.id), ["logs"]);
assert.equal(page2.json.items[0].name, "logs");
assert.equal(page2.json.next, undefined);
});
test("the bare Collection URL redirects to its trailing-slash form", async () => {
const res = await invoke({ path: `/space/${SPACE}/vault` });
assert.equal(res.status, 308);
assert.equal(res.headers.location, `${SPACE_URL}vault/`);
});
test("Collection Metadata: GET, replace under If-Match, create with If-None-Match", async () => {
await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "vault", name: "Vault" } });
const read = await invoke({ path: `/space/${SPACE}/vault/meta` });
assert.equal(read.status, 200);
assert.equal(read.json.name, "Vault");
assert.ok(read.headers.etag);
const replaced = await invoke({
method: "PUT",
path: `/space/${SPACE}/vault/meta`,
json: { id: "vault", name: "Vault 2", custom: { name: "My vault" }, encryption: { scheme: "edv", currentEpoch: "e1", epochs: [] } },
headers: { "if-match": read.headers.etag },
});
assert.equal(replaced.status, 200, JSON.stringify(replaced.json));
assert.equal(replaced.json.name, "Vault 2");
assert.deepEqual(replaced.json.custom, { name: "My vault" });
assert.equal(replaced.json.encryption.currentEpoch, "e1");
assert.equal(replaced.json.createdAt, read.json.createdAt);
assert.ok(replaced.headers.etag !== read.headers.etag);
const stale = await invoke({
method: "PUT",
path: `/space/${SPACE}/vault/meta`,
json: { name: "x" },
headers: { "if-match": read.headers.etag },
});
assert.equal(stale.status, 412);
const created = await invoke({
method: "PUT",
path: `/space/${SPACE}/fresh/meta`,
json: { id: "fresh", name: "Fresh" },
headers: { "if-none-match": "*" },
});
assert.equal(created.status, 201);
const again = await invoke({
method: "PUT",
path: `/space/${SPACE}/fresh/meta`,
json: { name: "Fresh" },
headers: { "if-none-match": "*" },
});
assert.equal(again.status, 412);
const missing = await invoke({ path: `/space/${SPACE}/absent/meta` });
assert.equal(missing.status, 404);
});
test("an implicit Collection has readable, unversioned metadata", async () => {
await seedObject(fakes, SPACE, "collections/logs/log.json", { entries: [] });
const res = await invoke({ path: `/space/${SPACE}/logs/meta` });
assert.equal(res.status, 200);
assert.deepEqual(res.json.type, ["Collection"]);
assert.equal(res.headers.etag, undefined);
});
test("DELETE /space/{s}/{c}/ removes the Collection, its content, metadata and policies", async () => {
await invoke({ method: "POST", path: `/space/${SPACE}/`, json: { id: "vault" } });
await invoke({ method: "PUT", path: `/space/${SPACE}/vault/doc`, json: { a: 1 } });
await invoke({ method: "PUT", path: `/space/${SPACE}/vault/doc/meta`, json: { custom: { name: "n" } } });
await invoke({ method: "PUT", path: `/space/${SPACE}/vault/policy`, json: { type: "PublicCanRead" } });
const res = await invoke({ method: "DELETE", path: `/space/${SPACE}/vault/` });
assert.equal(res.status, 204);
assert.deepEqual(objectKeys(), ["meta/space.json"]);
const gone = await invoke({ method: "DELETE", path: `/space/${SPACE}/vault/` });
assert.equal(gone.status, 404);
});
// --- resources -------------------------------------------------------------------
test("PUT creates then updates a Resource with validators and the spec's status codes", async () => {
const created = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 }, headers: { "key-epoch": "e1" } });
assert.equal(created.status, 201, created.body);
assert.equal(created.headers.location, `${SPACE_URL}docs/one`);
assert.ok(created.headers.etag);
assert.equal(created.headers["content-type"], undefined);
assert.equal(created.body, "");
// A first write into a new collection gives it metadata.
assert.ok(objectKeys().includes("meta/docs.json"));
const updated = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 2 }, headers: { "if-match": created.headers.etag } });
assert.equal(updated.status, 204);
assert.ok(updated.headers.etag && updated.headers.etag !== created.headers.etag);
const stale = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 3 }, headers: { "if-match": created.headers.etag } });
assert.equal(stale.status, 412);
const insert = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 3 }, headers: { "if-none-match": "*" } });
assert.equal(insert.status, 412);
const read = await invoke({ path: `/space/${SPACE}/docs/one` });
assert.equal(read.status, 200);
assert.deepEqual(read.json, { v: 2 });
assert.equal(read.headers.etag, updated.headers.etag);
assert.equal(read.headers["content-type"], "application/json");
assert.ok(read.headers["last-modified"]);
// A read with Last-Modified and no Cache-Control would be heuristically
// cached by browsers; the server requires revalidation instead
assert.equal(read.headers["cache-control"], "no-cache");
const cached = await invoke({ path: `/space/${SPACE}/docs/one`, headers: { "if-none-match": updated.headers.etag } });
assert.equal(cached.status, 304);
assert.equal(cached.body, "");
assert.equal(cached.headers["cache-control"], "no-cache");
const head = await invoke({ method: "HEAD", path: `/space/${SPACE}/docs/one` });
assert.equal(head.status, 200);
assert.equal(head.body, "");
assert.equal(head.headers.etag, updated.headers.etag);
});
test("a Resource write needs a signature and a Digest that matches the body", async () => {
const unsigned = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 }, signer: null });
assert.equal(unsigned.status, 401);
assert.equal(unsigned.json.type, "https://w3id.org/pws#missing-authorization");
// Signed over one body, delivered with another.
const signed = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 }, deliveredJson: { v: 2 } });
assert.equal(signed.status, 400);
assert.equal(signed.json.type, "https://w3id.org/pws#invalid-authorization-header");
});
test("POST /space/{s}/{c}/ creates a Resource with a server-assigned id", async () => {
const res = await invoke({ method: "POST", path: `/space/${SPACE}/docs/`, json: { hello: "world" } });
assert.equal(res.status, 201, res.body);
assert.match(res.json.id, /^[0-9a-f-]{36}$/);
assert.equal(res.headers.location, `${SPACE_URL}docs/${res.json.id}`);
assert.equal(res.json.url, res.headers.location);
assert.ok(res.headers.etag);
const read = await invoke({ path: `/space/${SPACE}/docs/${res.json.id}` });
assert.deepEqual(read.json, { hello: "world" });
});
test("binary content round-trips base64-encoded", async () => {
const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
const put = await invoke({ method: "PUT", path: `/space/${SPACE}/files/pic.png`, body: bytes, contentType: "image/png" });
assert.equal(put.status, 201, put.body);
const read = await invoke({ path: `/space/${SPACE}/files/pic.png` });
assert.equal(read.status, 200);
assert.equal(read.headers["content-type"], "image/png");
assert.equal(read.isBase64Encoded, true);
assert.deepEqual(Buffer.from(read.body, "base64"), bytes);
});
test("the Resource listing pages and carries the stamps", async () => {
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/a`, json: { v: 1 }, headers: { "key-epoch": "e1" } });
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/b`, json: { v: 2 } });
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/c`, json: { v: 3 } });
const page1 = await invoke({ path: `/space/${SPACE}/docs/?limit=2` });
assert.equal(page1.status, 200);
assert.equal(page1.json.id, "docs");
assert.equal(page1.json.url, `${SPACE_URL}docs/`);
assert.deepEqual(page1.json.type, ["Collection"]);
assert.deepEqual(page1.json.items.map((item) => item.id), ["a", "b"]);
assert.equal(page1.json.items[0].epoch, "e1");
assert.equal(page1.json.items[0].contentType, "application/json");
assert.equal(page1.json.items[0].url, `${SPACE_URL}docs/a`);
assert.ok(page1.json.next.startsWith(`${SPACE_URL}docs/?cursor=`));
const page2 = await invoke({ path: page1.json.next.slice(BASE.length) });
assert.deepEqual(page2.json.items.map((item) => item.id), ["c"]);
assert.equal(page2.json.next, undefined);
const bad = await invoke({ path: `/space/${SPACE}/docs/?cursor=%%%` });
assert.equal(bad.status, 400);
});
test("DELETE removes a Resource permanently, with its metadata and policy", async () => {
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 } });
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one/meta`, json: { custom: { name: "n" } } });
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one/policy`, json: { type: "PublicCanRead" } });
const res = await invoke({ method: "DELETE", path: `/space/${SPACE}/docs/one` });
assert.equal(res.status, 204);
assert.deepEqual(objectKeys().filter((key) => key.includes("one")), []);
const again = await invoke({ method: "DELETE", path: `/space/${SPACE}/docs/one` });
assert.equal(again.status, 404);
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/two`, json: { v: 1 } });
const guarded = await invoke({ method: "DELETE", path: `/space/${SPACE}/docs/two`, headers: { "if-match": '"nope"' } });
assert.equal(guarded.status, 412);
});
test("percent-encoded resource ids verify and round-trip", async () => {
const id = "Sushi-Chef%2C-Digital%20Credentials.json";
const put = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/${id}`, json: { ok: true } });
assert.equal(put.status, 201, put.body);
assert.equal(put.headers.location, `${SPACE_URL}docs/${id}`);
assert.ok(objectKeys().includes("collections/docs/Sushi-Chef,-Digital Credentials.json"));
const read = await invoke({ path: `/space/${SPACE}/docs/${id}` });
assert.deepEqual(read.json, { ok: true });
});
// --- resource metadata -----------------------------------------------------------
test("Resource Metadata derives from the content and takes a custom annotation", async () => {
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 }, headers: { "key-epoch": "e1", "writer-id": "me" } });
const derived = await invoke({ path: `/space/${SPACE}/docs/one/meta` });
assert.equal(derived.status, 200);
assert.equal(derived.json.contentType, "application/json");
assert.equal(derived.json.size, 7);
assert.equal(derived.json.epoch, "e1");
assert.equal(derived.json.writerId, "me");
assert.equal(derived.json.createdBy, controllerKey.controller);
assert.ok(derived.json.createdAt && derived.json.updatedAt);
assert.equal(derived.headers.etag, undefined);
const created = await invoke({
method: "PUT",
path: `/space/${SPACE}/docs/one/meta`,
json: { custom: { name: "A note", tags: { k: "v" } } },
headers: { "if-none-match": "*" },
});
assert.equal(created.status, 201, JSON.stringify(created.json));
assert.ok(created.headers.etag);
assert.deepEqual(created.json.custom, { name: "A note", tags: { k: "v" } });
assert.equal(created.json.contentType, "application/json");
const read = await invoke({ path: `/space/${SPACE}/docs/one/meta` });
assert.equal(read.headers.etag, created.headers.etag);
const replaced = await invoke({
method: "PUT",
path: `/space/${SPACE}/docs/one/meta`,
json: { custom: { name: "B" } },
headers: { "if-match": created.headers.etag },
});
assert.equal(replaced.status, 200);
const missing = await invoke({ path: `/space/${SPACE}/docs/absent/meta` });
assert.equal(missing.status, 404);
});
// --- policies and public reads ---------------------------------------------------
test("policies are versioned and PublicCanRead opens unsigned reads at the covered scope", async () => {
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 } });
const hidden = await invoke({ path: `/space/${SPACE}/docs/one`, signer: null });
assert.equal(hidden.status, 404);
const set = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one/policy`, json: { type: "PublicCanRead" } });
assert.equal(set.status, 201);
assert.ok(set.headers.etag);
const get = await invoke({ path: `/space/${SPACE}/docs/one/policy` });
assert.deepEqual(get.json, { type: "PublicCanRead" });
assert.equal(get.headers.etag, set.headers.etag);
const open = await invoke({ path: `/space/${SPACE}/docs/one`, signer: null });
assert.equal(open.status, 200);
assert.deepEqual(open.json, { v: 1 });
// The policy covers the resource, not its siblings or the listing.
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/two`, json: { v: 2 } });
assert.equal((await invoke({ path: `/space/${SPACE}/docs/two`, signer: null })).status, 404);
const listing = await invoke({ path: `/space/${SPACE}/docs/`, signer: null });
assert.equal(listing.status, 200);
assert.deepEqual(listing.json.items, []);
// Never the policy itself, never a write.
assert.equal((await invoke({ path: `/space/${SPACE}/docs/one/policy`, signer: null })).status, 404);
assert.equal((await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 9 }, signer: null })).status, 401);
const cleared = await invoke({ method: "DELETE", path: `/space/${SPACE}/docs/one/policy` });
assert.equal(cleared.status, 204);
assert.equal((await invoke({ path: `/space/${SPACE}/docs/one`, signer: null })).status, 404);
// A collection-scoped policy covers the listing and every member.
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/policy`, json: { type: "PublicCanRead" } });
assert.equal((await invoke({ path: `/space/${SPACE}/docs/two`, signer: null })).status, 200);
const publicList = await invoke({ path: `/space/${SPACE}/docs/`, signer: null });
assert.equal(publicList.json.items.length, 2);
});
// --- authorization ---------------------------------------------------------------
test("requests to an unregistered Space, by a stranger, or with a tampered signature are 404", async () => {
const unregistered = await invoke({ path: `/space/dcc-was-00000000-0000-4000-8000-000000000009/meta` });
assert.equal(unregistered.status, 404);
const stranger = await invoke({ path: `/space/${SPACE}/meta`, signer: strangerKey });
assert.equal(stranger.status, 404);
const tampered = await invoke({ path: `/space/${SPACE}/meta`, tamper: true });
assert.equal(tampered.status, 404);
const strangerWrite = await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 }, signer: strangerKey });
assert.equal(strangerWrite.status, 404);
// A listing answers empty rather than 404.
const listing = await invoke({ path: `/space/${SPACE}/`, signer: strangerKey });
assert.equal(listing.status, 200);
assert.deepEqual(listing.json.items, []);
});
test("DELETE /space/{s}/ removes the bucket and the registry row", async () => {
await invoke({ method: "PUT", path: `/space/${SPACE}/docs/one`, json: { v: 1 } });
const res = await invoke({ method: "DELETE", path: `/space/${SPACE}/` });
assert.equal(res.status, 204);
assert.equal(fakes.s3.buckets.has(SPACE), false);
assert.equal(fakes.dynamo.tables["was-spaces"].has(`${BASE}/space/${SPACE}`), false);
const after = await invoke({ path: `/space/${SPACE}/meta` });
assert.equal(after.status, 404);
});
// --- did:webvh controllers ---------------------------------------------------
const ACCOUNT = "dcc-was-0000aaaa-0000-4000-8000-0000000000ab";
test("a did:webvh-controlled Space authorizes the keys its current document lists", async () => {
const account = await mintWebvh({ path: ACCOUNT });
await seedSpace(fakes, { spaceId: ACCOUNT, controller: account.did });
await seedWebvhLog(fakes, ACCOUNT, account.jsonl);
// The key, signing as its verification method in the document
const ok = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: asWebvh(controllerKey, account.did) });
assert.equal(ok.status, 200, JSON.stringify(ok.json));
assert.equal(ok.json.controller, account.did);
// The same key under its did:key name is not the controller
const asKey = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: controllerKey });
assert.equal(asKey.status, 404);
// A key the document does not list, signing under the account's name
const stranger = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: asWebvh(strangerKey, account.did) });
assert.equal(stranger.status, 404);
// Writes work the same way
const put = await invoke({
method: "PUT",
path: `/space/${ACCOUNT}/notes/one`,
json: { v: 1 },
signer: asWebvh(controllerKey, account.did),
});
assert.equal(put.status, 201);
});
test("a key added to the document is accepted before the cache expires", async () => {
const account = await mintWebvh({ path: ACCOUNT });
await seedSpace(fakes, { spaceId: ACCOUNT, controller: account.did });
await seedWebvhLog(fakes, ACCOUNT, account.jsonl);
// The first request caches the one-key document
const first = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: asWebvh(controllerKey, account.did) });
assert.equal(first.status, 200);
// A second key joins the same log (a new credential); the cache still
// holds the old document, and the new key is accepted at once
const added = strangerKey.fingerprint();
const members = [controllerKey.fingerprint(), added];
const grown = await updateDID({
log: account.log,
signer: signerFromDidKeySigner(controllerKey.signer()),
updateKeys: [`did:key:${controllerKey.fingerprint()}`],
verificationMethods: members.map((publicKeyMultibase) => ({ type: "Multikey", publicKeyMultibase })),
vmIdFragment: "multibase",
authentication: members.map((m) => `#${m}`),
assertionMethod: members.map((m) => `#${m}`),
capabilityInvocation: members.map((m) => `#${m}`),
capabilityDelegation: members.map((m) => `#${m}`),
});
await seedObject(fakes, bucketOf(ACCOUNT), "collections/id/did.jsonl", logToJsonlString(grown.log), "text/jsonl");
const asNew = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: asWebvh(strangerKey, account.did) });
assert.equal(asNew.status, 200, JSON.stringify(asNew.json));
});
test("a did:webvh whose log is hosted elsewhere is fetched over HTTPS", async () => {
const account = await mintWebvh({ domain: "elsewhere.test", path: "alice" });
await seedSpace(fakes, { spaceId: ACCOUNT, controller: account.did });
const requested = [];
const realFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
requested.push(String(url));
return new Response(account.jsonl, { status: 200, headers: { "content-type": "text/jsonl" } });
};
try {
const res = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: asWebvh(controllerKey, account.did) });
assert.equal(res.status, 200, JSON.stringify(res.json));
assert.deepEqual(requested, ["https://elsewhere.test/alice/did.jsonl"]);
} finally {
globalThis.fetch = realFetch;
}
});
test("a Space whose did:webvh log is missing refuses every signed request", async () => {
const account = await mintWebvh({ path: ACCOUNT });
await seedSpace(fakes, { spaceId: ACCOUNT, controller: account.did });
const res = await invoke({ path: `/space/${ACCOUNT}/meta`, signer: asWebvh(controllerKey, account.did) });
assert.equal(res.status, 404);
});
test("PUT /space/{s}/meta promotes a did:key controller to a did:webvh that lists the key", async () => {
const account = await mintWebvh({ path: SPACE });
await seedWebvhLog(fakes, SPACE, account.jsonl);
const current = await invoke({ path: `/space/${SPACE}/meta` });
const promoted = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { name: "Test Space", controller: account.did },
headers: { "if-match": current.headers.etag },
});
assert.equal(promoted.status, 200, JSON.stringify(promoted.json));
assert.equal(promoted.json.controller, account.did);
assert.equal(promoted.json.createdBy, controllerKey.controller);
assert.equal(fakes.dynamo.tables["was-spaces"].get(`${BASE}/space/${SPACE}`).did.S, account.did);
// From now on the did:key form no longer invokes; the document's key does
const asKey = await invoke({ path: `/space/${SPACE}/meta` });
assert.equal(asKey.status, 404);
const asAccount = await invoke({ path: `/space/${SPACE}/meta`, signer: asWebvh(controllerKey, account.did) });
assert.equal(asAccount.status, 200);
// And the controller cannot move again
const again = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { name: "Test Space", controller: controllerKey.controller },
headers: { "if-match": asAccount.headers.etag },
signer: asWebvh(controllerKey, account.did),
});
assert.equal(again.status, 400);
assert.equal(again.json.type, "https://w3id.org/pws#controller-mismatch");
});
test("PUT /space/{s}/meta refuses a promotion to a did:webvh that does not list the invoking key", async () => {
const account = await mintWebvh({ key: strangerKey, path: SPACE });
await seedWebvhLog(fakes, SPACE, account.jsonl);
const current = await invoke({ path: `/space/${SPACE}/meta` });
const res = await invoke({
method: "PUT",
path: `/space/${SPACE}/meta`,
json: { name: "Test Space", controller: account.did },
headers: { "if-match": current.headers.etag },
});
assert.equal(res.status, 400);
assert.equal(res.json.type, "https://w3id.org/pws#controller-mismatch");
assert.equal(fakes.dynamo.tables["was-spaces"].get(`${BASE}/space/${SPACE}`).did.S, controllerKey.controller);
});
test("PUT /space/{s}/meta provisions an unlock Space whose id is derived from the signing DID", async () => {
const id = deriveSpaceId(controllerKey.controller);
const body = { name: "Unlock", controller: controllerKey.controller, type: ["AuxiliarySpace", "Space", "UnlockSpace"] };
const created = await invoke({ method: "PUT", path: `/space/${id}/meta`, json: body, headers: { "if-none-match": "*" } });
assert.equal(created.status, 201, JSON.stringify(created.json));
assert.equal(created.json.id, id);
assert.equal(created.json.controller, controllerKey.controller);
assert.deepEqual(created.json.type, body.type);
assert.ok(created.headers.etag);
assert.ok(fakes.s3.buckets.has(bucketOf(id)));
assert.notEqual(bucketOf(id), id);
assert.match(bucketOf(id), /^dcc-was-[0-9a-f]{40}$/);
const row = fakes.dynamo.tables["was-spaces"].get(`${BASE}/space/${id}`);
assert.equal(row.did.S, controllerKey.controller);
assert.deepEqual(row.type.L.map((entry) => entry.S), body.type);
// It is an ordinary Space from here: readable, writable, re-configurable
const read = await invoke({ path: `/space/${id}/meta` });
assert.equal(read.status, 200);
const record = await invoke({ method: "PUT", path: `/space/${id}/keyring/keyring.json`, json: { wrapped: "..." } });
assert.equal(record.status, 201);
assert.ok(fakes.s3.buckets.get(bucketOf(id)).has("collections/keyring/keyring.json"));
const renamed = await invoke({
method: "PUT",
path: `/space/${id}/meta`,
json: { ...body, name: "Passphrase" },
headers: { "if-match": read.headers.etag },
});
assert.equal(renamed.status, 200);
assert.equal(renamed.json.name, "Passphrase");
// And deletable, bucket and registry row alike
const deleted = await invoke({ method: "DELETE", path: `/space/${id}/` });
assert.equal(deleted.status, 204);
assert.ok(!fakes.s3.buckets.has(bucketOf(id)));
assert.ok(!fakes.dynamo.tables["was-spaces"].has(`${BASE}/space/${id}`));
});
test("self-provisioning is refused for any id not derived from the signer, and for a non-unlock type", async () => {
const mine = deriveSpaceId(controllerKey.controller);
const theirs = deriveSpaceId(strangerKey.controller);
const unlock = ["AuxiliarySpace", "Space", "UnlockSpace"];
// Someone else's unlock id
const stolen = await invoke({
method: "PUT",
path: `/space/${theirs}/meta`,
json: { name: "Unlock", controller: strangerKey.controller, type: unlock },
headers: { "if-none-match": "*" },
});
assert.equal(stolen.status, 404);
// A server-assigned-looking id nobody registered
const unknown = await invoke({
method: "PUT",
path: `/space/dcc-was-00000000-0000-4000-8000-0000000000ff/meta`,
json: { name: "Unlock", controller: controllerKey.controller, type: unlock },
headers: { "if-none-match": "*" },
});
assert.equal(unknown.status, 404);
// The derived id, but not an unlock Space
const plain = await invoke({
method: "PUT",
path: `/space/${mine}/meta`,
json: { name: "Mine", controller: controllerKey.controller },
headers: { "if-none-match": "*" },
});
assert.equal(plain.status, 400);
assert.ok(!fakes.s3.buckets.has(bucketOf(mine)));
// Unsigned
const unsigned = await invoke({
method: "PUT",
path: `/space/${mine}/meta`,
json: { name: "Unlock", controller: controllerKey.controller, type: unlock },
headers: { "if-none-match": "*" },
signer: null,
});
assert.equal(unsigned.status, 404);
});
// --- delegated capabilities ----------------------------------------------------
// The controller delegates a capability on the whole Space to the stranger,
// under `SuiteClass`, allowing the actions given.
async function delegateSpace(SuiteClass, allowedActions = ["GET", "PUT", "DELETE"]) {
const client = new ZcapClient({ SuiteClass, delegationSigner: controllerKey.signer() });
return client.delegate({
capability: rootCapabilityId(SPACE_URL),
controller: strangerKey.controller,
invocationTarget: SPACE_URL,
allowedActions,
expires: new Date(Date.now() + 24 * 3600 * 1000),
});
}
test("a delegated capability authorizes Resource operations under either proof suite, and container operations stay root-only", async () => {
for (const SuiteClass of [EddsaJcs2022, Ed25519Signature2020]) {
const capability = await delegateSpace(SuiteClass);
const path = `/space/${SPACE}/keyring/${SuiteClass.name}`;
const created = await invoke({ method: "PUT", path, json: { v: 1 }, signer: strangerKey, capability });
assert.equal(created.status, 201, `${SuiteClass.name}: ${created.body}`);
const read = await invoke({ path, signer: strangerKey, capability });
assert.equal(read.status, 200, `${SuiteClass.name}: ${read.body}`);
assert.deepEqual(read.json, { v: 1 });
const removed = await invoke({ method: "DELETE", path, signer: strangerKey, capability });
assert.equal(removed.status, 204, `${SuiteClass.name}: ${removed.body}`);
// The Space itself, its metadata and a Collection are container
// operations: a delegated capability is refused with a 404
const spaceGone = await invoke({ method: "DELETE", path: `/space/${SPACE}/`, signer: strangerKey, capability });
assert.equal(spaceGone.status, 404);
assert.ok(fakes.s3.buckets.has(bucketOf(SPACE)));
const collectionGone = await invoke({ method: "DELETE", path: `/space/${SPACE}/keyring/`, signer: strangerKey, capability });
assert.equal(collectionGone.status, 404);
}
});
test("a delegated capability is refused for an action it does not allow, and without it the stranger is refused", async () => {
const readOnly = await delegateSpace(EddsaJcs2022, ["GET"]);
const write = await invoke({ method: "PUT", path: `/space/${SPACE}/keyring/record`, json: { v: 1 }, signer: strangerKey, capability: readOnly });
assert.equal(write.status, 404);
const bare = await invoke({ method: "PUT", path: `/space/${SPACE}/keyring/record`, json: { v: 1 }, signer: strangerKey });
assert.equal(bare.status, 404);
assert.ok(!objectKeys().some((key) => key.startsWith("keyring/")));
});