kryptheon 0.1.64 → 0.1.65

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;
@@ -300,6 +321,9 @@ function permissionFor(method, pathOrTemplate, policy) {
300
321
  lastHit = true;
301
322
  } else if (a === verb) {
302
323
  score += 1;
324
+ } else if (meaningOf(a) && meaningOf(a) === meaningOf(verb)) {
325
+ // PUT and settings.write: the method's own word wins over one of the same meaning
326
+ score += 0.5;
303
327
  } else if (a === 'manage') {
304
328
  // "team.manage" covers what is done to the team's parts: PATCH /team/5/role (round 26). One that names the
305
329
  // part itself still wins, scoring more; a read never reaches here (manage is not a read word).
@@ -309,16 +333,84 @@ function permissionFor(method, pathOrTemplate, policy) {
309
333
  }
310
334
  found.push({ permission: perm, score: score, lastHit: lastHit });
311
335
  }
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' };
336
+ const strict = (() => {
337
+ if (!found.length) return null;
338
+ const lastWordsAny = statics.length > 0 && parsed.params.length > 0 && statics[statics.length - 1] !== undefined && parsed.segs[parsed.segs.length - 1] !== '{id}';
339
+ found.sort((a, b) => (b.lastHit ? 1 : 0) - (a.lastHit ? 1 : 0) || b.score - a.score);
340
+ const best = found[0];
341
+ // "/shipments/5/notes": the end of the address names something none of the
342
+ // permissions does, so the permission of "shipments" would be a guess.
343
+ if (!best.lastHit && lastWordsAny) return { ambiguous: true, why: 'the end of the address (' + statics[statics.length - 1] + ') matches no permission name' };
344
+ const tied = found.filter((f) => f.lastHit === best.lastHit && f.score === best.score);
345
+ if (tied.length > 1) return { ambiguous: true, why: 'it fits ' + tied.map((t) => t.permission).join(' and ') + ' equally' };
346
+ return { permission: best.permission, how: 'by the words in the address' };
347
+ })();
348
+ if (strict && strict.permission) return strict;
349
+ return (isGet ? null : sameMeaning(policy, statics, pathWords, verb)) || strict;
350
+ }
351
+
352
+ /** What a change no rule names does, by the words at the end of its address ("execute" -> approve), or null. */
353
+ function unruledMeaning(action, policy) {
354
+ const statics = String(action.template).split('/').filter((x) => x && x !== '{id}');
355
+ const last = statics.length ? wordsOf(statics[statics.length - 1]) : [];
356
+ return last.map(meaningOf).find(Boolean) || null;
357
+ }
358
+
359
+ /** Whether a role holds any permission that does this (approve, role, write...), on anything. */
360
+ function holdsMeaning(policy, role, meaning) {
361
+ const key = Object.keys(policy.roles).find((r) => r.toLowerCase() === String(role || '').toLowerCase());
362
+ if (!key) return false;
363
+ return policy.roles[key].some((perm) => {
364
+ if (perm === '*' || perm.endsWith('.*')) return true;
365
+ const parts = (policy.parts && policy.parts[perm]) || partsOf(perm);
366
+ if (!parts) return false;
367
+ if (meaning === 'role') return parts.resource.concat(parts.actions).some((x) => meaningOf(x) === 'role') && !parts.actions.every((a) => READ_WORDS.has(a));
368
+ return parts.actions.some((a) => meaningOf(a) === meaning);
369
+ });
370
+ }
371
+
372
+ /**
373
+ * A change whose address ends in a word no permission names, given the
374
+ * permission of the policy's own word of the same meaning: for the same
375
+ * resource ("execute" -> payouts.approve, "update" -> settings.write), or, for
376
+ * a word about roles ("promote", "grant"), the policy's permission over roles.
377
+ * Only when exactly one fits best; anything else stays unnamed.
378
+ */
379
+ function sameMeaning(policy, statics, pathWords, verb) {
380
+ if (Array.from(pathWords).some((w) => CREDENTIAL_WORD.test(w))) return null;
381
+ const last = statics.length ? wordsOf(statics[statics.length - 1].replace(FILE_EXTENSIONS, '')) : [];
382
+ // 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
383
+ const doing = last.filter((w) => meaningOf(w));
384
+ const resources = new Set();
385
+ for (const perm of permissionsOf(policy)) for (const r of ((policy.parts && policy.parts[perm]) || partsOf(perm) || { resource: [] }).resource) resources.add(r);
386
+ // "/settings" ends in a resource a permission names: what is done is its method; "/shipments/5/notes" ends in something else
387
+ if (!doing.length && verb && last.length && last.every((w) => resources.has(w))) doing.push(verb);
388
+ for (const w of doing) {
389
+ const meaning = meaningOf(w);
390
+ if (!meaning) continue;
391
+ const fits = [];
392
+ for (const perm of permissionsOf(policy)) {
393
+ const parts = (policy.parts && policy.parts[perm]) || partsOf(perm);
394
+ if (!parts || parts.actions.every((a) => READ_WORDS.has(a))) continue;
395
+ const hits = parts.resource.filter((r) => pathWords.has(r)).length;
396
+ if (meaning === 'role') {
397
+ // a permission over roles: its resource or what it allows is a role ("roles.write", "team.roles", "members.manage_roles")
398
+ const all = parts.resource.concat(parts.actions);
399
+ if (!all.some((x) => meaningOf(x) === 'role')) continue;
400
+ const changes = parts.actions.some((a) => meaningOf(a) === 'write' || meaningOf(a) === 'role' || a === 'manage');
401
+ if (!changes) continue;
402
+ fits.push({ permission: perm, rank: hits * 2 + (parts.actions.some((a) => meaningOf(a) === 'write') ? 1 : 0) });
403
+ } else {
404
+ if (!hits || !parts.actions.some((a) => meaningOf(a) === meaning)) continue;
405
+ fits.push({ permission: perm, rank: hits * 2 + (parts.actions.includes(meaning) ? 1 : 0) });
406
+ }
407
+ }
408
+ if (!fits.length) continue;
409
+ fits.sort((a, b) => b.rank - a.rank);
410
+ 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' };
411
+ return { permission: fits[0].permission, how: 'by a word of the same meaning (' + w + ' -> ' + fits[0].permission + ')' };
412
+ }
413
+ return null;
322
414
  }
