kryptheon 0.1.58 → 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,20 +88,29 @@ 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
- // the other common shape: "roles": ["owner", "viewer"] and "rules": [{ "action": "read:orders", "allow": ["owner", "viewer"] }] (round 25)
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)
92
95
  if (Array.isArray(json.roles) && Array.isArray(json.rules)) {
93
96
  const names = json.roles.filter((r) => typeof r === 'string' && r.trim()).map((r) => r.trim());
94
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();
95
99
  for (const rule of json.rules) {
96
- if (!rule || typeof rule.action !== 'string' || !rule.action.trim() || !Array.isArray(rule.allow) || rule.allow.some((r) => typeof r !== 'string')) {
97
- problems.push('each of "rules" must be { "action": "read:orders", "allow": ["owner", ...] }.');
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": [...] }.');
98
102
  break;
99
103
  }
100
104
  const unknown = rule.allow.find((r) => !names.includes(r.trim()) && r.trim() !== '*');
101
- if (unknown) problems.push('rule "' + rule.action + '" allows "' + unknown + '", which is not in "roles".');
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
+ }
102
111
  }
103
112
  if (!problems.length) {
104
- for (const name of names) roles[name] = json.rules.filter((rule) => rule.allow.some((r) => r.trim() === name || r.trim() === '*')).map((rule) => rule.action.trim());
113
+ for (const name of names) roles[name] = json.rules.filter((rule) => rule.allow.some((r) => r.trim() === name || r.trim() === '*')).map(nameOf);
105
114
  if (names.length < 2) problems.push('it needs at least two roles to compare.');
106
115
  }
107
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.');
@@ -122,7 +131,7 @@ function checkPolicy(json) {
122
131
  const written = ['tenant_rules', 'tenantRules'].map((key) => json[key]).find((v) => Array.isArray(v) && v.some((x) => typeof x === 'string' && x.trim()));
123
132
  const boundary = typeof json.tenantBoundary === 'string' ? json.tenantBoundary : written ? written.filter((x) => typeof x === 'string').join(' ') : '';
124
133
  const tenants = boundary.trim() !== '' || json.tenants === true;
125
- return { ok: true, problems: [], policy: { roles: roles, tenants: tenants, boundary: boundary, extra: k } };
134
+ return { ok: true, problems: [], policy: { roles: roles, tenants: tenants, boundary: boundary, extra: k, parts: parts } };
126
135
  }
127
136
 
128
137
  /** Whether `role` has `permission` ("*" and "resource.*" are allowed in the file). */
@@ -272,7 +281,7 @@ function permissionFor(method, pathOrTemplate, policy) {
272
281
  const verb = METHOD_VERB[m];
273
282
  const found = [];
274
283
  for (const perm of permissionsOf(policy)) {
275
- const parts = partsOf(perm);
284
+ const parts = (policy.parts && policy.parts[perm]) || partsOf(perm);
276
285
  if (!parts) continue;
277
286
  const resource = parts.resource;
278
287
  const actions = parts.actions;
@@ -291,6 +300,11 @@ function permissionFor(method, pathOrTemplate, policy) {
291
300
  lastHit = true;
292
301
  } else if (a === verb) {
293
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;
294
308
  }
295
309
  }
296
310
  found.push({ permission: perm, score: score, lastHit: lastHit });
@@ -435,10 +449,23 @@ function diffLines(template, a, b) {
435
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('; '));
436
450
  }
437
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 [];
438
457
  }
439
458
  if (a && b && typeof a === 'object' && typeof b === 'object') {
440
- const fields = Object.keys(Object.assign({}, a, b)).filter((f) => JSON.stringify(a[f]) !== JSON.stringify(b[f]));
441
- 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('; ')];
442
469
  }
443
470
  return [template + ': the answer changed'];
444
471
  }
