source: Klonkt/test/guardianship.test.js@ b60cf25

Last change on this file since b60cf25 was b60cf25, checked in by Robin <roboburr@…>, 3 months ago

guardianship: §1 is flat in beide richtingen, ook bij accept

Backport van 0261730 op main. Het Offer-pad belet een ward om te offeren
(a_ward_cannot_guard), maar het Accept-pad kende geen spiegelbeeld: een actor
die al wards heeft kon een guardianship-Offer accepteren en werd zo ward én
guardian tegelijk. §1 eist flatheid in beide richtingen.

De fout meldt zich niet. actorProps() kiest met een if/else één rol en
publiceert dan shaer:guardians terwijl shaer:isGuardian wegvalt: lokaal
blijven escalaties van de eigen wards binnenkomen, terwijl elke remote
§4-check de actor als malformed leest en laat vallen.

357 tests groen in een echte 1.6-omgeving (eigen npm ci, nodemailer 6.10.1
zoals stable vraagt, niet main's 9.x). Controleproef gedraaid: zonder de
controle wordt de nieuwe test rood en valt ook 'a guardian leaving sends an
Undo (§3.2)' om, doordat de actor dan werkelijk ward wordt.

Closes shaer-pmo.

Co-Authored-By: Claude Opus 5 <noreply@…>

  • Property mode set to 100644
File size: 13.5 KB
Line 
1// The guardianship module (FEP-633c) — the multi-party handshake (§3).
2// Everyone lives on one in-memory instance here, so the handshake copies all
3// converge locally; that also exercises the "multiple local parties" routing.
4import { test } from 'node:test';
5import assert from 'node:assert/strict';
6
7process.env.DATABASE_PATH = ':memory:';
8process.env.PUBLIC_BASE_URL = 'https://test.example';
9
10const dbMod = await import('../src/config/database.js');
11const db = dbMod.default;
12dbMod.initializeDatabase();
13const AP = (await import('../src/services/ActivityPubService.js')).default;
14const G = await import('../src/services/guardianship/index.js');
15
16function site(id, slug) {
17 db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary) VALUES (?,?,?,?,?)').run(id, slug, slug, 'u1', id === 's1' ? 1 : 0);
18 return db.prepare('SELECT * FROM sites WHERE id = ?').get(id);
19}
20db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)').run('u1', 'u1', 'u1@test', 'x', 'god');
21const parent = site('s1', 'parent'); // first guardian-candidate
22const kid = site('s2', 'kid'); // ward
23const gran = site('s3', 'gran'); // second guardian-candidate (co-approver later)
24const A = (slug) => `https://test.example/ap/users/${slug}`;
25const [ME, KID, GRAN] = [A('parent'), A('kid'), A('gran')];
26
27// No network: the handshake delivers by feeding each activity straight into the
28// inbound handler of every addressed local party (what real S2S would do).
29G.wireHandshake({
30 selfId: A,
31 localSlug: (uri) => (uri.startsWith('https://test.example/ap/users/') ? uri.split('/').pop() : null),
32 deriveHandle: (uri) => '@' + uri.split('/').pop() + '@test.example',
33 fetchActor: async () => null,
34 deliverTo: async (fromSite, toUri, activity) => {
35 const slug = toUri.split('/').pop();
36 const s = db.prepare('SELECT * FROM sites WHERE slug = ?').get(slug);
37 if (s) await G.handleGuardianshipInbox(s, activity);
38 return { delivered: true };
39 },
40 onEvent: null,
41});
42
43const offerIdFrom = (r) => r.id;
44
45test('first guardian: a free ward commits on its own single accept', async () => {
46 const off = await G.handleGuardianshipOutbox(parent, {
47 type: 'Offer', object: { type: 'Relationship', subject: KID, relationship: 'shaer:Guardian', object: ME },
48 });
49 assert.equal(off.status, 202);
50 const id = offerIdFrom(off);
51
52 // The kid sees the offer needing its accept; the candidate already agreed
53 // (the Offer is the candidate's accept), so it just waits.
54 const kidQ = G.offersCollection(`${KID}/queues/offers`, 'kid', KID).orderedItems;
55 assert.equal(kidQ.length, 1);
56 assert.equal(kidQ[0]['shaer:needsMyAccept'], true);
57 assert.deepEqual(kidQ[0]['shaer:acceptedBy'], [ME]); // candidate accepted via the offer
58 const parentQ0 = G.offersCollection(`${ME}/queues/offers`, 'parent', ME).orderedItems;
59 assert.equal(parentQ0[0]['shaer:needsMyAccept'], false); // candidate already agreed
60
61 // Not committed until the ward agrees.
62 assert.deepEqual(G.listGuardians('kid'), []);
63
64 // The kid accepts → free ward, no existing guardian to co-approve → commit.
65 const done = await G.handleGuardianshipOutbox(kid, { type: 'Accept', object: id });
66 assert.equal(done.committed, true);
67 assert.deepEqual(G.listGuardians('kid').map((g) => g.other_uri), [ME]);
68 assert.deepEqual(G.listWards('parent').map((w) => w.other_uri), [KID]);
69 // other_handle is the display @handle (not the escalation inbox handle).
70 assert.equal(G.listGuardians('kid')[0].other_handle, '@parent@test.example');
71 assert.equal(G.listWards('parent')[0].other_handle, '@kid@test.example');
72
73 // The ward actor now names its guardian; parent reads as guardian (§2).
74 assert.deepEqual(AP.buildActor('https://test.example', kid)['shaer:guardians'], [ME]);
75 assert.equal(AP.buildActor('https://test.example', parent)['shaer:isGuardian'], true);
76 // §1 mutual exclusion: the ward is not also a guardian.
77 assert.equal(AP.buildActor('https://test.example', kid)['shaer:isGuardian'], undefined);
78});
79
80test('second guardian needs the EXISTING guardian to co-accept (§3.1.2)', async () => {
81 // Gran offers to also guard the kid (who already has parent).
82 const off = await G.handleGuardianshipOutbox(gran, {
83 type: 'Offer', object: { type: 'Relationship', subject: KID, relationship: 'shaer:Guardian', object: GRAN },
84 });
85 const id = offerIdFrom(off);
86 // The existing guardian (parent) is a party and must accept.
87 const parentQ = G.offersCollection(`${ME}/queues/offers`, 'parent', ME).orderedItems.find((o) => o.id === id);
88 assert.ok(parentQ, 'parent sees the co-guardianship offer');
89 assert.deepEqual(parentQ['shaer:existingGuardians'], [ME]);
90
91 // The kid accepts, but now it IS a ward: NOT committed, because the existing
92 // guardian (parent) has not co-accepted (§3.1.2). The candidate (gran) already
93 // agreed via the offer, so no separate gran accept is needed.
94 const early = await G.handleGuardianshipOutbox(kid, { type: 'Accept', object: id });
95 assert.equal(early.committed, false);
96 assert.equal(G.listGuardians('kid').length, 1, 'still just the first guardian');
97
98 // The existing guardian co-accepts → tally complete → commit.
99 await G.handleGuardianshipOutbox(parent, { type: 'Accept', object: id });
100 assert.deepEqual(G.listGuardians('kid').map((g) => g.other_uri).sort(), [GRAN, ME].sort());
101});
102
103test('a single Reject from a required party voids the offer (§3.2)', async () => {
104 // parent offers to guard gran (who is free).
105 const off = await G.handleGuardianshipOutbox(parent, {
106 type: 'Offer', object: { type: 'Relationship', subject: GRAN, relationship: 'shaer:Guardian', object: ME },
107 });
108 const id = offerIdFrom(off);
109 await G.handleGuardianshipOutbox(gran, { type: 'Reject', object: id });
110 const q = G.offersCollection(`${ME}/queues/offers`, 'parent', ME).orderedItems.find((o) => o.id === id);
111 assert.equal(q, undefined, 'voided offer leaves the queue');
112 assert.equal(G.listWards('parent').some((w) => w.other_uri === GRAN), false);
113});
114
115test('a ward cannot become a guardian (§1)', async () => {
116 const r = await G.handleGuardianshipOutbox(kid, {
117 type: 'Offer', object: { type: 'Relationship', subject: A('someone'), relationship: 'shaer:Guardian', object: KID },
118 });
119 assert.equal(r.status, 403);
120 assert.equal(r.error, 'a_ward_cannot_guard');
121});
122
123test('a guardian cannot be guarded either: §1 is flat in both directions', async () => {
124 // parent guards kid by now, and gran (a guardian, so free to offer) offers
125 // to guard parent. The offer itself is fine; only parent's accept would
126 // make one actor ward and guardian at once.
127 assert.ok(G.listWards('parent').length, 'parent already guards someone');
128 const off = await G.handleGuardianshipOutbox(gran, {
129 type: 'Offer', object: { type: 'Relationship', subject: ME, relationship: 'shaer:Guardian', object: GRAN },
130 });
131 assert.equal(off.status, 202, 'a guardian may still offer to guard');
132 const id = offerIdFrom(off);
133
134 const r = await G.handleGuardianshipOutbox(parent, { type: 'Accept', object: id });
135 assert.equal(r.status, 403);
136 assert.equal(r.error, 'a_guardian_cannot_be_guarded');
137
138 // Nothing recorded, and the actor document still reads as a pure guardian.
139 // Without the check actorProps() would have flipped it to a ward silently.
140 assert.deepEqual(G.listGuardians('parent'), []);
141 const doc = AP.buildActor('https://test.example', parent);
142 assert.equal(doc['shaer:isGuardian'], true);
143 assert.equal(doc['shaer:guardians'], undefined);
144
145 // The candidate and the existing guardians are untouched by the check, so
146 // the offer is refusable in the ordinary way rather than stuck.
147 await G.handleGuardianshipOutbox(parent, { type: 'Reject', object: id });
148});
149
150test('only the candidate may offer (§3.1 fixed initiator)', async () => {
151 const r = await G.handleGuardianshipOutbox(parent, {
152 type: 'Offer', object: { type: 'Relationship', subject: A('newkid'), relationship: 'shaer:Guardian', object: GRAN },
153 });
154 assert.equal(r.status, 403);
155 assert.equal(r.error, 'only_the_candidate_offers');
156});
157
158test('helpRequest props only ride direct notes', () => {
159 assert.equal(G.isHelpRequest({ 'shaer:helpRequest': true }), true);
160 assert.equal(G.isHelpRequest({}), false);
161});
162
163// ── §3.2/§3.3: ending a guardianship ─────────────────────────────────────
164// This used to be a local delete that never left the building: the guardian's
165// dashboard forgot the ward, while the ward's server kept listing them in
166// shaer:guardians. Robin calls that a bug, and it is: the Undo has to travel.
167// At this point in the file the kid has two guardians, parent and gran.
168
169test('a guardian leaving sends an Undo that both sides act on (§3.2)', async () => {
170 assert.deepEqual(G.listGuardians('kid').map((g) => g.other_uri).sort(), [ME, GRAN].sort(), 'two guardians to start');
171
172 const r = await G.endGuardianship(gran, KID);
173 assert.equal(r.status, 202);
174 assert.equal(r.delivered, true, 'the Undo went out, it is not a local delete');
175
176 // The ward's own actor document is the thing that had to change.
177 assert.deepEqual(G.listGuardians('kid').map((g) => g.other_uri), [ME]);
178 assert.deepEqual(AP.buildActor('https://test.example', kid)['shaer:guardians'], [ME]);
179 assert.deepEqual(G.listWards('gran'), [], 'and the leaving guardian lost the ward');
180 assert.deepEqual(G.listWards('parent').map((w) => w.other_uri), [KID], 'the other guardian stays');
181});
182
183test('the last guardian cannot walk out alone: that is emancipation (§3.4)', async () => {
184 const r = await G.endGuardianship(parent, KID);
185 assert.equal(r.status, 409);
186 assert.equal(r.error, 'would_emancipate');
187 // Nothing moved on either side. Emptying shaer:guardians takes the flow of
188 // §3.4 (three consenting adults, or a majority plus two witnesses), never one
189 // party's click.
190 assert.deepEqual(G.listGuardians('kid').map((g) => g.other_uri), [ME]);
191 assert.deepEqual(G.listWards('parent').map((w) => w.other_uri), [KID]);
192});
193
194test('an Undo for a ward that is not yours is refused', async () => {
195 const r = await G.endGuardianship(gran, KID); // gran already left
196 assert.equal(r.status, 404);
197 assert.equal(r.error, 'not_my_ward');
198});
199
200test('the same Undo over C2S takes the same path', async () => {
201 // A Guardian app POSTs this to its own outbox; the dashboard button calls
202 // endGuardianship directly. One path, so the two cannot drift apart.
203 const undo = { type: 'Undo', object: { type: 'Relationship', subject: KID, relationship: 'shaer:Guardian', object: GRAN } };
204 const mine = await G.handleGuardianshipOutbox(gran, undo);
205 assert.equal(mine.status, 404, 'gran no longer guards the kid');
206
207 // And you cannot end someone else's relation by describing it.
208 const notMine = await G.handleGuardianshipOutbox(parent, undo);
209 assert.equal(notMine.status, 403);
210 assert.equal(notMine.error, 'not_your_relation');
211});
212
213test('an inbound Undo from someone who is not the guardian changes nothing', async () => {
214 const before = G.listGuardians('kid').map((g) => g.other_uri);
215 await G.handleGuardianshipInbox(kid, {
216 actor: GRAN, // gran claims to end PARENT's relation
217 type: 'Undo', object: { type: 'Relationship', subject: KID, relationship: 'shaer:Guardian', object: ME },
218 });
219 assert.deepEqual(G.listGuardians('kid').map((g) => g.other_uri), before);
220});
221
222test('a ward on this same instance is updated even though nothing is delivered', async () => {
223 // The browser found this: an inbox on this machine is not reachable over HTTP
224 // from this machine (nor should it be), so a co-located ward never receives
225 // the Undo. The guardian's side had dropped the ward while the ward's side
226 // still listed the guardian. Each instance must write what it hosts.
227 const kid2 = site('s4', 'kid2');
228 const g1 = site('s5', 'g1');
229 const g2 = site('s6', 'g2');
230 const [KID2, G1, G2] = [A('kid2'), A('g1'), A('g2')];
231
232 const o1 = await G.handleGuardianshipOutbox(g1, {
233 type: 'Offer', object: { type: 'Relationship', subject: KID2, relationship: 'shaer:Guardian', object: G1 } });
234 await G.handleGuardianshipOutbox(kid2, { type: 'Accept', object: o1.id });
235 const o2 = await G.handleGuardianshipOutbox(g2, {
236 type: 'Offer', object: { type: 'Relationship', subject: KID2, relationship: 'shaer:Guardian', object: G2 } });
237 await G.handleGuardianshipOutbox(kid2, { type: 'Accept', object: o2.id });
238 await G.handleGuardianshipOutbox(g1, { type: 'Accept', object: o2.id });
239 assert.deepEqual(G.listGuardians('kid2').map((g) => g.other_uri).sort(), [G1, G2].sort());
240
241 // Now deliver nothing at all, the way a loopback inbox behaves in practice.
242 const wired = {
243 selfId: A,
244 localSlug: (uri) => (uri.startsWith('https://test.example/ap/users/') ? uri.split('/').pop() : null),
245 deriveHandle: (uri) => '@' + uri.split('/').pop() + '@test.example',
246 fetchActor: async () => null,
247 deliverTo: async () => ({ delivered: false }),
248 onEvent: null,
249 };
250 G.wireHandshake(wired);
251 const r = await G.endGuardianship(g2, KID2);
252 assert.equal(r.status, 202);
253 assert.equal(r.delivered, false, 'nothing went over the wire');
254 assert.deepEqual(G.listWards('g2'), [], "the guardian's side is clear");
255 assert.deepEqual(G.listGuardians('kid2').map((g) => g.other_uri), [G1], "and so is the ward's");
256 assert.deepEqual(AP.buildActor('https://test.example', kid2)['shaer:guardians'], [G1]);
257
258 // Even undelivered, it must not empty the set: that is still emancipation.
259 const last = await G.endGuardianship(g1, KID2);
260 assert.equal(last.status, 409);
261 assert.deepEqual(G.listGuardians('kid2').map((g) => g.other_uri), [G1]);
262});
Note: See TracBrowser for help on using the repository browser.