kryptheon 0.1.52 → 0.1.54

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.
@@ -0,0 +1,874 @@
1
+ // Authorization across accounts: the same action, tried by every account the
2
+ // policy names, judged against what the policy says that account may do.
3
+ //
4
+ // What it does:
5
+ // - signs in as each seeded test account on its own, each with its own
6
+ // cookies (never shared, never kept after the run);
7
+ // - reads the actions to try from the person's recorded journey (the
8
+ // requests the browser made), keeping only those the policy has a rule for;
9
+ // - sends each one as the accounts the policy says may NOT do it, and as the
10
+ // accounts it says may (so a valid access is never reported);
11
+ // - judges what happened from what the app returned and what was stored
12
+ // before and after - never from a 200 alone, and never from a 403 alone.
13
+ //
14
+ // Each attempt ends as exactly one of:
15
+ // allowed-as-intended the account may, and it worked
16
+ // denied-as-intended the account may not, nothing came back and nothing changed
17
+ // confirmed-failure the account may not, and it got data or changed something
18
+ // ambiguous not enough to say - never turned into a finding
19
+ //
20
+ // What it never does: run against anything but this computer (localhost,
21
+ // 127.0.0.1, ::1, and only the origins it was told), follow a redirect to
22
+ // another host, delete anything, create accounts, or keep a password or cookie
23
+ // in the evidence. It changes data only on the app it was pointed at, and puts
24
+ // back what it changed through the baseline (owner) account; whatever it cannot
25
+ // put back is said, and the optional `reset` is the person's own way to do it.
26
+ //
27
+ // The policy is data (see kryptheon-authz.policy.round22.json): who the
28
+ // accounts are, what the app's requests look like, and what each role may do.
29
+ // It is never read out of the app being tested.
30
+
31
+ const probe = require('./kryptheon-probe.js');
32
+
33
+ const VERDICT = {
34
+ ALLOWED: 'allowed-as-intended',
35
+ DENIED: 'denied-as-intended',
36
+ FAILURE: 'confirmed-failure',
37
+ AMBIGUOUS: 'ambiguous',
38
+ };
39
+ const KINDS = ['roleChange', 'workOrderRead', 'finance', 'workOrderModify', 'job'];
40
+ const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]', '::1'];
41
+ const MAX_REQUESTS = 600;
42
+ const MAX_TEXT = 300000;
43
+ const EXCERPT = 240;
44
+
45
+ // --- the one place that decides where requests may go ---------------------
46
+
47
+ /**
48
+ * The origin requests may go to. Only this computer, and only an origin named
49
+ * in `allow` when one is given: anything else throws, before any request.
50
+ */
51
+ function assertLocalTarget(baseUrl, allow) {
52
+ let u;
53
+ try {
54
+ u = new URL(String(baseUrl));
55
+ } catch (err) {
56
+ throw new Error('authz: "' + baseUrl + '" is not an address');
57
+ }
58
+ if (!/^https?:$/.test(u.protocol)) throw new Error('authz: only http or https addresses are allowed');
59
+ if (!LOCAL_HOSTS.includes(u.hostname.toLowerCase())) {
60
+ throw new Error('authz: refused ' + u.origin + ' - this only runs against localhost or 127.0.0.1');
61
+ }
62
+ if (allow && allow.length && !allow.includes(u.origin)) {
63
+ throw new Error('authz: refused ' + u.origin + ' - it is not in the allowed origins (' + allow.join(', ') + ')');
64
+ }
65
+ return u.origin;
66
+ }
67
+
68
+ // --- hiding secrets -------------------------------------------------------
69
+
70
+ const SECRET_KEY = /^(pass(word|code)?|secret|token|authorization|cookie|set-cookie|session|sid)$/i;
71
+
72
+ /** Text with every secret value, and any session cookie, taken out. */
73
+ function redact(text, secrets) {
74
+ let s = String(text == null ? '' : text);
75
+ for (const v of secrets || []) {
76
+ if (typeof v !== 'string' || v.length < 3) continue;
77
+ s = s.split(v).join('[hidden]').split(encodeURIComponent(v)).join('[hidden]');
78
+ }
79
+ s = s.replace(/((?:connect\.sid|sid|session(?:id)?|token|jwt|auth[\w-]*)\s*=\s*)[^;\s"',]+/gi, '$1[hidden]');
80
+ return s;
81
+ }
82
+
83
+ /** A value with secret-named keys blanked and secret text taken out. */
84
+ function redactValue(value, secrets) {
85
+ if (value == null) return value;
86
+ if (typeof value === 'string') return redact(value, secrets);
87
+ if (Array.isArray(value)) return value.map((x) => redactValue(x, secrets));
88
+ if (typeof value === 'object') {
89
+ const out = {};
90
+ for (const k of Object.keys(value)) out[k] = SECRET_KEY.test(k) ? '[hidden]' : redactValue(value[k], secrets);
91
+ return out;
92
+ }
93
+ return value;
94
+ }
95
+
96
+ // --- small helpers --------------------------------------------------------
97
+
98
+ function getPath(obj, dotted) {
99
+ if (!dotted) return obj;
100
+ let cur = obj;
101
+ for (const part of String(dotted).split('.')) {
102
+ if (cur == null) return undefined;
103
+ cur = cur[part];
104
+ }
105
+ return cur;
106
+ }
107
+
108
+ const clip = (s, n) => {
109
+ const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim();
110
+ return t.length > n ? t.slice(0, n) + '...' : t;
111
+ };
112
+
113
+ /** /api/work-orders/12 -> /api/work-orders/{id}; ids are numbers or uuids. */
114
+ function templateOf(p) {
115
+ return String(p || '').split('?')[0].split('/').map((seg) => (/^\d+$/.test(seg) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(seg) ? '{id}' : seg)).join('/');
116
+ }
117
+
118
+ function fillTemplate(template, id) {
119
+ return String(template).replace('{id}', encodeURIComponent(String(id)));
120
+ }
121
+
122
+ // --- the policy -----------------------------------------------------------
123
+
124
+ /** The policy, checked. Throws a sentence about what is missing. */
125
+ function checkPolicy(policy) {
126
+ const need = (cond, what) => {
127
+ if (!cond) throw new Error('authz policy: ' + what);
128
+ };
129
+ need(policy && typeof policy === 'object', 'is missing');
130
+ need(policy.roles && Object.keys(policy.roles).length >= 2, 'roles: needs at least two accounts');
131
+ for (const [role, acct] of Object.entries(policy.roles)) need(acct && acct.email, 'roles.' + role + '.email is missing');
132
+ need(policy.baselineRole && policy.roles[policy.baselineRole], 'baselineRole must name one of the roles (the account that may read and restore everything)');
133
+ need(policy.login && policy.login.path, 'login.path is missing');
134
+ need(policy.identity && policy.identity.path && policy.identity.idPath, 'identity.path and identity.idPath are missing');
135
+ need(policy.cases && typeof policy.cases === 'object', 'cases is missing');
136
+ for (const [kind, c] of Object.entries(policy.cases)) {
137
+ need(KINDS.includes(kind), 'cases.' + kind + ' is not one of ' + KINDS.join(', '));
138
+ need(c.match && c.match.path, 'cases.' + kind + '.match.path is missing');
139
+ need(c.permissions, 'cases.' + kind + '.permissions is missing');
140
+ for (const role of Object.keys(policy.roles)) {
141
+ need(c.permissions[role] !== undefined || kind === 'finance', 'cases.' + kind + '.permissions.' + role + ' is missing');
142
+ }
143
+ }
144
+ return policy;
145
+ }
146
+
147
+ /** What `rule` allows this account on this record. */
148
+ function mayDo(rule, actorId, item, cfg) {
149
+ if (rule === 'allow' || rule === 'all') return true;
150
+ if (rule === 'own') return item != null && actorId != null && String(item[cfg.ownerField]) === String(actorId);
151
+ if (rule === 'assigned') return item != null && actorId != null && String(item[cfg.assigneeField]) === String(actorId);
152
+ return false;
153
+ }
154
+
155
+ // --- the journey: what the browser did ------------------------------------
156
+
157
+ /**
158
+ * Journey entries from a Kryptheon probe result's events (writes) - the
159
+ * recorded flows' own requests.
160
+ */
161
+ function journeyFromEvents(events) {
162
+ const out = [];
163
+ for (const e of events || []) {
164
+ if (!e || !e.method || !e.path) continue;
165
+ out.push({ method: String(e.method).toUpperCase(), path: String(e.path), status: e.status, body: e.body !== undefined ? e.body : e.data });
166
+ }
167
+ return out;
168
+ }
169
+
170
+ /** Journey entries from a HAR file's JSON (a browser's own record of its requests). */
171
+ function journeyFromHar(har) {
172
+ const out = [];
173
+ const entries = (har && har.log && har.log.entries) || [];
174
+ for (const e of entries) {
175
+ if (!e || !e.request || !e.request.url) continue;
176
+ let u;
177
+ try {
178
+ u = new URL(e.request.url);
179
+ } catch (err) {
180
+ continue;
181
+ }
182
+ if (/\.(css|js|png|jpe?g|gif|svg|ico|woff2?|map)$/i.test(u.pathname)) continue;
183
+ let body;
184
+ const text = e.request.postData && e.request.postData.text;
185
+ if (text) {
186
+ try {
187
+ body = JSON.parse(text);
188
+ } catch (err) {
189
+ body = text;
190
+ }
191
+ }
192
+ // A recorded sign-in carries a password: it never leaves this reader.
193
+ out.push({ method: String(e.request.method).toUpperCase(), path: u.pathname + (u.search || ''), status: e.response && e.response.status, body: redactValue(body) });
194
+ }
195
+ return out;
196
+ }
197
+
198
+ /**
199
+ * Which cases the journey exercised, and so which are tried. A case with no
200
+ * matching request in the journey is skipped - said as not exercised, never
201
+ * as passed. Returns { active: {kind: {entries, templates}}, skipped: [{kind, why}] }.
202
+ */
203
+ function discover(policy, journey) {
204
+ const active = {};
205
+ const skipped = [];
206
+ for (const kind of KINDS) {
207
+ const c = policy.cases[kind];
208
+ if (!c) {
209
+ skipped.push({ kind: kind, why: 'the policy has no rule for it' });
210
+ continue;
211
+ }
212
+ const methodRe = new RegExp(c.match.method || '^.*$', 'i');
213
+ const pathRe = new RegExp(c.match.path);
214
+ const hits = (journey || []).filter((j) => methodRe.test(j.method) && pathRe.test(String(j.path).split('?')[0]));
215
+ if (!hits.length) {
216
+ skipped.push({ kind: kind, why: 'the recorded journey never made a request the policy has a rule for (' + c.match.path + ')' });
217
+ continue;
218
+ }
219
+ const templates = [];
220
+ for (const h of hits) {
221
+ const t = templateOf(h.path);
222
+ if (!templates.some((x) => x.template === t && x.method === h.method)) templates.push({ method: h.method, template: t, body: h.body });
223
+ }
224
+ active[kind] = { entries: hits, templates: templates };
225
+ }
226
+ return { active: active, skipped: skipped };
227
+ }
228
+
229
+ // --- how a reply is read --------------------------------------------------
230
+
231
+ const SIGN_IN_FORM = /<input[^>]*type\s*=\s*["']?password/i;
232
+ // probe.accepted only knows /login and /signin; an app's own page is often login.html.
233
+ const SIGN_IN_TO = /(^|\/)(log-?in|sign-?in|auth)(\.\w+)?(\/|$)/i;
234
+
235
+ /**
236
+ * What the app said, in words that matter here:
237
+ * refused | accepted | redirect | server-error | no-answer. A redirect to the
238
+ * sign-in page or with an error in its address is refused; any other redirect
239
+ * after a write is not enough to say (found on blind rounds 19 and 21) and is
240
+ * left to the stored state. A 2xx that is only an error message, or the
241
+ * sign-in page, is refused.
242
+ */
243
+ function replyOf(res) {
244
+ if (!res || res.error) return { kind: 'no-answer', note: res && res.error ? res.error : 'no answer' };
245
+ const s = res.status;
246
+ if (s >= 500) return { kind: 'server-error', note: 'the app answered ' + s };
247
+ if (s >= 400) return { kind: 'refused', note: 'the app answered ' + s };
248
+ if (s >= 300) {
249
+ const w = { status: s, to: res.location || '', from: '' };
250
+ if (!res.location) return { kind: 'redirect', note: 'redirect (' + s + ') with no address' };
251
+ if (!SIGN_IN_TO.test(String(res.location).split(/[?#]/)[0]) && probe.accepted(w)) return { kind: 'redirect', note: 'redirect (' + s + ') to ' + clip(res.location, 80) };
252
+ return { kind: 'refused', note: 'redirect (' + s + ') to ' + clip(res.location, 80) };
253
+ }
254
+ if (SIGN_IN_FORM.test(res.text || '')) return { kind: 'refused', note: 'the sign-in page came back' };
255
+ const j = res.json;
256
+ if (j && typeof j === 'object' && !Array.isArray(j)) {
257
+ const keys = Object.keys(j);
258
+ if ((j.ok === false || j.success === false) || (typeof j.error === 'string' && keys.every((k) => ['error', 'message', 'ok', 'success', 'status', 'code'].includes(k)))) {
259
+ return { kind: 'refused', note: 'answered ' + s + ' with an error message: ' + clip(j.error || j.message, 80) };
260
+ }
261
+ }
262
+ return { kind: 'accepted', note: 'the app answered ' + s };
263
+ }
264
+
265
+ // --- markers: what proves protected content came back ----------------------
266
+
267
+ /** Strings of a value, anywhere in it, that are long enough to be telling. */
268
+ function stringsOf(value, minLength, out) {
269
+ const into = out || [];
270
+ if (typeof value === 'string') {
271
+ if (value.length >= minLength) into.push(value);
272
+ } else if (Array.isArray(value)) {
273
+ value.forEach((x) => stringsOf(x, minLength, into));
274
+ } else if (value && typeof value === 'object') {
275
+ Object.keys(value).forEach((k) => stringsOf(value[k], minLength, into));
276
+ }
277
+ return into;
278
+ }
279
+
280
+ /** Strings that look like identifiers (an email, an id with digits) - not status words. */
281
+ function identifierLike(s) {
282
+ return /@/.test(s) || (/\d/.test(s) && /[A-Za-z_-]/.test(s) && s.length >= 6);
283
+ }
284
+
285
+ /** Which of these markers the reply's body carries. */
286
+ function foundIn(res, markers) {
287
+ const body = String((res && res.text) || '');
288
+ const found = [];
289
+ for (const m of markers) if (m && body.includes(m) && !found.includes(m)) found.push(m);
290
+ return found;
291
+ }
292
+
293
+ // --- judging --------------------------------------------------------------
294
+
295
+ /**
296
+ * A read. `allowed` is what the policy says. `found` is how many of the
297
+ * protected record's own words came back, however the app answered.
298
+ */
299
+ function judgeRead(input) {
300
+ const reply = input.reply;
301
+ const found = input.found || 0;
302
+ if (input.allowed) {
303
+ if (found > 0) return { verdict: VERDICT.ALLOWED, reason: 'the account may read it, and the record came back' };
304
+ if (reply.kind === 'refused') return { verdict: VERDICT.AMBIGUOUS, reason: 'the account may read it but was refused (' + reply.note + ') - needs review, not a leak' };
305
+ return { verdict: VERDICT.AMBIGUOUS, reason: 'the account may read it, but none of the record was seen in the answer (' + reply.note + ')' };
306
+ }
307
+ if (found > 0) return { verdict: VERDICT.FAILURE, reason: 'the account may not read it, and ' + found + ' piece(s) of its content came back (' + reply.note + ')' };
308
+ if (reply.kind === 'server-error' || reply.kind === 'no-answer') return { verdict: VERDICT.AMBIGUOUS, reason: 'no clear answer (' + reply.note + ') - cannot tell whether anything was held back' };
309
+ return { verdict: VERDICT.DENIED, reason: 'none of the protected content came back (' + reply.note + ')' };
310
+ }
311
+
312
+ /**
313
+ * A write. `changed` is what the stored state shows: true, false, or null when
314
+ * it could not be read. `leaked` is whether protected content came back in the
315
+ * answer to a write that was not allowed.
316
+ */
317
+ function judgeWrite(input) {
318
+ const reply = input.reply;
319
+ if (input.changed === null || input.changed === undefined) {
320
+ return { verdict: VERDICT.AMBIGUOUS, reason: 'the stored state could not be read before and after, so the effect is not known (' + reply.note + ')' };
321
+ }
322
+ if (input.allowed) {
323
+ if (input.changed) return { verdict: VERDICT.ALLOWED, reason: 'the account may do it, and the stored state changed as expected' };
324
+ return { verdict: VERDICT.AMBIGUOUS, reason: 'the account may do it, but nothing changed (' + reply.note + ') - needs review, not a finding' };
325
+ }
326
+ if (input.changed) return { verdict: VERDICT.FAILURE, reason: 'the account may not do it, and the stored state changed (' + reply.note + ')' };
327
+ if (input.leaked) return { verdict: VERDICT.FAILURE, reason: 'the account may not do it; nothing changed, but protected content came back in the answer (' + reply.note + ')' };
328
+ if (reply.kind === 'refused') return { verdict: VERDICT.DENIED, reason: 'refused (' + reply.note + ') and the stored state is unchanged' };
329
+ if (reply.kind === 'server-error' || reply.kind === 'no-answer') return { verdict: VERDICT.AMBIGUOUS, reason: 'no clear answer (' + reply.note + '); the stored state is unchanged' };
330
+ return { verdict: VERDICT.AMBIGUOUS, reason: 'the app took the request (' + reply.note + ') but nothing changed - it may have ignored it; needs review' };
331
+ }
332
+
333
+ // --- sessions -------------------------------------------------------------
334
+
335
+ /** One account's own browser: its own cookies, nothing shared. */
336
+ function makeSession(ctx, role, email, password) {
337
+ const jar = new Map();
338
+ return {
339
+ role: role,
340
+ email: email,
341
+ password: password,
342
+ jar: jar,
343
+ id: null,
344
+ ownRole: null,
345
+ async send(method, p, opts) {
346
+ return ctx.request(this, method, p, opts || {});
347
+ },
348
+ };
349
+ }
350
+
351
+ function cookieHeader(jar) {
352
+ return Array.from(jar.entries()).map(([k, v]) => k + '=' + v).join('; ');
353
+ }
354
+
355
+ function storeCookies(jar, res) {
356
+ let list = [];
357
+ if (res.headers && typeof res.headers.getSetCookie === 'function') list = res.headers.getSetCookie();
358
+ else if (res.headers && res.headers.get('set-cookie')) list = [res.headers.get('set-cookie')];
359
+ for (const line of list) {
360
+ const first = String(line).split(';')[0];
361
+ const eq = first.indexOf('=');
362
+ if (eq > 0) {
363
+ const name = first.slice(0, eq).trim();
364
+ const value = first.slice(eq + 1).trim();
365
+ if (value === '' || /;\s*expires=Thu, 01 Jan 1970/i.test(line)) jar.delete(name);
366
+ else jar.set(name, value);
367
+ }
368
+ }
369
+ }
370
+
371
+ function makeContext(options) {
372
+ const origin = assertLocalTarget(options.baseUrl, options.allowOrigins);
373
+ const fetchImpl = options.fetch || globalThis.fetch;
374
+ const secrets = Object.values(options.passwords || {}).filter(Boolean);
375
+ const ctx = { origin: origin, requests: 0, secrets: secrets };
376
+ ctx.request = async function (session, method, p, opts) {
377
+ method = String(method).toUpperCase();
378
+ if (method === 'DELETE') throw new Error('authz: this check never deletes anything');
379
+ if (String(p).startsWith('//') || /^[a-z]+:/i.test(String(p))) throw new Error('authz: refused a request to "' + p + '" - paths only, on the allowed origin');
380
+ if (++ctx.requests > (options.maxRequests || MAX_REQUESTS)) throw new Error('authz: stopped - more than ' + (options.maxRequests || MAX_REQUESTS) + ' requests in one run');
381
+ const url = new URL(p, origin);
382
+ if (url.origin !== origin) throw new Error('authz: refused a request to another origin');
383
+ const headers = { accept: 'application/json, text/html;q=0.8' };
384
+ const cookie = cookieHeader(session.jar);
385
+ if (cookie) headers.cookie = cookie;
386
+ let body;
387
+ if (opts.json !== undefined) {
388
+ headers['content-type'] = 'application/json';
389
+ body = JSON.stringify(opts.json);
390
+ } else if (opts.form) {
391
+ headers['content-type'] = 'application/x-www-form-urlencoded';
392
+ body = new URLSearchParams(opts.form).toString();
393
+ }
394
+ let res;
395
+ try {
396
+ res = await fetchImpl(url.href, { method: method, headers: headers, body: body, redirect: 'manual', signal: AbortSignal.timeout(options.timeoutMs || 15000) });
397
+ } catch (err) {
398
+ return { error: redact(err && err.message, secrets), status: 0 };
399
+ }
400
+ storeCookies(session.jar, res);
401
+ let text = '';
402
+ try {
403
+ text = (await res.text()).slice(0, MAX_TEXT);
404
+ } catch (err) {
405
+ text = '';
406
+ }
407
+ let json;
408
+ try {
409
+ json = text ? JSON.parse(text) : undefined;
410
+ } catch (err) {
411
+ json = undefined;
412
+ }
413
+ return { status: res.status, location: res.headers.get('location') || '', text: text, json: json };
414
+ };
415
+ return ctx;
416
+ }
417
+
418
+ async function signIn(ctx, policy, session) {
419
+ const l = policy.login;
420
+ const fields = {};
421
+ fields[l.emailField || 'email'] = session.email;
422
+ fields[l.passwordField || 'password'] = session.password;
423
+ const res = l.as === 'form' ? await session.send('POST', l.path, { form: fields }) : await session.send('POST', l.path, { json: fields });
424
+ const reply = replyOf(res);
425
+ if (reply.kind === 'refused' || reply.kind === 'server-error' || reply.kind === 'no-answer') {
426
+ throw new Error('authz: could not sign in as ' + session.role + ' (' + reply.note + ')');
427
+ }
428
+ const me = await session.send('GET', policy.identity.path);
429
+ const id = getPath(me.json, policy.identity.idPath);
430
+ if (me.status !== 200 || id == null) throw new Error('authz: signed in as ' + session.role + ' but could not read who that is (' + policy.identity.path + ' answered ' + me.status + ')');
431
+ session.id = id;
432
+ session.ownRole = getPath(me.json, policy.identity.rolePath);
433
+ }
434
+
435
+ // --- evidence -------------------------------------------------------------
436
+
437
+ function evidenceOf(ctx, base, extra) {
438
+ const e = Object.assign({}, base, extra);
439
+ e.request = redactValue(e.request, ctx.secrets);
440
+ if (e.response) {
441
+ e.response = Object.assign({}, e.response, { bodyExcerpt: redact(e.response.bodyExcerpt, ctx.secrets) });
442
+ }
443
+ e.before = redactValue(e.before, ctx.secrets);
444
+ e.after = redactValue(e.after, ctx.secrets);
445
+ return e;
446
+ }
447
+
448
+ function responseSummary(res, reply, found) {
449
+ return { status: res.status, location: res.location || undefined, reading: reply.kind, bodyExcerpt: clip(res.text, EXCERPT), protectedPiecesSeen: found };
450
+ }
451
+
452
+ function reproduction(ctx, session, base, method, p, body, readAs, readPath, before, after) {
453
+ const steps = [
454
+ 'Start the app on ' + ctx.origin + ' with its seeded test database.',
455
+ 'Sign in as ' + session.role + ' (' + session.email + ') with that account\'s seeded password.',
456
+ 'Send ' + method + ' ' + p + (body !== undefined ? ' with body ' + JSON.stringify(body) : '') + ' using that account\'s own session.',
457
+ ];
458
+ if (readPath) steps.push((readAs ? 'As ' + readAs + ', read ' : 'Read ') + readPath + ' before and after: before ' + JSON.stringify(before) + ', after ' + JSON.stringify(after) + '.');
459
+ else steps.push('Look at the answer: it is judged by whether the protected content is in it.');
460
+ return steps;
461
+ }
462
+
463
+ // --- the run --------------------------------------------------------------
464
+
465
+ /**
466
+ * Runs every case the journey exercised. Options:
467
+ * baseUrl, allowOrigins, policy, journey, passwords { role: password },
468
+ * reset (async (caseName) => void, optional: the person's own way to put the
469
+ * database back), fetch (for tests), maxRequests, log.
470
+ * Returns { origin, results: [...evidence], findings: [...], skipped: [...],
471
+ * counts, notes }.
472
+ */
473
+ async function runAuthz(options) {
474
+ const policy = checkPolicy(options.policy);
475
+ const ctx = makeContext(options);
476
+ const log = options.log || (() => {});
477
+ const notes = [];
478
+ const disc = discover(policy, options.journey);
479
+ const roles = Object.keys(policy.roles);
480
+ const base = policy.baselineRole;
481
+
482
+ const sessions = {};
483
+ for (const role of roles) {
484
+ const pw = (options.passwords || {})[role];
485
+ if (!pw) throw new Error('authz: no password given for ' + role + ' (set KRYPTHEON_AUTHZ_PASSWORD_' + role.toUpperCase() + ')');
486
+ sessions[role] = makeSession(ctx, role, policy.roles[role].email, pw);
487
+ }
488
+ for (const role of roles) {
489
+ await signIn(ctx, policy, sessions[role]);
490
+ log('signed in as ' + role);
491
+ }
492
+ const owner = sessions[base];
493
+ const results = [];
494
+
495
+ const add = (c, session, target, action, request, res, reply, found, before, after, verdictInfo, expected, restored, readPath) => {
496
+ results.push(evidenceOf(ctx, {
497
+ case: c,
498
+ actor: { role: session.role, email: session.email },
499
+ target: target,
500
+ action: action,
501
+ expected: expected,
502
+ request: request,
503
+ }, {
504
+ response: res ? responseSummary(res, reply, found) : undefined,
505
+ before: before,
506
+ after: after,
507
+ verdict: verdictInfo.verdict,
508
+ reason: verdictInfo.reason,
509
+ restored: restored,
510
+ reproduce: reproduction(ctx, session, null, request.method, request.path, request.body, ['roleChange', 'job'].includes(c) ? null : base, readPath, before, after),
511
+ }));
512
+ };
513
+
514
+ const rolesNow = async () => {
515
+ const out = {};
516
+ for (const role of roles) {
517
+ const me = await sessions[role].send('GET', policy.identity.path);
518
+ out[role] = me.status === 200 ? getPath(me.json, policy.identity.rolePath) : null;
519
+ }
520
+ return out;
521
+ };
522
+ const resetFor = async (name) => {
523
+ if (typeof options.reset === 'function') await options.reset(name);
524
+ };
525
+
526
+ // ---- 1. role changes
527
+ if (disc.active.roleChange) {
528
+ await resetFor('roleChange');
529
+ const c = policy.cases.roleChange;
530
+ const tpl = disc.active.roleChange.templates[0];
531
+ const field = c.bodyField || 'role';
532
+ const values = c.values || ['manager', 'technician', 'member'];
533
+ const tryChange = async (session, targetRole, newValue, expectedAllowed) => {
534
+ const target = sessions[targetRole];
535
+ const p = fillTemplate(tpl.template, target.id);
536
+ const before = await rolesNow();
537
+ const body = {};
538
+ body[field] = newValue;
539
+ const res = await session.send(tpl.method, p, { json: body });
540
+ const reply = replyOf(res);
541
+ const after = await rolesNow();
542
+ const changedRoles = roles.filter((r) => before[r] !== after[r]);
543
+ const known = roles.every((r) => before[r] !== null && after[r] !== null);
544
+ const verdictInfo = judgeWrite({ allowed: expectedAllowed, reply: reply, changed: known ? changedRoles.length > 0 : null, leaked: false });
545
+ let restored = true;
546
+ for (const r of changedRoles) {
547
+ const back = {};
548
+ back[field] = before[r];
549
+ await owner.send(tpl.method, fillTemplate(tpl.template, sessions[r].id), { json: back });
550
+ }
551
+ if (changedRoles.length) restored = JSON.stringify(await rolesNow()) === JSON.stringify(before);
552
+ add('roleChange', session, { type: 'user', role: targetRole, id: target.id }, tpl.method + ' ' + tpl.template, { method: tpl.method, path: p, body: body }, res, reply, 0, before, after, verdictInfo,
553
+ expectedAllowed ? 'allow' : 'deny', restored, policy.identity.path + ', for every account with its own session');
554
+ };
555
+ for (const role of roles) {
556
+ const allowed = c.permissions[role] === 'allow';
557
+ const peer = roles.find((r) => r !== role && r !== base) || base;
558
+ if (allowed) {
559
+ const peerNow = (await rolesNow())[peer];
560
+ await tryChange(sessions[role], peer, values.find((v) => v !== peerNow) || values[0], true);
561
+ continue;
562
+ }
563
+ await tryChange(sessions[role], role, c.ownerValue || 'owner', false);
564
+ const peerNow = (await rolesNow())[peer];
565
+ await tryChange(sessions[role], peer, values.find((v) => v !== peerNow) || values[0], false);
566
+ }
567
+ }
568
+
569
+ // ---- work orders: who owns what is read once, by the baseline account
570
+ const wo = policy.workOrders;
571
+ let items = [];
572
+ const needItems = disc.active.workOrderRead || disc.active.workOrderModify;
573
+ if (needItems) {
574
+ if (!wo) throw new Error('authz policy: workOrders is missing (collection, item, ownerField, assigneeField)');
575
+ const list = await owner.send('GET', wo.collection);
576
+ items = getPath(list.json, wo.listPath) || [];
577
+ if (!Array.isArray(items) || !items.length) {
578
+ notes.push('No work orders were readable as ' + base + ' - the work-order cases could not be tried.');
579
+ items = [];
580
+ }
581
+ }
582
+ const markersFor = (item) => stringsOf((wo.markerFields || ['title']).map((f) => item[f]), 4);
583
+ const chooseFor = (session, rule) => {
584
+ const permitted = items.filter((it) => mayDo(rule, session.id, it, wo));
585
+ const forbidden = items.filter((it) => !mayDo(rule, session.id, it, wo));
586
+ // Different owners first, so "a peer's record" is tried before a second of the same.
587
+ const seen = new Set();
588
+ const spread = [];
589
+ for (const it of forbidden) {
590
+ const k = String(it[wo.ownerField]);
591
+ if (!seen.has(k)) { seen.add(k); spread.push(it); }
592
+ }
593
+ return { permitted: permitted.slice(0, 1), forbidden: spread.concat(forbidden.filter((x) => !spread.includes(x))).slice(0, 2) };
594
+ };
595
+ const targetOf = (it) => ({ type: 'work-order', id: it[wo.idField || 'id'], owner: it[wo.ownerField], assignee: it[wo.assigneeField] });
596
+
597
+ // ---- 2. work-order reads
598
+ if (disc.active.workOrderRead && items.length) {
599
+ await resetFor('workOrderRead');
600
+ const c = policy.cases.workOrderRead;
601
+ const tpl = disc.active.workOrderRead.templates[0];
602
+ for (const role of roles) {
603
+ const s = sessions[role];
604
+ const pick = chooseFor(s, c.permissions[role]);
605
+ for (const [it, allowed] of pick.permitted.map((x) => [x, true]).concat(pick.forbidden.map((x) => [x, false]))) {
606
+ const p = fillTemplate(tpl.template, it[wo.idField || 'id']);
607
+ const res = await s.send('GET', p);
608
+ const reply = replyOf(res);
609
+ const found = foundIn(res, markersFor(it)).length;
610
+ add('workOrderRead', s, targetOf(it), 'GET ' + tpl.template, { method: 'GET', path: p }, res, reply, found, undefined, undefined,
611
+ judgeRead({ allowed: allowed, reply: reply, found: found }), allowed ? 'allow' : 'deny', true, null);
612
+ }
613
+ // The whole list, too: it must not hold records the account may not read.
614
+ const resList = await s.send('GET', wo.collection);
615
+ const replyList = replyOf(resList);
616
+ const rows = getPath(resList.json, wo.listPath);
617
+ if (Array.isArray(rows)) {
618
+ const idOf = (r) => String(r[wo.idField || 'id']);
619
+ const known = new Map(items.map((it) => [idOf(it), it]));
620
+ const extra = rows.filter((r) => known.has(idOf(r)) && !mayDo(c.permissions[role], s.id, known.get(idOf(r)), wo));
621
+ const verdictInfo = extra.length
622
+ ? { verdict: VERDICT.FAILURE, reason: 'the list holds ' + extra.length + ' work order(s) this account may not read (ids ' + extra.slice(0, 5).map(idOf).join(', ') + ')' }
623
+ : { verdict: rows.length ? VERDICT.ALLOWED : VERDICT.AMBIGUOUS, reason: rows.length ? 'every work order in the list is one this account may read' : 'the list was empty - nothing to judge' };
624
+ add('workOrderRead', s, { type: 'work-order list', count: rows.length }, 'GET ' + wo.collection, { method: 'GET', path: wo.collection }, resList, replyList, extra.length, undefined, undefined, verdictInfo,
625
+ 'list only what is permitted', true, null);
626
+ }
627
+ }
628
+ }
629
+
630
+ // ---- 3. finance
631
+ if (disc.active.finance) {
632
+ await resetFor('finance');
633
+ const c = policy.cases.finance;
634
+ const endpoints = Array.from(new Set(disc.active.finance.templates.map((t) => t.template)));
635
+ for (const ep of endpoints) {
636
+ const scope = (c.scopes && c.scopes[ep]) || 'whole';
637
+ const truth = await owner.send('GET', ep);
638
+ const truthRecords = (getPath(truth.json, c.recordsPath || '') || truth.json);
639
+ const recordList = Array.isArray(truthRecords) ? truthRecords : (truthRecords && typeof truthRecords === 'object' ? Object.values(truthRecords).find(Array.isArray) || [] : []);
640
+ if (truth.status !== 200 || !recordList.length) {
641
+ notes.push('Finance endpoint ' + ep + ' returned no records for ' + base + ' - it could not be judged.');
642
+ continue;
643
+ }
644
+ for (const role of roles) {
645
+ const s = sessions[role];
646
+ const allowed = (c.permissions[role] === 'allow') && true;
647
+ const res = await s.send('GET', ep);
648
+ const reply = replyOf(res);
649
+ // Records that belong to the account asking are its own to see.
650
+ const others = recordList.filter((r) => !stringsOf(r, 3).includes(s.email));
651
+ const pool = scope === 'others' ? others : recordList;
652
+ const markers = Array.from(new Set(stringsOf(pool, 6).filter(identifierLike)));
653
+ const own = scope === 'others' ? new Set(stringsOf(recordList.filter((r) => stringsOf(r, 3).includes(s.email)), 6)) : new Set();
654
+ const found = foundIn(res, markers.filter((m) => !own.has(m) && m !== s.email)).length;
655
+ const allowedHere = scope === 'others' ? (allowed ? true : false) : allowed;
656
+ let info;
657
+ if (scope === 'others' && !allowed) {
658
+ // A member reading only their own invoices is a valid access.
659
+ info = found > 0
660
+ ? { verdict: VERDICT.FAILURE, reason: 'other accounts\' records came back (' + found + ' piece(s)) (' + reply.note + ')' }
661
+ : (reply.kind === 'server-error' || reply.kind === 'no-answer'
662
+ ? { verdict: VERDICT.AMBIGUOUS, reason: 'no clear answer (' + reply.note + ')' }
663
+ : { verdict: VERDICT.DENIED, reason: 'no other account\'s record came back (' + reply.note + ')' });
664
+ } else {
665
+ info = judgeRead({ allowed: allowedHere, reply: reply, found: found });
666
+ }
667
+ add('finance', s, { type: 'finance endpoint', path: ep, scope: scope }, 'GET ' + ep, { method: 'GET', path: ep }, res, reply, found, undefined, undefined, info,
668
+ allowedHere ? 'allow' : (scope === 'others' ? 'own records only' : 'deny'), true, null);
669
+ }
670
+ }
671
+ }
672
+
673
+ // ---- 4. work-order modifications
674
+ if (disc.active.workOrderModify && items.length) {
675
+ await resetFor('workOrderModify');
676
+ const c = policy.cases.workOrderModify;
677
+ const tpl = disc.active.workOrderModify.templates[0];
678
+ const field = wo.modifyField || 'description';
679
+ let n = 0;
680
+ for (const role of roles) {
681
+ const s = sessions[role];
682
+ const pick = chooseFor(s, c.permissions[role]);
683
+ for (const [it, allowed] of pick.permitted.map((x) => [x, true]).concat(pick.forbidden.map((x) => [x, false]))) {
684
+ const id = it[wo.idField || 'id'];
685
+ const p = fillTemplate(tpl.template, id);
686
+ const readOne = async () => {
687
+ const r = await owner.send('GET', fillTemplate(wo.item, id));
688
+ const rec = getPath(r.json, wo.itemPath);
689
+ return rec && rec[field] !== undefined ? rec : null;
690
+ };
691
+ const beforeRec = await readOne();
692
+ const marker = 'kx-authz-' + Date.now().toString(36) + '-' + (++n);
693
+ const body = {};
694
+ body[field] = marker;
695
+ const res = await s.send(tpl.method, p, { json: body });
696
+ const reply = replyOf(res);
697
+ const afterRec = await readOne();
698
+ const known = beforeRec !== null && afterRec !== null;
699
+ const changed = known ? String(afterRec[field]) !== String(beforeRec[field]) : null;
700
+ const leaked = !allowed && res.status >= 200 && res.status < 300 && foundIn(res, markersFor(it)).length > 0;
701
+ const info = judgeWrite({ allowed: allowed, reply: reply, changed: changed, leaked: leaked });
702
+ let restored = true;
703
+ if (known && changed) {
704
+ const back = {};
705
+ back[field] = beforeRec[field];
706
+ await owner.send(tpl.method, p, { json: back });
707
+ const again = await readOne();
708
+ restored = again !== null && String(again[field]) === String(beforeRec[field]);
709
+ }
710
+ add('workOrderModify', s, targetOf(it), tpl.method + ' ' + tpl.template, { method: tpl.method, path: p, body: body }, res, reply, leaked ? 1 : 0,
711
+ known ? { [field]: beforeRec[field] } : null, known ? { [field]: afterRec[field] } : null, info, allowed ? 'allow' : 'deny', restored, fillTemplate(wo.item, id));
712
+ }
713
+ }
714
+ }
715
+
716
+ // ---- 5. the restricted background job
717
+ if (disc.active.job) {
718
+ const c = policy.cases.job;
719
+ const tpl = disc.active.job.templates[0];
720
+ const reads = c.sideEffectReads || [];
721
+ const count = async () => {
722
+ let total = 0;
723
+ let readable = true;
724
+ for (const role of roles) {
725
+ for (const r of reads) {
726
+ const res = await sessions[role].send('GET', r.path);
727
+ const list = getPath(res.json, r.listPath);
728
+ if (res.status === 200 && Array.isArray(list)) total += list.length;
729
+ else readable = false;
730
+ }
731
+ }
732
+ return readable && reads.length ? total : null;
733
+ };
734
+ const attempt = async (role, allowed) => {
735
+ const s = sessions[role];
736
+ const before = await count();
737
+ const res = await s.send(tpl.method, fillTemplate(tpl.template, ''), { json: {} });
738
+ const reply = replyOf(res);
739
+ const after = await count();
740
+ const changed = before === null || after === null ? null : after > before;
741
+ const info = judgeWrite({ allowed: allowed, reply: reply, changed: changed, leaked: false });
742
+ add('job', s, { type: 'background job', path: tpl.template }, tpl.method + ' ' + tpl.template, { method: tpl.method, path: tpl.template, body: {} }, res, reply, 0,
743
+ { totalNotificationsAcrossAccounts: before }, { totalNotificationsAcrossAccounts: after }, info, allowed ? 'allow' : 'deny', typeof options.reset === 'function', reads.map((r) => r.path).join(', ') + ', for every account with its own session');
744
+ return info.verdict;
745
+ };
746
+ // A job that may run must be seen to change something first, or a denied
747
+ // attempt that did nothing visible could not be told from a refused one.
748
+ await resetFor('job');
749
+ const allowedRole = roles.find((r) => c.permissions[r] === 'allow');
750
+ let precondition = null;
751
+ if (allowedRole) {
752
+ precondition = await attempt(allowedRole, true);
753
+ await resetFor('job');
754
+ }
755
+ if (typeof options.reset !== 'function') {
756
+ notes.push('No reset was given, so the notifications the job created cannot be put back; the denied attempts ran AFTER the allowed one and are judged against the total, which already includes it.');
757
+ }
758
+ for (const role of roles) {
759
+ if (role === allowedRole) continue;
760
+ const allowed = c.permissions[role] === 'allow';
761
+ await attempt(role, allowed);
762
+ await resetFor('job');
763
+ }
764
+ if (precondition !== VERDICT.ALLOWED) notes.push('The job did not visibly change anything for ' + allowedRole + ' (' + precondition + '), so a denied attempt that did nothing visible is judged ambiguous rather than denied only where the answer was not a refusal.');
765
+ }
766
+
767
+ const counts = {};
768
+ for (const r of results) {
769
+ counts[r.case] = counts[r.case] || {};
770
+ counts[r.case][r.verdict] = (counts[r.case][r.verdict] || 0) + 1;
771
+ }
772
+ return {
773
+ origin: ctx.origin,
774
+ requests: ctx.requests,
775
+ results: results,
776
+ findings: results.filter((r) => r.verdict === VERDICT.FAILURE),
777
+ skipped: disc.skipped,
778
+ counts: counts,
779
+ notes: notes,
780
+ };
781
+ }
782
+
783
+ /** The result as lines a person can read. */
784
+ function reportLines(run) {
785
+ const lines = ['Authorization check against ' + run.origin + ' (' + run.requests + ' requests)', ''];
786
+ for (const kind of KINDS) {
787
+ const rows = run.results.filter((r) => r.case === kind);
788
+ if (!rows.length) continue;
789
+ lines.push(kind + ':');
790
+ for (const r of rows) {
791
+ lines.push(' [' + r.verdict + '] ' + r.actor.role + ' -> ' + r.action + ' on ' + (r.target.type || '') + ' ' + (r.target.id !== undefined ? r.target.id : (r.target.role || r.target.path || '')) + ' - ' + r.reason);
792
+ }
793
+ }
794
+ for (const s of run.skipped) lines.push('NOT TRIED: ' + s.kind + ' - ' + s.why);
795
+ for (const n of run.notes) lines.push('NOTE: ' + n);
796
+ lines.push('');
797
+ lines.push(run.findings.length + ' confirmed authorization failure(s).');
798
+ return lines;
799
+ }
800
+
801
+ module.exports = {
802
+ VERDICT: VERDICT,
803
+ KINDS: KINDS,
804
+ assertLocalTarget: assertLocalTarget,
805
+ redact: redact,
806
+ redactValue: redactValue,
807
+ checkPolicy: checkPolicy,
808
+ mayDo: mayDo,
809
+ templateOf: templateOf,
810
+ journeyFromEvents: journeyFromEvents,
811
+ journeyFromHar: journeyFromHar,
812
+ discover: discover,
813
+ replyOf: replyOf,
814
+ judgeRead: judgeRead,
815
+ judgeWrite: judgeWrite,
816
+ runAuthz: runAuthz,
817
+ reportLines: reportLines,
818
+ // Used by kryptheon-roles.js, which tries the same thing for any app.
819
+ makeContext: makeContext,
820
+ makeSession: makeSession,
821
+ stringsOf: stringsOf,
822
+ identifierLike: identifierLike,
823
+ foundIn: foundIn,
824
+ clip: clip,
825
+ getPath: getPath,
826
+ };
827
+
828
+ // --- command line -----------------------------------------------------------
829
+ // node kryptheon-authz.js run --base http://127.0.0.1:4173 --policy policy.json --journey journey.json|journey.har
830
+ // [--out report.json] [--reset ./reset.js] [--allow-origin http://127.0.0.1:4173]
831
+ // Passwords are read from KRYPTHEON_AUTHZ_PASSWORD_<ROLE>, never from a file or a flag.
832
+
833
+ function argsOf(argv) {
834
+ const out = { allow: [] };
835
+ for (let i = 0; i < argv.length; i++) {
836
+ const a = argv[i];
837
+ if (a === '--allow-origin') out.allow.push(argv[++i]);
838
+ else if (a.startsWith('--')) out[a.slice(2)] = argv[++i];
839
+ else if (!out.command) out.command = a;
840
+ }
841
+ return out;
842
+ }
843
+
844
+ async function main(argv) {
845
+ const fs = require('fs');
846
+ const path = require('path');
847
+ const args = argsOf(argv);
848
+ if (args.command !== 'run' || !args.base || !args.policy || !args.journey) {
849
+ console.log('usage: node kryptheon-authz.js run --base http://127.0.0.1:PORT --policy policy.json --journey journey.json|.har [--out report.json] [--reset reset.js] [--allow-origin ORIGIN]');
850
+ console.log('passwords: KRYPTHEON_AUTHZ_PASSWORD_<ROLE> in the environment');
851
+ return 2;
852
+ }
853
+ const policy = JSON.parse(fs.readFileSync(args.policy, 'utf8'));
854
+ const raw = JSON.parse(fs.readFileSync(args.journey, 'utf8'));
855
+ const journey = Array.isArray(raw) ? raw : journeyFromHar(raw);
856
+ const passwords = {};
857
+ for (const role of Object.keys(policy.roles || {})) passwords[role] = process.env['KRYPTHEON_AUTHZ_PASSWORD_' + role.toUpperCase()];
858
+ let reset;
859
+ if (args.reset) reset = require(path.resolve(args.reset));
860
+ const run = await runAuthz({ baseUrl: args.base, allowOrigins: args.allow.length ? args.allow : [new URL(args.base).origin], policy: policy, journey: journey, passwords: passwords, reset: reset, log: (m) => console.log(m) });
861
+ console.log(reportLines(run).join('\n'));
862
+ if (args.out) {
863
+ fs.writeFileSync(args.out, JSON.stringify({ origin: run.origin, requests: run.requests, counts: run.counts, notes: run.notes, skipped: run.skipped, findings: run.findings, results: run.results }, null, 2));
864
+ console.log('Evidence written to ' + args.out);
865
+ }
866
+ return run.findings.length ? 1 : 0;
867
+ }
868
+
869
+ if (require.main === module) {
870
+ main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
871
+ console.error(String(err && err.message ? err.message : err));
872
+ process.exit(3);
873
+ });
874
+ }