323
415
 
324
416
  // --- the journey: what the recordings did -----------------------------------
@@ -627,6 +719,11 @@ async function checkAccess(input) {
627
719
  // 2. the actions, and the permission each needs
628
720
  const mapped = [];
629
721
  const reads = [];
722
+ const unruled = [];
723
+ // the roles with the fewest permissions: who a change no rule names is tried as
724
+ const counts = Object.keys(policy.roles || {}).map((r) => (policy.roles[r].includes('*') ? Infinity : policy.roles[r].length));
725
+ const fewest = counts.length ? Math.min.apply(null, counts) : Infinity;
726
+ const lowest = new Set(Object.keys(policy.roles || {}).filter((r) => (policy.roles[r].includes('*') ? Infinity : policy.roles[r].length) === fewest));
630
727
  for (const a of journey.actions) {
631
728
  if (a.method === 'DELETE') {
632
729
  skipped.push({ what: a.method + ' ' + a.template, why: 'not tried: this check never sends a delete' });
@@ -636,6 +733,11 @@ async function checkAccess(input) {
636
733
  if (p && p.permission) {
637
734
  mapped.push(Object.assign({ permission: p.permission, how: p.how }, a));
638
735
  out.mapping.push({ method: a.method, template: a.template, permission: p.permission, how: p.how });
736
+ } 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)))) {
737
+ // Asked for (the API check): a change no rule names is still tried, as the roles with the fewest permissions only.
738
+ // What it is about is its own words; a change that gets through is only a thing to check - no rule says who may.
739
+ unruled.push(Object.assign({ permission: null, unruled: { meaning: unruledMeaning(a, policy) } }, a));
740
+ 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
741
  } else {
640
742
  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
743
  }
@@ -644,6 +746,7 @@ async function checkAccess(input) {
644
746
  const getTemplates = new Set(journey.actions.filter((a) => a.method === 'GET').map((a) => a.template));
645
747
  const identityPaths = new Set(candidates);
646
748
  const snapshotReads = reads.filter((a) => !identityPaths.has(a.template) && !/health|public/i.test(a.template)).slice(0, MAX_SNAPSHOT);
749
+ const snapshotTemplates = new Set(snapshotReads.map((a) => a.template));
647
750
 
648
751
  const accountsOf = (orgKey) => (orgKey === null ? sessions : (orgs.get(orgKey) || { sessions: [] }).sessions);
649
752
  const permOf = new Map(mapped.map((a) => [a.method + ' ' + a.template, a.permission]));
@@ -827,6 +930,9 @@ async function checkAccess(input) {
827
930
  }
828
931
  }