@@ -881,14 +908,20 @@ function bodyRecord(action, body, getTemplates, want) {
881
908
  */
882
909
  function bodyRecords(action, body, getTemplates) {
883
910
  const out = [];
911
+ const one = (v) => ['string', 'number'].includes(typeof v);
884
912
  for (const key of Object.keys(body || {})) {
885
- if (!/^[A-Za-z]+(?:_[A-Za-z]+)*_?[iI]d$/.test(key) || key.toLowerCase() === 'id' || !['string', 'number'].includes(typeof body[key])) continue;
886
- const words = key.replace(/_?[iI]d$/, '').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase().split('_').filter(Boolean);
887
- const stem = singular(words[words.length - 1] || '');
888
- const listing = Array.from(getTemplates || []).find((t) => !t.includes('{id}') && singular(t.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem);
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;
889
922
  if (!listing) continue;
890
923
  const segs = listing.split('/').filter(Boolean).concat('{id}');
891
- out.push({ key: key, like: { template: listing + '/{id}', segs: segs, params: [{ index: segs.length - 1, value: body[key] }], by: action.by } });
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 } });
892
925
  }
893
926
  return out;
894
927
  }
@@ -937,6 +970,7 @@ async function tryOnce(x) {
937
970
  // what to send
938
971
  let body;
939
972
  let bodyItem = null;
973
+ let bodyKey = null;
940
974
  if (!isGet) {
941
975
  body = sampleBody(a);
942
976
  // a body that names another record (shipmentId, order_id) is pointed at the target's organization too
@@ -948,8 +982,19 @@ async function tryOnce(x) {
948
982
  const j = x.rotate.get(k2) || 0;
949
983
  x.rotate.set(k2, j + 1);
950
984
  const pick = alt[j % alt.length];
951
- body[named.key] = pick.value;
985
+ body[named.key] = named.many ? [pick.value] : pick.value;
952
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
+ }
953
998
  }
954
999
  }
955
1000
  // A role named in the body: a refused account tries to make itself the most
@@ -990,8 +1035,13 @@ async function tryOnce(x) {
990
1035
  return snap;
991
1036
  };
992
1037
  const before = await withPerson(reader ? await x.snapshot(targetOrg) : {});
