@adaptic/backend 0.0.1057 → 0.0.1059
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/auth/authorization-map.cjs +306 -0
- package/auth/authorization-map.d.ts +143 -0
- package/auth/cortex-auth-checker.cjs +172 -0
- package/auth/cortex-auth-checker.d.ts +114 -0
- package/auth/credential-fields.cjs +51 -0
- package/auth/credential-fields.d.ts +19 -0
- package/auth/credential-redaction.cjs +134 -0
- package/auth/credential-redaction.d.ts +60 -0
- package/auth/graphql-auth-shadow.cjs +317 -0
- package/auth/graphql-auth-shadow.d.ts +194 -0
- package/auth/membership-write-authority.cjs +131 -0
- package/auth/membership-write-authority.d.ts +110 -0
- package/auth/mutation-authorization.cjs +376 -0
- package/auth/mutation-authorization.d.ts +261 -0
- package/auth/nested-write-inspector.cjs +189 -0
- package/auth/nested-write-inspector.d.ts +94 -0
- package/auth/nested-write-policy.cjs +189 -0
- package/auth/nested-write-policy.d.ts +99 -0
- package/auth/service-token.cjs +339 -0
- package/auth/service-token.d.ts +106 -0
- package/auth/tenancy-scope.cjs +736 -0
- package/auth/tenancy-scope.d.ts +347 -0
- package/auth/token-verifier.cjs +451 -0
- package/auth/token-verifier.d.ts +153 -0
- package/auth/totp.cjs +265 -0
- package/auth/totp.d.ts +111 -0
- package/auth/user-write-content.cjs +116 -0
- package/auth/user-write-content.d.ts +47 -0
- package/auth/ws-auth-context.cjs +75 -0
- package/auth/ws-auth-context.d.ts +69 -0
- package/config/jwtConfig.cjs +57 -0
- package/config/jwtConfig.d.ts +16 -0
- package/config/metrics.cjs +356 -0
- package/config/metrics.d.ts +128 -0
- package/config/persisted-queries.cjs +122 -0
- package/config/persisted-queries.d.ts +40 -0
- package/config/server-only-models.cjs +166 -0
- package/config/server-only-models.d.ts +89 -0
- package/config/tracing.d.ts +24 -0
- package/esm/auth/service-token.d.ts +12 -0
- package/esm/auth/service-token.mjs +27 -5
- package/esm/config/jwtConfig.mjs +5 -1
- package/generated/typegraphql-prisma/enhance.cjs +3 -3
- package/generated/typegraphql-prisma/index.cjs +6 -6
- package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
- package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
- package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
- package/middleware/audit-log-write-redaction.cjs +143 -0
- package/middleware/audit-log-write-redaction.d.ts +82 -0
- package/middleware/audit-logger.cjs +378 -0
- package/middleware/audit-logger.d.ts +158 -0
- package/middleware/audit-payload-guard.cjs +107 -0
- package/middleware/audit-payload-guard.d.ts +85 -0
- package/middleware/auth.cjs +66 -0
- package/middleware/auth.d.ts +41 -0
- package/middleware/credential-field-guard.cjs +514 -0
- package/middleware/credential-field-guard.d.ts +173 -0
- package/middleware/generated-type-names.cjs +77 -0
- package/middleware/generated-type-names.d.ts +44 -0
- package/middleware/graphql-validation-plugin.cjs +310 -0
- package/middleware/graphql-validation-plugin.d.ts +98 -0
- package/middleware/guard-log-throttle.cjs +89 -0
- package/middleware/guard-log-throttle.d.ts +80 -0
- package/middleware/index.cjs +57 -0
- package/middleware/index.d.ts +14 -0
- package/middleware/input-validator.cjs +220 -0
- package/middleware/input-validator.d.ts +63 -0
- package/middleware/mandate-version-validation.cjs +131 -0
- package/middleware/mandate-version-validation.d.ts +41 -0
- package/middleware/mutation-account-facts.cjs +223 -0
- package/middleware/mutation-account-facts.d.ts +143 -0
- package/middleware/mutation-auth-guard.cjs +536 -0
- package/middleware/mutation-auth-guard.d.ts +100 -0
- package/middleware/mutation-membership-facts.cjs +276 -0
- package/middleware/mutation-membership-facts.d.ts +133 -0
- package/middleware/mutation-tenant-facts.cjs +132 -0
- package/middleware/mutation-tenant-facts.d.ts +81 -0
- package/middleware/query-complexity.cjs +182 -0
- package/middleware/query-complexity.d.ts +56 -0
- package/middleware/rate-limiter.cjs +223 -0
- package/middleware/rate-limiter.d.ts +93 -0
- package/middleware/rate-tier.cjs +111 -0
- package/middleware/rate-tier.d.ts +56 -0
- package/middleware/soft-delete.cjs +175 -0
- package/middleware/soft-delete.d.ts +146 -0
- package/middleware/tenancy-scoping.cjs +229 -0
- package/middleware/tenancy-scoping.d.ts +67 -0
- package/middleware/trading-policy-audit.cjs +353 -0
- package/middleware/trading-policy-audit.d.ts +184 -0
- package/middleware/types.cjs +17 -0
- package/middleware/types.d.ts +87 -0
- package/middleware/validation-examples.cjs +398 -0
- package/middleware/validation-examples.d.ts +76 -0
- package/package.json +10 -2
- package/readers/index.cjs +15 -0
- package/readers/index.d.ts +10 -0
- package/readers/intraday-lane-prefs.cjs +76 -0
- package/readers/intraday-lane-prefs.d.ts +45 -0
- package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
- package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
- package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
- package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
- package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
- package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
- package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
- package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
- package/health.cjs +0 -274
- package/server.cjs +0 -607
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Credential-field guard: stored credentials resolve, and can be filtered or
|
|
4
|
+
* sorted on, only for a verified service principal.
|
|
5
|
+
*
|
|
6
|
+
* ## Why this exists
|
|
7
|
+
*
|
|
8
|
+
* The `/graphql` context admits a request that presents no bearer token as a
|
|
9
|
+
* null principal — context-level enforcement is staged per
|
|
10
|
+
* `docs/security/2026-08-23-graphql-auth-enforcement-runbook.md` because live
|
|
11
|
+
* callers still depend on that path. The generated Prisma types expose every
|
|
12
|
+
* scalar column as a plain field, including the broker API key and secret on
|
|
13
|
+
* `AlpacaAccount` and the OAuth, session and invite tokens on the auth models.
|
|
14
|
+
* With a null principal admitted, those columns are readable by anyone who can
|
|
15
|
+
* reach the endpoint.
|
|
16
|
+
*
|
|
17
|
+
* Hiding the field alone is not enough. A filter, sort or cursor over a
|
|
18
|
+
* credential column is an oracle: `where: { APISecret: { startsWith: "a" } }`
|
|
19
|
+
* answers "does any row match" without ever selecting the field, and a caller
|
|
20
|
+
* can walk the whole secret one character at a time. `groupBy` and the
|
|
21
|
+
* `_min` / `_max` aggregates return the column's value directly. So the guard
|
|
22
|
+
* covers every way a query can observe a credential, not just the field.
|
|
23
|
+
*
|
|
24
|
+
* A stored credential is only ever needed by a service acting for the
|
|
25
|
+
* platform — the engine placing an order with an account's key. No end user,
|
|
26
|
+
* admin session or anonymous caller needs the raw value, so the read surface
|
|
27
|
+
* admits `kind: "server"` only. Writes of a credential are governed by the
|
|
28
|
+
* mutation authentication guard, not here.
|
|
29
|
+
*
|
|
30
|
+
* ## What is guarded
|
|
31
|
+
*
|
|
32
|
+
* 1. **Output** — a credential field on its model type and on that model's
|
|
33
|
+
* `GroupBy` / `MinAggregate` / `MaxAggregate` output types, and on the
|
|
34
|
+
* `CreateManyAndReturn…` / `UpdateManyAndReturn…` row types a bulk write
|
|
35
|
+
* returns.
|
|
36
|
+
* 2. **Filter and sort input** — any argument that names a credential field:
|
|
37
|
+
* a key in the model's own `…Where…`, `…OrderBy…` or `…Having…` input types
|
|
38
|
+
* at any nesting depth (AND / OR / NOT, relation filters reached from other
|
|
39
|
+
* models), and a `by` / `distinct` value of the model's `ScalarFieldEnum`.
|
|
40
|
+
* 3. **Copies in audit payloads** — `AuditLog` JSON payloads hold credentials
|
|
41
|
+
* copied from mutation variables. The same middleware serves them redacted
|
|
42
|
+
* to user and anonymous principals and refuses those principals predicates
|
|
43
|
+
* over them; the rules and their reasons are in `audit-payload-guard`.
|
|
44
|
+
*
|
|
45
|
+
* ## Modes (`CREDENTIAL_FIELD_GUARD_MODE`, read on every request)
|
|
46
|
+
*
|
|
47
|
+
* - `enforce` — deny with `FORBIDDEN`. This is the default, and the value any
|
|
48
|
+
* unset or unrecognised setting resolves to: a guard whose configuration
|
|
49
|
+
* cannot be read must refuse, never admit.
|
|
50
|
+
* - `shadow` — resolve unchanged, but count and log every access `enforce`
|
|
51
|
+
* would deny. Exists only to confirm, before enforcing, that no legitimate
|
|
52
|
+
* caller reads a credential without a service principal.
|
|
53
|
+
* - `off` — no-op.
|
|
54
|
+
*
|
|
55
|
+
* @module middleware/credential-field-guard
|
|
56
|
+
*/
|
|
57
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
58
|
+
exports.CREDENTIAL_READ_REMEDY = exports.auditPayloadAccessTotal = exports.credentialFieldAccessTotal = exports.CREDENTIAL_FIELDS = void 0;
|
|
59
|
+
exports.credentialPredicateFieldsFor = credentialPredicateFieldsFor;
|
|
60
|
+
exports.credentialOutputFieldsFor = credentialOutputFieldsFor;
|
|
61
|
+
exports.credentialEnumValuesFor = credentialEnumValuesFor;
|
|
62
|
+
exports.findGuardedArgumentReferences = findGuardedArgumentReferences;
|
|
63
|
+
exports.findCredentialArgumentReferences = findCredentialArgumentReferences;
|
|
64
|
+
exports.findCredentialOutputField = findCredentialOutputField;
|
|
65
|
+
exports.getCredentialFieldGuardMode = getCredentialFieldGuardMode;
|
|
66
|
+
exports.credentialAccessForbidden = credentialAccessForbidden;
|
|
67
|
+
exports.createCredentialFieldGuardMiddleware = createCredentialFieldGuardMiddleware;
|
|
68
|
+
exports.resetCredentialFieldGuardLogThrottle = resetCredentialFieldGuardLogThrottle;
|
|
69
|
+
const graphql_1 = require("graphql");
|
|
70
|
+
const prom_client_1 = require("prom-client");
|
|
71
|
+
const credential_fields_1 = require("../auth/credential-fields.cjs");
|
|
72
|
+
Object.defineProperty(exports, "CREDENTIAL_FIELDS", { enumerable: true, get: function () { return credential_fields_1.CREDENTIAL_FIELDS; } });
|
|
73
|
+
const metrics_1 = require("../config/metrics.cjs");
|
|
74
|
+
const logger_1 = require("../utils/logger.cjs");
|
|
75
|
+
const audit_payload_guard_1 = require("./audit-payload-guard.cjs");
|
|
76
|
+
const generated_type_names_1 = require("./generated-type-names.cjs");
|
|
77
|
+
const guard_log_throttle_1 = require("./guard-log-throttle.cjs");
|
|
78
|
+
/** Where the generated schema exposes each credential column. */
|
|
79
|
+
const CREDENTIAL_TYPES = (0, generated_type_names_1.indexGeneratedTypes)(credential_fields_1.CREDENTIAL_FIELDS);
|
|
80
|
+
/**
|
|
81
|
+
* The credential fields an input type's keys can reference as a predicate,
|
|
82
|
+
* or `undefined` when it is not a credential model's predicate type.
|
|
83
|
+
*
|
|
84
|
+
* @internal Exported for the schema-coverage test, which walks every input
|
|
85
|
+
* type in the served schema and fails if a credential column appears in a
|
|
86
|
+
* predicate type this function does not claim.
|
|
87
|
+
*/
|
|
88
|
+
function credentialPredicateFieldsFor(typeName) {
|
|
89
|
+
return CREDENTIAL_TYPES.predicateFields(typeName);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The credential fields an output type exposes as values, or `undefined`.
|
|
93
|
+
*
|
|
94
|
+
* @internal Exported for the schema-coverage test (see above).
|
|
95
|
+
*/
|
|
96
|
+
function credentialOutputFieldsFor(typeName) {
|
|
97
|
+
return CREDENTIAL_TYPES.outputFields(typeName);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The credential values a `<Model>ScalarFieldEnum` can name, or `undefined`.
|
|
101
|
+
*
|
|
102
|
+
* @internal Exported for the schema-coverage test (see above).
|
|
103
|
+
*/
|
|
104
|
+
function credentialEnumValuesFor(typeName) {
|
|
105
|
+
return CREDENTIAL_TYPES.enumFields(typeName);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Walk one argument value alongside its GraphQL input type and collect every
|
|
109
|
+
* place it names a guarded column.
|
|
110
|
+
*
|
|
111
|
+
* Type-directed rather than key-directed: a key called `token` is a
|
|
112
|
+
* credential only inside a credential model's predicate type, so an unrelated
|
|
113
|
+
* input that happens to use the same key name is never flagged.
|
|
114
|
+
*/
|
|
115
|
+
function collectInputReferences(type, value, found) {
|
|
116
|
+
var _a, _b;
|
|
117
|
+
if (value === null || value === undefined)
|
|
118
|
+
return;
|
|
119
|
+
const nullable = (0, graphql_1.getNullableType)(type);
|
|
120
|
+
if (nullable instanceof graphql_1.GraphQLList) {
|
|
121
|
+
const inner = nullable.ofType;
|
|
122
|
+
const items = Array.isArray(value) ? value : [value];
|
|
123
|
+
for (const item of items)
|
|
124
|
+
collectInputReferences(inner, item, found);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (nullable instanceof graphql_1.GraphQLEnumType) {
|
|
128
|
+
if (typeof value !== 'string')
|
|
129
|
+
return;
|
|
130
|
+
if ((_a = CREDENTIAL_TYPES.enumFields(nullable.name)) === null || _a === void 0 ? void 0 : _a.has(value)) {
|
|
131
|
+
found.credential.push(`${nullable.name}.${value}`);
|
|
132
|
+
}
|
|
133
|
+
if ((_b = (0, audit_payload_guard_1.auditPayloadEnumFieldsFor)(nullable.name)) === null || _b === void 0 ? void 0 : _b.has(value)) {
|
|
134
|
+
found.auditPayload.push(`${nullable.name}.${value}`);
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (nullable instanceof graphql_1.GraphQLInputObjectType && typeof value === 'object') {
|
|
139
|
+
const credential = CREDENTIAL_TYPES.predicateFields(nullable.name);
|
|
140
|
+
const auditPayload = (0, audit_payload_guard_1.auditPayloadPredicateFieldsFor)(nullable.name);
|
|
141
|
+
const fieldDefs = nullable.getFields();
|
|
142
|
+
for (const [key, child] of Object.entries(value)) {
|
|
143
|
+
if (child === undefined)
|
|
144
|
+
continue;
|
|
145
|
+
if (credential === null || credential === void 0 ? void 0 : credential.has(key))
|
|
146
|
+
found.credential.push(`${nullable.name}.${key}`);
|
|
147
|
+
if (auditPayload === null || auditPayload === void 0 ? void 0 : auditPayload.has(key))
|
|
148
|
+
found.auditPayload.push(`${nullable.name}.${key}`);
|
|
149
|
+
const def = fieldDefs[key];
|
|
150
|
+
if (def)
|
|
151
|
+
collectInputReferences(def.type, child, found);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Every guarded column a field's arguments name. Both lists are empty when
|
|
157
|
+
* the field takes no arguments or names no guarded column.
|
|
158
|
+
*/
|
|
159
|
+
function findGuardedArgumentReferences(info, args) {
|
|
160
|
+
const found = { credential: [], auditPayload: [] };
|
|
161
|
+
if (!args || Object.keys(args).length === 0)
|
|
162
|
+
return found;
|
|
163
|
+
const fieldDef = info.parentType.getFields()[info.fieldName];
|
|
164
|
+
if (!fieldDef)
|
|
165
|
+
return found;
|
|
166
|
+
for (const argDef of fieldDef.args) {
|
|
167
|
+
collectInputReferences(argDef.type, args[argDef.name], found);
|
|
168
|
+
}
|
|
169
|
+
return found;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Every credential reference in a field's arguments, as `TypeName.field`
|
|
173
|
+
* strings. Empty when the field takes no arguments or names no credential.
|
|
174
|
+
*/
|
|
175
|
+
function findCredentialArgumentReferences(info, args) {
|
|
176
|
+
return findGuardedArgumentReferences(info, args).credential;
|
|
177
|
+
}
|
|
178
|
+
/** The credential field this resolver outputs, as `TypeName.field`, if any. */
|
|
179
|
+
function findCredentialOutputField(info) {
|
|
180
|
+
const fields = CREDENTIAL_TYPES.outputFields(info.parentType.name);
|
|
181
|
+
return (fields === null || fields === void 0 ? void 0 : fields.has(info.fieldName))
|
|
182
|
+
? `${info.parentType.name}.${info.fieldName}`
|
|
183
|
+
: undefined;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Resolve the guard mode from `CREDENTIAL_FIELD_GUARD_MODE`. Anything other
|
|
187
|
+
* than an explicit `shadow` or `off` enforces.
|
|
188
|
+
*/
|
|
189
|
+
function getCredentialFieldGuardMode() {
|
|
190
|
+
var _a;
|
|
191
|
+
const raw = ((_a = process.env.CREDENTIAL_FIELD_GUARD_MODE) !== null && _a !== void 0 ? _a : '').trim().toLowerCase();
|
|
192
|
+
if (raw === 'shadow' || raw === 'off')
|
|
193
|
+
return raw;
|
|
194
|
+
return 'enforce';
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Credential-surface accesses by surface, decision and principal kind. The
|
|
198
|
+
* `would_deny` series in `shadow` is the list of callers that enforcement
|
|
199
|
+
* would break; it must be empty of legitimate callers before enforcing.
|
|
200
|
+
*/
|
|
201
|
+
exports.credentialFieldAccessTotal = new prom_client_1.Counter({
|
|
202
|
+
name: 'graphql_credential_field_access_total',
|
|
203
|
+
help: 'Reads of, or predicates over, stored credential columns on /graphql, by ' +
|
|
204
|
+
'surface (output | argument), decision (allowed | would_deny | denied) and ' +
|
|
205
|
+
'principal kind (server | admin | user | none). Only kind=server is allowed.',
|
|
206
|
+
labelNames: ['surface', 'decision', 'principal_kind'],
|
|
207
|
+
registers: [metrics_1.metricsRegistry],
|
|
208
|
+
});
|
|
209
|
+
/**
|
|
210
|
+
* Audit payload accesses by principals that read payloads redacted (user and
|
|
211
|
+
* anonymous). Reads (`output`) are counted by what redaction did to them;
|
|
212
|
+
* predicates (`argument`) by whether they were refused. In `shadow`,
|
|
213
|
+
* `would_redact` with `carried_value="true"` counts reads that served a stored
|
|
214
|
+
* credential value — the exposure enforcement closes.
|
|
215
|
+
*/
|
|
216
|
+
exports.auditPayloadAccessTotal = new prom_client_1.Counter({
|
|
217
|
+
name: 'graphql_audit_payload_access_total',
|
|
218
|
+
help: 'Reads of, or predicates over, AuditLog JSON payload columns on /graphql by a principal ' +
|
|
219
|
+
'that reads them redacted (user | none), by surface (output | argument), decision ' +
|
|
220
|
+
'(unchanged | redacted | would_redact | denied | would_deny), principal kind, and whether ' +
|
|
221
|
+
'a replaced value held anything (carried_value: true | false | n/a).',
|
|
222
|
+
labelNames: ['surface', 'decision', 'principal_kind', 'carried_value'],
|
|
223
|
+
registers: [metrics_1.metricsRegistry],
|
|
224
|
+
});
|
|
225
|
+
/**
|
|
226
|
+
* Longest caller-supplied value (forwarded chain, user agent, operation name,
|
|
227
|
+
* service subject) a log line or throttle key keeps, in characters.
|
|
228
|
+
*/
|
|
229
|
+
const MAX_ATTRIBUTION_LENGTH = 256;
|
|
230
|
+
/** Truncate a caller-supplied value so a padded one cannot bloat the log or the throttle. */
|
|
231
|
+
function bounded(value) {
|
|
232
|
+
return value.slice(0, MAX_ATTRIBUTION_LENGTH);
|
|
233
|
+
}
|
|
234
|
+
/** Throttle window for the identity log line, per distinct caller key. */
|
|
235
|
+
const LOG_THROTTLE_MS = 10 * 60 * 1000;
|
|
236
|
+
/**
|
|
237
|
+
* Distinct caller keys one scope (principal kind plus connection address) may
|
|
238
|
+
* log per window. Well above the handful of callers one edge address carries;
|
|
239
|
+
* a scope that spends it is rotating caller-supplied values, and says so.
|
|
240
|
+
*/
|
|
241
|
+
const LOG_KEYS_PER_SCOPE = 256;
|
|
242
|
+
/** Distinct scopes the throttle tracks per window. */
|
|
243
|
+
const LOG_MAX_SCOPES = 64;
|
|
244
|
+
const logThrottle = new guard_log_throttle_1.GuardLogThrottle({
|
|
245
|
+
windowMs: LOG_THROTTLE_MS,
|
|
246
|
+
keysPerScope: LOG_KEYS_PER_SCOPE,
|
|
247
|
+
maxScopes: LOG_MAX_SCOPES,
|
|
248
|
+
});
|
|
249
|
+
/**
|
|
250
|
+
* Charge one decision line to the throttle. Returns whether to write the line;
|
|
251
|
+
* when the scope has just spent its budget, writes the scope's single overflow
|
|
252
|
+
* notice instead and returns false.
|
|
253
|
+
*/
|
|
254
|
+
function admitLogLine(scope, key, nowMs) {
|
|
255
|
+
const verdict = logThrottle.admit(scope, key, nowMs);
|
|
256
|
+
if (verdict.action === 'log')
|
|
257
|
+
return true;
|
|
258
|
+
if (verdict.action === 'overflow') {
|
|
259
|
+
logger_1.logger.warn('[credential-field-guard] decision log budget spent for a caller scope', {
|
|
260
|
+
scope: verdict.scope,
|
|
261
|
+
keysPerScope: LOG_KEYS_PER_SCOPE,
|
|
262
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
263
|
+
consequence: 'further distinct callers in this scope are not logged until the window ends; ' +
|
|
264
|
+
'the decision counters still count every access',
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
/** Message for a credential column reached by a non-service principal. */
|
|
270
|
+
const CREDENTIAL_ACCESS_MESSAGE = '[credential-field-guard] credential access by a non-service principal';
|
|
271
|
+
/** Message for a predicate over an audit payload by a principal that reads it redacted. */
|
|
272
|
+
const AUDIT_PAYLOAD_PREDICATE_MESSAGE = '[credential-field-guard] audit payload predicate by a principal that reads payloads redacted';
|
|
273
|
+
/** Audit payload key paths one log line lists; the count is always logged. */
|
|
274
|
+
const MAX_LOGGED_PATHS = 16;
|
|
275
|
+
/** Log a denied or would-deny access at most once per caller key per window. */
|
|
276
|
+
function logDecision(message, decision, surface, references, principal, info, request, nowMs) {
|
|
277
|
+
var _a, _b, _c, _d;
|
|
278
|
+
const operationName = bounded((_c = (_b = (_a = info.operation) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : '<unnamed>');
|
|
279
|
+
const userAgent = bounded(headerValue((_d = request === null || request === void 0 ? void 0 : request.headers) === null || _d === void 0 ? void 0 : _d['user-agent']));
|
|
280
|
+
// The source is part of the key: two callers sending the same operation
|
|
281
|
+
// with the same user agent (every Node `fetch` sends `node`) are different
|
|
282
|
+
// callers, and a key without the source logs only the first of them per
|
|
283
|
+
// window — which is exactly the attribution a pre-enforcement review of the
|
|
284
|
+
// would-deny set depends on. The connection address scopes the key's budget
|
|
285
|
+
// (the caller cannot set it); the forwarded chain, which the caller can,
|
|
286
|
+
// only distinguishes keys inside that budget.
|
|
287
|
+
const source = callerSource(request);
|
|
288
|
+
const referenceKey = [...new Set(references)].sort().join(',');
|
|
289
|
+
const key = `${decision}|${surface}|${referenceKey}|${operationName}|${userAgent}|${source.forwardedFor}`;
|
|
290
|
+
if (!admitLogLine(`${principal}|${source.ip}`, key, nowMs))
|
|
291
|
+
return;
|
|
292
|
+
logger_1.logger.warn(message, {
|
|
293
|
+
decision,
|
|
294
|
+
surface,
|
|
295
|
+
references,
|
|
296
|
+
principalKind: principal,
|
|
297
|
+
operationName,
|
|
298
|
+
ip: source.ip,
|
|
299
|
+
forwardedFor: source.forwardedFor,
|
|
300
|
+
userAgent,
|
|
301
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Log a service principal's credential read at most once per caller key per
|
|
306
|
+
* window.
|
|
307
|
+
*
|
|
308
|
+
* Every holder of the service secret is `kind: "server"`, so the metric alone
|
|
309
|
+
* cannot say WHICH holder read a broker key. The signed credential's `sub`
|
|
310
|
+
* (`adaptic-engine:<host>:<pid>`, `adaptic-platform:…`, an operator toolkit's
|
|
311
|
+
* `adaptic-audit:…`) can, and it is what an operator needs to tell a known
|
|
312
|
+
* service from a leaked secret. It goes to the log, not the metric label,
|
|
313
|
+
* because host:pid is unbounded. A static `SERVER_AUTH_TOKEN` names no caller
|
|
314
|
+
* and logs as `<unattributed>`.
|
|
315
|
+
*/
|
|
316
|
+
function logServiceRead(sub, reference, info, request, nowMs) {
|
|
317
|
+
var _a, _b, _c;
|
|
318
|
+
const operationName = bounded((_c = (_b = (_a = info.operation) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : '<unnamed>');
|
|
319
|
+
const caller = bounded(sub !== null && sub !== void 0 ? sub : '<unattributed>');
|
|
320
|
+
const source = callerSource(request);
|
|
321
|
+
const key = `allowed|${caller}|${reference}|${operationName}|${source.forwardedFor}`;
|
|
322
|
+
if (!admitLogLine(`server|${source.ip}`, key, nowMs))
|
|
323
|
+
return;
|
|
324
|
+
logger_1.logger.info('[credential-field-guard] credential read by a service principal', {
|
|
325
|
+
decision: 'allowed',
|
|
326
|
+
serviceSub: caller,
|
|
327
|
+
reference,
|
|
328
|
+
operationName,
|
|
329
|
+
ip: source.ip,
|
|
330
|
+
forwardedFor: source.forwardedFor,
|
|
331
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Log an audit payload read that redaction changes, or would change, at most
|
|
336
|
+
* once per caller key per window. The line names the key paths that held
|
|
337
|
+
* credentials, never their values.
|
|
338
|
+
*/
|
|
339
|
+
function logAuditPayloadRead(decision, reference, paths, principal, info, request, nowMs) {
|
|
340
|
+
var _a, _b, _c, _d;
|
|
341
|
+
const operationName = bounded((_c = (_b = (_a = info.operation) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : '<unnamed>');
|
|
342
|
+
const userAgent = bounded(headerValue((_d = request === null || request === void 0 ? void 0 : request.headers) === null || _d === void 0 ? void 0 : _d['user-agent']));
|
|
343
|
+
const source = callerSource(request);
|
|
344
|
+
const key = `payload|${decision}|${reference}|${operationName}|${userAgent}|${source.forwardedFor}`;
|
|
345
|
+
if (!admitLogLine(`${principal}|${source.ip}`, key, nowMs))
|
|
346
|
+
return;
|
|
347
|
+
logger_1.logger.warn('[credential-field-guard] audit payload holding credentials read by a principal that reads payloads redacted', {
|
|
348
|
+
decision,
|
|
349
|
+
reference,
|
|
350
|
+
credentialPaths: paths.slice(0, MAX_LOGGED_PATHS).map((p) => bounded(p.path)),
|
|
351
|
+
credentialPathCount: paths.length,
|
|
352
|
+
carriedValue: paths.some((p) => p.carriesValue),
|
|
353
|
+
principalKind: principal,
|
|
354
|
+
operationName,
|
|
355
|
+
ip: source.ip,
|
|
356
|
+
forwardedFor: source.forwardedFor,
|
|
357
|
+
userAgent,
|
|
358
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Where a request came from, as far as this process can tell.
|
|
363
|
+
*
|
|
364
|
+
* `req.ip` is the address `trust proxy` resolves, and behind the production
|
|
365
|
+
* edge it resolves to the edge's own pool (an operator's laptop and a hosted
|
|
366
|
+
* service log the same handful of addresses), so on its own it cannot tell
|
|
367
|
+
* callers apart. The raw `X-Forwarded-For` chain carries the hops the edge
|
|
368
|
+
* saw. It is caller-supplied at its left end, so it is attribution evidence
|
|
369
|
+
* for an operator reading the log, never an identity the guard decides on.
|
|
370
|
+
*/
|
|
371
|
+
function callerSource(request) {
|
|
372
|
+
var _a, _b;
|
|
373
|
+
return {
|
|
374
|
+
ip: bounded((_a = request === null || request === void 0 ? void 0 : request.ip) !== null && _a !== void 0 ? _a : '<none>'),
|
|
375
|
+
forwardedFor: bounded(headerValue((_b = request === null || request === void 0 ? void 0 : request.headers) === null || _b === void 0 ? void 0 : _b['x-forwarded-for'])),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function headerValue(value) {
|
|
379
|
+
if (Array.isArray(value))
|
|
380
|
+
return value.join(',');
|
|
381
|
+
return value !== null && value !== void 0 ? value : '<none>';
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* What a refused credential reader should do next. The refusal is a
|
|
385
|
+
* deliberate, recorded control rather than a fault, and the text says so:
|
|
386
|
+
* callers who read it as an outage will otherwise ask for the guard to be
|
|
387
|
+
* relaxed instead of presenting a service identity.
|
|
388
|
+
*/
|
|
389
|
+
exports.CREDENTIAL_READ_REMEDY = 'Refused deliberately: since 2026-09-26 14:00Z stored broker credentials are readable ' +
|
|
390
|
+
'only by a verified service principal (a control on the risk register). Run operator ' +
|
|
391
|
+
'tools through the service-identity wrapper (scripts/account-audit/run-with-identity.mjs ' +
|
|
392
|
+
'in the adapticai/mono repo; it needs a mono checkout, which backend alone does not ' +
|
|
393
|
+
'include), or request a service principal from research engineering. Do not ask ' +
|
|
394
|
+
'for this guard to be returned to shadow.';
|
|
395
|
+
/**
|
|
396
|
+
* The refusal for a credential column reached by a non-service principal.
|
|
397
|
+
* Exported for the mutation authorization guard, which applies the predicate
|
|
398
|
+
* rule itself, ahead of this middleware (see `mutation-auth-guard`).
|
|
399
|
+
*/
|
|
400
|
+
function credentialAccessForbidden(references) {
|
|
401
|
+
return new graphql_1.GraphQLError('Forbidden: stored credentials are readable only by a service principal', {
|
|
402
|
+
extensions: {
|
|
403
|
+
code: 'FORBIDDEN',
|
|
404
|
+
references,
|
|
405
|
+
remedy: exports.CREDENTIAL_READ_REMEDY,
|
|
406
|
+
http: { status: 403 },
|
|
407
|
+
},
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
function forbiddenAuditPayloadPredicate(references) {
|
|
411
|
+
return new graphql_1.GraphQLError('Forbidden: audit payload columns can be filtered, sorted or grouped on only by a ' +
|
|
412
|
+
'service or admin principal', {
|
|
413
|
+
extensions: {
|
|
414
|
+
code: 'FORBIDDEN',
|
|
415
|
+
references,
|
|
416
|
+
http: { status: 403 },
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Create the TypeGraphQL global middleware that guards credential columns.
|
|
422
|
+
*
|
|
423
|
+
* Runs on every field. The hot path — a non-credential field with no
|
|
424
|
+
* arguments, or any field for a service principal — returns after a map
|
|
425
|
+
* lookup.
|
|
426
|
+
*
|
|
427
|
+
* @param options - Optional overrides for tests.
|
|
428
|
+
* @returns A {@link MiddlewareFn} for `buildSchema({ globalMiddlewares })`.
|
|
429
|
+
*/
|
|
430
|
+
function createCredentialFieldGuardMiddleware(options = {}) {
|
|
431
|
+
var _a, _b;
|
|
432
|
+
const resolveMode = (_a = options.modeProvider) !== null && _a !== void 0 ? _a : getCredentialFieldGuardMode;
|
|
433
|
+
const now = (_b = options.now) !== null && _b !== void 0 ? _b : Date.now;
|
|
434
|
+
return async ({ context, args, info }, next) => {
|
|
435
|
+
var _a, _b;
|
|
436
|
+
const proceed = () => next();
|
|
437
|
+
const output = findCredentialOutputField(info);
|
|
438
|
+
const principal = (_a = context.principal) !== null && _a !== void 0 ? _a : null;
|
|
439
|
+
if ((principal === null || principal === void 0 ? void 0 : principal.kind) === 'server') {
|
|
440
|
+
if (output && resolveMode() !== 'off') {
|
|
441
|
+
exports.credentialFieldAccessTotal.inc({
|
|
442
|
+
surface: 'output',
|
|
443
|
+
decision: 'allowed',
|
|
444
|
+
principal_kind: 'server',
|
|
445
|
+
});
|
|
446
|
+
logServiceRead(principal.sub, output, info, context.req, now());
|
|
447
|
+
}
|
|
448
|
+
return proceed();
|
|
449
|
+
}
|
|
450
|
+
const references = findGuardedArgumentReferences(info, args);
|
|
451
|
+
// Admins read audit payloads as stored, so only user and anonymous
|
|
452
|
+
// principals reach the payload rules below.
|
|
453
|
+
const payloadReader = !(0, audit_payload_guard_1.readsAuditPayloadRaw)(principal);
|
|
454
|
+
const payloadOutput = payloadReader ? (0, audit_payload_guard_1.auditPayloadOutputField)(info) : undefined;
|
|
455
|
+
const payloadRefs = payloadReader ? references.auditPayload : [];
|
|
456
|
+
if (!output &&
|
|
457
|
+
references.credential.length === 0 &&
|
|
458
|
+
!payloadOutput &&
|
|
459
|
+
payloadRefs.length === 0) {
|
|
460
|
+
return proceed();
|
|
461
|
+
}
|
|
462
|
+
const mode = resolveMode();
|
|
463
|
+
if (mode === 'off')
|
|
464
|
+
return proceed();
|
|
465
|
+
const principalLabel = (_b = principal === null || principal === void 0 ? void 0 : principal.kind) !== null && _b !== void 0 ? _b : 'none';
|
|
466
|
+
const nowMs = now();
|
|
467
|
+
const refusal = mode === 'enforce' ? 'denied' : 'would_deny';
|
|
468
|
+
if (output || references.credential.length > 0) {
|
|
469
|
+
const surface = output ? 'output' : 'argument';
|
|
470
|
+
const credentialRefs = output ? [output, ...references.credential] : references.credential;
|
|
471
|
+
exports.credentialFieldAccessTotal.inc({
|
|
472
|
+
surface,
|
|
473
|
+
decision: refusal,
|
|
474
|
+
principal_kind: principalLabel,
|
|
475
|
+
});
|
|
476
|
+
logDecision(CREDENTIAL_ACCESS_MESSAGE, refusal, surface, credentialRefs, principalLabel, info, context.req, nowMs);
|
|
477
|
+
if (mode === 'enforce')
|
|
478
|
+
throw credentialAccessForbidden(credentialRefs);
|
|
479
|
+
}
|
|
480
|
+
if (payloadRefs.length > 0) {
|
|
481
|
+
exports.auditPayloadAccessTotal.inc({
|
|
482
|
+
surface: 'argument',
|
|
483
|
+
decision: refusal,
|
|
484
|
+
principal_kind: principalLabel,
|
|
485
|
+
carried_value: 'n/a',
|
|
486
|
+
});
|
|
487
|
+
logDecision(AUDIT_PAYLOAD_PREDICATE_MESSAGE, refusal, 'argument', payloadRefs, principalLabel, info, context.req, nowMs);
|
|
488
|
+
if (mode === 'enforce')
|
|
489
|
+
throw forbiddenAuditPayloadPredicate(payloadRefs);
|
|
490
|
+
}
|
|
491
|
+
if (!payloadOutput)
|
|
492
|
+
return proceed();
|
|
493
|
+
const value = await proceed();
|
|
494
|
+
const { redacted, paths } = (0, audit_payload_guard_1.redactAuditPayload)(value);
|
|
495
|
+
const decision = paths.length === 0 ? 'unchanged' : mode === 'enforce' ? 'redacted' : 'would_redact';
|
|
496
|
+
exports.auditPayloadAccessTotal.inc({
|
|
497
|
+
surface: 'output',
|
|
498
|
+
decision,
|
|
499
|
+
principal_kind: principalLabel,
|
|
500
|
+
carried_value: String(paths.some((p) => p.carriesValue)),
|
|
501
|
+
});
|
|
502
|
+
if (paths.length > 0) {
|
|
503
|
+
logAuditPayloadRead(decision, payloadOutput, paths, principalLabel, info, context.req, nowMs);
|
|
504
|
+
}
|
|
505
|
+
// Under enforce the redacted copy is served even when no path was found:
|
|
506
|
+
// the copy is what the rule promises, the path list only describes it.
|
|
507
|
+
return mode === 'enforce' ? redacted : value;
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
/** @internal Test hook: forget the log throttle state. */
|
|
511
|
+
function resetCredentialFieldGuardLogThrottle() {
|
|
512
|
+
logThrottle.reset();
|
|
513
|
+
}
|
|
514
|
+
//# sourceMappingURL=credential-field-guard.js.map
|