@adaptic/backend-legacy 0.0.1038 → 0.0.1040

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.
Files changed (85) hide show
  1. package/esm/auth/authorization-map.d.ts +13 -1
  2. package/esm/auth/authorization-map.d.ts.map +1 -1
  3. package/esm/auth/authorization-map.js.map +1 -1
  4. package/esm/auth/authorization-map.mjs +14 -1
  5. package/esm/auth/credential-fields.d.ts +19 -0
  6. package/esm/auth/credential-fields.d.ts.map +1 -0
  7. package/esm/auth/credential-fields.js.map +1 -0
  8. package/esm/auth/credential-fields.mjs +42 -0
  9. package/esm/auth/credential-redaction.d.ts +56 -0
  10. package/esm/auth/credential-redaction.d.ts.map +1 -0
  11. package/esm/auth/credential-redaction.js.map +1 -0
  12. package/esm/auth/credential-redaction.mjs +99 -0
  13. package/esm/auth/mutation-authorization.d.ts +206 -0
  14. package/esm/auth/mutation-authorization.d.ts.map +1 -0
  15. package/esm/auth/mutation-authorization.js.map +1 -0
  16. package/esm/auth/mutation-authorization.mjs +271 -0
  17. package/esm/auth/nested-write-inspector.d.ts +94 -0
  18. package/esm/auth/nested-write-inspector.d.ts.map +1 -0
  19. package/esm/auth/nested-write-inspector.js.map +1 -0
  20. package/esm/auth/nested-write-inspector.mjs +185 -0
  21. package/esm/auth/nested-write-policy.d.ts +95 -0
  22. package/esm/auth/nested-write-policy.d.ts.map +1 -0
  23. package/esm/auth/nested-write-policy.js.map +1 -0
  24. package/esm/auth/nested-write-policy.mjs +154 -0
  25. package/esm/auth/service-token.d.ts +11 -1
  26. package/esm/auth/service-token.d.ts.map +1 -1
  27. package/esm/auth/service-token.js.map +1 -1
  28. package/esm/auth/service-token.mjs +31 -5
  29. package/esm/auth/token-verifier.d.ts +9 -1
  30. package/esm/auth/token-verifier.d.ts.map +1 -1
  31. package/esm/auth/token-verifier.js.map +1 -1
  32. package/esm/auth/user-write-content.d.ts +41 -0
  33. package/esm/auth/user-write-content.d.ts.map +1 -0
  34. package/esm/auth/user-write-content.js.map +1 -0
  35. package/esm/auth/user-write-content.mjs +100 -0
  36. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +55 -0
  37. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts.map +1 -0
  38. package/esm/middleware/__tests__/credential-field-coverage.harness.js.map +1 -0
  39. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +438 -0
  40. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +49 -0
  41. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -0
  42. package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -0
  43. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +402 -0
  44. package/esm/middleware/__tests__/ts-node-harness.d.ts +10 -0
  45. package/esm/middleware/__tests__/ts-node-harness.d.ts.map +1 -0
  46. package/esm/middleware/__tests__/ts-node-harness.js.map +1 -0
  47. package/esm/middleware/__tests__/ts-node-harness.mjs +71 -0
  48. package/esm/middleware/audit-logger.d.ts +18 -1
  49. package/esm/middleware/audit-logger.d.ts.map +1 -1
  50. package/esm/middleware/audit-logger.js.map +1 -1
  51. package/esm/middleware/audit-logger.mjs +36 -13
  52. package/esm/middleware/audit-payload-guard.d.ts +85 -0
  53. package/esm/middleware/audit-payload-guard.d.ts.map +1 -0
  54. package/esm/middleware/audit-payload-guard.js.map +1 -0
  55. package/esm/middleware/audit-payload-guard.mjs +97 -0
  56. package/esm/middleware/credential-field-guard.d.ts +55 -7
  57. package/esm/middleware/credential-field-guard.d.ts.map +1 -1
  58. package/esm/middleware/credential-field-guard.js.map +1 -1
  59. package/esm/middleware/credential-field-guard.mjs +275 -106
  60. package/esm/middleware/generated-type-names.d.ts +44 -0
  61. package/esm/middleware/generated-type-names.d.ts.map +1 -0
  62. package/esm/middleware/generated-type-names.js.map +1 -0
  63. package/esm/middleware/generated-type-names.mjs +73 -0
  64. package/esm/middleware/guard-log-throttle.d.ts +80 -0
  65. package/esm/middleware/guard-log-throttle.d.ts.map +1 -0
  66. package/esm/middleware/guard-log-throttle.js.map +1 -0
  67. package/esm/middleware/guard-log-throttle.mjs +87 -0
  68. package/esm/middleware/mutation-account-facts.d.ts +140 -0
  69. package/esm/middleware/mutation-account-facts.d.ts.map +1 -0
  70. package/esm/middleware/mutation-account-facts.js.map +1 -0
  71. package/esm/middleware/mutation-account-facts.mjs +212 -0
  72. package/esm/middleware/mutation-auth-guard.d.ts +82 -0
  73. package/esm/middleware/mutation-auth-guard.d.ts.map +1 -0
  74. package/esm/middleware/mutation-auth-guard.js.map +1 -0
  75. package/esm/middleware/mutation-auth-guard.mjs +425 -0
  76. package/esm/middleware/mutation-tenant-facts.d.ts +58 -0
  77. package/esm/middleware/mutation-tenant-facts.d.ts.map +1 -0
  78. package/esm/middleware/mutation-tenant-facts.js.map +1 -0
  79. package/esm/middleware/mutation-tenant-facts.mjs +75 -0
  80. package/esm/middleware/trading-policy-audit.d.ts +172 -0
  81. package/esm/middleware/trading-policy-audit.d.ts.map +1 -0
  82. package/esm/middleware/trading-policy-audit.js.map +1 -0
  83. package/esm/middleware/trading-policy-audit.mjs +309 -0
  84. package/package.json +1 -1
  85. package/server.cjs +27 -2