993
- // a write to an address that is also read (POST /returns/5/notes, GET /returns/5/notes) shows there
994
- const sameGet = reader && !isGet && a.params.length && x.getTemplates.has(a.template) ? pathNow : null;
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;
995
1045
  const readSame = async () => {
996
1046
  const f = sameGet ? await x.readerFor(targetOrg, sameGet, null, false) : null;
997
1047
  return f ? stable(f.res.json) : undefined;
@@ -1023,7 +1073,10 @@ async function tryOnce(x) {
1023
1073
  const reply = authz.replyOf(res);
1024
1074
  const foreign = actor.org && isGet ? foreignRecords(res.json, actor.org.key) : [];
1025
1075
  const ownMarked = actor.org && isGet ? ownRecords(res.json, actor.org.key) : 0;
1026
- let found = markers.length ? authz.foundIn(res, markers).length : 0;
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;
1027
1080
  // their record's own words now in our lists: a record of ours points at theirs (round 25: a transfer whose
1028
1081
  // destination was another organization's location, shown by name in our list of transfers)
1029
1082
  let pointedAt = [];
@@ -1047,6 +1100,8 @@ async function tryOnce(x) {
1047
1100
  changes: changes.slice(0, 6), protectedPiecesSeen: found,
1048
1101
  });
1049
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;
1050
1105
  // An answer to a try that was aimed across organizations is judged for that. For any other try, another
1051
1106
  // organization's records in the answer are a second finding, kept apart from what the role may do.
1052
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 });
@@ -1077,6 +1132,8 @@ async function tryOnce(x) {
1077
1132
  for (const who of writers) {
1078
1133
  await who.send(a.method, pathNow, a.encoding === 'form' ? { form: back } : { json: back });
1079
1134
  const again = await withPerson(await x.snapshot(targetOrg));
1135
+ const sameAgain = sameBefore !== undefined ? await readSame() : undefined;
1136
+ if (sameAgain !== undefined) again[sameGet] = sameAgain;
1080
1137
  if (x.compare(before, again).length === 0) {
1081
1138
  att.restored = true;
1082
1139
  break;
@@ -1102,18 +1159,26 @@ async function tryOnce(x) {
1102
1159
 
1103
1160
  // Fields whose values are one of a few words every organization uses: "submitted", "warehouse", "INR".
1104
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;
1105
1168
 
1106
1169
  /**
1107
1170
  * The values of a record that are a status or kind - words any organization's
1108
1171
  * records carry - and so prove nothing about whose record came back. Round 25:
1109
1172
  * "Only submitted purchase orders can be approved." held the other
1110
- * organization's status "submitted", and a refusal was called a leak.
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).
1111
1176
  */
1112
1177
  function wordsOfAnyRecord(value) {
1113
1178
  const out = new Set();
1114
1179
  (function walk(v, key) {
1115
1180
  if (typeof v === 'string') {
1116
- if ((key && SHARED_WORD_KEY.test(key)) || /^[a-z]+(_[a-z]+)*$/.test(v)) out.add(v);
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);
1117
1182
  } else if (Array.isArray(v)) v.forEach((x) => walk(x, key));
1118
1183
  else if (v && typeof v === 'object') Object.keys(v).forEach((k) => walk(v[k], k));
1119
1184
  })(value, null);
@@ -1141,6 +1206,20 @@ function foreignRecords(json, orgKey) {
1141
1206
  return out;
1142
1207
  }
1143
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
+
1144
1223
  /** How many records in an answer carry this organization's own mark. */
1145
1224
  function ownRecords(json, orgKey) {
1146
1225
  let n = 0;
@@ -1236,9 +1315,11 @@ function findingsOf(attempts, policy) {
1236
1315
  if (!groups.has(key)) groups.set(key, []);
1237
1316
  groups.get(key).push(a);
1238
1317
  }
1239
- for (const list of groups.values()) {
1318
+ for (const [key, list] of groups) {
1240
1319
  const first = list[0];
1241
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;
1242
1323
  const allowed = rolesWith(policy, first.permission);
1243
1324
  const thing = first.method + ' ' + first.template;
1244
1325
  const f = {
@@ -1256,11 +1337,15 @@ function findingsOf(attempts, policy) {
1256
1337
  };
1257
1338
  if (!proven) {
1258
1339
  f.severity = 'MEDIUM';
1259
- 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.';
1260
1343
  }
1261
1344
  for (const a of list.slice(0, 3)) f.proof.push.apply(f.proof, proofOf(a));
1262
1345
  if (list.length > 3) f.proof.push('... and ' + (list.length - 3) + ' more like it.');
1263
- 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.');
1264
1349
  f.fixPrompt = fixPrompt(f);
1265
1350
  findings.push(f);
1266
1351
  }
@@ -1270,7 +1355,7 @@ function findingsOf(attempts, policy) {
1270
1355
  /** After the controls ran: a refusal-less answer to a forbidden action that looks exactly like an allowed account's. */
1271
1356
  function markHints(attempts) {
1272
1357
  for (const a of attempts) {
1273
- 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;
1274
1359
  if (a.response.reading !== 'accepted' && a.response.reading !== 'redirect') continue;
1275
1360
  const control = attempts.find((c) => c.expected === 'allow' && c.method === a.method && c.template === a.template && c.verdict === V.ALLOWED);
1276
1361
  if (control && control.response.status === a.response.status && control.response.keys === a.response.keys) a.hint = true;
@@ -1508,6 +1593,11 @@ module.exports = {
1508
1593
  loadPolicy: loadPolicy,
1509
1594
  checkPolicy: checkPolicy,
1510
1595
  holds: holds,
1596
+ ORG_KEY: ORG_KEY,
1597
+ bodyRecords: bodyRecords,
1598
+ wordsOfAnyRecord: wordsOfAnyRecord,
1599
+ diffLines: diffLines,
1600
+ withoutOwn: withoutOwn,
1511
1601
  rolesWith: rolesWith,
1512
1602
  templateText: templateText,
1513
1603
  missingLines: missingLines,