829
932
  }
933
+ for (const action of unruled) {
934
+ 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 });
935
+ }
830
936
  // Asked for (the API check): every action once with no session at all, aimed at
831
937
  // the first organization's records and judged by its lists before and after.
832
938
  if (input.anonymous) {
@@ -850,26 +956,51 @@ async function checkAccess(input) {
850
956
  }
851
957
  chosen.push(p);
852
958
  }
853
- const cap = input.maxAttempts || MAX_ATTEMPTS;
959
+ // Sized to the app: each role and the accounts' own, every action (blind round 32), within a ceiling.
960
+ const roleCount = new Set(sessions.map((s) => s.role)).size;
961
+ const cap = input.maxAttempts || Math.min(MAX_ATTEMPTS_CEILING, Math.max(MAX_ATTEMPTS, (roleCount + 1) * (mapped.length + unruled.length) * 2));
854
962
  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;
963
+ // Kept first: what the policy says a role must be refused on a change, with the control that shows what an allowed
964
+ // change looks like; then refused reads, then the rest. They still run in the order planned (refusals first).
965
+ const tier = (p) => {
966
+ const write = p.action.method !== 'GET';
967
+ if (p.kind === 'role' && p.expected === 'deny' && write) return p.unruled ? 1 : 0;
968
+ if (p.kind === 'role' && p.expected === 'allow' && write) return 2;
969
+ if (p.kind === 'role' && p.expected === 'deny') return 3;
970
+ if (p.kind === 'tenant') return 4;
971
+ if (p.kind === 'signin') return 5;
972
+ return 6;
973
+ };
974
+ const order = chosen.map((p, i) => ({ p: p, i: i, t: tier(p) })).sort((x, y) => x.t - y.t || x.i - y.i);
975
+ const keep = new Set(order.slice(0, cap).map((o) => o.p));
976
+ const left = chosen.length - cap;
977
+ for (let i = chosen.length - 1; i >= 0; i--) if (!keep.has(chosen[i])) chosen.splice(i, 1);
978
+ notes.push(left + ' tries were left out to stay within ' + cap + ' (refusals of changes were kept first, then refusals of reads).');
857
979
  }
858
980
  out.planned = chosen.length;
981
+ // what the tries cost in requests: a picture before and after each, and a few more
982
+ ctx.limit = Math.max(ctx.limit, ctx.requests + chosen.length * (4 * Math.max(1, snapshotReads.length) + 12));
859
983
  const rotate = new Map();
860
984
  let n = 0;