@@ -29,11 +29,17 @@
29
29
  * ## What is guarded
30
30
  *
31
31
  * 1. **Output** — a credential field on its model type and on that model's
32
- * `GroupBy` / `MinAggregate` / `MaxAggregate` output types.
32
+ * `GroupBy` / `MinAggregate` / `MaxAggregate` output types, and on the
33
+ * `CreateManyAndReturn…` / `UpdateManyAndReturn…` row types a bulk write
34
+ * returns.
33
35
  * 2. **Filter and sort input** — any argument that names a credential field:
34
36
  * a key in the model's own `…Where…`, `…OrderBy…` or `…Having…` input types
35
37
  * at any nesting depth (AND / OR / NOT, relation filters reached from other
36
38
  * models), and a `by` / `distinct` value of the model's `ScalarFieldEnum`.
39
+ * 3. **Copies in audit payloads** — `AuditLog` JSON payloads hold credentials
40
+ * copied from mutation variables. The same middleware serves them redacted
41
+ * to user and anonymous principals and refuses those principals predicates
42
+ * over them; the rules and their reasons are in `audit-payload-guard`.
37
43
  *
38
44
  * ## Modes (`CREDENTIAL_FIELD_GUARD_MODE`, read on every request)
39
45
  *
@@ -49,88 +55,49 @@
49
55
  */
50
56
  import { GraphQLEnumType, GraphQLError, GraphQLInputObjectType, GraphQLList, getNullableType, } from 'graphql';
51
57
  import { Counter } from 'prom-client';
58
+ import { CREDENTIAL_FIELDS } from '../auth/credential-fields.mjs';
52
59
  import { metricsRegistry } from '../config/metrics.mjs';
53
60
  import { logger } from '../utils/logger.mjs';
61
+ import { auditPayloadOutputField, auditPayloadEnumFieldsFor, auditPayloadPredicateFieldsFor, readsAuditPayloadRaw, redactAuditPayload, } from './audit-payload-guard.mjs';
62
+ import { indexGeneratedTypes } from './generated-type-names.mjs';
63
+ import { GuardLogThrottle } from './guard-log-throttle.mjs';
54
64
  /**
55
- * Every stored credential column, by Prisma model. A column belongs here when
56
- * its value lets the holder act as someone: a broker or vendor API secret, an
57
- * OAuth access / refresh / id token, a session token, a one-time verification
58
- * or invite token.
65
+ * The stored credential columns this guard serves to a service principal
66
+ * only. Defined in `auth/credential-fields`, re-exported for existing callers.
59
67
  */
60
- export const CREDENTIAL_FIELDS = new Map([
61
- ['AlpacaAccount', new Set(['APIKey', 'APISecret'])],
62
- ['BrokerageAccount', new Set(['apiKey', 'apiSecret'])],
63
- [
64
- 'LlmConfiguration',
65
- new Set([
66
- 'openaiApiKey',
67
- 'anthropicApiKey',
68
- 'deepseekApiKey',
69
- 'kimiApiKey',
70
- 'qwenApiKey',
71
- 'xaiApiKey',
72
- 'geminiApiKey',
73
- 'deepinfraApiKey',
74
- ]),
75
- ],
76
- ['User', new Set(['openaiAPIKey'])],
77
- ['Account', new Set(['refresh_token', 'access_token', 'id_token'])],
78
- ['LinkedProvider', new Set(['accessToken', 'refreshToken'])],
79
- ['Session', new Set(['sessionToken'])],
80
- ['VerificationToken', new Set(['token'])],
81
- ['AccountLinkingRequest', new Set(['verificationToken'])],
82
- ['InviteToken', new Set(['token'])],
83
- ]);
68
+ export { CREDENTIAL_FIELDS };
69
+ /** Where the generated schema exposes each credential column. */
70
+ const CREDENTIAL_TYPES = indexGeneratedTypes(CREDENTIAL_FIELDS);
84
71
  /**
85
- * Output types that carry a model's column VALUES. The `Count` aggregate is
86
- * absent on purpose: it returns how many rows are non-null, never a value.
87
- */
88
- const VALUE_OUTPUT_SUFFIXES = ['', 'GroupBy', 'MinAggregate', 'MaxAggregate'];
89
- /** Output type name → the credential fields it exposes. */
90
- const OUTPUT_TYPE_FIELDS = new Map([...CREDENTIAL_FIELDS].flatMap(([model, fields]) => VALUE_OUTPUT_SUFFIXES.map((suffix) => [`${model}${suffix}`, fields])));
91
- /**
92
- * Model names longest-first, so the prefix match below attributes
93
- * `AccountLinkingRequestWhereInput` to `AccountLinkingRequest`, not `Account`.
72
+ * The credential fields an input type's keys can reference as a predicate,
73
+ * or `undefined` when it is not a credential model's predicate type.
74
+ *
75
+ * @internal Exported for the schema-coverage test, which walks every input
76
+ * type in the served schema and fails if a credential column appears in a
77
+ * predicate type this function does not claim.
94
78
  */
