@aria-framework/tenancy 0.0.0-stage → 0.1.0

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.
package/index.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @aria-framework/tenancy — the main-thread half of a multi-tenant app, as factories an app calls once with its own
3
+ * lookups and settings. The schema half (the tenant filter, the manifest, the settings layer, the migration command)
4
+ * is in @aria-framework/db-worker.
5
+ *
6
+ * lib/scope who a request works for, the scope seam, the write gate, authorship, the cross-tenant refusal
7
+ * lib/hosts host names and host resolution, per-tenant chrome
8
+ * lib/partners the partner store and provisioning, the acting routes, locals and banner
9
+ *
10
+ * No rule about who may see or do what lives here: each is a setting the app passes.
11
+ */
12
+
13
+ 'use strict';
14
+
15
+ module.exports = {
16
+ ...require('./lib/scope'),
17
+ ...require('./lib/hosts'),
18
+ ...require('./lib/partners')
19
+ };
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Resolve a partner from the hostname an ANONYMOUS request arrived on.
3
+ *
4
+ * MOVED from the apps' middleware/hostTenant.js (the starter's, which one app carries unchanged),
5
+ * with: a failed reload keeping the last good map (from the noc app), ONE `hostOf(req)` for the
6
+ * middleware and the lookups (from the wall app; the hub's `rawHostOf` is the same function),
7
+ * `partnerIdForRequest` (the wall app's; the hub's `partnerForRequest` is the same function) and
8
+ * `partnerOfHost` (the hub's). What was a require of the app's own files is now an argument:
9
+ *
10
+ * createHostTenant({ tenancy, db, logger, trustForwardedHost, chrome, isSignedIn, onForget, maxAgeMs })
11
+ * → { middleware(), partnerIdForRequest(req), partnerOfHost(host), forget() }
12
+ *
13
+ * ── WHY THIS EXISTS ────────────────────────────────────────────────────────────────────────────
14
+ *
15
+ * The staff login is the only request in an app with no tenant available: a person types a
16
+ * username and a password and nothing else. It resolves by natural key, and at house scope the
17
+ * row-level-security platform arm is `true`, so the lookup searched EVERY tenant.
18
+ *
19
+ * That is not a query to fix. The schema deliberately allows one username in two tenants —
20
+ * `UNIQUE (partner_id, username)` — because the whole point of the tier is that two businesses run
21
+ * independently and may each have an `admin`. The login then has two rows and no way to choose.
22
+ *
23
+ * In the desk app this happened for real and an operator found it rather than a test: a House user
24
+ * signed in successfully at a RESELLER's address. Nothing errored — the credentials were valid,
25
+ * just for the wrong tenant — and the session that came back was the House's, on the reseller's
26
+ * hostname.
27
+ *
28
+ * Resolving the tenant from the HOSTNAME removes the ambiguity rather than arbitrating it: you sign
29
+ * in as a partner only on that partner's own hostname, and platform operators sign in on the
30
+ * installation's own address.
31
+ *
32
+ * MOUNTED ON THE LOGIN ROUTERS, and nowhere else — see rule 1.
33
+ *
34
+ * ── THE SECURITY RULE, AND WHY IT IS SAFE HERE ─────────────────────────────────────────────────
35
+ *
36
+ * The scope part's contextFor refuses, by design, to narrow an anonymous request by anything the
37
+ * request carries: "a header or a query parameter naming a partner would be a tenant chosen by the
38
+ * caller." A `Host` header IS something the request carries, so this is an exception to a rule that
39
+ * exists for good reasons, and it is safe only under all of the following:
40
+ *
41
+ * 1. PUBLIC, UNAUTHENTICATED ROUTES ONLY. Enforced STRUCTURALLY by the app: mount it with
42
+ * `router.use()` (or per route) inside the login router, NOT with `app.use()`. That
43
+ * distinction is the whole guarantee — `app.use('/', mw, publicRouter)` would also run for
44
+ * every staff router mounted afterwards, because '/' matches everything and Express continues
45
+ * the chain when the public router declines. Mounted on the router it cannot reach a staff
46
+ * route at all, whatever anyone later changes about mount order. (The apps' own source checks
47
+ * of where it is mounted stay in the apps.)
48
+ * 2. IT GRANTS NOTHING. The host decides WHOSE login form applies. It cannot read anything and
49
+ * cannot authenticate anybody: a forged Host can only choose which tenant fails to recognise
50
+ * the credentials being offered.
51
+ * 3. AN AUTHENTICATED SESSION IGNORES IT. The moment the session is signed in (`isSignedIn`,
52
+ * the app's own answer: `session.user`, plus a portal contact where the app has one) the
53
+ * tenant comes from the SESSION and this middleware steps
54
+ * aside — otherwise changing hosts mid-session would move a signed-in person between tenants.
55
+ * 4. AN UNKNOWN HOST NARROWS TO THE HOUSE — it does not widen, and it does not merely "fall
56
+ * through". THIS IS THE FIX, and the distinction is everything:
57
+ *
58
+ * asHouse() { scope: 'platform', partnerId: <house> } policy: platform arm TRUE
59
+ * asPartner(house) { scope: 'partner', partnerId: <house> } policy: partner_id = house
60
+ *
61
+ * The app's request-scope middleware sends an anonymous request through asHouse, which sets
62
+ * the house id but leaves the scope PLATFORM — and the frozen policy is
63
+ * `CASE current_setting('app.scope') WHEN 'platform' THEN true ELSE partner_id = … END`. So
64
+ * the house id was set and the lookup still crossed every tenant. Re-entering as
65
+ * asPartner(house) narrows it, and the login ALWAYS runs inside exactly one tenant.
66
+ * 5. NO ENUMERATION. Nothing about the response may change per host: the login answers
67
+ * identically for a known and an unknown username, and it still must inside a resolved
68
+ * partner. This must not become a way to ask "does Acme have a user called jane?".
69
+ *
70
+ * ── WHY THE WHOLE MAP IS CACHED, RATHER THAN EACH HOST LOOKED UP ───────────────────────────────
71
+ *
72
+ * A per-host cache is the obvious design and it is a denial-of-service vector: an unknown host is a
73
+ * cache miss, so a flood of random Host values is either a database query each (load) or an
74
+ * unbounded Map (memory). Loading the whole set instead — partners WITH a portal_host is a tiny
75
+ * subset of a tiny table — makes an unknown host cost a failed Map lookup and nothing else, and
76
+ * bounds the memory by the number of partners rather than by the number of hostnames an attacker
77
+ * can invent.
78
+ *
79
+ * It also honours contextFor's promise that establishing a tenant "NEVER TOUCHES THE DATABASE" on
80
+ * the path of every request: this reads once per process, and again after forget().
81
+ *
82
+ * HOW STALE IT CAN BE. Without `maxAgeMs` the map has no age: it is read once and kept until
83
+ * forget() is called (or the process restarts). With it, a map older than that is read again on the
84
+ * next lookup. Either way every write that changes the mapping (create, host change,
85
+ * activate/deactivate) must call forget(); forget() reaches THIS process only, so a process that is
86
+ * not told keeps the old map until it restarts, or until `maxAgeMs` passes.
87
+ *
88
+ * AN OUTAGE IS LOGGED ONCE, not once per lookup: the first failed reload, then at most one line a
89
+ * minute with the count since, then one line when a reload succeeds again.
90
+ */
91
+
92
+ 'use strict';
93
+
94
+ const { hostFromHeader } = require('./hostname');
95
+
96
+ const fnOf = (o, name) => o && typeof o[name] === 'function';
97
+
98
+ /**
99
+ * @param {object} o
100
+ * @param {{asPartner: Function, asPlatform: Function, housePartnerId: Function}} o.tenancy
101
+ * @param {{invoke: Function}} o.db the app's DbClient (reads `Partner.all`)
102
+ * @param {{info: Function, warn: Function}} o.logger
103
+ * @param {boolean} o.trustForwardedHost REQUIRED: true only behind a proxy that OVERWRITES X-Forwarded-Host
104
+ * @param {{applyTo: Function}} o.chrome the app's request chrome, re-applied after narrowing
105
+ * @param {(session: object) => boolean} o.isSignedIn REQUIRED: is this session signed in (then it is stepped around)
106
+ * @param {() => void} [o.onForget] called by forget(), after the map is dropped
107
+ * @param {number} [o.maxAgeMs] reload a map older than this on the next lookup (default: never)
108
+ * @param {() => number} [o.now] the clock (ms); a test seam, default Date.now
109
+ */
110
+ function createHostTenant(o = {}) {
111
+ const { tenancy, db, logger, trustForwardedHost, chrome } = o;
112
+ if (!fnOf(tenancy, 'asPartner') || !fnOf(tenancy, 'asPlatform') || !fnOf(tenancy, 'housePartnerId')) {
113
+ throw new TypeError('createHostTenant: tenancy must be the app\'s createTenancy() result (asPartner, asPlatform, housePartnerId)');
114
+ }
115
+ if (!fnOf(db, 'invoke')) throw new TypeError('createHostTenant: db must be the app\'s DbClient (invoke)');
116
+ if (!fnOf(logger, 'info') || !fnOf(logger, 'warn')) throw new TypeError('createHostTenant: logger must have info and warn');
117
+ // REQUIRED, NO DEFAULT: which header names the tenant is a security decision about the deployment
118
+ // (see hostOf), and an app that forgets it must fail here rather than inherit an answer.
119
+ if (typeof trustForwardedHost !== 'boolean') {
120
+ throw new TypeError('createHostTenant: trustForwardedHost is required (true or false); true only when the proxy in front overwrites X-Forwarded-Host');
121
+ }
122
+ if (!fnOf(chrome, 'applyTo')) throw new TypeError('createHostTenant: chrome must have applyTo(res) (the app\'s request chrome)');
123
+ // REQUIRED, NO DEFAULT: apps differ (the desk counts its portal contact as signed in), and a default
124
+ // would narrow that app's signed-in contacts by whatever host they visit.
125
+ const { isSignedIn } = o;
126
+ if (typeof isSignedIn !== 'function') {
127
+ throw new TypeError('createHostTenant: isSignedIn is required: a function of the session, e.g. (s) => !!s.user');
128
+ }
129
+ const onForget = o.onForget === undefined ? null : o.onForget;
130
+ if (onForget !== null && typeof onForget !== 'function') throw new TypeError('createHostTenant: onForget must be a function');
131
+ const maxAgeMs = o.maxAgeMs == null ? null : o.maxAgeMs;
132
+ // A FLOOR, so no value can turn the bound into a reload on every request (1e-9 would).
133
+ if (maxAgeMs !== null && !(Number.isInteger(maxAgeMs) && maxAgeMs >= 1000)) {
134
+ throw new TypeError('createHostTenant: maxAgeMs must be a whole number of milliseconds, at least 1000 (or omitted: no age bound)');
135
+ }
136
+ const nowFn = o.now === undefined ? Date.now : o.now;
137
+ if (typeof nowFn !== 'function') throw new TypeError('createHostTenant: now must be a function returning milliseconds');
138
+ // A clock that does not answer a finite number would make every age comparison false, so every lookup
139
+ // would read the database. It throws instead, naming the option — before any read is made.
140
+ const now = () => {
141
+ const t = nowFn();
142
+ if (typeof t !== 'number' || !Number.isFinite(t)) {
143
+ throw new TypeError(`createHostTenant: now() must return a finite number of milliseconds; it returned ${String(t)}`);
144
+ }
145
+ return t;
146
+ };
147
+ const OUTAGE_LOG_EVERY_MS = 60 * 1000;
148
+
149
+ /** host → partner id, for ACTIVE partners that claim one. Null until first loaded, and after forget(). */
150
+ let _hosts = null;
151
+ /** The last host map built — what a failed reload answers with. Kept across forget(). */
152
+ let _hostsLast = null;
153
+ /** When _hosts was read (now()). */
154
+ let _loadedAt = 0;
155
+ /** Failed reloads since the last good one, those not yet in a log line, and when the last line was written. */
156
+ let _failures = 0;
157
+ let _unlogged = 0;
158
+ let _lastOutageLog = 0;
159
+
160
+ function noteFailure(e, kept) {
161
+ _failures++;
162
+ _unlogged++;
163
+ const t = now();
164
+ if (_failures === 1) {
165
+ logger.warn(`Partner hosts: reload failed, keeping the last map (${kept.size} hostname(s)): ${e.message}`);
166
+ } else if (t - _lastOutageLog >= OUTAGE_LOG_EVERY_MS) {
167
+ logger.warn(`Partner hosts: reload still failing, keeping the last map (${kept.size} hostname(s)); ${_unlogged} failed reload(s) since the last line: ${e.message}`);
168
+ } else {
169
+ return;
170
+ }
171
+ _unlogged = 0;
172
+ _lastOutageLog = t;
173
+ }
174
+
175
+ /**
176
+ * Drop the cache. Call after any write that can change the mapping — create, rename, host change,
177
+ * activate/deactivate — because a stale map either sends a partner's people to the installation's
178
+ * own login or keeps accepting a deactivated tenant's hostname.
179
+ */
180
+ function forget() {
181
+ _hosts = null;
182
+ if (onForget) onForget();
183
+ }
184
+
185
+ async function hostMap() {
186
+ const t = now(); // first, so a broken clock throws before any read
187
+ if (_hosts && (maxAgeMs === null || t - _loadedAt <= maxAgeMs)) return _hosts;
188
+ // PLATFORM SCOPE: `partners` is the installation's own data, and this runs inside asHouse for an
189
+ // anonymous request, where a partner-scoped read would see only the house's row.
190
+ let rows;
191
+ try {
192
+ rows = await tenancy.asPlatform(() => db.invoke('Partner', 'all'));
193
+ } catch (e) {
194
+ // A FAILED RELOAD KEEPS THE LAST GOOD MAP: a database blip after a forget() must not turn every
195
+ // partner's host into the house's. Not cached as fresh, so the next read tries again; with no
196
+ // map ever loaded the failure is the caller's, as before. The price, named: until a reload
197
+ // succeeds, a partner deactivated just before the blip still resolves by its host.
198
+ if (!_hostsLast) throw e;
199
+ noteFailure(e, _hostsLast);
200
+ return _hostsLast;
201
+ }
202
+ const m = new Map();
203
+ for (const p of rows || []) {
204
+ // is_active is part of the MAPPING, not a filter applied later: a deactivated partner's people
205
+ // cannot sign in at all, so its hostname must behave like an unrecognised one rather than
206
+ // resolving to a tenant whose logins are then refused with a confusing message.
207
+ if (p.portal_host && Number(p.is_active) === 1) {
208
+ m.set(String(p.portal_host).toLowerCase(), Number(p.id));
209
+ }
210
+ }
211
+ _hosts = m;
212
+ _hostsLast = m;
213
+ _loadedAt = t;
214
+ if (_failures) {
215
+ logger.info(`Partner hosts: reload succeeded again after ${_failures} failed reload(s)`);
216
+ _failures = 0;
217
+ _unlogged = 0;
218
+ }
219
+ if (m.size) logger.info(`Partner hosts: ${m.size} hostname(s) resolvable`);
220
+ return m;
221
+ }
222
+
223
+ // ── THE HOST HEADER, NOT THE FORWARDED ONE ──────────────────────────────────────────────────
224
+ //
225
+ // This once read `req.hostname`, which honours `trust proxy` — so with trust proxy set (which the
226
+ // deployment notes tell operators to do, for req.ip) Express prefers the client-supplied
227
+ // `X-Forwarded-Host`. nginx does not set that header by default and passes the client's copy
228
+ // through untouched, and nothing here overwrote it.
229
+ //
230
+ // That made an UNAUTHENTICATED caller the one who chose the tenant. A POST to a portal login at
231
+ // the installation's own address with `X-Forwarded-Host: acme.example.com` resolved partner
232
+ // Acme, re-entered as asPartner(acme), and minted a sign-in code sent through ACME'S transport
233
+ // under Acme's brand. The same header decided which tenant the staff login resolved a credential
234
+ // against, and which brand the sign-in page rendered.
235
+ //
236
+ // The validation was never the weak part — it only ever asked whether the value LOOKS like a
237
+ // hostname an operator could have saved, which a chosen one does.
238
+ //
239
+ // So the raw Host header is the default, and honouring the forwarded one is an explicit opt-in
240
+ // (`trustForwardedHost: true`) for deployments whose proxy overwrites it
241
+ // (`proxy_set_header X-Forwarded-Host $host;`) and where it therefore cannot carry client input.
242
+ // Even then Express reads X-Forwarded-Host only when its own `trust proxy` trusts the hop the
243
+ // request came from; otherwise req.hostname is the Host header. Trust proxy stays what it always
244
+ // was: an answer about req.ip, not about tenancy.
245
+ //
246
+ // ONE SPELLING for the middleware and both lookups, so they can never disagree about which header
247
+ // decides.
248
+
249
+ /** The request's hostname for tenancy, normalised; or null (no header, an IPv6 literal, not a hostname). */
250
+ function hostOf(req) {
251
+ const rawHost = trustForwardedHost
252
+ ? (req.hostname || (req.headers && req.headers.host))
253
+ : (req.headers && req.headers.host);
254
+ return hostFromHeader(rawHost);
255
+ }
256
+
257
+ /** The active partner whose portal host this is, or undefined. */
258
+ async function matchedPartner(host) {
259
+ if (!host) return undefined;
260
+ return (await hostMap()).get(host);
261
+ }
262
+
263
+ /**
264
+ * WHOSE HOST THIS REQUEST ARRIVED ON — the partner the middleware would put an anonymous request
265
+ * in: the active partner the host names, else the house. Resolves nothing into the request's
266
+ * scope; for a caller that must COMPARE (a customer portal: a contact session shown on another
267
+ * partner's host is ended; a contact looked up before sign-in).
268
+ *
269
+ * UNLIKE THE MIDDLEWARE, THIS DOES NOT STEP ASIDE FOR A SIGNED-IN SESSION (rule 3) AND DOES NOT
270
+ * FAIL OPEN. A staff cookie in the same browser says nothing about whose portal this is, and a
271
+ * resolution failure THROWS — the caller then answers an error rather than running at whatever
272
+ * scope the request already had, which for an anonymous request is platform scope.
273
+ *
274
+ * @returns {Promise<number>}
275
+ */
276
+ async function partnerIdForRequest(req) {
277
+ const matched = await matchedPartner(hostOf(req));
278
+ return matched != null ? matched : tenancy.housePartnerId();
279
+ }
280
+
281
+ /**
282
+ * THE PARTNER WHOSE ADDRESS THIS HOST IS, or null — no fallback to the house. The same map the
283
+ * sign-in resolves its tenant from, so a sign-in provider's realm and the sign-in on a host
284
+ * cannot disagree. `host` is a host name; anything hostFromHeader would not accept matches
285
+ * nothing.
286
+ *
287
+ * @returns {Promise<number|null>}
288
+ */
289
+ async function partnerOfHost(host) {
290
+ const h = hostFromHeader(host);
291
+ if (!h) return null;
292
+ const id = (await hostMap()).get(h);
293
+ return id == null ? null : id;
294
+ }
295
+
296
+ /**
297
+ * @returns {import('express').RequestHandler}
298
+ */
299
+ function middleware() {
300
+ return function hostTenantMiddleware(req, res, next) {
301
+ const s = req.session;
302
+ // RULE 3. A signed-in session's tenant comes from the session, and the request-scope
303
+ // middleware has already established it. Returning early rather than resolving-and-ignoring
304
+ // keeps that single-source property obvious to the next reader.
305
+ if (s && isSignedIn(s)) return next();
306
+
307
+ const host = hostOf(req);
308
+
309
+ // A hostname that cannot be a vanity host at all (an IPv6 literal, `localhost`, a bare IP)
310
+ // still has to be narrowed to the House — that is most of development and every bookmark to
311
+ // the bare installation address. So resolution continues with host = null rather than
312
+ // returning early.
313
+ //
314
+ // ── RESOLUTION IS GUARDED; next() IS NOT. THE SPLIT IS THE POINT. ───────────────────────
315
+ //
316
+ // Two failure modes have to be told apart, and the obvious shapes get one or the other wrong:
317
+ //
318
+ // .then(fulfil).catch(…) a downstream layer that rejects AFTER next() re-enters next()
319
+ // a second time, on a response already being handled, and logs
320
+ // the real error as a "host resolution failure".
321
+ // .then(fulfil, onReject) onReject does NOT catch failures of `fulfil` — that is what
322
+ // the two-argument form means. So anything thrown while
323
+ // resolving the house (a database with no house partner seeded,
324
+ // a pool blip) became an UNHANDLED REJECTION and took the
325
+ // process down. The desk app carried this shape and never
326
+ // fired it, because its house always exists; a harness driving
327
+ // the login route against a bare schema found it in one run.
328
+ //
329
+ // So: everything that can fail while DECIDING the tenant sits inside the try, and next() sits
330
+ // outside it. A resolution failure degrades to the scope the request-scope middleware already
331
+ // established; a downstream error is left entirely alone.
332
+ (async () => {
333
+ let target;
334
+ try {
335
+ const matched = await matchedPartner(host);
336
+ if (matched != null) {
337
+ // Recorded for the views and for the login routes, so a resolved host is not resolved twice.
338
+ req.partnerId = matched;
339
+ req.partnerHost = host;
340
+ target = matched;
341
+ } else {
342
+ // RULE 4: the House, in PARTNER scope. See the header — asHouse would leave the scope
343
+ // platform and the lookup would cross tenants again, which is the entire defect.
344
+ target = await tenancy.housePartnerId();
345
+ }
346
+ } catch (e) {
347
+ // FAILS OPEN TO WHATEVER THE REQUEST-SCOPE MIDDLEWARE ALREADY ESTABLISHED, which for an
348
+ // anonymous request is asHouse — platform scope. A deliberate trade, worth naming: this is
349
+ // the login page, and a database blip here would otherwise take every login down. The cost
350
+ // is that during such a blip the two-tenant ambiguity is back, so it is logged at warn.
351
+ // (A blip AFTER a map was loaded no longer reaches here: hostMap answers the last map.)
352
+ logger.warn(
353
+ `Partner host resolution failed for "${host || '(no host)'}" — falling back to the `
354
+ + `pre-existing scope, where a username in two tenants is ambiguous again: ${e.message}`);
355
+ return next();
356
+ }
357
+
358
+ // ── RE-RESOLVE THE VIEW DATA INSIDE THE NARROWED SCOPE ────────────────────────────────
359
+ //
360
+ // The app already put the timezone and the idle timeout on res.locals — for the scope the
361
+ // request had BEFORE this middleware, which for an anonymous request is the House. Narrowing
362
+ // the tenant here without re-resolving them is how a partner's login page comes to render
363
+ // with the House's settings. Cheap (a per-tenant Map hit), and the rule that keeps it
364
+ // correct is "re-resolve after anything that changes the tenant".
365
+ //
366
+ // OUTSIDE THE try: next() is called in here, and nothing downstream of it may be mistaken
367
+ // for a host-resolution failure.
368
+ return tenancy.asPartner(target, async () => {
369
+ await chrome.applyTo(res);
370
+ next();
371
+ });
372
+ })();
373
+ };
374
+ }
375
+
376
+ return { middleware, partnerIdForRequest, partnerOfHost, forget };
377
+ }
378
+
379
+ module.exports = { createHostTenant };