kryptheon 0.1.57 → 0.1.61

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.
@@ -88,7 +88,32 @@ function checkPolicy(json) {
88
88
  // A draft Kryptheon wrote from the code says what the code does today, not what the owner wants.
89
89
  if (json.draft !== undefined) return { ok: false, problems: ['it is still marked "draft": it lists what your code does today, not what you want. Edit each role to what you want, then delete the "draft" line.'] };
90
90
  const roles = {};
91
- if (!json.roles || typeof json.roles !== 'object' || Array.isArray(json.roles)) problems.push('"roles" must say, for each role, the list of permissions it has.');
91
+ // a permission's resource and action as the file wrote them, when it wrote them apart (round 26)
92
+ const parts = {};
93
+ // the other common shape: "roles": ["owner", "viewer"] and "rules": [{ "action": "read:orders", "allow": ["owner", "viewer"] }] (round 25),
94
+ // or with the resource apart: { "resource": "dispatch_runs", "action": "close", "allow": [...] } (round 26)
95
+ if (Array.isArray(json.roles) && Array.isArray(json.rules)) {
96
+ const names = json.roles.filter((r) => typeof r === 'string' && r.trim()).map((r) => r.trim());
97
+ if (names.length !== json.roles.length) problems.push('"roles" must be a list of role names.');
98
+ const nameOf = (rule) => (typeof rule.resource === 'string' && rule.resource.trim() ? rule.resource.trim() + '.' : '') + rule.action.trim();
99
+ for (const rule of json.rules) {
100
+ if (!rule || typeof rule.action !== 'string' || !rule.action.trim() || !Array.isArray(rule.allow) || rule.allow.some((r) => typeof r !== 'string') || (rule.resource !== undefined && typeof rule.resource !== 'string')) {
101
+ problems.push('each of "rules" must be { "action": "read:orders", "allow": ["owner", ...] }, or { "resource": "orders", "action": "read", "allow": [...] }.');
102
+ break;
103
+ }
104
+ const unknown = rule.allow.find((r) => !names.includes(r.trim()) && r.trim() !== '*');
105
+ if (unknown) problems.push('rule "' + nameOf(rule) + '" allows "' + unknown + '", which is not in "roles".');
106
+ if (typeof rule.resource === 'string' && rule.resource.trim()) {
107
+ const resource = wordsOf(rule.resource);
108
+ const actions = wordsOf(rule.action);
109
+ if (resource.length && actions.length) parts[nameOf(rule)] = { resource, actions };
110
+ }
111
+ }
112
+ if (!problems.length) {
113
+ for (const name of names) roles[name] = json.rules.filter((rule) => rule.allow.some((r) => r.trim() === name || r.trim() === '*')).map(nameOf);
114
+ if (names.length < 2) problems.push('it needs at least two roles to compare.');
115
+ }
116
+ } else if (!json.roles || typeof json.roles !== 'object' || Array.isArray(json.roles)) problems.push('"roles" must say, for each role, the list of permissions it has.');
92
117
  else {
93
118
  for (const name of Object.keys(json.roles)) {
94
119
  const list = json.roles[name];
@@ -102,8 +127,11 @@ function checkPolicy(json) {
102
127
  problems.push('"kryptheon.actions" must be a list of { "permission", "method", "path" }.');
103
128
  }
104
129
  if (problems.length) return { ok: false, problems: problems };
105
- const tenants = (typeof json.tenantBoundary === 'string' && json.tenantBoundary.trim() !== '') || json.tenants === true;
106
- return { ok: true, problems: [], policy: { roles: roles, tenants: tenants, boundary: typeof json.tenantBoundary === 'string' ? json.tenantBoundary : '', extra: k } };
130
+ // "tenant_rules": ["A user may only read or modify records belonging to their own workspace.", ...] says the same as "tenantBoundary"
131
+ const written = ['tenant_rules', 'tenantRules'].map((key) => json[key]).find((v) => Array.isArray(v) && v.some((x) => typeof x === 'string' && x.trim()));
132
+ const boundary = typeof json.tenantBoundary === 'string' ? json.tenantBoundary : written ? written.filter((x) => typeof x === 'string').join(' ') : '';
133
+ const tenants = boundary.trim() !== '' || json.tenants === true;
134
+ return { ok: true, problems: [], policy: { roles: roles, tenants: tenants, boundary: boundary, extra: k, parts: parts } };
107
135
  }
108
136
 
109
137
  /** Whether `role` has `permission` ("*" and "resource.*" are allowed in the file). */
@@ -209,6 +237,27 @@ function templateOfWritten(p) {
209
237
  return '/' + String(p || '').split(/[?#]/)[0].split('/').filter(Boolean).map((s) => (/^(\{[^}]*\}|:[A-Za-z_]\w*|<[^>]*>|\*)$/.test(s) ? '{id}' : s)).join('/');
210
238
  }
211
239
 
240
+ const VERB_WORDS = new Set([...READ_WORDS, 'create', 'add', 'update', 'edit', 'write', 'delete', 'remove', 'manage']);
241
+
242
+ /**
243
+ * A permission name split into what it is about and what it allows:
244
+ * "orders.read" -> orders / read; "read:purchase_orders" -> purchase, order / read;
245
+ * "orders:read" -> orders / read. Null when it is one word.
246
+ */
247
+ function partsOf(perm) {
248
+ const colon = String(perm).indexOf(':');
249
+ if (colon > 0) {
250
+ const left = wordsOf(perm.slice(0, colon));
251
+ const right = wordsOf(perm.slice(colon + 1));
252
+ if (!left.length || !right.length) return null;
253
+ // "orders:read" names the resource first; "read:orders" the action
254
+ if (right.every((w) => VERB_WORDS.has(w)) && !left.every((w) => VERB_WORDS.has(w))) return { resource: left, actions: right };
255
+ return { resource: right, actions: left };
256
+ }
257
+ const w = wordsOf(perm);
258
+ return w.length < 2 ? null : { resource: [w[0]], actions: w.slice(1) };
259
+ }
260
+
212
261
  /**
213
262
  * The permission an action needs, found from the words in its address and its
214
263
  * method - or null, or `ambiguous`. Strict on purpose: when two permissions
@@ -232,15 +281,16 @@ function permissionFor(method, pathOrTemplate, policy) {
232
281
  const verb = METHOD_VERB[m];
233
282
  const found = [];
234
283
  for (const perm of permissionsOf(policy)) {
235
- const w = wordsOf(perm);
236
- if (w.length < 2) continue;
237
- const resource = w[0];
238
- const actions = w.slice(1);
239
- if (!pathWords.has(resource)) continue;
284
+ const parts = (policy.parts && policy.parts[perm]) || partsOf(perm);
285
+ if (!parts) continue;
286
+ const resource = parts.resource;
287
+ const actions = parts.actions;
288
+ const hits = resource.filter((r) => pathWords.has(r)).length;
289
+ if (!hits) continue;
240
290
  const readish = actions.every((a) => READ_WORDS.has(a));
241
291
  if (isGet !== readish) continue;
242
- let score = 1;
243
- let lastHit = last.has(resource);
292
+ let score = hits;
293
+ let lastHit = resource.some((r) => last.has(r));
244
294
  for (const a of actions) {
245
295
  if (pathWords.has(a)) {
246
296
  score += 2;
@@ -250,6 +300,11 @@ function permissionFor(method, pathOrTemplate, policy) {
250
300
  lastHit = true;
251
301
  } else if (a === verb) {
252
302
  score += 1;
303
+ } else if (a === 'manage') {
304
+ // "team.manage" covers what is done to the team's parts: PATCH /team/5/role (round 26). One that names the
305
+ // part itself still wins, scoring more; a read never reaches here (manage is not a read word).
306
+ score += 1;
307
+ lastHit = true;
253
308
  }
254
309
  }
255
310
  found.push({ permission: perm, score: score, lastHit: lastHit });
@@ -394,10 +449,23 @@ function diffLines(template, a, b) {
394
449
  lines.push(template + ': record ' + id + ' changed - ' + fields.slice(0, 3).map((f) => f + ' ' + authz.clip(JSON.stringify(y[f]), 40) + ' -> ' + authz.clip(JSON.stringify(x[f]), 40)).join('; '));
395
450
  }
396
451
  if (lines.length) return lines;
452
+ // the same records in another order is no change (round 26: a refused settlement was called a change because
453
+ // the deliveries came back sorted differently)
454
+ const byId = (l) => l.slice().sort((p, q) => String(idOf(p)).localeCompare(String(idOf(q))));
455
+ const sorted = (v, l) => (Array.isArray(v) ? byId(l) : Object.assign({}, v, { [Object.keys(v).find((k) => v[k] === l)]: byId(l) }));
456
+ if (JSON.stringify(sorted(a, la)) === JSON.stringify(sorted(b, lb))) return [];
397
457
  }
398
458
  if (a && b && typeof a === 'object' && typeof b === 'object') {
399
- const fields = Object.keys(Object.assign({}, a, b)).filter((f) => JSON.stringify(a[f]) !== JSON.stringify(b[f]));
400
- return [template + ': ' + fields.slice(0, 4).map((f) => f + ' ' + authz.clip(JSON.stringify(a[f]), 40) + ' -> ' + authz.clip(JSON.stringify(b[f]), 40)).join('; ')];
459
+ // one record wrapped in its answer ({ shipment: {...} }) is named by the field inside that moved
460
+ const plain = (v) => v && typeof v === 'object' && !Array.isArray(v);
461
+ const moved = [];
462
+ for (const f of Object.keys(Object.assign({}, a, b))) {
463
+ if (JSON.stringify(a[f]) === JSON.stringify(b[f])) continue;
464
+ if (plain(a[f]) && plain(b[f])) {
465
+ for (const g of Object.keys(Object.assign({}, a[f], b[f]))) if (JSON.stringify(a[f][g]) !== JSON.stringify(b[f][g])) moved.push([f + '.' + g, a[f][g], b[f][g]]);
466
+ } else moved.push([f, a[f], b[f]]);
467
+ }
468
+ return [template + ': ' + moved.slice(0, 4).map(([f, x, y]) => f + ' ' + authz.clip(JSON.stringify(x), 40) + ' -> ' + authz.clip(JSON.stringify(y), 40)).join('; ')];
401
469
  }
402
470
  return [template + ': the answer changed'];
403
471
  }
@@ -521,7 +589,10 @@ async function checkAccess(input) {
521
589
  const me = await s.send('GET', p);
522
590
  if (me.status === 200 && me.json) {
523
591
  user = findUser(me.json) || (policy.anyRole ? findAnyUser(me.json) : null);
524
- if (user) break;
592
+ if (user) {
593
+ s.identityPath = p;
594
+ break;
595
+ }
525
596
  }
526
597
  }
527
598
  if (!user) {
@@ -697,7 +768,14 @@ async function checkAccess(input) {
697
768
  const listing = '/' + action.segs.slice(0, action.params[0].index).join('/');
698
769
  if (!getTemplates.has(listing)) {
699
770
  const mine = (seeded.get(listing) || []).filter((r) => r.org === orgKey);
700
- return mine.length ? mine : null;
771
+ if (mine.length) return mine;
772
+ // /team/:id, /users/:id with no list of them: the accounts signed in here are such records, with ids the app gave
773
+ if (PEOPLE.test(action.segs[action.params[0].index - 1] || '')) {
774
+ const people = accountsOf(orgKey).filter((ss) => ss.userId !== undefined && ss.userId !== null)
775
+ .map((ss) => ({ value: ss.userId, item: { id: ss.userId, email: ss.email, role: ss.role }, listing: listing, field: 'id' }));
776
+ return people.length ? people : null;
777
+ }
778
+ return null;
701
779
  }
702
780
  const items = await itemsOf(orgKey, listing);
703
781
  if (!items) return null;
@@ -721,7 +799,7 @@ async function checkAccess(input) {
721
799
  return text;
722
800
  };
723
801
  const markersOf = (value, known, requestText) =>
724
- Array.from(new Set(authz.stringsOf(value, 5))).filter((m) => !known.includes(m) && !requestText.includes(m)).slice(0, 60);
802
+ Array.from(new Set(authz.stringsOf(value, 5))).filter((m) => !known.includes(m) && !requestText.includes(m) && !wordsOfAnyRecord(value).has(m)).slice(0, 60);
725
803
 
726
804
  // 6. the tries
727
805
  const plan = [];
@@ -734,7 +812,9 @@ async function checkAccess(input) {
734
812
  plan.push({ action: action, actor: s, kind: 'role', expected: 'allow', org: s.org ? s.org.key : null });
735
813
  if (tenants && s.org) {
736
814
  if (aimable(action)) {
737
- for (const o of orgs.values()) if (o.key !== s.org.key) plan.push({ action: action, actor: s, kind: 'tenant', expected: 'deny', org: o.key });
815
+ // a write that names records only in its body: each of them aimed in its turn (from_location_id, then to_location_id)
816
+ const keys = action.method !== 'GET' && !action.params.length ? bodyRecords(action, action.data || {}, getTemplates).map((r) => r.key) : [null];
817
+ for (const o of orgs.values()) if (o.key !== s.org.key) for (const k of keys) plan.push({ action: action, actor: s, kind: 'tenant', expected: 'deny', org: o.key, bodyKey: k || undefined });
738
818
  } else if (!unaimed.has(action.method + ' ' + action.template)) {
739
819
  unaimed.add(action.method + ' ' + action.template);
740
820
  skipped.push({ what: action.method + ' ' + action.template, why: 'across organizations: nothing in the request names a record, so it cannot be aimed at another organization' });
@@ -815,16 +895,40 @@ async function checkAccess(input) {
815
895
  * The key in a request body that names another record (shipmentId, order_id),
816
896
  * with a stand-in for the address that lists those records: { key, like }.
817
897
  */
818
- function bodyRecord(action, body, getTemplates) {
819
- const key = Object.keys(body || {}).find((k) => /^[A-Za-z]+_?[iI]d$/.test(k) && k.toLowerCase() !== 'id' && ['string', 'number'].includes(typeof body[k]));
820
- if (!key) return null;
821
- const stem = singular(key.replace(/_?[iI]d$/, '').toLowerCase());
822
- const listing = Array.from(getTemplates || []).find((t) => !t.includes('{id}') && singular(t.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem);
823
- if (!listing) return null;
824
- const segs = listing.split('/').filter(Boolean).concat('{id}');
825
- return { key: key, like: { template: listing + '/{id}', segs: segs, params: [{ index: segs.length - 1, value: body[key] }], by: action.by } };
898
+ function bodyRecord(action, body, getTemplates, want) {
899
+ const all = bodyRecords(action, body, getTemplates);
900
+ return (want ? all.find((r) => r.key === want) : all[0]) || null;
901
+ }
902
+
903
+ /**
904
+ * Every key of a body that names another record and whose records the app
905
+ * lists, in the body's order: shipmentId, order_id - and from_location_id,
906
+ * to_location_id, each by its last word (round 25's transfer named its
907
+ * destination so, and was never aimed at another organization's location).
908
+ */
909
+ function bodyRecords(action, body, getTemplates) {
910
+ const out = [];
911
+ const one = (v) => ['string', 'number'].includes(typeof v);
912
+ for (const key of Object.keys(body || {})) {
913
+ // a list of ids names records too: work_order_ids = [7] (round 27: a dispatch run took another organization's)
914
+ const many = Array.isArray(body[key]) && body[key].length > 0 && body[key].every(one);
915
+ if (!/^[A-Za-z]+(?:_[A-Za-z]+)*_?[iI]ds?$/.test(key) || /^ids?$/i.test(key) || !(one(body[key]) || many)) continue;
916
+ const words = key.replace(/_?[iI]ds?$/, '').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase().split('_').filter(Boolean);
917
+ // the words together first (work_order: /work-orders), then the last one (to_location: /locations)
918
+ const stems = [singular(words.join('')), singular(words[words.length - 1] || '')];
919
+ const named = (t, stem) => !t.includes('{id}') && singular(t.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem;
920
+ const stem = stems.find((s) => Array.from(getTemplates || []).some((t) => named(t, s)));
921
+ const listing = stem ? Array.from(getTemplates || []).find((t) => named(t, stem)) : null;
922
+ if (!listing) continue;
923
+ const segs = listing.split('/').filter(Boolean).concat('{id}');
924
+ out.push({ key: key, many: many, like: { template: listing + '/{id}', segs: segs, params: [{ index: segs.length - 1, value: many ? body[key][0] : body[key] }], by: action.by } });
925
+ }
926
+ return out;
826
927
  }
827
928
 
929
+ // The last word of an address whose records are people.
930
+ const PEOPLE = /^(users?|team|teams|members?|memberships?|accounts?|staff|people|profiles?|employees?)$/i;
931
+
828
932
  /** One try: send, look, judge, put back. Returns the evidence, or null when the try had nothing to aim at. */
829
933
  async function tryOnce(x) {
830
934
  const { p, policy } = x;
@@ -866,10 +970,11 @@ async function tryOnce(x) {
866
970
  // what to send
867
971
  let body;
868
972
  let bodyItem = null;
973
+ let bodyKey = null;
869
974
  if (!isGet) {
870
975
  body = sampleBody(a);
871
976
  // a body that names another record (shipmentId, order_id) is pointed at the target's organization too
872
- const named = bodyRecord(a, body, x.getTemplates);
977
+ const named = bodyRecord(a, body, x.getTemplates, p.bodyKey);
873
978
  if (named) {
874
979
  const alt = await x.targetsFor(named.like, targetOrg);
875
980
  if (alt && alt.length) {
@@ -877,8 +982,19 @@ async function tryOnce(x) {
877
982
  const j = x.rotate.get(k2) || 0;
878
983
  x.rotate.set(k2, j + 1);
879
984
  const pick = alt[j % alt.length];
880
- body[named.key] = pick.value;
985
+ body[named.key] = named.many ? [pick.value] : pick.value;
881
986
  bodyItem = pick.item;
987
+ bodyKey = named.key;
988
+ }
989
+ // One reference across at a time: the body's other records are the caller's own (round 27: an invoice aimed
990
+ // at the other organization's work order still named its customer, so that customer's name was already in the
991
+ // caller's lists when its own try came, and the proof was lost).
992
+ if (p.kind === 'tenant' && actor.org) {
993
+ for (const other of bodyRecords(a, body, x.getTemplates)) {
994
+ if (other.key === named.key) continue;
995
+ const mine = await x.targetsFor(other.like, actor.org.key);
996
+ if (mine && mine.length) body[other.key] = other.many ? [mine[0].value] : mine[0].value;
997
+ }
882
998
  }
883
999
  }
884
1000
  // A role named in the body: a refused account tries to make itself the most
@@ -910,9 +1026,22 @@ async function tryOnce(x) {
910
1026
 
911
1027
  // what the app holds now
912
1028
  const reader = targetOrg !== null || p.kind === 'signin' || x.orgs.size === 0;
913
- const before = reader ? await x.snapshot(targetOrg) : {};
914
- // a write to an address that is also read (POST /returns/5/notes, GET /returns/5/notes) shows there
915
- const sameGet = reader && !isGet && a.params.length && x.getTemplates.has(a.template) ? pathNow : null;
1029
+ // a person's record: what they themselves are told about who they are shows the change (their role)
1030
+ const person = !isGet && target.item && target.item.email ? x.sessions.find((ss) => ss.email === target.item.email && ss.identityPath) : null;
1031
+ const withPerson = async (snap) => {
1032
+ if (!person) return snap;
1033
+ const r = await person.send('GET', person.identityPath);
1034
+ if (r.status === 200 && r.json !== undefined) snap['who am I, as ' + person.email] = stable(r.json);
1035
+ return snap;
1036
+ };
1037
+ const before = await withPerson(reader ? await x.snapshot(targetOrg) : {});
1038
+ // a write to an address that is also read (POST /returns/5/notes, GET /returns/5/notes) shows there; a step on a
1039
+ // record (POST /work-orders/5/approve) shows on the record's own address (GET /work-orders/5) - round 27: approve
1040
+ // set approved_by, which no list showed
1041
+ const segs = a.template.split('/');
1042
+ const detail = segs.slice(0, segs.indexOf('{id}') + 1).join('/');
1043
+ const readAt = reader && !isGet && a.params.length ? [a.template, detail].find((t) => x.getTemplates.has(t)) : null;
1044
+ const sameGet = readAt ? readAt.replace('{id}', encodeURIComponent(String(target.value))) : null;
916
1045
  const readSame = async () => {
917
1046
  const f = sameGet ? await x.readerFor(targetOrg, sameGet, null, false) : null;
918
1047
  return f ? stable(f.res.json) : undefined;
@@ -937,12 +1066,26 @@ async function tryOnce(x) {
937
1066
  }
938
1067
  }
939
1068
 
1069
+ // a write that names another organization's record in its body: our own lists, before and after
1070
+ const pointing = p.kind === 'tenant' && !isGet && bodyItem && actor.org && markers.length > 0;
1071
+ const ownBefore = pointing ? JSON.stringify(await x.snapshot(actor.org.key)) : '';
940
1072
  const res = await actor.send(a.method, pathNow, isGet ? {} : (a.encoding === 'form' ? { form: body } : { json: body }));
941
1073
  const reply = authz.replyOf(res);
942
1074
  const foreign = actor.org && isGet ? foreignRecords(res.json, actor.org.key) : [];
943
1075
  const ownMarked = actor.org && isGet ? ownRecords(res.json, actor.org.key) : 0;
944
- const found = markers.length ? authz.foundIn(res, markers).length : 0;
945
- const after = reader ? await x.snapshot(targetOrg) : {};
1076
+ // Across organizations, a piece found only inside records marked as the caller's own organization is the caller's
1077
+ // (round 27: every organization's audit says "Status set to open", and one statement stamped both organizations'
1078
+ // rows alike). A role's try is another matter: its own organization's records are what it may not see.
1079
+ let found = markers.length ? authz.foundIn(p.kind === 'tenant' && isGet && actor.org ? withoutOwn(res, actor.org.key) : res, markers).length : 0;
1080
+ // their record's own words now in our lists: a record of ours points at theirs (round 25: a transfer whose
1081
+ // destination was another organization's location, shown by name in our list of transfers)
1082
+ let pointedAt = [];
1083
+ if (pointing && (reply.kind === 'accepted' || reply.kind === 'redirect')) {
1084
+ const ownAfter = JSON.stringify(await x.snapshot(actor.org.key));
1085
+ pointedAt = markers.filter((m) => ownAfter.includes(m) && !ownBefore.includes(m));
1086
+ found += pointedAt.length;
1087
+ }
1088
+ const after = await withPerson(reader ? await x.snapshot(targetOrg) : {});
946
1089
  if (sameBefore !== undefined) {
947
1090
  const sameAfter = await readSame();
948
1091
  if (sameAfter !== undefined) after[sameGet] = sameAfter;
@@ -956,6 +1099,9 @@ async function tryOnce(x) {
956
1099
  target: { organization: orgName(targetOrg), record: target.value },
957
1100
  changes: changes.slice(0, 6), protectedPiecesSeen: found,
958
1101
  });
1102
+ if (pointedAt.length) att.pointedAt = { key: p.bodyKey || Object.keys(body).find((k) => body[k] === target.value) || null, words: pointedAt.slice(0, 3) };
1103
+ // another organization's record named in the body (work_order_ids = [4]): an answer like its own is a thing to check
1104
+ if (p.kind === 'tenant' && bodyKey) att.namedInBody = bodyKey;
959
1105
  // An answer to a try that was aimed across organizations is judged for that. For any other try, another
960
1106
  // organization's records in the answer are a second finding, kept apart from what the role may do.
961
1107
  att.verdictInfo = judge({ expected: p.expected, isGet: isGet, status: res.status, reply: reply, found: found, foreign: p.kind === 'tenant' ? foreign : [], markersKnown: markersKnown || ownMarked > 0, changed: changed, kind: p.kind });
@@ -985,7 +1131,9 @@ async function tryOnce(x) {
985
1131
  const writers = (x.orgs.get(targetOrg) ? x.orgs.get(targetOrg).sessions : x.sessions).filter((s) => holds(policy, s.role, a.permission)).concat([actor]);
986
1132
  for (const who of writers) {
987
1133
  await who.send(a.method, pathNow, a.encoding === 'form' ? { form: back } : { json: back });
988
- const again = await x.snapshot(targetOrg);
1134
+ const again = await withPerson(await x.snapshot(targetOrg));
1135
+ const sameAgain = sameBefore !== undefined ? await readSame() : undefined;
1136
+ if (sameAgain !== undefined) again[sameGet] = sameAgain;
989
1137
  if (x.compare(before, again).length === 0) {
990
1138
  att.restored = true;
991
1139
  break;
@@ -1009,6 +1157,34 @@ async function tryOnce(x) {
1009
1157
  return att;
1010
1158
  }
1011
1159
 
1160
+ // Fields whose values are one of a few words every organization uses: "submitted", "warehouse", "INR".
1161
+ const SHARED_WORD_KEY = /(^|_)(status|state|stage|type|kind|role|level|priority|currency|unit|method|category|visibility)$/i;
1162
+ // A day, or a time on the whole minute: any record of that day holds it (round 27: a dispatch run's run_date was
1163
+ // another organization's work order's due_date, both today, and was taken for that record).
1164
+ const DAY_LIKE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:00(\.0+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
1165
+ // Text Kryptheon itself sends (Kryptheon test, kx-roles, kx-test@kryptheon.invalid): found in another organization's
1166
+ // records it is the run's own doing (an audit line "Status set to Kryptheon test"), not a record that came back.
1167
+ const RUN_MADE = /kryptheon|(^|[^a-z])kx-/i;
1168
+
1169
+ /**
1170
+ * The values of a record that are a status or kind - words any organization's
1171
+ * records carry - and so prove nothing about whose record came back. Round 25:
1172
+ * "Only submitted purchase orders can be approved." held the other
1173
+ * organization's status "submitted", and a refusal was called a leak. An action
1174
+ * name is one too: every organization's audit says "work_order.status_changed"
1175
+ * (rounds 26 and 27).
1176
+ */
1177
+ function wordsOfAnyRecord(value) {
1178
+ const out = new Set();
1179
+ (function walk(v, key) {
1180
+ if (typeof v === 'string') {
1181
+ if ((key && SHARED_WORD_KEY.test(key)) || /^[a-z]+([._:-][a-z]+)*$/.test(v) || DAY_LIKE.test(v) || RUN_MADE.test(v)) out.add(v);
1182
+ } else if (Array.isArray(v)) v.forEach((x) => walk(x, key));
1183
+ else if (v && typeof v === 'object') Object.keys(v).forEach((k) => walk(v[k], k));
1184
+ })(value, null);
1185
+ return out;
1186
+ }
1187
+
1012
1188
  // A record's own mark of the organization it belongs to.
1013
1189
  const ORG_KEY = /^(org|organi[sz]ation|tenant|workspace|company)[_-]?id$/i;
1014
1190
 
@@ -1030,6 +1206,20 @@ function foreignRecords(json, orgKey) {
1030
1206
  return out;
1031
1207
  }
1032
1208
 
1209
+ /** An answer with the records marked as this organization's own taken out: { text } to look for markers in. */
1210
+ function withoutOwn(res, orgKey) {
1211
+ if (res.json === undefined) return res;
1212
+ const own = (v) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).some((k) => ORG_KEY.test(k) && String(v[k]) === String(orgKey));
1213
+ const strip = (v, depth) => {
1214
+ if (depth > 4 || v == null || typeof v !== 'object') return v;
1215
+ if (Array.isArray(v)) return v.filter((x) => !own(x)).map((x) => strip(x, depth + 1));
1216
+ const out = {};
1217
+ for (const k of Object.keys(v)) out[k] = strip(v[k], depth + 1);
1218
+ return out;
1219
+ };
1220
+ return { text: JSON.stringify(strip(res.json, 0)) };
1221
+ }
1222
+
1033
1223
  /** How many records in an answer carry this organization's own mark. */
1034
1224
  function ownRecords(json, orgKey) {
1035
1225
  let n = 0;
@@ -1105,7 +1295,8 @@ function proofOf(att) {
1105
1295
  if (att.changes && att.changes.length) {
1106
1296
  lines.push(' state: changed after the request (read before and after):');
1107
1297
  for (const c of att.changes.slice(0, 3)) lines.push(' ' + c);
1108
- } else if (att.protectedPiecesSeen) lines.push(' state: the answer itself held ' + att.protectedPiecesSeen + ' piece(s) of records this account may not see');
1298
+ } else if (att.pointedAt) lines.push(' state: saved, and this account\'s own lists now name the other organization\'s record' + (att.pointedAt.key ? ' (' + att.pointedAt.key + ')' : '') + ': ' + att.pointedAt.words.map((w) => JSON.stringify(w)).join(', '));
1299
+ else if (att.protectedPiecesSeen) lines.push(' state: the answer itself held ' + att.protectedPiecesSeen + ' piece(s) of records this account may not see');
1109
1300
  else lines.push(' state: unchanged');
1110
1301
  lines.push(' repeat: sign in as ' + att.actor.email + ', send ' + att.request.method + ' ' + att.request.path + (att.request.body && Object.keys(att.request.body).length ? ' with that body' : '') + ', then read the same lists as an allowed account');
1111
1302
  return lines;
@@ -1124,9 +1315,11 @@ function findingsOf(attempts, policy) {
1124
1315
  if (!groups.has(key)) groups.set(key, []);
1125
1316
  groups.get(key).push(a);
1126
1317
  }
1127
- for (const list of groups.values()) {
1318
+ for (const [key, list] of groups) {
1128
1319
  const first = list[0];
1129
1320
  const proven = first.verdict === V.FAILURE;
1321
+ // a thing to check where the same failure is already proven says nothing new
1322
+ if (!proven && groups.has(key.slice(0, -1) + 'p')) continue;
1130
1323
  const allowed = rolesWith(policy, first.permission);
1131
1324
  const thing = first.method + ' ' + first.template;
1132
1325
  const f = {
@@ -1144,11 +1337,15 @@ function findingsOf(attempts, policy) {
1144
1337
  };
1145
1338
  if (!proven) {
1146
1339
  f.severity = 'MEDIUM';
1147
- f.headline = 'A ' + first.actor.role + ' got the same successful answer as an allowed role from ' + thing + ' (' + first.permission + ') - to check, its effect was not visible.';
1340
+ f.headline = first.kind === 'tenant'
1341
+ ? '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.'
1342
+ : 'A ' + first.actor.role + ' got the same successful answer as an allowed role from ' + thing + ' (' + first.permission + ') - to check, its effect was not visible.';
1148
1343
  }
1149
1344
  for (const a of list.slice(0, 3)) f.proof.push.apply(f.proof, proofOf(a));
1150
1345
  if (list.length > 3) f.proof.push('... and ' + (list.length - 3) + ' more like it.');
1151
- if (!proven) f.proof.push('Nothing the recordings read changed, so this is not proven. Check by hand what ' + thing + ' does when a ' + first.actor.role + ' calls it.');
1346
+ if (!proven) f.proof.push(first.kind === 'tenant'
1347
+ ? '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.'
1348
+ : 'Nothing the recordings read changed, so this is not proven. Check by hand what ' + thing + ' does when a ' + first.actor.role + ' calls it.');
1152
1349
  f.fixPrompt = fixPrompt(f);
1153
1350
  findings.push(f);
1154
1351
  }
@@ -1158,7 +1355,7 @@ function findingsOf(attempts, policy) {
1158
1355
  /** After the controls ran: a refusal-less answer to a forbidden action that looks exactly like an allowed account's. */
1159
1356
  function markHints(attempts) {
1160
1357
  for (const a of attempts) {
1161
- if (a.verdict !== V.AMBIGUOUS || a.expected !== 'deny' || a.notTried || a.kind !== 'role') continue;
1358
+ if (a.verdict !== V.AMBIGUOUS || a.expected !== 'deny' || a.notTried || !(a.kind === 'role' || (a.kind === 'tenant' && a.namedInBody))) continue;
1162
1359
  if (a.response.reading !== 'accepted' && a.response.reading !== 'redirect') continue;
1163
1360
  const control = attempts.find((c) => c.expected === 'allow' && c.method === a.method && c.template === a.template && c.verdict === V.ALLOWED);
1164
1361
  if (control && control.response.status === a.response.status && control.response.keys === a.response.keys) a.hint = true;
@@ -1396,6 +1593,11 @@ module.exports = {
1396
1593
  loadPolicy: loadPolicy,
1397
1594
  checkPolicy: checkPolicy,
1398
1595
  holds: holds,
1596
+ ORG_KEY: ORG_KEY,
1597
+ bodyRecords: bodyRecords,
1598
+ wordsOfAnyRecord: wordsOfAnyRecord,
1599
+ diffLines: diffLines,
1600
+ withoutOwn: withoutOwn,
1399
1601
  rolesWith: rolesWith,
1400
1602
  templateText: templateText,
1401
1603
  missingLines: missingLines,