95
- const MODELS_LONGEST_FIRST = [...CREDENTIAL_FIELDS.keys()].sort((a, b) => b.length - a.length);
79
+ export function credentialPredicateFieldsFor(typeName) {
80
+ return CREDENTIAL_TYPES.predicateFields(typeName);
81
+ }
96
82
  /**
97
- * Input-type name fragments that make a type a read predicate (filter, sort,
98
- * cursor, aggregate filter) rather than a write payload. A `…WhereUniqueInput`
99
- * is also how a mutation selects its row, so a credential key there is an
100
- * oracle on a write path too.
83
+ * The credential fields an output type exposes as values, or `undefined`.
84
+ *
85
+ * @internal Exported for the schema-coverage test (see above).
101
86
  */
102
- const PREDICATE_TYPE_FRAGMENTS = ['Where', 'OrderBy', 'Having'];
87
+ export function credentialOutputFieldsFor(typeName) {
88
+ return CREDENTIAL_TYPES.outputFields(typeName);
89
+ }
103
90
  /**
104
- * The credential fields a named input type can reference, when the type is
105
- * one of a credential model's own predicate types; otherwise `undefined`.
91
+ * The credential values a `<Model>ScalarFieldEnum` can name, or `undefined`.
106
92
  *
107
- * Generated names start with the model name followed by an upper-case letter
108
- * (`AlpacaAccountWhereInput`, `AlpacaAccountOrderByWithRelationInput`), so a
109
- * model named `Account` does not claim `AccountLinkingRequestWhereInput`.
93
+ * @internal Exported for the schema-coverage test (see above).
110
94
  */
