@astram/core 1.1.0 → 1.3.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/authentication/index.d.ts +1 -0
- package/dist/authentication/index.d.ts.map +1 -1
- package/dist/authentication/index.js +2 -0
- package/dist/authentication/index.js.map +1 -1
- package/dist/authentication/service-account-authenticator.d.ts +82 -0
- package/dist/authentication/service-account-authenticator.d.ts.map +1 -0
- package/dist/authentication/service-account-authenticator.js +74 -0
- package/dist/authentication/service-account-authenticator.js.map +1 -0
- package/dist/authorization/gates/object-type.d.ts.map +1 -1
- package/dist/authorization/gates/object-type.js +17 -8
- package/dist/authorization/gates/object-type.js.map +1 -1
- package/dist/authorization/gates/tenant.d.ts +7 -4
- package/dist/authorization/gates/tenant.d.ts.map +1 -1
- package/dist/authorization/gates/tenant.js +30 -7
- package/dist/authorization/gates/tenant.js.map +1 -1
- package/dist/authorization/index.d.ts +1 -0
- package/dist/authorization/index.d.ts.map +1 -1
- package/dist/authorization/index.js +2 -0
- package/dist/authorization/index.js.map +1 -1
- package/dist/authorization/ports.d.ts +65 -0
- package/dist/authorization/ports.d.ts.map +1 -1
- package/dist/authorization/record/list-scope.d.ts +198 -0
- package/dist/authorization/record/list-scope.d.ts.map +1 -0
- package/dist/authorization/record/list-scope.js +153 -0
- package/dist/authorization/record/list-scope.js.map +1 -0
- package/dist/encryption/encryption-service.d.ts +63 -0
- package/dist/encryption/encryption-service.d.ts.map +1 -0
- package/dist/encryption/encryption-service.js +184 -0
- package/dist/encryption/encryption-service.js.map +1 -0
- package/dist/encryption/index.d.ts +17 -0
- package/dist/encryption/index.d.ts.map +1 -0
- package/dist/encryption/index.js +15 -0
- package/dist/encryption/index.js.map +1 -0
- package/dist/encryption/ports.d.ts +84 -0
- package/dist/encryption/ports.d.ts.map +1 -0
- package/dist/encryption/ports.js +18 -0
- package/dist/encryption/ports.js.map +1 -0
- package/dist/identity/broker.d.ts.map +1 -1
- package/dist/identity/broker.js +6 -0
- package/dist/identity/broker.js.map +1 -1
- package/dist/identity/index.d.ts +16 -1
- package/dist/identity/index.d.ts.map +1 -1
- package/dist/identity/index.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/secrets/index.d.ts +15 -0
- package/dist/secrets/index.d.ts.map +1 -0
- package/dist/secrets/index.js +14 -0
- package/dist/secrets/index.js.map +1 -0
- package/dist/secrets/ports.d.ts +45 -0
- package/dist/secrets/ports.d.ts.map +1 -0
- package/dist/secrets/ports.js +26 -0
- package/dist/secrets/ports.js.map +1 -0
- package/dist/secrets/resolve.d.ts +29 -0
- package/dist/secrets/resolve.d.ts.map +1 -0
- package/dist/secrets/resolve.js +49 -0
- package/dist/secrets/resolve.js.map +1 -0
- package/dist-cjs/authentication/index.js +2 -0
- package/dist-cjs/authentication/service-account-authenticator.js +78 -0
- package/dist-cjs/authorization/gates/object-type.js +17 -8
- package/dist-cjs/authorization/gates/tenant.js +30 -7
- package/dist-cjs/authorization/index.js +2 -0
- package/dist-cjs/authorization/record/list-scope.js +155 -0
- package/dist-cjs/encryption/encryption-service.js +189 -0
- package/dist-cjs/encryption/index.js +20 -0
- package/dist-cjs/encryption/ports.js +18 -0
- package/dist-cjs/identity/broker.js +6 -0
- package/dist-cjs/index.js +2 -0
- package/dist-cjs/secrets/index.js +21 -0
- package/dist-cjs/secrets/ports.js +29 -0
- package/dist-cjs/secrets/resolve.js +54 -0
- package/package.json +1 -1
|
@@ -15,10 +15,13 @@
|
|
|
15
15
|
* ── The order (deny wins; every ambiguity resolves to the deny/continue path,
|
|
16
16
|
* never to a bypass):
|
|
17
17
|
*
|
|
18
|
-
* 1.
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
18
|
+
* 1. IN SCOPE (`resource.tenantId ∈ principal.scopeSubtreeNodeIds` — the active
|
|
19
|
+
* node + all descendants, ADR-0027 — OR the resource carries no instance
|
|
20
|
+
* tenant) ⇒ `continue`. An in-memory set test against the login-cached subtree
|
|
21
|
+
* (zero per-request DB, ADR-0024). A feature/object-type-level resource with no
|
|
22
|
+
* `tenantId` is same-tenant BY CONSTRUCTION — there is no foreign instance to
|
|
23
|
+
* cross into. The subtree ALWAYS contains the active node itself, so this is a
|
|
24
|
+
* strict generalization of the old flat `tenantId === resource.tenantId`.
|
|
22
25
|
* 2. MISMATCH + root (STRICT `=== true`) ⇒ `continue` (break-glass,
|
|
23
26
|
* audited by a later layer — not this gate's concern).
|
|
24
27
|
* 3. MISMATCH + not root ⇒ consult {@link CrossTenantGrantPort}:
|
|
@@ -54,9 +57,29 @@ const grant_evaluator_js_1 = require("../cross-tenant/grant-evaluator.js");
|
|
|
54
57
|
function createTenantGate() {
|
|
55
58
|
return async function tenantGate(ctx) {
|
|
56
59
|
const { principal, action, resource, deps } = ctx;
|
|
57
|
-
// 1.
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
+
// 1. IN SCOPE — the resource's owning node is in the principal's active-scope
|
|
61
|
+
// SUBTREE (the node it acts under + all descendants, ADR-0027), OR there is
|
|
62
|
+
// no instance tenant (a feature/object-type resource with no foreign instance
|
|
63
|
+
// to cross into: same-tenant by construction).
|
|
64
|
+
// This is an IN-MEMORY set-membership test against the login-cached
|
|
65
|
+
// `scopeSubtreeNodeIds` — ZERO per-request DB (the ADR-0024 parity guarantee).
|
|
66
|
+
// A non-root principal reaches everything in its subtree (additive-down
|
|
67
|
+
// inheritance) and nothing outside it. `scopeSubtreeNodeIds` ALWAYS contains
|
|
68
|
+
// the active node itself (self-row, Task 2.2), so this GENERALIZES — never
|
|
69
|
+
// narrows — the old flat equality: the `tenantId === resource.tenantId` case
|
|
70
|
+
// is exactly the singleton-subtree case. Root's cross-tree span is NOT here;
|
|
71
|
+
// it is authoritative via `isRoot` (step 2 below). FAIL-CLOSED: an empty
|
|
72
|
+
// subtree makes `.includes` false for every node ⇒ falls through to root /
|
|
73
|
+
// cross-grant / deny (reaches nothing but its own via the self-node).
|
|
74
|
+
// DEFENSE-IN-DEPTH: `Array.isArray` guards a malformed/absent subtree (a
|
|
75
|
+
// JS-constructed Principal that omits the field despite the TS contract) —
|
|
76
|
+
// a non-array is treated as "no reachable scope" ⇒ deny, DETERMINISTICALLY,
|
|
77
|
+
// rather than relying on a thrown `undefined.includes` being caught as a
|
|
78
|
+
// fail-closed deny by the pipeline (fail-closed either way, but this is the
|
|
79
|
+
// explicit, non-crashy form).
|
|
80
|
+
const subtree = principal.scopeSubtreeNodeIds;
|
|
81
|
+
if (resource.tenantId === undefined ||
|
|
82
|
+
(Array.isArray(subtree) && subtree.includes(resource.tenantId))) {
|
|
60
83
|
return (0, decision_authority_js_1.gateContinue)();
|
|
61
84
|
}
|
|
62
85
|
// 2. Mismatch + root (break-glass). STRICT === true — a truthy
|
|
@@ -130,5 +130,7 @@ __exportStar(require("./delegation/operation-identity.js"), exports);
|
|
|
130
130
|
__exportStar(require("./record/owner-baseline.js"), exports);
|
|
131
131
|
// - INTEGRATION: the composed gate-6 record permit tier (baseline ∪ policy ∪ share, deny-wins):
|
|
132
132
|
__exportStar(require("./record/permit-tier.js"), exports);
|
|
133
|
+
// - LIST SCOPE: the decision-derived visible-set spec — sibling to decide() (Phase 1):
|
|
134
|
+
__exportStar(require("./record/list-scope.js"), exports);
|
|
133
135
|
// - INTEGRATION: the production gate-set wiring + fully-wired DecisionAuthority factory:
|
|
134
136
|
__exportStar(require("./gates/wiring.js"), exports);
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Phase 1 — the decision-DERIVED **list scope** ({@link computeListScope}), the NEW
|
|
4
|
+
* SIBLING to `decide()` (§7.1). `decide(principal, action, resource, context)` answers
|
|
5
|
+
* "may this ONE record be accessed?" — allow/deny. A LIST endpoint instead needs the
|
|
6
|
+
* *set* of visible rows pushed into the SQL WHERE (Invariant #8 — filter in the query,
|
|
7
|
+
* NEVER fetch-then-discard). `decide()`'s 4-arg signature is FROZEN and returns
|
|
8
|
+
* allow/deny only, so this module adds a sibling contract that produces an ABSTRACT,
|
|
9
|
+
* DB-agnostic description of the visible set — a {@link ListScopeSpec} — computed by a
|
|
10
|
+
* pure function that reproduces the EXACT composition semantics the record-permit tier
|
|
11
|
+
* (`permit-tier.ts`) uses. Phase 2 (the guard) translates the spec to SQL; Phase 3
|
|
12
|
+
* injects it into the engine's `list()`. THIS module is pure core logic — no DB, no
|
|
13
|
+
* SQL, no adapter.
|
|
14
|
+
*
|
|
15
|
+
* ── THE SEMANTICS IT REPRODUCES (this is the whole point). The visible set equals the
|
|
16
|
+
* set `decide()` allows, row-by-row. The record-permit tier it mirrors composes:
|
|
17
|
+
*
|
|
18
|
+
* 1. policy = evaluateRecordPolicy(ctx) // allow + explicitDeny booleans
|
|
19
|
+
* 2. explicitDeny ⇒ DENY (deny-wins, SHORT-CIRCUITS before share)
|
|
20
|
+
* 3. baseline = evaluateOwnerBaseline(ctx)
|
|
21
|
+
* policy.allow || baseline ⇒ ALLOW
|
|
22
|
+
* 4. share = evaluateRecordShare(ctx) // same-tenant share ∪ cross-tenant grant
|
|
23
|
+
* share ⇒ ALLOW
|
|
24
|
+
* 5. else ⇒ DENY
|
|
25
|
+
*
|
|
26
|
+
* ⇒ a record is VISIBLE iff:
|
|
27
|
+
* NOT policyDeny AND (policyAllow OR ownerBaseline OR share OR crossTenant),
|
|
28
|
+
* all WITHIN the tenant bound. Deny-wins is load-bearing: an explicit policy deny
|
|
29
|
+
* REMOVES a row even if a share/owner would include it — so the deny set is an
|
|
30
|
+
* EXCLUSION applied over the union (Phase 2 translates it as `AND NOT (…deny…)`).
|
|
31
|
+
*
|
|
32
|
+
* ── The OWNER-BASELINE posture mapping mirrors `owner-baseline.ts` EXACTLY (same branch
|
|
33
|
+
* precedence): `system` ⇒ all; `tenantScoped && !owned` ⇒ all; `owned` ⇒ owned-only
|
|
34
|
+
* (`ownerId === principal.id`, modeled as `{kind:'owned', ownerField:'ownerId', …}`);
|
|
35
|
+
* no access / unknown type ⇒ none (fail-closed — a rule/share must include the row).
|
|
36
|
+
*
|
|
37
|
+
* ── FAIL-CLOSED (ADR-0016). The ONE port call ({@link ListScopePort.listPolicyConditions})
|
|
38
|
+
* may throw a transient {@link AuthorizationUnavailableError}; this function does NOT
|
|
39
|
+
* catch it — a throw PROPAGATES so the read fails, never "unbounded". Swallowing it
|
|
40
|
+
* into an empty/unbounded spec would silently mis-scope the list (Invariant #8).
|
|
41
|
+
*
|
|
42
|
+
* ── PURE + zero-dep (ADR-0003). No framework / HTTP / DB / node imports; the only I/O is
|
|
43
|
+
* the single {@link ListScopePort} call (which reaches its store via the guard adapter).
|
|
44
|
+
*/
|
|
45
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
+
exports.computeListScope = computeListScope;
|
|
47
|
+
/**
|
|
48
|
+
* Map the object type's access posture to the owner-baseline scope contribution,
|
|
49
|
+
* mirroring `owner-baseline.ts` branch precedence EXACTLY:
|
|
50
|
+
* - no access posture / unknown type ⇒ `{kind:'none'}` (fail-closed).
|
|
51
|
+
* - `system` ⇒ `{kind:'all'}`.
|
|
52
|
+
* - `tenantScoped === true && owned !== true` ⇒ `{kind:'all'}` (the tenant bound
|
|
53
|
+
* already isolates; the record baseline adds no narrowing).
|
|
54
|
+
* - `owned === true` ⇒ `{kind:'owned', ownerField:'ownerId', principalId}` (DAC:
|
|
55
|
+
* only rows the principal owns). NOTE the precedence — a type that is BOTH
|
|
56
|
+
* `owned` and `tenantScoped` resolves via the OWNED branch (matches the baseline:
|
|
57
|
+
* its `tenantScoped` branch requires `owned !== true`).
|
|
58
|
+
* - explicitly ungoverned (all flags false) ⇒ `{kind:'none'}` (fail-closed).
|
|
59
|
+
*/
|
|
60
|
+
function ownerBaselineFor(access, principalId) {
|
|
61
|
+
if (!access)
|
|
62
|
+
return { kind: 'none' };
|
|
63
|
+
if (access.system === true)
|
|
64
|
+
return { kind: 'all' };
|
|
65
|
+
if (access.tenantScoped === true && access.owned !== true)
|
|
66
|
+
return { kind: 'all' };
|
|
67
|
+
if (access.owned === true) {
|
|
68
|
+
return { kind: 'owned', ownerField: 'ownerId', principalId };
|
|
69
|
+
}
|
|
70
|
+
return { kind: 'none' };
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Compute the abstract {@link ListScopeSpec} describing the set of records the principal
|
|
74
|
+
* may see for `(typeKey, action)` within their tenant — the list-form sibling to
|
|
75
|
+
* `decide()`, reproducing the record-permit tier's composition (§7.3.4 / ADR-0005/6/9).
|
|
76
|
+
*
|
|
77
|
+
* Logic (mirrors `permit-tier.ts`):
|
|
78
|
+
* - `tenantBound`: `principal.isRoot === true` ⇒ `'root-unbounded'` (root spans the
|
|
79
|
+
* control-plane; a data-plane list never reaches here for root — `decide()`'s coarse
|
|
80
|
+
* object-type gate already denied it upstream, so we simply honor `isRoot` for the
|
|
81
|
+
* bound). Else ⇒ `{role:'tenantSubtree', nodeIds: principal.scopeSubtreeNodeIds}`
|
|
82
|
+
* (every non-root list is bounded to the actor's REACHABLE SUBTREE — self + descendants,
|
|
83
|
+
* mirroring the tenant gate's `scopeSubtreeNodeIds` membership test, ADR-0027. Uniform —
|
|
84
|
+
* no per-type "is this hierarchy-scoped" flag. This is a NON-BREAKING generalization: a
|
|
85
|
+
* self-node-only principal's closure returns just that one node, i.e. the old flat
|
|
86
|
+
* `tenantId = ?` behavior. The guard translator, Task 3.3, expands the node set to the
|
|
87
|
+
* subtree via the `scope_closure` subquery — core carries only the root id(s), staying
|
|
88
|
+
* DB-agnostic).
|
|
89
|
+
* - `ownerBaseline`: root ⇒ `{kind:'all'}` (unbounded on control-plane). Else the
|
|
90
|
+
* posture mapping above.
|
|
91
|
+
* - `policyAllow`/`policyDeny`: from the ONE port call — mapped straight onto the spec.
|
|
92
|
+
* A transient throw PROPAGATES (NOT caught — fail-closed, ADR-0016).
|
|
93
|
+
* - `share`: always the abstract marker for the caller (Phase 2 resolves it). For root
|
|
94
|
+
* it is harmless (root's baseline is `all`, a superset); populated uniformly.
|
|
95
|
+
* - `crossTenant`: `{kind:'granted', …}` when NON-root (a non-root principal may hold a
|
|
96
|
+
* cross-tenant grant); root ⇒ `{kind:'none'}` — root needs no grant (it is unbounded
|
|
97
|
+
* on the control-plane; a data-plane list never reaches here for root).
|
|
98
|
+
*
|
|
99
|
+
* PURE except the ONE port call; NEVER throws except the propagated transient.
|
|
100
|
+
*/
|
|
101
|
+
async function computeListScope(deps, query) {
|
|
102
|
+
const { principal, action, typeKey } = query;
|
|
103
|
+
const isRoot = principal.isRoot === true;
|
|
104
|
+
// The reachable node set is the principal's CACHED subtree (self + descendants, resolved
|
|
105
|
+
// once at login — Task 2.2), the SAME set the tenant gate tests membership against. Using
|
|
106
|
+
// it directly (not re-querying the closure at list time) makes list ≡ decide equivalence
|
|
107
|
+
// hold BY CONSTRUCTION and keeps the list hot path closure-free. A fail-safe self-node-only
|
|
108
|
+
// principal has `[activeScopeNodeId]` here — identical to the old flat `tenantId = ?`.
|
|
109
|
+
const subtree = Array.isArray(principal.scopeSubtreeNodeIds) && principal.scopeSubtreeNodeIds.length > 0
|
|
110
|
+
? principal.scopeSubtreeNodeIds
|
|
111
|
+
: [principal.activeScopeNodeId];
|
|
112
|
+
const tenantBound = isRoot
|
|
113
|
+
? 'root-unbounded'
|
|
114
|
+
: { role: 'tenantSubtree', nodeIds: subtree };
|
|
115
|
+
const ownerBaseline = isRoot
|
|
116
|
+
? { kind: 'all' }
|
|
117
|
+
: ownerBaselineFor(deps.registry.resolveObjectType(typeKey)?.access, principal.id);
|
|
118
|
+
// The ONE I/O call. A transient AuthorizationUnavailableError PROPAGATES (fail-closed):
|
|
119
|
+
// it is NEVER caught here — swallowing it into an empty/unbounded spec would silently
|
|
120
|
+
// mis-scope the list (ADR-0016 / Invariant #8).
|
|
121
|
+
//
|
|
122
|
+
// The SUBJECT (principal id + role ids) is threaded so the adapter filters each policy
|
|
123
|
+
// rule group by its `rpr_subject_kind` / `rpr_subject_value` EXACTLY as decide()'s
|
|
124
|
+
// per-record `subjectMatches` does — otherwise a role-scoped rule would project to EVERY
|
|
125
|
+
// principal, a fail-open leak (HIGH-1). Root's baseline is already 'all' (a superset), so
|
|
126
|
+
// passing the subject is harmless for root and correct for non-root.
|
|
127
|
+
// Fetch policy rules for the WHOLE reachable subtree (`subtree` = the active node +
|
|
128
|
+
// descendants), NOT just the active node: a DENY rule scoped to a DESCENDANT node must
|
|
129
|
+
// exclude that node's records for a parent admin (deny-wins inherits DOWN, exactly as
|
|
130
|
+
// decide() applies it per-record at the record's own node). Plus global (NULL-tenant)
|
|
131
|
+
// rules. For a flat/self-node caller this is `[activeScopeNodeId]` — the old behavior.
|
|
132
|
+
const policy = await deps.listScope.listPolicyConditions(typeKey, subtree, action, {
|
|
133
|
+
principalId: principal.id,
|
|
134
|
+
roleIds: principal.roleIds,
|
|
135
|
+
});
|
|
136
|
+
const share = {
|
|
137
|
+
kind: 'shared-records',
|
|
138
|
+
principalId: principal.id,
|
|
139
|
+
roleIds: principal.roleIds,
|
|
140
|
+
action,
|
|
141
|
+
};
|
|
142
|
+
const crossTenant = isRoot
|
|
143
|
+
? { kind: 'none' }
|
|
144
|
+
: { kind: 'granted', principalId: principal.id, roleIds: principal.roleIds, action };
|
|
145
|
+
return {
|
|
146
|
+
typeKey,
|
|
147
|
+
action,
|
|
148
|
+
tenantBound,
|
|
149
|
+
ownerBaseline,
|
|
150
|
+
policyAllow: policy.allow,
|
|
151
|
+
policyDeny: policy.deny,
|
|
152
|
+
share,
|
|
153
|
+
crossTenant,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The **Encryption engine** (ADR-0031) — per-tenant envelope encryption for data at rest.
|
|
4
|
+
*
|
|
5
|
+
* `createEncryptionService({ crypto, dekStore, dekCache })` returns the ONE service the platform
|
|
6
|
+
* uses to encrypt/decrypt a tenant's data with that tenant's own DEK. It is PURE + zero-dep: all
|
|
7
|
+
* crypto, KMS, and persistence are injected ports (ADR-0003). The service:
|
|
8
|
+
* • resolves a tenant's DEK: cache → else load the WRAPPED DEK from the store → `crypto.unwrapDek`
|
|
9
|
+
* → cache it (so the hot path unwraps at most once per tenant per TTL);
|
|
10
|
+
* • PROVISIONS a DEK on first encrypt for a tenant (generate → wrap → persist the wrapped DEK);
|
|
11
|
+
* • binds the versioned ciphertext so a decrypt loads the exact DEK the data was written under
|
|
12
|
+
* (survives key rotation);
|
|
13
|
+
* • supports rotation (`rotateDek`) — the engine mints + persists a new DEK version; the batch
|
|
14
|
+
* re-encryption of existing rows is the consumer's job (the engine exposes the primitive).
|
|
15
|
+
*
|
|
16
|
+
* FAIL-CLOSED: a decrypt that can't resolve/unwrap the DEK or fails the AEAD tag THROWS — never
|
|
17
|
+
* returns plaintext, ciphertext, or empty. An encrypt that can't provision/wrap a DEK THROWS — a
|
|
18
|
+
* plaintext is NEVER written unencrypted as a fallback.
|
|
19
|
+
*
|
|
20
|
+
* THREAT MODEL (ADR-0031): defends the STORAGE boundary (disk/dump/backup → ciphertext only). Does
|
|
21
|
+
* NOT defend a compromised app host (it must hold the DEK in memory) or a compromised KMS.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.EncryptionError = exports.DecryptionError = void 0;
|
|
25
|
+
exports.createEncryptionService = createEncryptionService;
|
|
26
|
+
/** Thrown when a decrypt cannot proceed (missing/unwrappable DEK, tag mismatch). Fail-closed. */
|
|
27
|
+
class DecryptionError extends Error {
|
|
28
|
+
/** Underlying cause (a port outage, a tag mismatch) — for admin logging; never surfaced/leaked. */
|
|
29
|
+
cause;
|
|
30
|
+
constructor(message, cause) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = 'DecryptionError';
|
|
33
|
+
this.cause = cause;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
exports.DecryptionError = DecryptionError;
|
|
37
|
+
/** Thrown when an encrypt cannot provision/wrap a DEK. No plaintext is ever written unencrypted. */
|
|
38
|
+
class EncryptionError extends Error {
|
|
39
|
+
/** Underlying cause — for admin logging; never surfaced/leaked. */
|
|
40
|
+
cause;
|
|
41
|
+
constructor(message, cause) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = 'EncryptionError';
|
|
44
|
+
this.cause = cause;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.EncryptionError = EncryptionError;
|
|
48
|
+
function requireTenant(tenantId) {
|
|
49
|
+
if (typeof tenantId !== 'string' || tenantId.trim() === '') {
|
|
50
|
+
throw new EncryptionError('tenantId is required (non-empty).');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function createEncryptionService(deps) {
|
|
54
|
+
const { crypto, dekStore, dekCache } = deps;
|
|
55
|
+
/** Resolve a tenant's CURRENT DEK: cache → store(current) → unwrap → cache. Provisions on absence. */
|
|
56
|
+
async function currentDek(tenantId) {
|
|
57
|
+
// The cache holds the CURRENT dek only; a version bump evicts it (see rotateDek).
|
|
58
|
+
const cached = dekCache?.get(tenantId);
|
|
59
|
+
let record;
|
|
60
|
+
try {
|
|
61
|
+
record = await dekStore.getCurrent(tenantId);
|
|
62
|
+
}
|
|
63
|
+
catch (cause) {
|
|
64
|
+
// Store outage is NOT "no key" — fail closed loudly, never provision-over-an-outage.
|
|
65
|
+
throw new EncryptionError('DEK store unavailable', cause);
|
|
66
|
+
}
|
|
67
|
+
if (record === null) {
|
|
68
|
+
// First use for this tenant: provision a DEK (generate → wrap → persist v1).
|
|
69
|
+
return provisionDek(tenantId);
|
|
70
|
+
}
|
|
71
|
+
if (cached !== undefined)
|
|
72
|
+
return { dek: cached, version: record.version };
|
|
73
|
+
let dek;
|
|
74
|
+
try {
|
|
75
|
+
dek = await crypto.unwrapDek(record.wrapped, tenantId);
|
|
76
|
+
}
|
|
77
|
+
catch (cause) {
|
|
78
|
+
throw new EncryptionError('could not unwrap the current DEK', cause);
|
|
79
|
+
}
|
|
80
|
+
dekCache?.put(tenantId, dek);
|
|
81
|
+
return { dek, version: record.version };
|
|
82
|
+
}
|
|
83
|
+
/** Resolve a SPECIFIC version's DEK (for decrypting data under an older key). No provisioning. */
|
|
84
|
+
async function dekForVersion(tenantId, version) {
|
|
85
|
+
let record;
|
|
86
|
+
try {
|
|
87
|
+
record = await dekStore.getVersion(tenantId, version);
|
|
88
|
+
}
|
|
89
|
+
catch (cause) {
|
|
90
|
+
throw new DecryptionError('DEK store unavailable', cause);
|
|
91
|
+
}
|
|
92
|
+
if (record === null) {
|
|
93
|
+
throw new DecryptionError(`no DEK version ${version} for tenant '${tenantId}'`);
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
return await crypto.unwrapDek(record.wrapped, tenantId);
|
|
97
|
+
}
|
|
98
|
+
catch (cause) {
|
|
99
|
+
throw new DecryptionError('could not unwrap the DEK', cause);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function provisionDek(tenantId) {
|
|
103
|
+
let dek;
|
|
104
|
+
let wrapped;
|
|
105
|
+
try {
|
|
106
|
+
dek = await crypto.generateDek();
|
|
107
|
+
wrapped = await crypto.wrapDek(dek, tenantId);
|
|
108
|
+
}
|
|
109
|
+
catch (cause) {
|
|
110
|
+
throw new EncryptionError('could not generate/wrap a new DEK', cause);
|
|
111
|
+
}
|
|
112
|
+
const version = 1;
|
|
113
|
+
try {
|
|
114
|
+
await dekStore.put({ tenantId, version, wrapped });
|
|
115
|
+
}
|
|
116
|
+
catch (cause) {
|
|
117
|
+
// A concurrent provision may have created v1 first — re-read the current and use it (idempotent-ish).
|
|
118
|
+
const existing = await dekStore.getCurrent(tenantId).catch(() => null);
|
|
119
|
+
if (existing) {
|
|
120
|
+
const existingDek = await crypto.unwrapDek(existing.wrapped, tenantId);
|
|
121
|
+
dekCache?.put(tenantId, existingDek);
|
|
122
|
+
return { dek: existingDek, version: existing.version };
|
|
123
|
+
}
|
|
124
|
+
throw new EncryptionError('could not persist the new DEK', cause);
|
|
125
|
+
}
|
|
126
|
+
dekCache?.put(tenantId, dek);
|
|
127
|
+
return { dek, version };
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
async encryptFor(tenantId, plaintext) {
|
|
131
|
+
requireTenant(tenantId);
|
|
132
|
+
const { dek, version } = await currentDek(tenantId);
|
|
133
|
+
let ciphertext;
|
|
134
|
+
try {
|
|
135
|
+
ciphertext = await crypto.encrypt(plaintext, dek, tenantId);
|
|
136
|
+
}
|
|
137
|
+
catch (cause) {
|
|
138
|
+
throw new EncryptionError('encryption failed', cause);
|
|
139
|
+
}
|
|
140
|
+
return { tenantId, version, ciphertext };
|
|
141
|
+
},
|
|
142
|
+
async decryptFor(tenantId, envelope) {
|
|
143
|
+
requireTenant(tenantId);
|
|
144
|
+
// Defence in depth: the caller-supplied tenant MUST match the envelope's stamp.
|
|
145
|
+
if (envelope.tenantId !== tenantId) {
|
|
146
|
+
throw new DecryptionError('tenant mismatch between caller and envelope (cross-tenant guard)');
|
|
147
|
+
}
|
|
148
|
+
// Prefer the cached current DEK when the envelope is at the current version; else load by version.
|
|
149
|
+
const dek = await dekForVersion(tenantId, envelope.version);
|
|
150
|
+
try {
|
|
151
|
+
return await crypto.decrypt(envelope.ciphertext, dek, tenantId);
|
|
152
|
+
}
|
|
153
|
+
catch (cause) {
|
|
154
|
+
// A tag/AAD mismatch or malformed ciphertext → fail closed. Never leak plaintext/ciphertext.
|
|
155
|
+
throw new DecryptionError('decryption failed (tag mismatch or malformed ciphertext)', cause);
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
async rotateDek(tenantId) {
|
|
159
|
+
requireTenant(tenantId);
|
|
160
|
+
let current;
|
|
161
|
+
try {
|
|
162
|
+
current = await dekStore.getCurrent(tenantId);
|
|
163
|
+
}
|
|
164
|
+
catch (cause) {
|
|
165
|
+
throw new EncryptionError('DEK store unavailable', cause);
|
|
166
|
+
}
|
|
167
|
+
const nextVersion = (current?.version ?? 0) + 1;
|
|
168
|
+
let dek;
|
|
169
|
+
let wrapped;
|
|
170
|
+
try {
|
|
171
|
+
dek = await crypto.generateDek();
|
|
172
|
+
wrapped = await crypto.wrapDek(dek, tenantId);
|
|
173
|
+
await dekStore.put({ tenantId, version: nextVersion, wrapped });
|
|
174
|
+
}
|
|
175
|
+
catch (cause) {
|
|
176
|
+
throw new EncryptionError('could not rotate the DEK', cause);
|
|
177
|
+
}
|
|
178
|
+
// The new DEK is now current; drop the stale cached one so the next op unwraps the new one.
|
|
179
|
+
dekCache?.evict(tenantId);
|
|
180
|
+
dekCache?.put(tenantId, dek);
|
|
181
|
+
return nextVersion;
|
|
182
|
+
},
|
|
183
|
+
async destroyTenantKeys(tenantId) {
|
|
184
|
+
requireTenant(tenantId);
|
|
185
|
+
dekCache?.evict(tenantId);
|
|
186
|
+
await dekStore.destroy(tenantId);
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Engine seam: **Encryption** — per-tenant envelope encryption for data at rest (ADR-0031).
|
|
4
|
+
*
|
|
5
|
+
* `createEncryptionService` encrypts/decrypts a tenant's data with that tenant's own DEK; DEKs are
|
|
6
|
+
* wrapped by a KMS-held KEK and only wrapped DEKs are ever persisted. Pure + zero-dep (ADR-0003):
|
|
7
|
+
* crypto/KMS/persistence are injected ports, shipped as adapters in `@astram/guard`.
|
|
8
|
+
*
|
|
9
|
+
* THREAT MODEL (ADR-0031, stated honestly): defends the STORAGE boundary (stolen disk / DB dump /
|
|
10
|
+
* backup / leaked bucket → only ciphertext + wrapped DEKs). Does NOT defend a compromised app host
|
|
11
|
+
* or a compromised KMS. See `docs/Shield/140_Security_Hardening` + ADR-0031.
|
|
12
|
+
*
|
|
13
|
+
* ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.EncryptionError = exports.DecryptionError = exports.createEncryptionService = void 0;
|
|
17
|
+
var encryption_service_js_1 = require("./encryption-service.js");
|
|
18
|
+
Object.defineProperty(exports, "createEncryptionService", { enumerable: true, get: function () { return encryption_service_js_1.createEncryptionService; } });
|
|
19
|
+
Object.defineProperty(exports, "DecryptionError", { enumerable: true, get: function () { return encryption_service_js_1.DecryptionError; } });
|
|
20
|
+
Object.defineProperty(exports, "EncryptionError", { enumerable: true, get: function () { return encryption_service_js_1.EncryptionError; } });
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Encryption engine PORTS — the framework-agnostic contracts the {@link EncryptionService} uses,
|
|
4
|
+
* WITHOUT the engine ever knowing the algorithm, the KMS, or where wrapped DEKs are stored.
|
|
5
|
+
*
|
|
6
|
+
* ADR-0031 (envelope encryption / per-tenant DEKs) + ADR-0003 (zero-dep core): real crypto needs a
|
|
7
|
+
* library + native bindings and a KMS needs network/SDK — neither can live in `@astram/core`. The
|
|
8
|
+
* core defines only these interfaces; `@astram/guard` ships the concrete AEAD + KMS + DEK-store
|
|
9
|
+
* adapters and INJECTS them into `createEncryptionService`. Core stays at ZERO runtime deps.
|
|
10
|
+
*
|
|
11
|
+
* THREAT MODEL (ADR-0031, honest): this defends the STORAGE boundary (stolen disk / DB dump /
|
|
12
|
+
* backup / leaked bucket → only ciphertext + wrapped DEKs). It does NOT defend a compromised app
|
|
13
|
+
* host (the app must hold a tenant's DEK in memory to serve it) or a compromised KMS.
|
|
14
|
+
*
|
|
15
|
+
* SECURITY: no port implementation may log a plaintext, a DEK, or a plaintext key. DEKs and
|
|
16
|
+
* plaintext are transient inputs; they are never surfaced in a result, a reason, or a log.
|
|
17
|
+
*/
|
|
18
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -96,9 +96,15 @@ class BrokerImpl {
|
|
|
96
96
|
// any raw claim here, so an attacker-controllable `superuser`/`isPlatformSuperuser`
|
|
97
97
|
// claim cannot influence this value.
|
|
98
98
|
const isRoot = candidate.trustedRootSignal === true;
|
|
99
|
+
// Scope (ADR-0027) — INTERIM default (Task 2.1): the active scope node IS the home
|
|
100
|
+
// tenant, and the reachable subtree is JUST that self-node (`[tenantId]`). This
|
|
101
|
+
// reproduces today's flat self-tenant isolation EXACTLY (non-widening) until Task 2.2
|
|
102
|
+
// populates the real closure-resolved subtree (self + descendants) at session establishment.
|
|
99
103
|
return Object.freeze({
|
|
100
104
|
kind,
|
|
101
105
|
id,
|
|
106
|
+
activeScopeNodeId: tenantId,
|
|
107
|
+
scopeSubtreeNodeIds: Object.freeze([tenantId]),
|
|
102
108
|
tenantId,
|
|
103
109
|
roleIds,
|
|
104
110
|
isRoot,
|
package/dist-cjs/index.js
CHANGED
|
@@ -55,6 +55,8 @@ __exportStar(require("./session/index.js"), exports);
|
|
|
55
55
|
__exportStar(require("./risk/index.js"), exports);
|
|
56
56
|
__exportStar(require("./authorization/index.js"), exports);
|
|
57
57
|
__exportStar(require("./audit/index.js"), exports);
|
|
58
|
+
__exportStar(require("./encryption/index.js"), exports);
|
|
59
|
+
__exportStar(require("./secrets/index.js"), exports);
|
|
58
60
|
// Module-registers-metadata contract + pure derivation rules + completeness check.
|
|
59
61
|
__exportStar(require("./metadata/index.js"), exports);
|
|
60
62
|
// Admin Console (Layer 10) — a NEW top-level module (append-only; no frozen
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Engine seam: **Secrets** — env holds references, credentials resolved at runtime + rotatable
|
|
4
|
+
* (ADR-0032). `secret-ref:<path>` in env is a pointer (safe to commit/log); `resolveSecretRefs`
|
|
5
|
+
* fetches the real value at boot via an injected `SecretsProvider`. Pure + zero-dep (ADR-0003);
|
|
6
|
+
* backends (encrypted on-box store now; Vault / AWS SM / GCP SM later) ship in `@astram/guard`.
|
|
7
|
+
*
|
|
8
|
+
* SECURITY: a secret value is never logged/surfaced (only paths + versions). Fail-closed: an
|
|
9
|
+
* unresolvable reference aborts boot; a literal value is unchanged (backward compatible).
|
|
10
|
+
*
|
|
11
|
+
* ADR-0003: framework-agnostic — no framework / HTTP / DB / fs imports.
|
|
12
|
+
*/
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.resolveSecretRefs = exports.secretRefPath = exports.isSecretRef = exports.SECRET_REF_PREFIX = exports.SecretNotFoundError = void 0;
|
|
15
|
+
var ports_js_1 = require("./ports.js");
|
|
16
|
+
Object.defineProperty(exports, "SecretNotFoundError", { enumerable: true, get: function () { return ports_js_1.SecretNotFoundError; } });
|
|
17
|
+
var resolve_js_1 = require("./resolve.js");
|
|
18
|
+
Object.defineProperty(exports, "SECRET_REF_PREFIX", { enumerable: true, get: function () { return resolve_js_1.SECRET_REF_PREFIX; } });
|
|
19
|
+
Object.defineProperty(exports, "isSecretRef", { enumerable: true, get: function () { return resolve_js_1.isSecretRef; } });
|
|
20
|
+
Object.defineProperty(exports, "secretRefPath", { enumerable: true, get: function () { return resolve_js_1.secretRefPath; } });
|
|
21
|
+
Object.defineProperty(exports, "resolveSecretRefs", { enumerable: true, get: function () { return resolve_js_1.resolveSecretRefs; } });
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Secrets provider PORT (ADR-0032) — the framework-agnostic contract for fetching + rotating
|
|
4
|
+
* credentials, so the runtime reads a REFERENCE from env (`secret-ref:db/prod/password`) and the
|
|
5
|
+
* real value is resolved at boot from a secrets backend, NEVER hard-coded in env/Git.
|
|
6
|
+
*
|
|
7
|
+
* ADR-0003 (zero-dep core): the backend is a real dependency (a network vault SDK, or an encrypted
|
|
8
|
+
* on-box store using node crypto) — it cannot live here. Core defines only this interface;
|
|
9
|
+
* `@astram/guard` ships the concrete backends (a reference encrypted on-box store now; Vault / AWS
|
|
10
|
+
* Secrets Manager / GCP Secret Manager as drop-in adapters) and INJECTS one. Core stays zero-dep.
|
|
11
|
+
*
|
|
12
|
+
* SECURITY: a secret VALUE is never logged, never in an error message, never in an audit record —
|
|
13
|
+
* only the PATH + version. A `SecretsProvider` implementation MUST likewise never log a value.
|
|
14
|
+
* Fail-closed: a missing secret THROWS (must never silently resolve to '' — that would start the
|
|
15
|
+
* app with a hole where a credential belongs).
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.SecretNotFoundError = void 0;
|
|
19
|
+
/** Thrown by `resolve` when a referenced secret is absent — fail-closed (never a silent empty). */
|
|
20
|
+
class SecretNotFoundError extends Error {
|
|
21
|
+
cause;
|
|
22
|
+
constructor(path, cause) {
|
|
23
|
+
// NOTE: includes the PATH (safe — a pointer, not a value), never the value.
|
|
24
|
+
super(`secret not found: '${path}'`);
|
|
25
|
+
this.name = 'SecretNotFoundError';
|
|
26
|
+
this.cause = cause;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
exports.SecretNotFoundError = SecretNotFoundError;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SECRET_REF_PREFIX = void 0;
|
|
4
|
+
exports.isSecretRef = isSecretRef;
|
|
5
|
+
exports.secretRefPath = secretRefPath;
|
|
6
|
+
exports.resolveSecretRefs = resolveSecretRefs;
|
|
7
|
+
/** The prefix that marks an env value as a secret REFERENCE (a pointer, safe to log/commit). */
|
|
8
|
+
exports.SECRET_REF_PREFIX = 'secret-ref:';
|
|
9
|
+
/** True if `value` is a secret reference (not a literal). */
|
|
10
|
+
function isSecretRef(value) {
|
|
11
|
+
return typeof value === 'string' && value.startsWith(exports.SECRET_REF_PREFIX);
|
|
12
|
+
}
|
|
13
|
+
/** Extract the secret path from a reference (`secret-ref:db/prod/pw` → `db/prod/pw`). */
|
|
14
|
+
function secretRefPath(ref) {
|
|
15
|
+
return ref.slice(exports.SECRET_REF_PREFIX.length);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Resolve every `secret-ref:` value in `env` via `provider`, returning a NEW bag where references
|
|
19
|
+
* are replaced by their real values and literals are copied unchanged. Async (a fetch is I/O).
|
|
20
|
+
*
|
|
21
|
+
* Fail-closed: a reference with an EMPTY path, or one the provider cannot resolve, THROWS — the
|
|
22
|
+
* error names the ENV KEY + PATH (safe pointers), never the value. Non-string values are copied
|
|
23
|
+
* as-is. The input bag is not mutated.
|
|
24
|
+
*/
|
|
25
|
+
async function resolveSecretRefs(env, provider) {
|
|
26
|
+
const out = {};
|
|
27
|
+
// Resolve sequentially-collected refs; a single failure aborts the whole resolution (fail-closed).
|
|
28
|
+
const refs = [];
|
|
29
|
+
for (const [key, value] of Object.entries(env)) {
|
|
30
|
+
if (isSecretRef(value)) {
|
|
31
|
+
const path = secretRefPath(value);
|
|
32
|
+
if (path.trim() === '') {
|
|
33
|
+
throw new Error(`invalid secret reference for env '${key}': empty path`);
|
|
34
|
+
}
|
|
35
|
+
refs.push({ key, path });
|
|
36
|
+
out[key] = undefined; // placeholder; filled below
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
out[key] = value;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const { key, path } of refs) {
|
|
43
|
+
let resolved;
|
|
44
|
+
try {
|
|
45
|
+
resolved = await provider.resolve(path);
|
|
46
|
+
}
|
|
47
|
+
catch (cause) {
|
|
48
|
+
// Include the key + path (safe pointers), NEVER a value.
|
|
49
|
+
throw new Error(`could not resolve secret for env '${key}' (path '${path}')`, { cause });
|
|
50
|
+
}
|
|
51
|
+
out[key] = resolved;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astram/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Astram framework — sealed security core (Identity, Authentication, Session, Risk, Authorization, Audit). ZERO framework deps — the portable decision brain (ADR-0003). The frozen public contract consumers build against; installed, not edited (ADR-0023).",
|
|
6
6
|
"type": "module",
|