kryptheon 0.1.64 → 0.1.66

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.
@@ -53,6 +53,9 @@ const LOCAL_ONLY = true;
53
53
  const NONE = 'There is no recording to learn the requests of your app from. Record the flows of each role:';
54
54
  const V = authz.VERDICT;
55
55
  const MAX_ATTEMPTS = 400;
56
+ // The tries sized to the app (roles x actions), never past this (blind round 32: 8 accounts, 5 roles and 65 routes
57
+ // planned 496 tries; 96 were left out of a fixed 400, and three owner-only routes were never tried by a lower role).
58
+ const MAX_ATTEMPTS_CEILING = 1500;
56
59
  const MAX_SNAPSHOT = 12;
57
60
  const EXCERPT = 200;
58
61
  const IDENTITY_PATHS = ['/api/me', '/api/auth/me', '/api/session', '/api/whoami', '/api/user', '/api/users/me', '/api/profile', '/me'];
@@ -239,6 +242,24 @@ function templateOfWritten(p) {
239
242
 
240
243
  const VERB_WORDS = new Set([...READ_WORDS, 'create', 'add', 'update', 'edit', 'write', 'delete', 'remove', 'manage']);
241
244
 
245
+ // Words of the same meaning, for what a route does and what a permission allows (round 30: POST /payouts/{id}/execute
246
+ // next to payouts.approve, PUT /settings next to settings.write, a promote-to-owner route next to roles.write).
247
+ const SAME_MEANING = {
248
+ approve: ['approve', 'execute', 'pay', 'run', 'process', 'release', 'disburse', 'settle', 'authorize', 'authorise', 'finalize', 'finalise'],
249
+ role: ['role', 'promote', 'demote', 'grant', 'revoke', 'elevate', 'permission', 'privilege'],
250
+ write: ['write', 'update', 'edit', 'modify', 'change', 'put', 'patch', 'save', 'set'],
251
+ create: ['create', 'add', 'new'],
252
+ delete: ['delete', 'remove', 'destroy'],
253
+ };
254
+ // An address about a credential (set-password, rotate-key): never given a permission by a word of the same meaning,
255
+ // nor tried when no rule names it - a made-up value sent there could lock an account out of the test copy.
256
+ const CREDENTIAL_WORD = /^(password|passwd|passcode|passphrase|pin|secret|token|otp|totp|mfa|2fa|key|apikey|credential)$/;
257
+ /** The meaning a word is one of ("execute" -> approve), or null. */
258
+ function meaningOf(word) {
259
+ const w = String(word || '');
260
+ return Object.keys(SAME_MEANING).find((k) => SAME_MEANING[k].includes(w)) || null;
261
+ }
262
+
242
263
  /**
243
264
  * A permission name split into what it is about and what it allows:
244
265
  * "orders.read" -> orders / read; "read:purchase_orders" -> purchase, order / read;
@@ -291,8 +312,12 @@ function permissionFor(method, pathOrTemplate, policy) {
291
312
  if (isGet !== readish) continue;
292
313
  let score = hits;
293
314
  let lastHit = resource.some((r) => last.has(r));
315
+ const firstWords = (statics.map((s) => wordsOf(s).filter((w) => !SKIP_WORDS.has(w) && !/^v\d+$/.test(w))).find((ws) => ws.length)) || [];
316
+ const firstHit = resource.some((r) => firstWords.includes(r));
317
+ let actionInPath = false;
294
318
  for (const a of actions) {
295
319
  if (pathWords.has(a)) {
320
+ actionInPath = true;
296
321
  score += 2;
297
322
  if (last.has(a)) lastHit = true;
298
323
  } else if (a === 'export' && extension) {
@@ -300,6 +325,9 @@ function permissionFor(method, pathOrTemplate, policy) {
300
325
  lastHit = true;
301
326
  } else if (a === verb) {
302
327
  score += 1;
328
+ } else if (meaningOf(a) && meaningOf(a) === meaningOf(verb)) {
329
+ // PUT and settings.write: the method's own word wins over one of the same meaning
330
+ score += 0.5;
303
331
  } else if (a === 'manage') {
304
332
  // "team.manage" covers what is done to the team's parts: PATCH /team/5/role (round 26). One that names the
305
333
  // part itself still wins, scoring more; a read never reaches here (manage is not a read word).
@@ -307,18 +335,95 @@ function permissionFor(method, pathOrTemplate, policy) {
307
335
  lastHit = true;
308
336
  }
309
337
  }
310
- found.push({ permission: perm, score: score, lastHit: lastHit });
338
+ found.push({ permission: perm, score: score, lastHit: lastHit, firstHit: firstHit, actionInPath: actionInPath });
311
339
  }
312
- if (!found.length) return null;
313
- const lastWordsAny = statics.length > 0 && parsed.params.length > 0 && statics[statics.length - 1] !== undefined && parsed.segs[parsed.segs.length - 1] !== '{id}';
314
- found.sort((a, b) => (b.lastHit ? 1 : 0) - (a.lastHit ? 1 : 0) || b.score - a.score);
315
- const best = found[0];
316
- // "/shipments/5/notes": the end of the address names something none of the
317
- // permissions does, so the permission of "shipments" would be a guess.
318
- if (!best.lastHit && lastWordsAny) return { ambiguous: true, why: 'the end of the address (' + statics[statics.length - 1] + ') matches no permission name' };
319
- const tied = found.filter((f) => f.lastHit === best.lastHit && f.score === best.score);
320
- if (tied.length > 1) return { ambiguous: true, why: 'it fits ' + tied.map((t) => t.permission).join(' and ') + ' equally' };
321
- return { permission: best.permission, how: 'by the words in the address' };
340
+ const strict = (() => {
341
+ if (!found.length) return null;
342
+ const lastWordsAny = statics.length > 0 && parsed.params.length > 0 && statics[statics.length - 1] !== undefined && parsed.segs[parsed.segs.length - 1] !== '{id}';
343
+ found.sort((a, b) => (b.lastHit ? 1 : 0) - (a.lastHit ? 1 : 0) || b.score - a.score);
344
+ const best = found[0];
345
+ // A named action at the end of an address with no record in it (POST /jobs/reconcile-client): a permission found
346
+ // only by a noun inside that name (clients.write - "write" is nowhere in the address) is what the action works on,
347
+ // not what it is; the permission of the address's first word (jobs.run) is. Round 33: finance, which may run jobs,
348
+ // was called a role failure for running one.
349
+ const lastSeg = statics.length > 1 ? wordsOf(statics[statics.length - 1].replace(FILE_EXTENSIONS, '')) : [];
350
+ if (!parsed.params.length && lastSeg.length > 1 && best.lastHit && !best.actionInPath && !best.firstHit) {
351
+ const own = found.filter((f) => f.firstHit && f.permission !== best.permission);
352
+ if (own.length === 1) return { permission: own[0].permission, how: 'by the first word of the address (its end names what it works on)' };
353
+ }
354
+ // "/shipments/5/notes": the end of the address names something none of the
355
+ // permissions does, so the permission of "shipments" would be a guess.
356
+ if (!best.lastHit && lastWordsAny) return { ambiguous: true, why: 'the end of the address (' + statics[statics.length - 1] + ') matches no permission name' };
357
+ const tied = found.filter((f) => f.lastHit === best.lastHit && f.score === best.score);
358
+ if (tied.length > 1) return { ambiguous: true, why: 'it fits ' + tied.map((t) => t.permission).join(' and ') + ' equally' };
359
+ return { permission: best.permission, how: 'by the words in the address' };
360
+ })();
361
+ if (strict && strict.permission) return strict;
362
+ return (isGet ? null : sameMeaning(policy, statics, pathWords, verb)) || strict;
363
+ }
364
+
365
+ /** What a change no rule names does, by the words at the end of its address ("execute" -> approve), or null. */
366
+ function unruledMeaning(action, policy) {
367
+ const statics = String(action.template).split('/').filter((x) => x && x !== '{id}');
368
+ const last = statics.length ? wordsOf(statics[statics.length - 1]) : [];
369
+ return last.map(meaningOf).find(Boolean) || null;
370
+ }
371
+
372
+ /** Whether a role holds any permission that does this (approve, role, write...), on anything. */
373
+ function holdsMeaning(policy, role, meaning) {
374
+ const key = Object.keys(policy.roles).find((r) => r.toLowerCase() === String(role || '').toLowerCase());
375
+ if (!key) return false;
376
+ return policy.roles[key].some((perm) => {
377
+ if (perm === '*' || perm.endsWith('.*')) return true;
378
+ const parts = (policy.parts && policy.parts[perm]) || partsOf(perm);
379
+ if (!parts) return false;
380
+ if (meaning === 'role') return parts.resource.concat(parts.actions).some((x) => meaningOf(x) === 'role') && !parts.actions.every((a) => READ_WORDS.has(a));
381
+ return parts.actions.some((a) => meaningOf(a) === meaning);
382
+ });
383
+ }
384
+
385
+ /**
386
+ * A change whose address ends in a word no permission names, given the
387
+ * permission of the policy's own word of the same meaning: for the same
388
+ * resource ("execute" -> payouts.approve, "update" -> settings.write), or, for
389
+ * a word about roles ("promote", "grant"), the policy's permission over roles.
390
+ * Only when exactly one fits best; anything else stays unnamed.
391
+ */
392
+ function sameMeaning(policy, statics, pathWords, verb) {
393
+ if (Array.from(pathWords).some((w) => CREDENTIAL_WORD.test(w))) return null;
394
+ const last = statics.length ? wordsOf(statics[statics.length - 1].replace(FILE_EXTENSIONS, '')) : [];
395
+ // the words of the end of the address that say what is done; an address that ends in its resource says it by its method
396
+ const doing = last.filter((w) => meaningOf(w));
397
+ const resources = new Set();
398
+ for (const perm of permissionsOf(policy)) for (const r of ((policy.parts && policy.parts[perm]) || partsOf(perm) || { resource: [] }).resource) resources.add(r);
399
+ // "/settings" ends in a resource a permission names: what is done is its method; "/shipments/5/notes" ends in something else
400
+ if (!doing.length && verb && last.length && last.every((w) => resources.has(w))) doing.push(verb);
401
+ for (const w of doing) {
402
+ const meaning = meaningOf(w);
403
+ if (!meaning) continue;
404
+ const fits = [];
405
+ for (const perm of permissionsOf(policy)) {
406
+ const parts = (policy.parts && policy.parts[perm]) || partsOf(perm);
407
+ if (!parts || parts.actions.every((a) => READ_WORDS.has(a))) continue;
408
+ const hits = parts.resource.filter((r) => pathWords.has(r)).length;
409
+ if (meaning === 'role') {
410
+ // a permission over roles: its resource or what it allows is a role ("roles.write", "team.roles", "members.manage_roles")
411
+ const all = parts.resource.concat(parts.actions);
412
+ if (!all.some((x) => meaningOf(x) === 'role')) continue;
413
+ const changes = parts.actions.some((a) => meaningOf(a) === 'write' || meaningOf(a) === 'role' || a === 'manage');
414
+ if (!changes) continue;
415
+ fits.push({ permission: perm, rank: hits * 2 + (parts.actions.some((a) => meaningOf(a) === 'write') ? 1 : 0) });
416
+ } else {
417
+ if (!hits || !parts.actions.some((a) => meaningOf(a) === meaning)) continue;
418
+ fits.push({ permission: perm, rank: hits * 2 + (parts.actions.includes(meaning) ? 1 : 0) });
419
+ }
420
+ }
421
+ if (!fits.length) continue;
422
+ fits.sort((a, b) => b.rank - a.rank);
423
+ if (fits.length > 1 && fits[1].rank === fits[0].rank) return { ambiguous: true, why: 'by a word of the same meaning (' + w + ') it fits ' + fits.filter((f) => f.rank === fits[0].rank).map((f) => f.permission).join(' and ') + ' equally' };
424
+ return { permission: fits[0].permission, how: 'by a word of the same meaning (' + w + ' -> ' + fits[0].permission + ')' };
425
+ }
426
+ return null;
322
427
  }
323
428
 
324
429
  // --- the journey: what the recordings did -----------------------------------
@@ -627,6 +732,11 @@ async function checkAccess(input) {
627
732
  // 2. the actions, and the permission each needs
628
733
  const mapped = [];
629
734
  const reads = [];
735
+ const unruled = [];
736
+ // the roles with the fewest permissions: who a change no rule names is tried as
737
+ const counts = Object.keys(policy.roles || {}).map((r) => (policy.roles[r].includes('*') ? Infinity : policy.roles[r].length));
738
+ const fewest = counts.length ? Math.min.apply(null, counts) : Infinity;
739
+ const lowest = new Set(Object.keys(policy.roles || {}).filter((r) => (policy.roles[r].includes('*') ? Infinity : policy.roles[r].length) === fewest));
630
740
  for (const a of journey.actions) {
631
741
  if (a.method === 'DELETE') {
632
742
  skipped.push({ what: a.method + ' ' + a.template, why: 'not tried: this check never sends a delete' });
@@ -636,6 +746,11 @@ async function checkAccess(input) {
636
746
  if (p && p.permission) {
637
747
  mapped.push(Object.assign({ permission: p.permission, how: p.how }, a));
638
748
  out.mapping.push({ method: a.method, template: a.template, permission: p.permission, how: p.how });
749
+ } else if (input.tryUnruled && !policy.anyRole && a.method !== 'GET' && a.method !== 'HEAD' && lowest.size && fewest !== Infinity && !a.segs.some((seg) => seg !== '{id}' && wordsOf(seg).some((w) => CREDENTIAL_WORD.test(w)))) {
750
+ // Asked for (the API check): a change no rule names is still tried, as the roles with the fewest permissions only.
751
+ // What it is about is its own words; a change that gets through is only a thing to check - no rule says who may.
752
+ unruled.push(Object.assign({ permission: null, unruled: { meaning: unruledMeaning(a, policy) } }, a));
753
+ skipped.push({ what: a.method + ' ' + a.template, why: 'not judged: ' + (p && p.ambiguous ? p.why : 'no permission in ' + POLICY_FILE + ' is named like this address') + '. Tried only as ' + Array.from(lowest).join(', ') + ' (the fewest permissions); a change that gets through is to check. Name its permission in ' + POLICY_FILE + ' under kryptheon.actions to judge it' });
639
754
  } else {
640
755
  skipped.push({ what: a.method + ' ' + a.template, why: p && p.ambiguous ? 'not judged: ' + p.why + '. Name its permission in ' + POLICY_FILE + ' under kryptheon.actions' : 'not judged: no permission in ' + POLICY_FILE + ' is named like this address. Name it under kryptheon.actions to include it' });
641
756
  }
@@ -644,6 +759,7 @@ async function checkAccess(input) {
644
759
  const getTemplates = new Set(journey.actions.filter((a) => a.method === 'GET').map((a) => a.template));
645
760
  const identityPaths = new Set(candidates);
646
761
  const snapshotReads = reads.filter((a) => !identityPaths.has(a.template) && !/health|public/i.test(a.template)).slice(0, MAX_SNAPSHOT);
762
+ const snapshotTemplates = new Set(snapshotReads.map((a) => a.template));
647
763
 
648
764
  const accountsOf = (orgKey) => (orgKey === null ? sessions : (orgs.get(orgKey) || { sessions: [] }).sessions);
649
765
  const permOf = new Map(mapped.map((a) => [a.method + ' ' + a.template, a.permission]));
@@ -827,6 +943,9 @@ async function checkAccess(input) {
827
943
  }
828
944
  }
829
945
  }
946
+ for (const action of unruled) {
947
+ for (const s of sessions) if (lowest.has(s.role)) plan.push({ action: action, actor: s, kind: 'role', expected: 'deny', org: s.org ? s.org.key : null, unruled: true });
948
+ }
830
949
  // Asked for (the API check): every action once with no session at all, aimed at
831
950
  // the first organization's records and judged by its lists before and after.
832
951
  if (input.anonymous) {
@@ -850,26 +969,51 @@ async function checkAccess(input) {
850
969
  }
851
970
  chosen.push(p);
852
971
  }
853
- const cap = input.maxAttempts || MAX_ATTEMPTS;
972
+ // Sized to the app: each role and the accounts' own, every action (blind round 32), within a ceiling.
973
+ const roleCount = new Set(sessions.map((s) => s.role)).size;
974
+ const cap = input.maxAttempts || Math.min(MAX_ATTEMPTS_CEILING, Math.max(MAX_ATTEMPTS, (roleCount + 1) * (mapped.length + unruled.length) * 2));
854
975
  if (chosen.length > cap) {
855
- notes.push((chosen.length - cap) + ' tries were left out to stay within ' + cap + ' (refusals were kept first).');
856
- chosen.length = cap;
976
+ // Kept first: what the policy says a role must be refused on a change, with the control that shows what an allowed
977
+ // change looks like; then refused reads, then the rest. They still run in the order planned (refusals first).
978
+ const tier = (p) => {
979
+ const write = p.action.method !== 'GET';
980
+ if (p.kind === 'role' && p.expected === 'deny' && write) return p.unruled ? 1 : 0;
981
+ if (p.kind === 'role' && p.expected === 'allow' && write) return 2;
982
+ if (p.kind === 'role' && p.expected === 'deny') return 3;
983
+ if (p.kind === 'tenant') return 4;
984
+ if (p.kind === 'signin') return 5;
985
+ return 6;
986
+ };
987
+ const order = chosen.map((p, i) => ({ p: p, i: i, t: tier(p) })).sort((x, y) => x.t - y.t || x.i - y.i);
988
+ const keep = new Set(order.slice(0, cap).map((o) => o.p));
989
+ const left = chosen.length - cap;
990
+ for (let i = chosen.length - 1; i >= 0; i--) if (!keep.has(chosen[i])) chosen.splice(i, 1);
991
+ notes.push(left + ' tries were left out to stay within ' + cap + ' (refusals of changes were kept first, then refusals of reads).');
857
992
  }
858
993
  out.planned = chosen.length;
994
+ // what the tries cost in requests: a picture before and after each, and a few more
995
+ ctx.limit = Math.max(ctx.limit, ctx.requests + chosen.length * (4 * Math.max(1, snapshotReads.length) + 12));
859
996
  const rotate = new Map();
860
997
  let n = 0;
861
- for (const p of chosen) {
862
- if (stopped()) {
863
- out.stopped = true;
864
- break;
998
+ try {
999
+ for (const p of chosen) {
1000
+ if (stopped()) {
1001
+ out.stopped = true;
1002
+ break;
1003
+ }
1004
+ n++;
1005
+ const a = p.action;
1006
+ const label = (p.kind === 'tenant' ? 'across organizations: ' : '') + p.actor.role + ' ' + a.method + ' ' + a.template;
1007
+ say(' ' + n + ' of ' + chosen.length + ': ' + label);
1008
+ const att = await tryOnce({ p, ctx, policy, orgs, snapshot, compare, targetsFor, itemsOf, markersOf, knownTo, readerFor, rotate, tenants, sessions, hide, getTemplates, snapshotTemplates, actions: journey.actions });
1009
+ if (Array.isArray(att)) out.attempts.push.apply(out.attempts, att);
1010
+ else if (att) out.attempts.push(att);
865
1011
  }
866
- n++;
867
- const a = p.action;
868
- const label = (p.kind === 'tenant' ? 'across organizations: ' : '') + p.actor.role + ' ' + a.method + ' ' + a.template;
869
- say(' ' + n + ' of ' + chosen.length + ': ' + label);
870
- const att = await tryOnce({ p, ctx, policy, orgs, snapshot, compare, targetsFor, itemsOf, markersOf, knownTo, readerFor, rotate, tenants, sessions, hide, getTemplates });
871
- if (Array.isArray(att)) out.attempts.push.apply(out.attempts, att);
872
- else if (att) out.attempts.push(att);
1012
+ } catch (err) {
1013
+ if (!authz.isRequestLimit(err)) throw err;
1014
+ // the tries made are kept and judged; the rest are said, not passed over in silence
1015
+ out.stopped = true;
1016
+ notes.push('The request limit (' + err.limit + ') was reached after ' + (n - 1) + ' of ' + chosen.length + ' tries; the rest were not tried.');
873
1017
  }
874
1018
  // An action every account was answered 401 for is not reached with a session cookie (an API key, say): nothing can be said about it.
875
1019
  const groups = new Map();
@@ -1044,27 +1188,49 @@ async function tryOnce(x) {
1044
1188
  // set approved_by, which no list showed
1045
1189
  const segs = a.template.split('/');
1046
1190
  const detail = segs.slice(0, segs.indexOf('{id}') + 1).join('/');
1047
- const readAt = reader && !isGet && a.params.length ? [a.template, detail].find((t) => x.getTemplates.has(t)) : null;
1048
- const sameGet = readAt ? readAt.replace('{id}', encodeURIComponent(String(target.value))) : null;
1191
+ // A change to an address with no record in it that is also read (PUT /settings, GET /settings) shows there too -
1192
+ // round 30: with 30 lists before it, GET /settings was not among the reads taken before and after each try, and a
1193
+ // member's change of the settings was "taken, nothing changed".
1194
+ const plainSame = reader && !isGet && !a.params.length && x.getTemplates.has(a.template) && !x.snapshotTemplates.has(a.template);
1195
+ const readAt = reader && !isGet && a.params.length ? [a.template, detail].find((t) => x.getTemplates.has(t)) : plainSame ? a.template : null;
1196
+ let sameGet = readAt ? readAt.replace('{id}', encodeURIComponent(String(target.value))) : null;
1049
1197
  const readSame = async () => {
1050
1198
  const f = sameGet ? await x.readerFor(targetOrg, sameGet, null, false) : null;
1051
1199
  return f ? stable(f.res.json) : undefined;
1052
1200
  };
1053
- const sameBefore = await readSame();
1201
+ let sameBefore = await readSame();
1202
+ // read twice: an address that changes by itself shows nothing about the try
1203
+ if (plainSame && sameBefore !== undefined && JSON.stringify(await readSame()) !== JSON.stringify(sameBefore)) {
1204
+ sameBefore = undefined;
1205
+ sameGet = null;
1206
+ }
1207
+ // what that address holds is the record the change is made to: an edit sends a value it does not already hold, and
1208
+ // is put back with what it held (a member's change of the settings after a manager's sent the same value, and changed nothing)
1209
+ const plainItem = plainSame && sameBefore && typeof sameBefore === 'object' && !Array.isArray(sameBefore) ? sameBefore : null;
1210
+ if (plainItem && /^(PATCH|PUT)$/.test(a.method)) {
1211
+ const flat = (k) => String(k).split('_').join('').toLowerCase();
1212
+ for (const k of Object.keys(body)) {
1213
+ const held = Object.keys(plainItem).find((h) => flat(h) === flat(k));
1214
+ if (held !== undefined && typeof body[k] === 'string' && String(plainItem[held]) === body[k] && /kx-roles/.test(body[k])) body[k] = body[k] + ' ' + Math.random().toString(36).slice(2, 5);
1215
+ }
1216
+ }
1054
1217
  if (sameBefore !== undefined) before[sameGet] = sameBefore;
1055
1218
  const known = await x.knownTo(actor);
1056
1219
 
1057
1220
  // truth: the records a read would disclose
1058
1221
  let markers = [];
1059
1222
  let markersKnown = false;
1223
+ let theirs;
1060
1224
  if (isGet || p.expected === 'deny') {
1061
1225
  if (isGet && !a.params.length) {
1062
1226
  const found = await x.readerFor(targetOrg, a.template, a.permission, true);
1063
1227
  if (found) {
1228
+ theirs = found.res.json;
1064
1229
  markers = x.markersOf(found.res.json, known, requestText);
1065
1230
  markersKnown = markers.length > 0;
1066
1231
  }
1067
1232
  } else if (target.item || bodyItem) {
1233
+ theirs = target.item || bodyItem;
1068
1234
  markers = x.markersOf(target.item || bodyItem, known, requestText);
1069
1235
  markersKnown = markers.length > 0;
1070
1236
  }
@@ -1087,7 +1253,14 @@ async function tryOnce(x) {
1087
1253
  // Across organizations, a piece found only inside records marked as the caller's own organization is the caller's
1088
1254
  // (round 27: every organization's audit says "Status set to open", and one statement stamped both organizations'
1089
1255
  // rows alike). A role's try is another matter: its own organization's records are what it may not see.
1090
- let found = markers.length ? authz.foundIn(p.kind === 'tenant' && isGet && actor.org ? withoutOwn(res, actor.org.key) : res, markers).length : 0;
1256
+ // A value that came back only inside records with ids of their own, none of them the other organization's, is a
1257
+ // name both organizations' records happen to share, not their record (round 30: an integration of the same name).
1258
+ // At an address that names no record, a default both organizations are given at the same place (a time zone in the
1259
+ // settings) is not theirs either (round 33).
1260
+ const shared = p.kind === 'tenant' && isGet && markers.length
1261
+ ? authz.sharedOnly(res.json, theirs, markers).concat(!a.params.length ? authz.sameDefaults(res.json, theirs, markers) : [])
1262
+ : [];
1263
+ let found = markers.length ? authz.foundIn(p.kind === 'tenant' && isGet && actor.org ? withoutOwn(res, actor.org.key) : res, markers.filter((m) => !shared.includes(m))).length : 0;
1091
1264
  // their record's own words now in our lists: a record of ours points at theirs (round 25: a transfer whose
1092
1265
  // destination was another organization's location, shown by name in our list of transfers)
1093
1266
  let pointedAt = [];
@@ -1105,7 +1278,19 @@ async function tryOnce(x) {
1105
1278
  // shows every organization's rows shows those change when the caller's own order is made: the caller's doing, not
1106
1279
  // the other organization's (round 28: a revenue report of every event moved for the caller's own event).
1107
1280
  const ownIds = p.kind === 'tenant' && bodyKey ? Object.keys(body).filter((k) => k !== bodyKey && /_?[iI]d$/.test(k) && ['string', 'number'].includes(typeof body[k])).map((k) => String(body[k])) : [];
1108
- const changes = x.compare(before, after).filter((l) => !ownIds.some((v) => l.includes(': record ' + v + ' changed - ')));
1281
+ // Refused (401/403): a new row in another list than the route's own (an overview, an activity feed that logs
1282
+ // the refusal itself) is not this request's effect; a changed record, or a new row in its own list, still is.
1283
+ // Harness, round 27: a finance account's create was refused 403 while two rows appeared in /api/overview.
1284
+ const ownList = '/' + a.segs.slice(0, a.params.length ? a.params[0].index : a.segs.length).join('/');
1285
+ const refusedOutright = res.status === 401 || res.status === 403;
1286
+ // Likewise a row gone from another list (an overview of the 6 soonest work orders, while another check moves them):
1287
+ // not this refused request's effect, unless the request named that row (a refused delete that deleted it anyway).
1288
+ // Harness, round 27: a viewer's POST /api/maintenance/run was refused 403 while rows 6, 9, 11 left /api/overview.
1289
+ const namedIds = new Set(String(pathNow).split('?')[0].split('/').filter(Boolean)
1290
+ .concat(Object.values(body || {}).filter((v) => ['string', 'number'].includes(typeof v)).map(String)));
1291
+ const goneElsewhere = (l) => { const m = / record (.+) is gone$/.exec(String(l)); return !!m && !namedIds.has(m[1]); };
1292
+ const changes = x.compare(before, after).filter((l) => !ownIds.some((v) => l.includes(': record ' + v + ' changed - ')))
1293
+ .filter((l) => !(refusedOutright && String(l).split(':')[0] !== ownList && (/ a new record appeared /.test(' ' + l + ' ') || goneElsewhere(l))));
1109
1294
  const changed = Object.keys(before).length ? changes.length > 0 : null;
1110
1295
 
1111
1296
  const att = Object.assign(base, {
@@ -1123,6 +1308,20 @@ async function tryOnce(x) {
1123
1308
  att.verdict = att.verdictInfo.verdict;
1124
1309
  att.reason = att.verdictInfo.reason;
1125
1310
  delete att.verdictInfo;
1311
+ // A change no rule names, tried as the roles with the fewest permissions: never proven, only a thing to check - and
1312
+ // said only when that role may do nothing of the kind anywhere in the policy and the code's own role check does not
1313
+ // name it (round 30: an execute and a promote-to-owner route the policy has no word for).
1314
+ if (p.unruled) {
1315
+ const through = reply.kind === 'accepted' || reply.kind === 'redirect';
1316
+ att.unruled = true;
1317
+ if (att.verdict === V.FAILURE || through) {
1318
+ att.verdict = V.AMBIGUOUS;
1319
+ att.reason = 'no permission in ' + POLICY_FILE + ' names this change, and the app let ' + actor.role + ' (the fewest permissions) do it (' + reply.note + ') - to check';
1320
+ }
1321
+ const meaning = a.unruled && a.unruled.meaning;
1322
+ const codeLets = Array.isArray(a.guardRoles) && a.guardRoles.some((r) => String(r).toLowerCase() === String(actor.role).toLowerCase());
1323
+ att.hint = Boolean((through || changed) && meaning && !holdsMeaning(policy, actor.role, meaning) && !codeLets);
1324
+ }
1126
1325
 
1127
1326
  // put back what it changed, when it can. An accepted write whose effect no page showed is not claimed as put back.
1128
1327
  att.restored = true;
@@ -1132,25 +1331,52 @@ async function tryOnce(x) {
1132
1331
  // An edit is put back with the values the record had before: by an account
1133
1332
  // that may edit it, and failing that by the account that did it - the same
1134
1333
  // missing check lets it undo it.
1135
- const original = target.item && /^(PATCH|PUT)$/.test(a.method) ? target.item : null;
1334
+ // A step on a record (POST /team/{id}/role) is put back like an edit: blind round 32, a manager's and an
1335
+ // admin's role changes were proven and left behind, and the next run met accounts that were owners.
1336
+ const onRecord = a.method === 'POST' && a.params.length === 1;
1337
+ const original = (target.item || plainItem) && (/^(PATCH|PUT)$/.test(a.method) || onRecord) ? (target.item || plainItem) : null;
1136
1338
  if (original) {
1137
- const back = {};
1138
1339
  // The body says recipientName where the record says recipient_name: the same field.
1139
1340
  const plain = (k) => String(k).replace(/[^A-Za-z0-9]/g, '').toLowerCase();
1140
1341
  const held = new Map(Object.keys(original).map((k) => [plain(k), k]));
1141
- for (const k of Object.keys(body || {})) {
1142
- const at = original[k] !== undefined ? k : held.get(plain(k));
1143
- if (at !== undefined && original[at] !== undefined) back[k] = original[at];
1342
+ const backFor = (keys) => {
1343
+ const back = {};
1344
+ for (const k of keys) {
1345
+ const at = original[k] !== undefined ? k : held.get(plain(k));
1346
+ if (at !== undefined && original[at] !== undefined) back[k] = original[at];
1347
+ }
1348
+ return back;
1349
+ };
1350
+ // the step itself with the values the record held; then any other change on the same records whose body
1351
+ // names a field that moved (POST /team/{id}/promote-owner has no body: POST /team/{id}/role {role} puts it back)
1352
+ const moved = [];
1353
+ for (const l of changes) {
1354
+ const rest = String(l).split(' changed - ')[1];
1355
+ if (rest) for (const part of rest.split(/, (?=\w+ )/)) { const f = part.split(' ')[0]; if (f && !moved.includes(f)) moved.push(f); }
1356
+ }
1357
+ const ways = [{ act: a, path: pathNow, back: backFor(Object.keys(body || {})) }];
1358
+ const listOf = (t) => t.split('/{id}')[0];
1359
+ for (const other of x.actions || []) {
1360
+ if (other === a || !/^(POST|PUT|PATCH)$/.test(other.method) || other.params.length !== 1 || listOf(other.template) !== listOf(a.template)) continue;
1361
+ const keys = Object.keys(other.fullData || other.data || {}).filter((k) => moved.some((m) => plain(m) === plain(k)));
1362
+ if (keys.length) ways.push({ act: other, path: other.template.replace('{id}', encodeURIComponent(String(target.value))), back: backFor(keys) });
1144
1363
  }
1145
- if (Object.keys(back).length) {
1146
- const writers = (x.orgs.get(targetOrg) ? x.orgs.get(targetOrg).sessions : x.sessions).filter((s) => holds(policy, s.role, a.permission)).concat([actor]);
1364
+ const sessionsHere = x.orgs.get(targetOrg) ? x.orgs.get(targetOrg).sessions : x.sessions;
1365
+ for (const way of ways) {
1366
+ if (att.restored || !Object.keys(way.back).length) continue;
1367
+ // whoever the policy says may, then every other account of that organization, then the one that did it:
1368
+ // putting a record back with any account the app lets do it is right (blind round 32: an admin had made
1369
+ // itself owner, and only the admin - whom the app refuses - was asked to undo it)
1370
+ const holders = sessionsHere.filter((s) => holds(policy, s.role, way.act.permission));
1371
+ const writers = holders.concat(sessionsHere.filter((s) => !holders.includes(s) && s !== actor), [actor]);
1147
1372
  for (const who of writers) {
1148
- await who.send(a.method, pathNow, a.encoding === 'form' ? { form: back } : { json: back });
1373
+ await who.send(way.act.method, way.path, way.act.encoding === 'form' ? { form: way.back } : { json: way.back });
1149
1374
  const again = await withPerson(await x.snapshot(targetOrg));
1150
1375
  const sameAgain = sameBefore !== undefined ? await readSame() : undefined;
1151
1376
  if (sameAgain !== undefined) again[sameGet] = sameAgain;
1152
1377
  if (x.compare(before, again).length === 0) {
1153
1378
  att.restored = true;
1379
+ att.restoredBy = way.act.method + ' ' + way.act.template + ' as ' + who.email;
1154
1380
  break;
1155
1381
  }
1156
1382
  }
@@ -1293,7 +1519,7 @@ function fixPrompt(f) {
1293
1519
  'Kryptheon signed in as different test accounts and sent the same request from each. ' + f.headline,
1294
1520
  '',
1295
1521
  'Fix it in the server code that handles ' + f.where + ': decide who may call it from the signed-in user\'s role on the server, ' +
1296
- 'not in the page. The permissions file (' + POLICY_FILE + ') says ' + f.type + ' is for ' + roleList(f.allowedRoles || []) + ' only.',
1522
+ 'not in the page. ' + (f.unruled ? 'The permissions file (' + POLICY_FILE + ') names no permission for it: decide who may, and check that role on the server.' : 'The permissions file (' + POLICY_FILE + ') says ' + f.type + ' is for ' + roleList(f.allowedRoles || []) + ' only.'),
1297
1523
  ];
1298
1524
  if (f.kind === 'tenant') lines.push('Look the record up together with the signed-in user\'s organization (WHERE id = ? AND org_id = ?), so another organization\'s record is "not found" - for reads, edits and every sub-address of it.');
1299
1525
  lines.push('', 'What Kryptheon saw:', '');
@@ -1335,7 +1561,7 @@ function findingsOf(attempts, policy) {
1335
1561
  const proven = first.verdict === V.FAILURE;
1336
1562
  // a thing to check where the same failure is already proven says nothing new
1337
1563
  if (!proven && groups.has(key.slice(0, -1) + 'p')) continue;
1338
- const allowed = rolesWith(policy, first.permission);
1564
+ const allowed = first.unruled ? [] : rolesWith(policy, first.permission);
1339
1565
  const thing = first.method + ' ' + first.template;
1340
1566
  const f = {
1341
1567
  severity: first.kind === 'tenant' ? 'CRITICAL' : 'HIGH',
@@ -1356,9 +1582,16 @@ function findingsOf(attempts, policy) {
1356
1582
  ? 'Sent another organization\'s record (' + first.namedInBody + ') to ' + thing + ', a user got the same successful answer as for its own - to check, its effect was not visible.'
1357
1583
  : 'A ' + first.actor.role + ' got the same successful answer as an allowed role from ' + thing + ' (' + first.permission + ') - to check, its effect was not visible.';
1358
1584
  }
1585
+ if (first.unruled) {
1586
+ f.unruled = true;
1587
+ f.severity = 'MEDIUM';
1588
+ f.status = 'verification required';
1589
+ f.headline = 'A ' + first.actor.role + ' (the role with the fewest permissions) can use ' + thing + ', which no permission in ' + POLICY_FILE + ' names - to check whether it should.';
1590
+ }
1359
1591
  for (const a of list.slice(0, 3)) f.proof.push.apply(f.proof, proofOf(a));
1360
1592
  if (list.length > 3) f.proof.push('... and ' + (list.length - 3) + ' more like it.');
1361
- if (!proven) f.proof.push(first.kind === 'tenant'
1593
+ if (first.unruled) f.proof.push('No rule in ' + POLICY_FILE + ' says who may do this, so it is not proven. Check by hand whether a ' + first.actor.role + ' should, and name its permission under kryptheon.actions.');
1594
+ else if (!proven) f.proof.push(first.kind === 'tenant'
1362
1595
  ? 'Nothing the recordings read changed, so this is not proven: the app may have stored it, or ignored it. Check by hand whether ' + thing + ' looks up ' + first.namedInBody + ' in the caller\'s own organization.'
1363
1596
  : 'Nothing the recordings read changed, so this is not proven. Check by hand what ' + thing + ' does when a ' + first.actor.role + ' calls it.');
1364
1597
  f.fixPrompt = fixPrompt(f);