111
- function predicateFieldsFor(typeName) {
112
- for (const model of MODELS_LONGEST_FIRST) {
113
- if (!typeName.startsWith(model))
114
- continue;
115
- const rest = typeName.slice(model.length);
116
- if (!/^[A-Z]/.test(rest))
117
- continue;
118
- if (!PREDICATE_TYPE_FRAGMENTS.some((f) => rest.includes(f)))
119
- return undefined;
120
- return CREDENTIAL_FIELDS.get(model);
121
- }
122
- return undefined;
123
- }
124
- /** The credential fields a `<Model>ScalarFieldEnum` can name, if it is one. */
125
- function enumFieldsFor(typeName) {
126
- const suffix = 'ScalarFieldEnum';
127
- if (!typeName.endsWith(suffix))
128
- return undefined;
129
- return CREDENTIAL_FIELDS.get(typeName.slice(0, -suffix.length));
95
+ export function credentialEnumValuesFor(typeName) {
96
+ return CREDENTIAL_TYPES.enumFields(typeName);
130
97
  }
131
98
  /**
132
99
  * Walk one argument value alongside its GraphQL input type and collect every
133
- * place it names a credential field, as `TypeName.field` strings.
100
+ * place it names a guarded column.
134
101
  *
135
102
  * Type-directed rather than key-directed: a key called `token` is a
136
103
  * credential only inside a credential model's predicate type, so an unrelated
@@ -148,20 +115,27 @@ function collectInputReferences(type, value, found) {
148
115
  return;
149
116
  }
150
117
  if (nullable instanceof GraphQLEnumType) {
151
- const fields = enumFieldsFor(nullable.name);
152
- if (fields && typeof value === 'string' && fields.has(value)) {
153
- found.push(`${nullable.name}.${value}`);
118
+ if (typeof value !== 'string')
119
+ return;
120
+ if (CREDENTIAL_TYPES.enumFields(nullable.name)?.has(value)) {
121
+ found.credential.push(`${nullable.name}.${value}`);
122
+ }
123
+ if (auditPayloadEnumFieldsFor(nullable.name)?.has(value)) {
124
+ found.auditPayload.push(`${nullable.name}.${value}`);
154
125
  }
155
126
  return;
156
127
  }
157
128
  if (nullable instanceof GraphQLInputObjectType && typeof value === 'object') {
158
- const guarded = predicateFieldsFor(nullable.name);
129
+ const credential = CREDENTIAL_TYPES.predicateFields(nullable.name);
130
+ const auditPayload = auditPayloadPredicateFieldsFor(nullable.name);
159
131
  const fieldDefs = nullable.getFields();
160
132
  for (const [key, child] of Object.entries(value)) {
161
133
  if (child === undefined)
162
134
  continue;
163
- if (guarded?.has(key))
164
- found.push(`${nullable.name}.${key}`);
135
+ if (credential?.has(key))
136
+ found.credential.push(`${nullable.name}.${key}`);
137
+ if (auditPayload?.has(key))
138
+ found.auditPayload.push(`${nullable.name}.${key}`);
165
139
  const def = fieldDefs[key];
166
140
  if (def)
167
141
  collectInputReferences(def.type, child, found);
@@ -169,11 +143,11 @@ function collectInputReferences(type, value, found) {
169
143
  }
170
144
  }
171
145
  /**
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.
146
+ * Every guarded column a field's arguments name. Both lists are empty when
147
+ * the field takes no arguments or names no guarded column.
174
148
  */
175
- export function findCredentialArgumentReferences(info, args) {
176
- const found = [];
149
+ export function findGuardedArgumentReferences(info, args) {
150
+ const found = { credential: [], auditPayload: [] };
177
151
  if (!args || Object.keys(args).length === 0)
178
152
  return found;
179
153
  const fieldDef = info.parentType.getFields()[info.fieldName];
@@ -184,9 +158,16 @@ export function findCredentialArgumentReferences(info, args) {
184
158
  }
185
159
  return found;
186
160
  }
161
+ /**
162
+ * Every credential reference in a field's arguments, as `TypeName.field`
163
+ * strings. Empty when the field takes no arguments or names no credential.
164
+ */
165
+ export function findCredentialArgumentReferences(info, args) {
166
+ return findGuardedArgumentReferences(info, args).credential;
167
+ }
187
168
  /** The credential field this resolver outputs, as `TypeName.field`, if any. */
188
169
  export function findCredentialOutputField(info) {
189
- const fields = OUTPUT_TYPE_FIELDS.get(info.parentType.name);
170
+ const fields = CREDENTIAL_TYPES.outputFields(info.parentType.name);
190
171
  return fields?.has(info.fieldName)
191
172
  ? `${info.parentType.name}.${info.fieldName}`
192
173
  : undefined;
@@ -214,33 +195,171 @@ export const credentialFieldAccessTotal = new Counter({
214
195
  labelNames: ['surface', 'decision', 'principal_kind'],
215
196
  registers: [metricsRegistry],
216
197
  });
198
+ /**
199
+ * Audit payload accesses by principals that read payloads redacted (user and
200
+ * anonymous). Reads (`output`) are counted by what redaction did to them;
201
+ * predicates (`argument`) by whether they were refused. In `shadow`,
202
+ * `would_redact` with `carried_value="true"` counts reads that served a stored
203
+ * credential value — the exposure enforcement closes.
204
+ */
205
+ export const auditPayloadAccessTotal = new Counter({
206
+ name: 'graphql_audit_payload_access_total',
207
+ help: 'Reads of, or predicates over, AuditLog JSON payload columns on /graphql by a principal ' +
208
+ 'that reads them redacted (user | none), by surface (output | argument), decision ' +
209
+ '(unchanged | redacted | would_redact | denied | would_deny), principal kind, and whether ' +
210
+ 'a replaced value held anything (carried_value: true | false | n/a).',
211
+ labelNames: ['surface', 'decision', 'principal_kind', 'carried_value'],
212
+ registers: [metricsRegistry],
213
+ });
214
+ /**
215
+ * Longest caller-supplied value (forwarded chain, user agent, operation name,
216
+ * service subject) a log line or throttle key keeps, in characters.
217
+ */
218
+ const MAX_ATTRIBUTION_LENGTH = 256;
219
+ /** Truncate a caller-supplied value so a padded one cannot bloat the log or the throttle. */
220
+ function bounded(value) {
221
+ return value.slice(0, MAX_ATTRIBUTION_LENGTH);
222
+ }
217
223
  /** Throttle window for the identity log line, per distinct caller key. */
218
224
  const LOG_THROTTLE_MS = 10 * 60 * 1000;
219
- /** Most distinct caller keys the throttle remembers before it resets. */
220
- const LOG_THROTTLE_MAX_KEYS = 5_000;
221
- const lastLoggedAt = new Map();
225
+ /**
226
+ * Distinct caller keys one scope (principal kind plus connection address) may
227
+ * log per window. Well above the handful of callers one edge address carries;
228
+ * a scope that spends it is rotating caller-supplied values, and says so.
229
+ */
230
+ const LOG_KEYS_PER_SCOPE = 256;
231
+ /** Distinct scopes the throttle tracks per window. */
232
+ const LOG_MAX_SCOPES = 64;
233
+ const logThrottle = new GuardLogThrottle({
234
+ windowMs: LOG_THROTTLE_MS,
235
+ keysPerScope: LOG_KEYS_PER_SCOPE,
236
+ maxScopes: LOG_MAX_SCOPES,
237
+ });
238
+ /**
239
+ * Charge one decision line to the throttle. Returns whether to write the line;
240
+ * when the scope has just spent its budget, writes the scope's single overflow
241
+ * notice instead and returns false.
242
+ */
243
+ function admitLogLine(scope, key, nowMs) {
244
+ const verdict = logThrottle.admit(scope, key, nowMs);
245
+ if (verdict.action === 'log')
246
+ return true;
247
+ if (verdict.action === 'overflow') {
248
+ logger.warn('[credential-field-guard] decision log budget spent for a caller scope', {
249
+ scope: verdict.scope,
250
+ keysPerScope: LOG_KEYS_PER_SCOPE,
251
+ dedupWindowMs: LOG_THROTTLE_MS,
252
+ consequence: 'further distinct callers in this scope are not logged until the window ends; ' +
253
+ 'the decision counters still count every access',
254
+ });
255
+ }
256
+ return false;
257
+ }
258
+ /** Message for a credential column reached by a non-service principal. */
259
+ const CREDENTIAL_ACCESS_MESSAGE = '[credential-field-guard] credential access by a non-service principal';
260
+ /** Message for a predicate over an audit payload by a principal that reads it redacted. */
261
+ const AUDIT_PAYLOAD_PREDICATE_MESSAGE = '[credential-field-guard] audit payload predicate by a principal that reads payloads redacted';
262
+ /** Audit payload key paths one log line lists; the count is always logged. */
263
+ const MAX_LOGGED_PATHS = 16;
222
264
  /** Log a denied or would-deny access at most once per caller key per window. */
223
- function logDecision(decision, surface, references, principal, info, request, nowMs) {
224
- const operationName = info.operation?.name?.value ?? '<unnamed>';
225
- const userAgent = headerValue(request?.headers?.['user-agent']);
226
- const key = `${decision}|${surface}|${principal}|${references.join(',')}|${operationName}|${userAgent}`;
227
- const previous = lastLoggedAt.get(key);
228
- if (previous !== undefined && nowMs - previous < LOG_THROTTLE_MS)
265
+ function logDecision(message, decision, surface, references, principal, info, request, nowMs) {
266
+ const operationName = bounded(info.operation?.name?.value ?? '<unnamed>');
267
+ const userAgent = bounded(headerValue(request?.headers?.['user-agent']));
268
+ // The source is part of the key: two callers sending the same operation
269
+ // with the same user agent (every Node `fetch` sends `node`) are different
270
+ // callers, and a key without the source logs only the first of them per
271
+ // window — which is exactly the attribution a pre-enforcement review of the
272
+ // would-deny set depends on. The connection address scopes the key's budget
273
+ // (the caller cannot set it); the forwarded chain, which the caller can,
274
+ // only distinguishes keys inside that budget.
275
+ const source = callerSource(request);
276
+ const referenceKey = [...new Set(references)].sort().join(',');
277
+ const key = `${decision}|${surface}|${referenceKey}|${operationName}|${userAgent}|${source.forwardedFor}`;
278
+ if (!admitLogLine(`${principal}|${source.ip}`, key, nowMs))
229
279
  return;
230
- if (lastLoggedAt.size >= LOG_THROTTLE_MAX_KEYS)
231
- lastLoggedAt.clear();
232
- lastLoggedAt.set(key, nowMs);
233
- logger.warn('[credential-field-guard] credential access by a non-service principal', {
280
+ logger.warn(message, {
234
281
  decision,
235
282
  surface,
236
283
  references,
237
284
  principalKind: principal,
238
285
  operationName,
239
- ip: request?.ip,
286
+ ip: source.ip,
287
+ forwardedFor: source.forwardedFor,
288
+ userAgent,
289
+ dedupWindowMs: LOG_THROTTLE_MS,
290
+ });
291
+ }
292
+ /**
293
+ * Log a service principal's credential read at most once per caller key per
294
+ * window.
295
+ *
296
+ * Every holder of the service secret is `kind: "server"`, so the metric alone
297
+ * cannot say WHICH holder read a broker key. The signed credential's `sub`
298
+ * (`adaptic-engine:<host>:<pid>`, `adaptic-platform:…`, an operator toolkit's
299
+ * `adaptic-audit:…`) can, and it is what an operator needs to tell a known
300
+ * service from a leaked secret. It goes to the log, not the metric label,
301
+ * because host:pid is unbounded. A static `SERVER_AUTH_TOKEN` names no caller
302
+ * and logs as `<unattributed>`.
303
+ */
304
+ function logServiceRead(sub, reference, info, request, nowMs) {
305
+ const operationName = bounded(info.operation?.name?.value ?? '<unnamed>');
306
+ const caller = bounded(sub ?? '<unattributed>');
307
+ const source = callerSource(request);
308
+ const key = `allowed|${caller}|${reference}|${operationName}|${source.forwardedFor}`;
309
+ if (!admitLogLine(`server|${source.ip}`, key, nowMs))
310
+ return;
311
+ logger.info('[credential-field-guard] credential read by a service principal', {
312
+ decision: 'allowed',
313
+ serviceSub: caller,
314
+ reference,
315
+ operationName,
316
+ ip: source.ip,
317
+ forwardedFor: source.forwardedFor,
318
+ dedupWindowMs: LOG_THROTTLE_MS,
319
+ });
320
+ }
321
+ /**
322
+ * Log an audit payload read that redaction changes, or would change, at most
323
+ * once per caller key per window. The line names the key paths that held
324
+ * credentials, never their values.
325
+ */
326
+ function logAuditPayloadRead(decision, reference, paths, principal, info, request, nowMs) {
327
+ const operationName = bounded(info.operation?.name?.value ?? '<unnamed>');
328
+ const userAgent = bounded(headerValue(request?.headers?.['user-agent']));
329
+ const source = callerSource(request);
330
+ const key = `payload|${decision}|${reference}|${operationName}|${userAgent}|${source.forwardedFor}`;
331
+ if (!admitLogLine(`${principal}|${source.ip}`, key, nowMs))
332
+ return;
333
+ logger.warn('[credential-field-guard] audit payload holding credentials read by a principal that reads payloads redacted', {
334
+ decision,
335
+ reference,
336
+ credentialPaths: paths.slice(0, MAX_LOGGED_PATHS).map((p) => bounded(p.path)),
337
+ credentialPathCount: paths.length,
338
+ carriedValue: paths.some((p) => p.carriesValue),
339
+ principalKind: principal,
340
+ operationName,
341
+ ip: source.ip,
342
+ forwardedFor: source.forwardedFor,
240
343
  userAgent,
241
344
  dedupWindowMs: LOG_THROTTLE_MS,
242
345
  });
243
346
  }
347
+ /**
348
+ * Where a request came from, as far as this process can tell.
349
+ *
350
+ * `req.ip` is the address `trust proxy` resolves, and behind the production
351
+ * edge it resolves to the edge's own pool (an operator's laptop and a hosted
352
+ * service log the same handful of addresses), so on its own it cannot tell
353
+ * callers apart. The raw `X-Forwarded-For` chain carries the hops the edge
354
+ * saw. It is caller-supplied at its left end, so it is attribution evidence
355
+ * for an operator reading the log, never an identity the guard decides on.
356
+ */
357
+ function callerSource(request) {
358
+ return {
359
+ ip: bounded(request?.ip ?? '<none>'),
360
+ forwardedFor: bounded(headerValue(request?.headers?.['x-forwarded-for'])),
361
+ };
362
+ }
244
363
  function headerValue(value) {
245
364
  if (Array.isArray(value))
246
365
  return value.join(',');
@@ -255,6 +374,16 @@ function forbidden(references) {
255
374
  },
256
375
  });
257
376
  }
377
+ function forbiddenAuditPayloadPredicate(references) {
378
+ return new GraphQLError('Forbidden: audit payload columns can be filtered, sorted or grouped on only by a ' +
379
+ 'service or admin principal', {
380
+ extensions: {
381
+ code: 'FORBIDDEN',
382
+ references,
383
+ http: { status: 403 },
384
+ },
385
+ });
386
+ }
258
387
  /**
259
388
  * Create the TypeGraphQL global middleware that guards credential columns.
260
389
  *
@@ -279,32 +408,72 @@ export function createCredentialFieldGuardMiddleware(options = {}) {
279
408
  decision: 'allowed',
280
409
  principal_kind: 'server',
281
410
  });
411
+ logServiceRead(principal.sub, output, info, context.req, now());
282
412
  }
283
413
  return proceed();
284
414
  }
285
- const argumentRefs = findCredentialArgumentReferences(info, args);
286
- if (!output && argumentRefs.length === 0)
415
+ const references = findGuardedArgumentReferences(info, args);
416
+ // Admins read audit payloads as stored, so only user and anonymous
417
+ // principals reach the payload rules below.
418
+ const payloadReader = !readsAuditPayloadRaw(principal);
419
+ const payloadOutput = payloadReader ? auditPayloadOutputField(info) : undefined;
420
+ const payloadRefs = payloadReader ? references.auditPayload : [];
421
+ if (!output &&
422
+ references.credential.length === 0 &&
423
+ !payloadOutput &&
424
+ payloadRefs.length === 0) {
287
425
  return proceed();
426
+ }
288
427
  const mode = resolveMode();
289
428
  if (mode === 'off')
290
429
  return proceed();
291
- const surface = output ? 'output' : 'argument';
292
- const references = output ? [output, ...argumentRefs] : argumentRefs;
293
430
  const principalLabel = principal?.kind ?? 'none';
294
- const decision = mode === 'enforce' ? 'denied' : 'would_deny';
295
- credentialFieldAccessTotal.inc({
296
- surface,
431
+ const nowMs = now();
432
+ const refusal = mode === 'enforce' ? 'denied' : 'would_deny';
433
+ if (output || references.credential.length > 0) {
434
+ const surface = output ? 'output' : 'argument';
435
+ const credentialRefs = output ? [output, ...references.credential] : references.credential;
436
+ credentialFieldAccessTotal.inc({
437
+ surface,
438
+ decision: refusal,
439
+ principal_kind: principalLabel,
440
+ });
441
+ logDecision(CREDENTIAL_ACCESS_MESSAGE, refusal, surface, credentialRefs, principalLabel, info, context.req, nowMs);
442
+ if (mode === 'enforce')
443
+ throw forbidden(credentialRefs);
444
+ }
445
+ if (payloadRefs.length > 0) {
446
+ auditPayloadAccessTotal.inc({
447
+ surface: 'argument',
448
+ decision: refusal,
449
+ principal_kind: principalLabel,
450
+ carried_value: 'n/a',
451
+ });
452
+ logDecision(AUDIT_PAYLOAD_PREDICATE_MESSAGE, refusal, 'argument', payloadRefs, principalLabel, info, context.req, nowMs);
453
+ if (mode === 'enforce')
454
+ throw forbiddenAuditPayloadPredicate(payloadRefs);
455
+ }
456
+ if (!payloadOutput)
457
+ return proceed();
458
+ const value = await proceed();
459
+ const { redacted, paths } = redactAuditPayload(value);
460
+ const decision = paths.length === 0 ? 'unchanged' : mode === 'enforce' ? 'redacted' : 'would_redact';
461
+ auditPayloadAccessTotal.inc({
462
+ surface: 'output',
297
463
  decision,
298
464
  principal_kind: principalLabel,
465
+ carried_value: String(paths.some((p) => p.carriesValue)),
299
466
  });
300
- logDecision(decision, surface, references, principalLabel, info, context.req, now());
301
- if (mode === 'enforce')
302
- throw forbidden(references);
303
- return proceed();
467
+ if (paths.length > 0) {
468
+ logAuditPayloadRead(decision, payloadOutput, paths, principalLabel, info, context.req, nowMs);
469
+ }
470
+ // Under enforce the redacted copy is served even when no path was found:
471
+ // the copy is what the rule promises, the path list only describes it.
472
+ return mode === 'enforce' ? redacted : value;
304
473
  };
305
474
  }
306
475
  /** @internal Test hook: forget the log throttle state. */
307
476
  export function resetCredentialFieldGuardLogThrottle() {
308
- lastLoggedAt.clear();
477
+ logThrottle.reset();
309
478
  }
310
479
  //# sourceMappingURL=credential-field-guard.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Where the generated GraphQL schema exposes a Prisma model's columns, by
3
+ * type-name convention.
4
+ *
5
+ * typegraphql-prisma names every type after its model, so a guard that must
6
+ * cover "every way a query can observe column X of model M" can derive the
7
+ * whole surface from the model name: the output types that carry column
8
+ * VALUES, the input types that act as predicates over them, and the scalar
9
+ * enum that names them in `by` / `distinct`. The rules live here, once, so
10
+ * each guard that keys on a set of columns applies the same naming rules.
11
+ *
12
+ * @module middleware/generated-type-names
13
+ */
14
+ /**
15
+ * Output types that carry a model's column VALUES, as name suffixes on the
16
+ * model. The `Count` aggregate is absent on purpose: it returns how many rows
17
+ * are non-null, never a value.
18
+ */
19
+ export declare const VALUE_OUTPUT_SUFFIXES: readonly ["", "GroupBy", "MinAggregate", "MaxAggregate"];
20
+ /**
21
+ * Output types that carry a model's column VALUES, as name prefixes on the
22
+ * model. `createManyAndReturn<Model>` / `updateManyAndReturn<Model>` return
23
+ * the written rows as their own generated type rather than as `<Model>`, so a
24
+ * guard keyed only on the model type would serve the guarded columns of every
25
+ * row such a mutation touches — including columns the caller did not write.
26
+ */
27
+ export declare const VALUE_OUTPUT_PREFIXES: readonly ["CreateManyAndReturn", "UpdateManyAndReturn"];
28
+ /** Lookups from a generated type name to the guarded columns it exposes. */
29
+ export interface GeneratedTypeIndex {
30
+ /** Guarded columns an output type carries as values, if any. */
31
+ outputFields(typeName: string): ReadonlySet<string> | undefined;
32
+ /** Guarded columns an input type's keys can reference as a predicate, if any. */
33
+ predicateFields(typeName: string): ReadonlySet<string> | undefined;
34
+ /** Guarded columns a `<Model>ScalarFieldEnum` can name, if it is one. */
35
+ enumFields(typeName: string): ReadonlySet<string> | undefined;
36
+ }
37
+ /**
38
+ * Index the generated types of every model in `fieldsByModel`.
39
+ *
40
+ * @param fieldsByModel - Guarded column names, by Prisma model name.
41
+ * @returns Lookups over the generated type names.
42
+ */
43
+ export declare function indexGeneratedTypes(fieldsByModel: ReadonlyMap<string, ReadonlySet<string>>): GeneratedTypeIndex;
44
+ //# sourceMappingURL=generated-type-names.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generated-type-names.d.ts","sourceRoot":"","sources":["../../../src/middleware/generated-type-names.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,0DAA2D,CAAC;AAE9F;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,yDAA0D,CAAC;AAY7F,4EAA4E;AAC5E,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IAChE,iFAAiF;IACjF,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IACnE,yEAAyE;IACzE,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;CAC/D;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,GACtD,kBAAkB,CAoCpB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generated-type-names.js","sourceRoot":"","sources":["../../../src/middleware/generated-type-names.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,cAAc,CAAU,CAAC;AAE9F;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,qBAAqB,EAAE,qBAAqB,CAAU,CAAC;AAE7F;;;;;GAKG;AACH,MAAM,wBAAwB,GAAG,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAU,CAAC;AAEzE,MAAM,wBAAwB,GAAG,iBAAiB,CAAC;AAYnD;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CACjC,aAAuD;IAEvD,MAAM,OAAO,GAA6C,IAAI,GAAG,CAC/D,CAAC,GAAG,aAAa,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC;QAC9C,GAAG,qBAAqB,CAAC,GAAG,CAC1B,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,GAAG,MAAM,EAAE,EAAE,MAAM,CAAkC,CAC3E;QACD,GAAG,qBAAqB,CAAC,GAAG,CAC1B,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,GAAG,MAAM,GAAG,KAAK,EAAE,EAAE,MAAM,CAAkC,CAC3E;KACF,CAAC,CACH,CAAC;IAEF,gDAAgD;IAChD,+EAA+E;IAC/E,MAAM,kBAAkB,GAAG,CAAC,GAAG,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;IAEzF,OAAO;QACL,YAAY,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QACjD,sEAAsE;QACtE,0EAA0E;QAC1E,2CAA2C;QAC3C,eAAe,EAAE,CAAC,QAAQ,EAAE,EAAE;YAC5B,KAAK,MAAM,KAAK,IAAI,kBAAkB,EAAE,CAAC;gBACvC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAC;oBAAE,SAAS;gBAC1C,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBAC1C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;oBAAE,SAAS;gBACnC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;oBAAE,OAAO,SAAS,CAAC;gBAC9E,OAAO,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,UAAU,EAAE,CAAC,QAAQ,EAAE,EAAE,CACvB,QAAQ,CAAC,QAAQ,CAAC,wBAAwB,CAAC;YACzC,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC;YACxE,CAAC,CAAC,SAAS;KAChB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Where the generated GraphQL schema exposes a Prisma model's columns, by
3
+ * type-name convention.
4
+ *
5
+ * typegraphql-prisma names every type after its model, so a guard that must
6
+ * cover "every way a query can observe column X of model M" can derive the
7
+ * whole surface from the model name: the output types that carry column
8
+ * VALUES, the input types that act as predicates over them, and the scalar
9
+ * enum that names them in `by` / `distinct`. The rules live here, once, so
10
+ * each guard that keys on a set of columns applies the same naming rules.
11
+ *
12
+ * @module middleware/generated-type-names
13
+ */
14
+ /**
15
+ * Output types that carry a model's column VALUES, as name suffixes on the
16
+ * model. The `Count` aggregate is absent on purpose: it returns how many rows
17
+ * are non-null, never a value.
18
+ */
19
+ export const VALUE_OUTPUT_SUFFIXES = ['', 'GroupBy', 'MinAggregate', 'MaxAggregate'];
20
+ /**
21
+ * Output types that carry a model's column VALUES, as name prefixes on the
22
+ * model. `createManyAndReturn<Model>` / `updateManyAndReturn<Model>` return
23
+ * the written rows as their own generated type rather than as `<Model>`, so a
24
+ * guard keyed only on the model type would serve the guarded columns of every
25
+ * row such a mutation touches — including columns the caller did not write.
26
+ */
27
+ export const VALUE_OUTPUT_PREFIXES = ['CreateManyAndReturn', 'UpdateManyAndReturn'];
28
+ /**
29
+ * Input-type name fragments that make a type a read predicate (filter, sort,
30
+ * cursor, aggregate filter) rather than a write payload. A `…WhereUniqueInput`
31
+ * is also how a mutation selects its row, so a guarded key there is an oracle
32
+ * on a write path too.
33
+ */
34
+ const PREDICATE_TYPE_FRAGMENTS = ['Where', 'OrderBy', 'Having'];
35
+ const SCALAR_FIELD_ENUM_SUFFIX = 'ScalarFieldEnum';
36
+ /**
37
+ * Index the generated types of every model in `fieldsByModel`.
38
+ *
39
+ * @param fieldsByModel - Guarded column names, by Prisma model name.
40
+ * @returns Lookups over the generated type names.
41
+ */
42
+ export function indexGeneratedTypes(fieldsByModel) {
43
+ const outputs = new Map([...fieldsByModel].flatMap(([model, fields]) => [
44
+ ...VALUE_OUTPUT_SUFFIXES.map((suffix) => [`${model}${suffix}`, fields]),
45
+ ...VALUE_OUTPUT_PREFIXES.map((prefix) => [`${prefix}${model}`, fields]),
46
+ ]));
47
+ // Longest-first, so the prefix match attributes
48
+ // `AccountLinkingRequestWhereInput` to `AccountLinkingRequest`, not `Account`.
49
+ const modelsLongestFirst = [...fieldsByModel.keys()].sort((a, b) => b.length - a.length);
50
+ return {
51
+ outputFields: (typeName) => outputs.get(typeName),
52
+ // Generated names start with the model name followed by an upper-case
53
+ // letter (`AlpacaAccountWhereInput`), so a model named `Account` does not
54
+ // claim `AccountLinkingRequestWhereInput`.
55
+ predicateFields: (typeName) => {
56
+ for (const model of modelsLongestFirst) {
57
+ if (!typeName.startsWith(model))
58
+ continue;
59
+ const rest = typeName.slice(model.length);
60
+ if (!/^[A-Z]/.test(rest))
61
+ continue;
62
+ if (!PREDICATE_TYPE_FRAGMENTS.some((f) => rest.includes(f)))
63
+ return undefined;
64
+ return fieldsByModel.get(model);
65
+ }
66
+ return undefined;
67
+ },
68
+ enumFields: (typeName) => typeName.endsWith(SCALAR_FIELD_ENUM_SUFFIX)
69
+ ? fieldsByModel.get(typeName.slice(0, -SCALAR_FIELD_ENUM_SUFFIX.length))
70
+ : undefined,
71
+ };
72
+ }
73
+ //# sourceMappingURL=generated-type-names.js.map