@astram/guard 0.39.0 → 0.40.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/dist/agent/agent-provenance.d.ts +24 -0
- package/dist/agent/agent-provenance.d.ts.map +1 -1
- package/dist/agent/agent-provenance.js +33 -1
- package/dist/auth/auth.module.d.ts.map +1 -1
- package/dist/auth/auth.module.js +40 -2
- package/dist/auth/tokens.d.ts +14 -0
- package/dist/auth/tokens.d.ts.map +1 -1
- package/dist/auth/tokens.js +16 -2
- package/dist/authentication/service-account-principal.d.ts +29 -0
- package/dist/authentication/service-account-principal.d.ts.map +1 -0
- package/dist/authentication/service-account-principal.js +55 -0
- package/dist/enforcement/facts-version.d.ts +22 -0
- package/dist/enforcement/facts-version.d.ts.map +1 -0
- package/dist/enforcement/facts-version.js +34 -0
- package/dist/enforcement/global-enforcement.guard.d.ts +9 -26
- package/dist/enforcement/global-enforcement.guard.d.ts.map +1 -1
- package/dist/enforcement/global-enforcement.guard.js +48 -177
- package/dist/enforcement/session-facts-reload.d.ts +66 -0
- package/dist/enforcement/session-facts-reload.d.ts.map +1 -0
- package/dist/enforcement/session-facts-reload.js +168 -0
- package/dist/identity/identity-actions.d.ts +1 -1
- package/dist/identity/identity-actions.d.ts.map +1 -1
- package/dist/identity/identity-actions.js +4 -0
- package/dist/internal.d.ts +23 -0
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +36 -1
- package/dist/module/shield-tokens.d.ts +60 -11
- package/dist/module/shield-tokens.d.ts.map +1 -1
- package/dist/notifications/notification.service.d.ts +3 -0
- package/dist/notifications/notification.service.d.ts.map +1 -1
- package/dist/notifications/notification.service.js +9 -0
- package/dist/request-auth/request-principal.d.ts +5 -0
- package/dist/request-auth/request-principal.d.ts.map +1 -1
- package/dist/request-auth/request-principal.js +7 -1
- package/dist/request-auth/session-token-binder.d.ts +79 -6
- package/dist/request-auth/session-token-binder.d.ts.map +1 -1
- package/dist/request-auth/session-token-binder.js +264 -173
- package/dist/session/call-principals.d.ts +54 -0
- package/dist/session/call-principals.d.ts.map +1 -0
- package/dist/session/call-principals.js +38 -0
- package/dist/session/session-principal.d.ts +86 -0
- package/dist/session/session-principal.d.ts.map +1 -0
- package/dist/session/session-principal.js +139 -0
- package/package.json +5 -5
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
* and the stored value carries no secret (claims only — ids, not credentials).
|
|
25
25
|
*/
|
|
26
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
|
-
exports.SessionTokenBinder = exports.REBIND_ON_ROTATE_SCRIPT = void 0;
|
|
27
|
+
exports.SessionTokenBinder = exports.CLAIMS_REWRITE_CAS_SCRIPT = exports.MFA_STATE_CAS_SCRIPT = exports.REBIND_ON_ROTATE_SCRIPT = void 0;
|
|
28
28
|
exports.factsSlot = factsSlot;
|
|
29
29
|
exports.liveRoleIds = liveRoleIds;
|
|
30
30
|
/** A valid stamp: a non-negative safe integer. */
|
|
@@ -173,6 +173,82 @@ function stripMfaState(claims) {
|
|
|
173
173
|
delete next[k];
|
|
174
174
|
return next;
|
|
175
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Parse, validate and normalize a stored claims payload (an access-token or a session-claims
|
|
178
|
+
* entry). `null` (fail closed) when the JSON is unparseable or a required field is missing or of
|
|
179
|
+
* the wrong type. The optional slots are rebuilt so junk cannot ride through: a malformed cached
|
|
180
|
+
* facts or scope subtree slot is dropped (absent), and a subtree version stamp survives only beside
|
|
181
|
+
* a validated subtree. Shared by {@link SessionTokenBinder.resolve} and
|
|
182
|
+
* {@link SessionTokenBinder.resolveSession} (one parser, Shield #3).
|
|
183
|
+
*/
|
|
184
|
+
function parseBoundClaims(raw) {
|
|
185
|
+
let parsed;
|
|
186
|
+
try {
|
|
187
|
+
parsed = JSON.parse(raw);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
if (typeof parsed?.id !== 'string' ||
|
|
193
|
+
typeof parsed?.tenantId !== 'string' ||
|
|
194
|
+
!Array.isArray(parsed?.roleIds) ||
|
|
195
|
+
typeof parsed?.kind !== 'string' ||
|
|
196
|
+
typeof parsed?.isRoot !== 'boolean' ||
|
|
197
|
+
typeof parsed?.sessionId !== 'string' ||
|
|
198
|
+
typeof parsed?.mustReenroll !== 'boolean') {
|
|
199
|
+
return null; // malformed → fail closed.
|
|
200
|
+
}
|
|
201
|
+
// Normalize the OPTIONAL cached-facts slot (ADR-0011): a malformed/legacy/absent
|
|
202
|
+
// slot is scrubbed to `undefined` (→ the guard enters the ALS with `cachedFacts:
|
|
203
|
+
// null` → gate 5 DB-reloads). Present + well-formed → the validated CoarseGrants.
|
|
204
|
+
// Never fabricated. Rebuild the object so a malformed slot cannot ride through.
|
|
205
|
+
const cachedFacts = parseCachedFacts(parsed.cachedFacts);
|
|
206
|
+
parsed = cachedFacts === undefined ? stripCachedFacts(parsed) : { ...parsed, cachedFacts };
|
|
207
|
+
// Normalize the OPTIONAL scope-subtree slot (ADR-0027 / Task 2.2): an absent, empty, or
|
|
208
|
+
// malformed slot is scrubbed to ABSENT (→ `principalFromClaims` falls back to the self-node,
|
|
209
|
+
// non-widening); a well-formed non-empty array is the validated cached subtree. Never
|
|
210
|
+
// fabricated — rebuild the object so a junk slot cannot ride through into a Principal.
|
|
211
|
+
const scopeSubtreeNodeIds = parseScopeSubtree(parsed.scopeSubtreeNodeIds);
|
|
212
|
+
parsed =
|
|
213
|
+
scopeSubtreeNodeIds === undefined
|
|
214
|
+
? stripScopeSubtree(parsed)
|
|
215
|
+
: { ...parsed, scopeSubtreeNodeIds };
|
|
216
|
+
// The subtree's version stamp (Phase 1C) rides only beside a validated subtree; a junk or
|
|
217
|
+
// orphaned stamp is dropped (→ treated as unknown → one re-derive at the next reload).
|
|
218
|
+
if (scopeSubtreeNodeIds === undefined ||
|
|
219
|
+
!isSubtreeVersion(parsed.scopeSubtreeVersion)) {
|
|
220
|
+
parsed = stripSubtreeVersion(parsed);
|
|
221
|
+
}
|
|
222
|
+
return parsed;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Overlay the session-authoritative state from the raw session-claims entry `liveness` onto
|
|
226
|
+
* `parsed`. MUST-REENROLL is read from the SESSION-CLAIMS entry, NOT the per-token entry — so
|
|
227
|
+
* `clearReenroll(sessionId)` (which cannot know each outstanding access token) flips it for the
|
|
228
|
+
* LIVE token on the very next request. The token stays the same; only this bound claim changes. A
|
|
229
|
+
* malformed or legacy session-claims entry that lacks the flag is treated as `false` (default
|
|
230
|
+
* safe: an old binding predating this field must not spuriously lock a session).
|
|
231
|
+
*/
|
|
232
|
+
function overlaySessionState(parsed, liveness) {
|
|
233
|
+
let mustReenroll = parsed.mustReenroll;
|
|
234
|
+
// The mandatory-2FA state (D-2) is authoritative on the same entry, for the same reason: a
|
|
235
|
+
// recompute or a device confirm keyed by session id reaches every live token at once. The
|
|
236
|
+
// per-token copies are never trusted.
|
|
237
|
+
let mfa = {};
|
|
238
|
+
try {
|
|
239
|
+
const sess = JSON.parse(liveness);
|
|
240
|
+
mustReenroll = sess?.mustReenroll === true;
|
|
241
|
+
mfa = readMfaState(sess);
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
mustReenroll = false; // unparseable session-claims → treat as not-reenroll.
|
|
245
|
+
}
|
|
246
|
+
const hasMfa = Object.keys(mfa).length > 0;
|
|
247
|
+
if (!hasMfa && !MFA_STATE_KEYS.some((k) => k in parsed)) {
|
|
248
|
+
return mustReenroll === parsed.mustReenroll ? parsed : { ...parsed, mustReenroll };
|
|
249
|
+
}
|
|
250
|
+
return { ...stripMfaState(parsed), mustReenroll, ...mfa };
|
|
251
|
+
}
|
|
176
252
|
/** Redis key prefix for the access-token → claims binding. */
|
|
177
253
|
const AT_KEY_PREFIX = 'shield:at:';
|
|
178
254
|
/** Redis key prefix for the session-id → claims binding (survives token rotation). */
|
|
@@ -249,13 +325,39 @@ const REBIND_REFUSED = 0;
|
|
|
249
325
|
* entry is still exactly ARGV[1] (the value the caller read and judged), keeping its remaining TTL.
|
|
250
326
|
* One script, so of N concurrent recomputes exactly one writes. Returns 1 when written, else 0.
|
|
251
327
|
*/
|
|
252
|
-
|
|
328
|
+
exports.MFA_STATE_CAS_SCRIPT = `
|
|
253
329
|
local cur = redis.call('GET', KEYS[1])
|
|
254
330
|
if cur ~= ARGV[1] then return 0 end
|
|
255
331
|
local ttl = redis.call('PTTL', KEYS[1])
|
|
256
332
|
if ttl <= 0 then return 0 end
|
|
257
333
|
redis.call('SET', KEYS[1], ARGV[2], 'PX', ttl, 'XX')
|
|
258
334
|
return 1`;
|
|
335
|
+
/**
|
|
336
|
+
* The session-claims rewrites' compare-and-set (background-agent-tasks QA-1 P2-1): `refreshGrants`,
|
|
337
|
+
* `rederiveScopeSubtree`, `clearReenroll`, `restrictMfaEnrollment` and `clearRestriction` read an
|
|
338
|
+
* entry, transform it and write it back. Written
|
|
339
|
+
* as GET → PTTL → `SET … XX`, a concurrent writer landing between the read and the write (a
|
|
340
|
+
* `restrictMfaEnrollment` restriction + epoch bump, another rewrite) was overwritten by the older
|
|
341
|
+
* copy. This writes ARGV[2] only if the entry is still exactly ARGV[1] (the value the caller read
|
|
342
|
+
* and transformed), keeping its remaining TTL (`PTTL` here, never extended) and `XX` (a deleted
|
|
343
|
+
* entry is never re-created).
|
|
344
|
+
*
|
|
345
|
+
* 1 written.
|
|
346
|
+
* 0 the entry changed since the read: the caller re-reads and re-applies its transformation.
|
|
347
|
+
* -1 the entry is gone or has no TTL: nothing is written, and nothing to retry.
|
|
348
|
+
*/
|
|
349
|
+
exports.CLAIMS_REWRITE_CAS_SCRIPT = `
|
|
350
|
+
local cur = redis.call('GET', KEYS[1])
|
|
351
|
+
if cur == false then return -1 end
|
|
352
|
+
if cur ~= ARGV[1] then return 0 end
|
|
353
|
+
local ttl = redis.call('PTTL', KEYS[1])
|
|
354
|
+
if ttl <= 0 then return -1 end
|
|
355
|
+
redis.call('SET', KEYS[1], ARGV[2], 'PX', ttl, 'XX')
|
|
356
|
+
return 1`;
|
|
357
|
+
const CLAIMS_CAS_WRITTEN = 1;
|
|
358
|
+
const CLAIMS_CAS_CHANGED = 0;
|
|
359
|
+
/** Re-reads after a compare-and-set miss before giving up (fail closed: the next request recomputes). */
|
|
360
|
+
const CLAIMS_CAS_RETRIES = 2;
|
|
259
361
|
/** How long refresh waits for Redis to answer PING before answering 503 (ADR-0035, F1). */
|
|
260
362
|
const DEFAULT_PING_TIMEOUT_MS = 1_000;
|
|
261
363
|
class SessionTokenBinder {
|
|
@@ -486,41 +588,52 @@ class SessionTokenBinder {
|
|
|
486
588
|
*
|
|
487
589
|
* Each entry is rewritten only when it still belongs to `sessionId` + `tenantId` (a concurrent
|
|
488
590
|
* scope-switch moved it → left alone) and `facts` is fresher than what it holds (a slower request
|
|
489
|
-
* never overwrites newer facts). Each keeps its remaining TTL and is written
|
|
591
|
+
* never overwrites newer facts). Each keeps its remaining TTL and is written by compare-and-set
|
|
592
|
+
* ({@link CLAIMS_REWRITE_CAS_SCRIPT}: a concurrent writer's change is re-read and kept, a logout
|
|
490
593
|
* that deleted it wins). Best-effort: any Redis error or miss → that entry is skipped; the caller
|
|
491
594
|
* still uses the reloaded roles for the current request. Returns `true` when the access-token
|
|
492
595
|
* entry was rewritten.
|
|
596
|
+
*
|
|
597
|
+
* `accessToken` `null` (background-agent-tasks SPEC v9 §5 C, the off-request facts refresh): the
|
|
598
|
+
* token currently bound to the session ({@link currentAccessToken}), when there is one; the
|
|
599
|
+
* session-claims entry is rewritten either way.
|
|
493
600
|
*/
|
|
494
601
|
async refreshGrants(accessToken, sessionId, tenantId, facts, roleIds) {
|
|
495
602
|
const slot = factsSlot(facts);
|
|
496
|
-
const rewrite =
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
cachedFacts: slot,
|
|
512
|
-
...(roleIds !== undefined ? { roleIds: [...roleIds] } : {}),
|
|
513
|
-
};
|
|
514
|
-
return (await this.redis.set(key, JSON.stringify(next), 'PX', ttl, 'XX')) === 'OK';
|
|
515
|
-
}
|
|
516
|
-
catch {
|
|
517
|
-
return false;
|
|
518
|
-
}
|
|
519
|
-
};
|
|
520
|
-
const tokenRewritten = await rewrite(atKey(accessToken));
|
|
603
|
+
const rewrite = (key) => this.compareAndRewrite(key, (raw) => {
|
|
604
|
+
const current = JSON.parse(raw);
|
|
605
|
+
if (current?.sessionId !== sessionId || current?.tenantId !== tenantId)
|
|
606
|
+
return null;
|
|
607
|
+
if (!isFresher(slot, parseCachedFacts(current.cachedFacts)))
|
|
608
|
+
return null;
|
|
609
|
+
const next = {
|
|
610
|
+
...current,
|
|
611
|
+
cachedFacts: slot,
|
|
612
|
+
...(roleIds !== undefined ? { roleIds: [...roleIds] } : {}),
|
|
613
|
+
};
|
|
614
|
+
return JSON.stringify(next);
|
|
615
|
+
});
|
|
616
|
+
const token = accessToken ?? (await this.currentAccessToken(sessionId));
|
|
617
|
+
const tokenRewritten = token !== null ? await rewrite(atKey(token)) : false;
|
|
521
618
|
await rewrite(sessClaimsKey(sessionId));
|
|
522
619
|
return tokenRewritten;
|
|
523
620
|
}
|
|
621
|
+
/**
|
|
622
|
+
* The access token currently bound to `sessionId` (the session → token entry every bind and
|
|
623
|
+
* rotation writes), or `null` when none is bound or Redis errors. Only for the off-request facts
|
|
624
|
+
* refresh's write-back ({@link refreshGrants} / {@link rederiveScopeSubtree} with a `null`
|
|
625
|
+
* token), which then rewrites that token's entry exactly as the request on it would. Never
|
|
626
|
+
* returned outside the binder.
|
|
627
|
+
*/
|
|
628
|
+
async currentAccessToken(sessionId) {
|
|
629
|
+
try {
|
|
630
|
+
const token = await this.redis.get(sessAtKey(sessionId));
|
|
631
|
+
return typeof token === 'string' && token !== '' ? token : null;
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
524
637
|
/**
|
|
525
638
|
* SCOPE-SWITCH re-bind (Task 5.2, ADR-0027 / ADR-0024). A principal is switching which
|
|
526
639
|
* active node it acts under; re-bind its CURRENT session (the same access token — no
|
|
@@ -642,39 +755,31 @@ class SessionTokenBinder {
|
|
|
642
755
|
* (a concurrent refresh already wrote something at least as fresh → left alone). Each keeps its
|
|
643
756
|
* remaining TTL (a re-derive never extends a session). Best-effort: any Redis error or miss →
|
|
644
757
|
* `false`; the caller still uses the fresh subtree for the current request and a later reload
|
|
645
|
-
* retries. Returns `true` when the access-token entry was rewritten.
|
|
758
|
+
* retries. Returns `true` when the access-token entry was rewritten. `accessToken` `null`: the
|
|
759
|
+
* session's current token, as in {@link refreshGrants}.
|
|
646
760
|
*/
|
|
647
761
|
async rederiveScopeSubtree(accessToken, sessionId, tenantId, subtree, version) {
|
|
648
762
|
if (subtree.length === 0 || !isSubtreeVersion(version))
|
|
649
763
|
return false;
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
current.scopeSubtreeVersion >= version) {
|
|
660
|
-
return false;
|
|
661
|
-
}
|
|
662
|
-
const ttl = await this.redis.pttl(key);
|
|
663
|
-
if (ttl <= 0)
|
|
664
|
-
return false;
|
|
665
|
-
const next = {
|
|
666
|
-
...current,
|
|
667
|
-
scopeSubtreeNodeIds: [...subtree],
|
|
668
|
-
scopeSubtreeVersion: version,
|
|
669
|
-
};
|
|
670
|
-
await this.redis.set(key, JSON.stringify(next), 'PX', ttl);
|
|
671
|
-
return true;
|
|
672
|
-
}
|
|
673
|
-
catch {
|
|
674
|
-
return false;
|
|
764
|
+
// Compare-and-set (QA-1 P2-1): a concurrent writer's change is re-read and kept; a logout /
|
|
765
|
+
// end-sessions that deleted the entry between the read and the write wins (never re-created).
|
|
766
|
+
const rewrite = (key) => this.compareAndRewrite(key, (raw) => {
|
|
767
|
+
const current = JSON.parse(raw);
|
|
768
|
+
if (current?.sessionId !== sessionId || current?.tenantId !== tenantId)
|
|
769
|
+
return null;
|
|
770
|
+
if (isSubtreeVersion(current.scopeSubtreeVersion) &&
|
|
771
|
+
current.scopeSubtreeVersion >= version) {
|
|
772
|
+
return null;
|
|
675
773
|
}
|
|
676
|
-
|
|
677
|
-
|
|
774
|
+
const next = {
|
|
775
|
+
...current,
|
|
776
|
+
scopeSubtreeNodeIds: [...subtree],
|
|
777
|
+
scopeSubtreeVersion: version,
|
|
778
|
+
};
|
|
779
|
+
return JSON.stringify(next);
|
|
780
|
+
});
|
|
781
|
+
const token = accessToken ?? (await this.currentAccessToken(sessionId));
|
|
782
|
+
const tokenRewritten = token !== null ? await rewrite(atKey(token)) : false;
|
|
678
783
|
await rewrite(sessClaimsKey(sessionId));
|
|
679
784
|
return tokenRewritten;
|
|
680
785
|
}
|
|
@@ -694,43 +799,9 @@ class SessionTokenBinder {
|
|
|
694
799
|
}
|
|
695
800
|
if (raw === null)
|
|
696
801
|
return null;
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
parsed = JSON.parse(raw);
|
|
700
|
-
}
|
|
701
|
-
catch {
|
|
702
|
-
return null;
|
|
703
|
-
}
|
|
704
|
-
if (typeof parsed?.id !== 'string' ||
|
|
705
|
-
typeof parsed?.tenantId !== 'string' ||
|
|
706
|
-
!Array.isArray(parsed?.roleIds) ||
|
|
707
|
-
typeof parsed?.kind !== 'string' ||
|
|
708
|
-
typeof parsed?.isRoot !== 'boolean' ||
|
|
709
|
-
typeof parsed?.sessionId !== 'string' ||
|
|
710
|
-
typeof parsed?.mustReenroll !== 'boolean') {
|
|
802
|
+
const parsed = parseBoundClaims(raw);
|
|
803
|
+
if (parsed === null)
|
|
711
804
|
return null; // malformed → fail closed.
|
|
712
|
-
}
|
|
713
|
-
// Normalize the OPTIONAL cached-facts slot (ADR-0011): a malformed/legacy/absent
|
|
714
|
-
// slot is scrubbed to `undefined` (→ the guard enters the ALS with `cachedFacts:
|
|
715
|
-
// null` → gate 5 DB-reloads). Present + well-formed → the validated CoarseGrants.
|
|
716
|
-
// Never fabricated. Rebuild the object so a malformed slot cannot ride through.
|
|
717
|
-
const cachedFacts = parseCachedFacts(parsed.cachedFacts);
|
|
718
|
-
parsed = cachedFacts === undefined ? stripCachedFacts(parsed) : { ...parsed, cachedFacts };
|
|
719
|
-
// Normalize the OPTIONAL scope-subtree slot (ADR-0027 / Task 2.2): an absent, empty, or
|
|
720
|
-
// malformed slot is scrubbed to ABSENT (→ `principalFromClaims` falls back to the self-node,
|
|
721
|
-
// non-widening); a well-formed non-empty array is the validated cached subtree. Never
|
|
722
|
-
// fabricated — rebuild the object so a junk slot cannot ride through into a Principal.
|
|
723
|
-
const scopeSubtreeNodeIds = parseScopeSubtree(parsed.scopeSubtreeNodeIds);
|
|
724
|
-
parsed =
|
|
725
|
-
scopeSubtreeNodeIds === undefined
|
|
726
|
-
? stripScopeSubtree(parsed)
|
|
727
|
-
: { ...parsed, scopeSubtreeNodeIds };
|
|
728
|
-
// The subtree's version stamp (Phase 1C) rides only beside a validated subtree; a junk or
|
|
729
|
-
// orphaned stamp is dropped (→ treated as unknown → one re-derive at the next reload).
|
|
730
|
-
if (scopeSubtreeNodeIds === undefined ||
|
|
731
|
-
!isSubtreeVersion(parsed.scopeSubtreeVersion)) {
|
|
732
|
-
parsed = stripSubtreeVersion(parsed);
|
|
733
|
-
}
|
|
734
805
|
// SESSION-LIVENESS GATE: the per-token binding alone is not enough — a logout
|
|
735
806
|
// revokes the session but cannot reach every outstanding access-token key. So we
|
|
736
807
|
// ALSO require the session-claims entry (which `unbindSession` deletes on logout)
|
|
@@ -745,30 +816,36 @@ class SessionTokenBinder {
|
|
|
745
816
|
}
|
|
746
817
|
if (liveness === null)
|
|
747
818
|
return null; // session revoked (logout) → deny.
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
819
|
+
return overlaySessionState(parsed, liveness);
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Resolve a SESSION (not an access token) to its bound claims, from the session-claims entry
|
|
823
|
+
* alone (background-agent-tasks SPEC §5 B): the same validation and normalization as
|
|
824
|
+
* {@link resolve} ({@link parseBoundClaims}) and the same session-authoritative overlay of the
|
|
825
|
+
* re-enrol flag and the mandatory-2FA state ({@link overlaySessionState}), applied to the one
|
|
826
|
+
* entry that `unbindSession` deletes on logout, admin end-sessions and the disable sweep. It is
|
|
827
|
+
* the entry every claims rewrite (rotation, live-grants rebind, subtree re-derive, scope switch)
|
|
828
|
+
* writes beside the access-token entry, so it carries the session's current claims.
|
|
829
|
+
*
|
|
830
|
+
* `null` (fail closed) when the entry is gone (ended), malformed, bound to another session id, or
|
|
831
|
+
* Redis errors. One Redis GET; never on the guard's per-request path.
|
|
832
|
+
*/
|
|
833
|
+
async resolveSession(sessionId) {
|
|
834
|
+
if (typeof sessionId !== 'string' || sessionId === '')
|
|
835
|
+
return null;
|
|
836
|
+
let raw;
|
|
759
837
|
try {
|
|
760
|
-
|
|
761
|
-
mustReenroll = sess?.mustReenroll === true;
|
|
762
|
-
mfa = readMfaState(sess);
|
|
838
|
+
raw = await this.redis.get(sessClaimsKey(sessionId));
|
|
763
839
|
}
|
|
764
840
|
catch {
|
|
765
|
-
|
|
766
|
-
}
|
|
767
|
-
const hasMfa = Object.keys(mfa).length > 0;
|
|
768
|
-
if (!hasMfa && !MFA_STATE_KEYS.some((k) => k in parsed)) {
|
|
769
|
-
return mustReenroll === parsed.mustReenroll ? parsed : { ...parsed, mustReenroll };
|
|
841
|
+
return null; // Redis unavailable → fail closed.
|
|
770
842
|
}
|
|
771
|
-
|
|
843
|
+
if (raw === null)
|
|
844
|
+
return null; // session ended → deny.
|
|
845
|
+
const parsed = parseBoundClaims(raw);
|
|
846
|
+
if (parsed === null || parsed.sessionId !== sessionId)
|
|
847
|
+
return null;
|
|
848
|
+
return overlaySessionState(parsed, raw);
|
|
772
849
|
}
|
|
773
850
|
/**
|
|
774
851
|
* MANDATORY-2FA RECOMPUTE write (R2.5, D-2): store a re-evaluated requirement on the
|
|
@@ -812,7 +889,7 @@ class SessionTokenBinder {
|
|
|
812
889
|
mfaRequirementVersion: state.mfaRequirementVersion,
|
|
813
890
|
mfaStateEpoch: expectedEpoch + 1,
|
|
814
891
|
};
|
|
815
|
-
const written = await this.redis.eval(MFA_STATE_CAS_SCRIPT, 1, key, raw, JSON.stringify(next));
|
|
892
|
+
const written = await this.redis.eval(exports.MFA_STATE_CAS_SCRIPT, 1, key, raw, JSON.stringify(next));
|
|
816
893
|
return Number(written) === 1;
|
|
817
894
|
}
|
|
818
895
|
catch {
|
|
@@ -841,22 +918,22 @@ class SessionTokenBinder {
|
|
|
841
918
|
/**
|
|
842
919
|
* R2.7 defence in depth: restrict the session NOW (`restriction: 'mfa_enrollment'`, any grace
|
|
843
920
|
* deadline dropped) after a removal left the user with no confirmed factor while a policy applies.
|
|
844
|
-
* Unconditional
|
|
845
|
-
* increments the epoch, so an in-flight recompute that read the old state cannot lift it. The
|
|
921
|
+
* Unconditional on the stored state (no epoch or stamp precondition: restricting is always the
|
|
922
|
+
* safe direction), and it increments the epoch, so an in-flight recompute that read the old state cannot lift it. The
|
|
846
923
|
* re-enrol flag and the requirement stamp are kept. Returns `false` when the entry is gone or Redis
|
|
847
924
|
* failed.
|
|
925
|
+
*
|
|
926
|
+
* Written by compare-and-set ({@link compareAndRewrite}, background-agent-tasks QA-1 P2-1
|
|
927
|
+
* follow-up): the restriction is re-applied to the FRESH entry on every attempt, so a concurrent
|
|
928
|
+
* rewrite landing between the read and the write (live grants, subtree, scope, re-enrol clear)
|
|
929
|
+
* keeps its facts and the restriction still lands; a logout in that window wins (never
|
|
930
|
+
* re-created); the remaining TTL is kept. A writer changing the entry on every read exhausts the
|
|
931
|
+
* retries → `false` (the caller answers 503: fail closed).
|
|
848
932
|
*/
|
|
849
933
|
async restrictMfaEnrollment(sessionId) {
|
|
850
|
-
|
|
851
|
-
try {
|
|
852
|
-
const raw = await this.redis.get(key);
|
|
853
|
-
if (raw === null)
|
|
854
|
-
return false;
|
|
934
|
+
return this.compareAndRewrite(sessClaimsKey(sessionId), (raw) => {
|
|
855
935
|
const current = JSON.parse(raw);
|
|
856
936
|
const stored = readMfaState(current);
|
|
857
|
-
const ttl = await this.redis.pttl(key);
|
|
858
|
-
if (ttl <= 0)
|
|
859
|
-
return false;
|
|
860
937
|
const next = {
|
|
861
938
|
...stripMfaState(current),
|
|
862
939
|
restriction: stored.restriction === 'reenroll' ? 'reenroll' : 'mfa_enrollment',
|
|
@@ -865,11 +942,8 @@ class SessionTokenBinder {
|
|
|
865
942
|
: {}),
|
|
866
943
|
mfaStateEpoch: (stored.mfaStateEpoch ?? 0) + 1,
|
|
867
944
|
};
|
|
868
|
-
return
|
|
869
|
-
}
|
|
870
|
-
catch {
|
|
871
|
-
return false;
|
|
872
|
-
}
|
|
945
|
+
return JSON.stringify(next);
|
|
946
|
+
});
|
|
873
947
|
}
|
|
874
948
|
/**
|
|
875
949
|
* DEVICE CONFIRM clear (R2.3, AC-7): the user now has a confirmed factor, so lift BOTH reasons
|
|
@@ -878,31 +952,37 @@ class SessionTokenBinder {
|
|
|
878
952
|
* that started before the confirm cannot write its stale result back. The live token's next
|
|
879
953
|
* request is unrestricted (it is not re-minted). Best-effort: a gone entry or a Redis error leaves
|
|
880
954
|
* the session as it is (still restricted: the safe direction).
|
|
955
|
+
*
|
|
956
|
+
* Written by compare-and-set ({@link compareAndRewrite}, background-agent-tasks QA-1 P2-1
|
|
957
|
+
* follow-up). The clear lifts only the mandatory-2FA state it READ: the epoch on its first read
|
|
958
|
+
* is the one it intends to supersede. When a re-read (after a compare miss) carries a different
|
|
959
|
+
* epoch, a restriction, recompute or other clear landed in its window and is newer than what this
|
|
960
|
+
* clear judged, so nothing is written (a concurrent `restrictMfaEnrollment` survives; the session
|
|
961
|
+
* stays as that writer left it, the safe direction). A rewrite that leaves the epoch alone (live
|
|
962
|
+
* grants, subtree, re-enrol clear) is kept and the clear re-applied on top. A logout in the window
|
|
963
|
+
* wins (never re-created); the remaining TTL is kept.
|
|
881
964
|
*/
|
|
882
965
|
async clearRestriction(sessionId) {
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
if (raw === null)
|
|
887
|
-
return;
|
|
966
|
+
let intendedEpoch;
|
|
967
|
+
// best-effort: a miss leaves the session restricted; the user can confirm again or sign in again.
|
|
968
|
+
await this.compareAndRewrite(sessClaimsKey(sessionId), (raw) => {
|
|
888
969
|
const current = JSON.parse(raw);
|
|
889
970
|
const stored = readMfaState(current);
|
|
890
|
-
const
|
|
891
|
-
if (
|
|
892
|
-
|
|
971
|
+
const epoch = stored.mfaStateEpoch ?? 0;
|
|
972
|
+
if (intendedEpoch === undefined)
|
|
973
|
+
intendedEpoch = epoch;
|
|
974
|
+
else if (epoch !== intendedEpoch)
|
|
975
|
+
return null; // a newer mandatory-2FA state: never lift it.
|
|
893
976
|
const next = {
|
|
894
977
|
...stripMfaState(current),
|
|
895
978
|
mustReenroll: false,
|
|
896
979
|
...(stored.mfaRequirementVersion !== undefined
|
|
897
980
|
? { mfaRequirementVersion: stored.mfaRequirementVersion }
|
|
898
981
|
: {}),
|
|
899
|
-
mfaStateEpoch:
|
|
982
|
+
mfaStateEpoch: epoch + 1,
|
|
900
983
|
};
|
|
901
|
-
|
|
902
|
-
}
|
|
903
|
-
catch {
|
|
904
|
-
// best-effort: the session stays restricted; the user can confirm again or sign in again.
|
|
905
|
-
}
|
|
984
|
+
return JSON.stringify(next);
|
|
985
|
+
});
|
|
906
986
|
}
|
|
907
987
|
/**
|
|
908
988
|
* Clear the ENFORCED-RE-ENROLL flag for a session — the re-secure is complete
|
|
@@ -918,40 +998,51 @@ class SessionTokenBinder {
|
|
|
918
998
|
* dead / will re-deny) — we simply return. Idempotent.
|
|
919
999
|
*/
|
|
920
1000
|
async clearReenroll(sessionId) {
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
return; // expired/no-expiry between get and pttl → leave it.
|
|
949
|
-
const updated = { ...parsed, mustReenroll: false };
|
|
1001
|
+
// Compare-and-set (QA-1 P2-1), keeping the remaining TTL (clearing the flag never extends the
|
|
1002
|
+
// session life): a concurrent restriction / epoch bump is re-read and kept; a logout between the
|
|
1003
|
+
// read and the write wins (never resurrect the entry). Redis unavailable, a gone entry or a
|
|
1004
|
+
// malformed one → nothing (resolve() fails a malformed entry closed; the gate re-evaluates next
|
|
1005
|
+
// request); a failed clear just means the next re-secure attempt retries.
|
|
1006
|
+
await this.compareAndRewrite(sessClaimsKey(sessionId), (raw) => {
|
|
1007
|
+
let parsed;
|
|
1008
|
+
try {
|
|
1009
|
+
parsed = JSON.parse(raw);
|
|
1010
|
+
}
|
|
1011
|
+
catch {
|
|
1012
|
+
return null;
|
|
1013
|
+
}
|
|
1014
|
+
if (parsed.mustReenroll === false)
|
|
1015
|
+
return null; // already clear — idempotent no-op.
|
|
1016
|
+
return JSON.stringify({ ...parsed, mustReenroll: false });
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Read `key`, transform it and write the result back only if the entry is unchanged since the
|
|
1021
|
+
* read ({@link CLAIMS_REWRITE_CAS_SCRIPT}: remaining TTL kept, `XX`). `transform` returns the new
|
|
1022
|
+
* payload, or `null` for "leave it" (it may throw: that is a miss too). On a compare miss the entry
|
|
1023
|
+
* is re-read and the same transformation re-applied to the fresh value (so a concurrent writer's
|
|
1024
|
+
* change is kept), at most {@link CLAIMS_CAS_RETRIES} times; then `false` (fail closed, the next
|
|
1025
|
+
* request or poll recomputes). A gone entry, a Redis error or a `null` transform → `false`.
|
|
1026
|
+
*/
|
|
1027
|
+
async compareAndRewrite(key, transform) {
|
|
950
1028
|
try {
|
|
951
|
-
|
|
1029
|
+
for (let attempt = 0; attempt <= CLAIMS_CAS_RETRIES; attempt += 1) {
|
|
1030
|
+
const raw = await this.redis.get(key);
|
|
1031
|
+
if (raw === null)
|
|
1032
|
+
return false;
|
|
1033
|
+
const next = transform(raw);
|
|
1034
|
+
if (next === null)
|
|
1035
|
+
return false;
|
|
1036
|
+
const outcome = Number(await this.redis.eval(exports.CLAIMS_REWRITE_CAS_SCRIPT, 1, key, raw, next));
|
|
1037
|
+
if (outcome === CLAIMS_CAS_WRITTEN)
|
|
1038
|
+
return true;
|
|
1039
|
+
if (outcome !== CLAIMS_CAS_CHANGED)
|
|
1040
|
+
return false;
|
|
1041
|
+
}
|
|
1042
|
+
return false;
|
|
952
1043
|
}
|
|
953
1044
|
catch {
|
|
954
|
-
|
|
1045
|
+
return false;
|
|
955
1046
|
}
|
|
956
1047
|
}
|
|
957
1048
|
/** Drop an access-token binding. Idempotent. */
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The port behind `SHIELD_CALL_PRINCIPALS` (background-agent-tasks SPEC v2 §5 B, v9 §5 C): the
|
|
3
|
+
* per-call principals a background or unattended agent run re-derives before every call, built by
|
|
4
|
+
* guard code (Shield #3), and the off-request session facts refresh its liveness poll uses once a
|
|
5
|
+
* session's cached facts are unusable. Provided and exported by `AuthModule` (`auth: true`) over the
|
|
6
|
+
* guard's own session token binder, API-key store, decision authority, subtree resolver and
|
|
7
|
+
* mandatory-2FA service instances; on `@astram/guard/internal` for `@astram/agent` only. Never used
|
|
8
|
+
* on the guard's per-request path. No method throws.
|
|
9
|
+
*/
|
|
10
|
+
import type { Principal } from '@astram/core';
|
|
11
|
+
import { type SessionClaimsReader, type SessionFactsRefreshDeps } from './session-principal.js';
|
|
12
|
+
import { type ApiKeyRecordReader } from '../authentication/service-account-principal.js';
|
|
13
|
+
export interface CallPrincipals {
|
|
14
|
+
/** Redis only (one GET). `null` ⇒ ended, revoked, tenant changed, other user, restricted, error. */
|
|
15
|
+
principalForSession(sessionId: string, tenantId: string, userId: string): Promise<Principal | null>;
|
|
16
|
+
/**
|
|
17
|
+
* The guard's `ask_…` lookup (one MariaDB query, as on every `ask_…` request). `keyId` is the key
|
|
18
|
+
* version the run started under. `null` ⇒ rotated, revoked, expired, account not active or gone,
|
|
19
|
+
* other tenant, tenant company gone, error.
|
|
20
|
+
*/
|
|
21
|
+
principalForServiceAccount(accountId: string, keyId: number, tenantId: string): Promise<Principal | null>;
|
|
22
|
+
/**
|
|
23
|
+
* background-agent-tasks SPEC v9 §5 C: refresh the session's cached facts through the guard's own
|
|
24
|
+
* request-path reload (`refreshSessionFacts`): one `loadCoarseGrants` read when they are absent,
|
|
25
|
+
* past their time bound or behind the version; written back as a request writes them. For the
|
|
26
|
+
* liveness POLL only, never per call. `null` ⇒ the session-claims entry is gone (refresh idle
|
|
27
|
+
* passed, logout, end-sessions), tenant changed, other user, root, restricted, recompute failed,
|
|
28
|
+
* no derivable version, or any error (fail closed).
|
|
29
|
+
*/
|
|
30
|
+
refreshSessionFacts(sessionId: string, tenantId: string, userId: string): Promise<Principal | null>;
|
|
31
|
+
}
|
|
32
|
+
export declare class GuardCallPrincipals implements CallPrincipals {
|
|
33
|
+
private readonly binder;
|
|
34
|
+
/** `null` when no API-key store is wired: every service-account call is `null`. */
|
|
35
|
+
private readonly keyStore;
|
|
36
|
+
private readonly now;
|
|
37
|
+
/**
|
|
38
|
+
* The guard's reload collaborators (`null` when no decision authority is wired: every refresh
|
|
39
|
+
* is `null`, fail closed). Its `tokenBinder` is the same binder instance as `binder`.
|
|
40
|
+
*/
|
|
41
|
+
private readonly refresh;
|
|
42
|
+
constructor(binder: SessionClaimsReader,
|
|
43
|
+
/** `null` when no API-key store is wired: every service-account call is `null`. */
|
|
44
|
+
keyStore: ApiKeyRecordReader | null, now?: () => number,
|
|
45
|
+
/**
|
|
46
|
+
* The guard's reload collaborators (`null` when no decision authority is wired: every refresh
|
|
47
|
+
* is `null`, fail closed). Its `tokenBinder` is the same binder instance as `binder`.
|
|
48
|
+
*/
|
|
49
|
+
refresh?: SessionFactsRefreshDeps | null);
|
|
50
|
+
principalForSession(sessionId: string, tenantId: string, userId: string): Promise<Principal | null>;
|
|
51
|
+
principalForServiceAccount(accountId: string, keyId: number, tenantId: string): Promise<Principal | null>;
|
|
52
|
+
refreshSessionFacts(sessionId: string, tenantId: string, userId: string): Promise<Principal | null>;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=call-principals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"call-principals.d.ts","sourceRoot":"","sources":["../../src/session/call-principals.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,EAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,gDAAgD,CAAC;AAExD,MAAM,WAAW,cAAc;IAC7B,oGAAoG;IACpG,mBAAmB,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;IAC7B;;;;OAIG;IACH,0BAA0B,CACxB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;IAC7B;;;;;;;OAOG;IACH,mBAAmB,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;CAC9B;AAED,qBAAa,mBAAoB,YAAW,cAAc;IAEtD,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,mFAAmF;IACnF,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,OAAO;gBARP,MAAM,EAAE,mBAAmB;IAC5C,mFAAmF;IAClE,QAAQ,EAAE,kBAAkB,GAAG,IAAI,EACnC,GAAG,GAAE,MAAM,MAAiB;IAC7C;;;OAGG;IACc,OAAO,GAAE,uBAAuB,GAAG,IAAW;IAGjE,mBAAmB,CACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;IAItB,0BAA0B,CAC9B,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;IAKtB,mBAAmB,CACvB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;CAI7B"}
|