861
- for (const p of chosen) {
862
- if (stopped()) {
863
- out.stopped = true;
864
- break;
985
+ try {
986
+ for (const p of chosen) {
987
+ if (stopped()) {
988
+ out.stopped = true;
989
+ break;
990
+ }
991
+ n++;
992
+ const a = p.action;
993
+ const label = (p.kind === 'tenant' ? 'across organizations: ' : '') + p.actor.role + ' ' + a.method + ' ' + a.template;
994
+ say(' ' + n + ' of ' + chosen.length + ': ' + label);
995
+ const att = await tryOnce({ p, ctx, policy, orgs, snapshot, compare, targetsFor, itemsOf, markersOf, knownTo, readerFor, rotate, tenants, sessions, hide, getTemplates, snapshotTemplates, actions: journey.actions });
996
+ if (Array.isArray(att)) out.attempts.push.apply(out.attempts, att);
997
+ else if (att) out.attempts.push(att);
865
998
  }
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);
999
+ } catch (err) {
1000
+ if (!authz.isRequestLimit(err)) throw err;
1001
+ // the tries made are kept and judged; the rest are said, not passed over in silence
1002
+ out.stopped = true;
1003
+ notes.push('The request limit (' + err.limit + ') was reached after ' + (n - 1) + ' of ' + chosen.length + ' tries; the rest were not tried.');
873
1004
  }
874
1005
  // 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
1006
  const groups = new Map();
@@ -1044,27 +1175,49 @@ async function tryOnce(x) {
1044
1175
  // set approved_by, which no list showed
1045
1176
  const segs = a.template.split('/');
1046
1177
  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;
1178
+ // A change to an address with no record in it that is also read (PUT /settings, GET /settings) shows there too -
1179
+ // round 30: with 30 lists before it, GET /settings was not among the reads taken before and after each try, and a
1180
+ // member's change of the settings was "taken, nothing changed".
1181
+ const plainSame = reader && !isGet && !a.params.length && x.getTemplates.has(a.template) && !x.snapshotTemplates.has(a.template);
1182
+ const readAt = reader && !isGet && a.params.length ? [a.template, detail].find((t) => x.getTemplates.has(t)) : plainSame ? a.template : null;
1183
+ let sameGet = readAt ? readAt.replace('{id}', encodeURIComponent(String(target.value))) : null;
1049
1184
  const readSame = async () => {
1050
1185
  const f = sameGet ? await x.readerFor(targetOrg, sameGet, null, false) : null;
1051
1186
  return f ? stable(f.res.json) : undefined;
1052
1187
  };
1053
- const sameBefore = await readSame();
1188
+ let sameBefore = await readSame();
1189
+ // read twice: an address that changes by itself shows nothing about the try
1190
+ if (plainSame && sameBefore !== undefined && JSON.stringify(await readSame()) !== JSON.stringify(sameBefore)) {
1191
+ sameBefore = undefined;
1192
+ sameGet = null;
1193
+ }
1194
+ // what that address holds is the record the change is made to: an edit sends a value it does not already hold, and
1195
+ // 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)
1196
+ const plainItem = plainSame && sameBefore && typeof sameBefore === 'object' && !Array.isArray(sameBefore) ? sameBefore : null;
1197
+ if (plainItem && /^(PATCH|PUT)$/.test(a.method)) {
1198
+ const flat = (k) => String(k).split('_').join('').toLowerCase();
1199
+ for (const k of Object.keys(body)) {
1200
+ const held = Object.keys(plainItem).find((h) => flat(h) === flat(k));
1201
+ 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);
1202
+ }
1203
+ }
1054
1204
  if (sameBefore !== undefined) before[sameGet] = sameBefore;
1055
1205
  const known = await x.knownTo(actor);
1056
1206
 
1057
1207
  // truth: the records a read would disclose
1058
1208
  let markers = [];
1059
1209
  let markersKnown = false;
1210
+ let theirs;
1060
1211
  if (isGet || p.expected === 'deny') {
1061
1212
  if (isGet && !a.params.length) {
1062
1213
  const found = await x.readerFor(targetOrg, a.template, a.permission, true);
1063
1214
  if (found) {
1215
+ theirs = found.res.json;
1064
1216
  markers = x.markersOf(found.res.json, known, requestText);
1065
1217
  markersKnown = markers.length > 0;
1066
1218
  }
1067
1219
  } else if (target.item || bodyItem) {
1220
+ theirs = target.item || bodyItem;
1068
1221
  markers = x.markersOf(target.item || bodyItem, known, requestText);
1069
1222
  markersKnown = markers.length > 0;
1070
1223
  }
@@ -1087,7 +1240,10 @@ async function tryOnce(x) {
1087
1240
  // Across organizations, a piece found only inside records marked as the caller's own organization is the caller's
1088
1241
  // (round 27: every organization's audit says "Status set to open", and one statement stamped both organizations'
1089
1242
  // 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;
1243
+ // A value that came back only inside records with ids of their own, none of them the other organization's, is a
1244
+ // name both organizations' records happen to share, not their record (round 30: an integration of the same name).
1245
+ const shared = p.kind === 'tenant' && isGet && markers.length ? authz.sharedOnly(res.json, theirs, markers) : [];
1246
+ 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
1247
  // their record's own words now in our lists: a record of ours points at theirs (round 25: a transfer whose
1092
1248
  // destination was another organization's location, shown by name in our list of transfers)
1093
1249
  let pointedAt = [];
@@ -1105,7 +1261,13 @@ async function tryOnce(x) {
1105
1261
  // shows every organization's rows shows those change when the caller's own order is made: the caller's doing, not
1106
1262
  // the other organization's (round 28: a revenue report of every event moved for the caller's own event).
1107
1263
  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 - ')));
1264
+ // Refused (401/403): a new row in another list than the route's own (an overview, an activity feed that logs
1265
+ // the refusal itself) is not this request's effect; a changed record, or a new row in its own list, still is.
1266
+ // Harness, round 27: a finance account's create was refused 403 while two rows appeared in /api/overview.
1267
+ const ownList = '/' + a.segs.slice(0, a.params.length ? a.params[0].index : a.segs.length).join('/');
1268
+ const refusedOutright = res.status === 401 || res.status === 403;
1269
+ const changes = x.compare(before, after).filter((l) => !ownIds.some((v) => l.includes(': record ' + v + ' changed - ')))
1270
+ .filter((l) => !(refusedOutright && / a new record appeared /.test(' ' + l + ' ') && String(l).split(':')[0] !== ownList));
1109
1271
  const changed = Object.keys(before).length ? changes.length > 0 : null;
1110
1272
 
1111
1273
  const att = Object.assign(base, {
@@ -1123,6 +1285,20 @@ async function tryOnce(x) {
1123
1285
  att.verdict = att.verdictInfo.verdict;
1124
1286
  att.reason = att.verdictInfo.reason;
1125
1287
  delete att.verdictInfo;
1288
+ // A change no rule names, tried as the roles with the fewest permissions: never proven, only a thing to check - and
1289
+ // said only when that role may do nothing of the kind anywhere in the policy and the code's own role check does not
1290
+ // name it (round 30: an execute and a promote-to-owner route the policy has no word for).
1291
+ if (p.unruled) {
1292
+ const through = reply.kind === 'accepted' || reply.kind === 'redirect';
1293
+ att.unruled = true;
1294
+ if (att.verdict === V.FAILURE || through) {
1295
+ att.verdict = V.AMBIGUOUS;
1296
+ 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';
1297
+ }
1298
+ const meaning = a.unruled && a.unruled.meaning;
1299
+ const codeLets = Array.isArray(a.guardRoles) && a.guardRoles.some((r) => String(r).toLowerCase() === String(actor.role).toLowerCase());
1300
+ att.hint = Boolean((through || changed) && meaning && !holdsMeaning(policy, actor.role, meaning) && !codeLets);
1301
+ }
1126
1302
 
1127
1303
  // put back what it changed, when it can. An accepted write whose effect no page showed is not claimed as put back.
1128
1304
  att.restored = true;
@@ -1132,25 +1308,52 @@ async function tryOnce(x) {
1132
1308
  // An edit is put back with the values the record had before: by an account
1133
1309
  // that may edit it, and failing that by the account that did it - the same
1134
1310
  // missing check lets it undo it.
1135
- const original = target.item && /^(PATCH|PUT)$/.test(a.method) ? target.item : null;
1311
+ // A step on a record (POST /team/{id}/role) is put back like an edit: blind round 32, a manager's and an
1312
+ // admin's role changes were proven and left behind, and the next run met accounts that were owners.
1313
+ const onRecord = a.method === 'POST' && a.params.length === 1;
1314
+ const original = (target.item || plainItem) && (/^(PATCH|PUT)$/.test(a.method) || onRecord) ? (target.item || plainItem) : null;
1136
1315
  if (original) {
1137
- const back = {};
1138
1316
  // The body says recipientName where the record says recipient_name: the same field.
1139
1317
  const plain = (k) => String(k).replace(/[^A-Za-z0-9]/g, '').toLowerCase();
1140
1318
  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];
1319
+ const backFor = (keys) => {
1320
+ const back = {};
1321
+ for (const k of keys) {
1322
+ const at = original[k] !== undefined ? k : held.get(plain(k));
1323
+ if (at !== undefined && original[at] !== undefined) back[k] = original[at];
1324
+ }
1325
+ return back;
1326
+ };
1327
+ // the step itself with the values the record held; then any other change on the same records whose body
1328
+ // names a field that moved (POST /team/{id}/promote-owner has no body: POST /team/{id}/role {role} puts it back)
1329
+ const moved = [];
1330
+ for (const l of changes) {
1331
+ const rest = String(l).split(' changed - ')[1];
1332
+ if (rest) for (const part of rest.split(/, (?=\w+ )/)) { const f = part.split(' ')[0]; if (f && !moved.includes(f)) moved.push(f); }
1333
+ }
1334
+ const ways = [{ act: a, path: pathNow, back: backFor(Object.keys(body || {})) }];
1335
+ const listOf = (t) => t.split('/{id}')[0];
1336
+ for (const other of x.actions || []) {
1337
+ if (other === a || !/^(POST|PUT|PATCH)$/.test(other.method) || other.params.length !== 1 || listOf(other.template) !== listOf(a.template)) continue;
1338
+ const keys = Object.keys(other.fullData || other.data || {}).filter((k) => moved.some((m) => plain(m) === plain(k)));
1339
+ if (keys.length) ways.push({ act: other, path: other.template.replace('{id}', encodeURIComponent(String(target.value))), back: backFor(keys) });
1144
1340
  }
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]);
1341
+ const sessionsHere = x.orgs.get(targetOrg) ? x.orgs.get(targetOrg).sessions : x.sessions;
1342
+ for (const way of ways) {
1343
+ if (att.restored || !Object.keys(way.back).length) continue;
1344
+ // whoever the policy says may, then every other account of that organization, then the one that did it:
1345
+ // putting a record back with any account the app lets do it is right (blind round 32: an admin had made
1346
+ // itself owner, and only the admin - whom the app refuses - was asked to undo it)
1347
+ const holders = sessionsHere.filter((s) => holds(policy, s.role, way.act.permission));
1348
+ const writers = holders.concat(sessionsHere.filter((s) => !holders.includes(s) && s !== actor), [actor]);
1147
1349
  for (const who of writers) {
1148
- await who.send(a.method, pathNow, a.encoding === 'form' ? { form: back } : { json: back });
1350
+ await who.send(way.act.method, way.path, way.act.encoding === 'form' ? { form: way.back } : { json: way.back });
1149
1351
  const again = await withPerson(await x.snapshot(targetOrg));
1150
1352
  const sameAgain = sameBefore !== undefined ? await readSame() : undefined;
1151
1353
  if (sameAgain !== undefined) again[sameGet] = sameAgain;
1152
1354
  if (x.compare(before, again).length === 0) {
1153
1355
  att.restored = true;
1356
+ att.restoredBy = way.act.method + ' ' + way.act.template + ' as ' + who.email;
1154
1357
  break;
1155
1358
  }
1156
1359
  }
@@ -1293,7 +1496,7 @@ function fixPrompt(f) {
1293
1496
  'Kryptheon signed in as different test accounts and sent the same request from each. ' + f.headline,
1294
1497
  '',
1295
1498
  '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.',
1499
+ '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
1500
  ];
1298
1501
  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
1502
  lines.push('', 'What Kryptheon saw:', '');
@@ -1335,7 +1538,7 @@ function findingsOf(attempts, policy) {
1335
1538
  const proven = first.verdict === V.FAILURE;
1336
1539
  // a thing to check where the same failure is already proven says nothing new
1337
1540
  if (!proven && groups.has(key.slice(0, -1) + 'p')) continue;
1338
- const allowed = rolesWith(policy, first.permission);
1541
+ const allowed = first.unruled ? [] : rolesWith(policy, first.permission);
1339
1542
  const thing = first.method + ' ' + first.template;
1340
1543
  const f = {
1341
1544
  severity: first.kind === 'tenant' ? 'CRITICAL' : 'HIGH',
@@ -1356,9 +1559,16 @@ function findingsOf(attempts, policy) {
1356
1559
  ? '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
1560
  : '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
1561
  }
1562
+ if (first.unruled) {
1563
+ f.unruled = true;
1564
+ f.severity = 'MEDIUM';
1565
+ f.status = 'verification required';
1566
+ 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.';
1567
+ }
1359
1568
  for (const a of list.slice(0, 3)) f.proof.push.apply(f.proof, proofOf(a));
1360
1569
  if (list.length > 3) f.proof.push('... and ' + (list.length - 3) + ' more like it.');
1361
- if (!proven) f.proof.push(first.kind === 'tenant'
1570
+ 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.');
1571
+ else if (!proven) f.proof.push(first.kind === 'tenant'
1362
1572
  ? '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
1573
  : 'Nothing the recordings read changed, so this is not proven. Check by hand what ' + thing + ' does when a ' + first.actor.role + ' calls it.');
1364
1574
  f.fixPrompt = fixPrompt(f);