@adaptic/backend 0.0.1057 → 0.0.1058
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 +316 -0
- package/auth/service-token.d.ts +94 -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 +52 -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/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
|
@@ -1,575 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Out-of-process harness for `mutation-auth-guard.test.ts`.
|
|
3
|
-
*
|
|
4
|
-
* The generated TypeGraphQL resolvers need `emitDecoratorMetadata`, which
|
|
5
|
-
* vitest's esbuild transform does not emit, so a schema built from them cannot
|
|
6
|
-
* be constructed inside the vitest worker. This harness runs under ts-node,
|
|
7
|
-
* builds a schema from the GENERATED TradingPolicy, AlpacaAccount, User,
|
|
8
|
-
* tenancy (Organization, OrgMembership, Fund, FundAssignment,
|
|
9
|
-
* BrokerageAccount), AuditLog and Configuration resolvers with the guard
|
|
10
|
-
* installed exactly as `server.ts` installs it
|
|
11
|
-
* (`installMutationAuthGuard` on the built schema),
|
|
12
|
-
* serves it through a real ApolloServer carrying the production HTTP-status
|
|
13
|
-
* plugin (so a refusal's HTTP status is observed, not assumed), runs every
|
|
14
|
-
* scenario against a recording fake Prisma client, and prints one JSON
|
|
15
|
-
* document the test asserts on.
|
|
16
|
-
*
|
|
17
|
-
* Run directly:
|
|
18
|
-
* npx ts-node --transpile-only src/middleware/__tests__/mutation-auth-guard.harness.ts
|
|
19
|
-
*/
|
|
20
|
-
import 'reflect-metadata';
|
|
21
|
-
import { ApolloServer } from '@apollo/server';
|
|
22
|
-
import { buildSchema } from 'type-graphql';
|
|
23
|
-
import { TradingPolicyCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/TradingPolicy/TradingPolicyCrudResolver.mjs';
|
|
24
|
-
import { AlpacaAccountCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/AlpacaAccount/AlpacaAccountCrudResolver.mjs';
|
|
25
|
-
import { UserCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/User/UserCrudResolver.mjs';
|
|
26
|
-
import { OrganizationCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/Organization/OrganizationCrudResolver.mjs';
|
|
27
|
-
import { OrgMembershipCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/OrgMembership/OrgMembershipCrudResolver.mjs';
|
|
28
|
-
import { FundCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/Fund/FundCrudResolver.mjs';
|
|
29
|
-
import { FundAssignmentCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/FundAssignment/FundAssignmentCrudResolver.mjs';
|
|
30
|
-
import { BrokerageAccountCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/BrokerageAccount/BrokerageAccountCrudResolver.mjs';
|
|
31
|
-
import { AuditLogCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/AuditLog/AuditLogCrudResolver.mjs';
|
|
32
|
-
import { ConfigurationCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/Configuration/ConfigurationCrudResolver.mjs';
|
|
33
|
-
import { createHttpStatusMapperPlugin } from '../../plugins/http-status-mapper.mjs';
|
|
34
|
-
import { installMutationAuthGuard, mutationAuthorizationTotal, resetMutationAuthLogThrottle, } from '../mutation-auth-guard.mjs';
|
|
35
|
-
import { mutationAuditBypassedTotal, mutationAuditWriteFailuresTotal } from '../trading-policy-audit.mjs';
|
|
36
|
-
export const API_KEY = 'PKMUTATIONGUARDKEY00000000';
|
|
37
|
-
export const API_SECRET = 'mutation-guard-secret-value-that-must-never-leak';
|
|
38
|
-
const U_OWNER = '11111111-1111-4111-8111-111111111111';
|
|
39
|
-
const U_STRANGER = '22222222-2222-4222-8222-222222222222';
|
|
40
|
-
const U_FUND = '33333333-3333-4333-8333-333333333333';
|
|
41
|
-
const U_OTHER = '44444444-4444-4444-8444-444444444444';
|
|
42
|
-
const FUND_1 = '55555555-5555-4555-8555-555555555555';
|
|
43
|
-
const FUND_2 = '77777777-7777-4777-8777-777777777777';
|
|
44
|
-
const ORG_2 = '88888888-8888-4888-8888-888888888888';
|
|
45
|
-
const ORG_1 = 'org-1';
|
|
46
|
-
/** An organization its creator has just written: no members, no funds. */
|
|
47
|
-
const ORG_NEW = '99999999-9999-4999-8999-999999999999';
|
|
48
|
-
/** An organization that admits sign-ups from one email domain. */
|
|
49
|
-
const ORG_DOMAIN = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
|
50
|
-
const U_ORG_OWNER = 'b0000000-0000-4000-8000-000000000001';
|
|
51
|
-
const U_ORG_ADMIN = 'b0000000-0000-4000-8000-000000000002';
|
|
52
|
-
const U_ORG_MEMBER = 'b0000000-0000-4000-8000-000000000003';
|
|
53
|
-
const U_FUND_MANAGER = 'b0000000-0000-4000-8000-000000000004';
|
|
54
|
-
const U_FUND_TRADER = 'b0000000-0000-4000-8000-000000000005';
|
|
55
|
-
const U_FOUNDER = 'b0000000-0000-4000-8000-000000000006';
|
|
56
|
-
const U_JOINER = 'b0000000-0000-4000-8000-000000000007';
|
|
57
|
-
const ACCOUNTS = {
|
|
58
|
-
a1: { id: 'a1', userId: U_OWNER, type: 'LIVE', brokerageAccount: null },
|
|
59
|
-
a2: { id: 'a2', userId: U_OTHER, type: 'PAPER', brokerageAccount: { fundId: FUND_1 } },
|
|
60
|
-
a3: { id: 'a3', userId: U_OTHER, type: 'LIVE', brokerageAccount: { fundId: FUND_2 } },
|
|
61
|
-
};
|
|
62
|
-
const POLICIES = {
|
|
63
|
-
p1: { id: 'p1', alpacaAccountId: 'a1' },
|
|
64
|
-
p2: { id: 'p2', alpacaAccountId: 'a2' },
|
|
65
|
-
p3: { id: 'p3', alpacaAccountId: 'a3' },
|
|
66
|
-
};
|
|
67
|
-
/**
|
|
68
|
-
* The tenancy rows: U_FUND is assigned FUND_1 (org-1) as a VIEWER; FUND_2
|
|
69
|
-
* (ORG_2) bridges the LIVE account a3. org-1 has an OWNER, an ADMIN and a
|
|
70
|
-
* MEMBER, and FUND_1 a MANAGER and a TRADER.
|
|
71
|
-
*/
|
|
72
|
-
const TENANCY = {
|
|
73
|
-
organization: [
|
|
74
|
-
{ id: ORG_1, deletedAt: null, emailDomains: [] },
|
|
75
|
-
{ id: ORG_2, deletedAt: null, emailDomains: [] },
|
|
76
|
-
{ id: ORG_NEW, deletedAt: null, emailDomains: [] },
|
|
77
|
-
{ id: ORG_DOMAIN, deletedAt: null, emailDomains: ['join.example'] },
|
|
78
|
-
],
|
|
79
|
-
orgMembership: [
|
|
80
|
-
{ id: 'om2', organizationId: ORG_2, userId: U_OTHER, role: 'MEMBER' },
|
|
81
|
-
{ id: 'om-owner', organizationId: ORG_1, userId: U_ORG_OWNER, role: 'OWNER' },
|
|
82
|
-
{ id: 'om-admin', organizationId: ORG_1, userId: U_ORG_ADMIN, role: 'ADMIN' },
|
|
83
|
-
{ id: 'om-member', organizationId: ORG_1, userId: U_ORG_MEMBER, role: 'MEMBER' },
|
|
84
|
-
{ id: 'om-domain', organizationId: ORG_DOMAIN, userId: U_OTHER, role: 'OWNER' },
|
|
85
|
-
],
|
|
86
|
-
fund: [
|
|
87
|
-
{ id: FUND_1, organizationId: ORG_1 },
|
|
88
|
-
{ id: FUND_2, organizationId: ORG_2 },
|
|
89
|
-
],
|
|
90
|
-
fundAssignment: [
|
|
91
|
-
{ id: 'fa1', fundId: FUND_1, userId: U_FUND, role: 'VIEWER' },
|
|
92
|
-
{ id: 'fa2', fundId: FUND_2, userId: U_OTHER, role: 'MANAGER' },
|
|
93
|
-
{ id: 'fa-manager', fundId: FUND_1, userId: U_FUND_MANAGER, role: 'MANAGER' },
|
|
94
|
-
{ id: 'fa-trader', fundId: FUND_1, userId: U_FUND_TRADER, role: 'TRADER' },
|
|
95
|
-
],
|
|
96
|
-
brokerageAccount: [
|
|
97
|
-
{ id: 'ba1', fundId: FUND_1, engineAccountId: 'a2' },
|
|
98
|
-
{ id: 'ba2', fundId: FUND_2, engineAccountId: 'a3' },
|
|
99
|
-
],
|
|
100
|
-
notificationEvent: [],
|
|
101
|
-
notificationDelivery: [],
|
|
102
|
-
notificationPreference: [],
|
|
103
|
-
};
|
|
104
|
-
/** Evaluate the `where` shapes the guard's scope check builds (equality, `in`, `AND`, `OR`). */
|
|
105
|
-
function matches(row, where) {
|
|
106
|
-
return Object.entries(where).every(([key, condition]) => {
|
|
107
|
-
if (key === 'AND')
|
|
108
|
-
return condition.every((c) => matches(row, c));
|
|
109
|
-
if (key === 'OR')
|
|
110
|
-
return condition.some((c) => matches(row, c));
|
|
111
|
-
if (condition !== null && typeof condition === 'object' && 'in' in condition) {
|
|
112
|
-
return condition.in.includes(row[key]);
|
|
113
|
-
}
|
|
114
|
-
if (condition !== null && typeof condition === 'object' && 'equals' in condition) {
|
|
115
|
-
return row[key] === condition.equals;
|
|
116
|
-
}
|
|
117
|
-
// A compound unique selector (`organizationId_userId: { organizationId, userId }`).
|
|
118
|
-
if (condition !== null && typeof condition === 'object' && !(key in row)) {
|
|
119
|
-
return matches(row, condition);
|
|
120
|
-
}
|
|
121
|
-
return row[key] === condition;
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
/** Project a fixture row onto a Prisma `select`, including `_count` and a to-one relation. */
|
|
125
|
-
function project(delegate, row, select) {
|
|
126
|
-
if (!select)
|
|
127
|
-
return { id: row.id };
|
|
128
|
-
const out = {};
|
|
129
|
-
for (const [key, wanted] of Object.entries(select)) {
|
|
130
|
-
if (key === '_count') {
|
|
131
|
-
const counted = wanted.select;
|
|
132
|
-
const counts = {};
|
|
133
|
-
if ('members' in counted)
|
|
134
|
-
counts.members = TENANCY.orgMembership.filter((m) => m.organizationId === row.id).length;
|
|
135
|
-
if ('funds' in counted)
|
|
136
|
-
counts.funds = TENANCY.fund.filter((f) => f.organizationId === row.id).length;
|
|
137
|
-
out._count = counts;
|
|
138
|
-
}
|
|
139
|
-
else if (delegate === 'fundAssignment' && key === 'fund') {
|
|
140
|
-
const fund = TENANCY.fund.find((f) => f.id === row.fundId);
|
|
141
|
-
out.fund = fund ? project('fund', fund, wanted.select) : null;
|
|
142
|
-
}
|
|
143
|
-
else {
|
|
144
|
-
out[key] = row[key];
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
return out;
|
|
148
|
-
}
|
|
149
|
-
const PRINCIPALS = {
|
|
150
|
-
none: null,
|
|
151
|
-
server: { kind: 'server', sub: 'adaptic-engine:host-1:42' },
|
|
152
|
-
staticServer: { kind: 'server' },
|
|
153
|
-
admin: { kind: 'admin', sub: '66666666-6666-4666-8666-666666666666', roles: ['admin'] },
|
|
154
|
-
owner: { kind: 'user', sub: U_OWNER, email: 'owner@example.test', roles: [] },
|
|
155
|
-
stranger: { kind: 'user', sub: U_STRANGER, roles: [] },
|
|
156
|
-
fundUser: { kind: 'user', sub: U_FUND, roles: [] },
|
|
157
|
-
orgOwner: { kind: 'user', sub: U_ORG_OWNER, roles: [] },
|
|
158
|
-
orgAdmin: { kind: 'user', sub: U_ORG_ADMIN, roles: [] },
|
|
159
|
-
// The token claims a role the caller does not hold: authority is read from
|
|
160
|
-
// the database, never from the claim.
|
|
161
|
-
orgMember: { kind: 'user', sub: U_ORG_MEMBER, roles: ['fund_operator'] },
|
|
162
|
-
fundManager: { kind: 'user', sub: U_FUND_MANAGER, roles: [] },
|
|
163
|
-
fundTrader: { kind: 'user', sub: U_FUND_TRADER, roles: [] },
|
|
164
|
-
founder: { kind: 'user', sub: U_FOUNDER, roles: [] },
|
|
165
|
-
joiner: { kind: 'user', sub: U_JOINER, roles: [] },
|
|
166
|
-
};
|
|
167
|
-
const FLIP_LIVE = 'mutation Flip { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: true } }) { id realtimeTradingEnabled } }';
|
|
168
|
-
const FLIP_FUND = 'mutation FlipFund { updateOneTradingPolicy(where: { alpacaAccountId: "a2" }, data: { killSwitchEnabled: { set: true } }) { id } }';
|
|
169
|
-
const ALIASED = 'mutation Batch { a: updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { killSwitchEnabled: { set: true } }) { id } ' +
|
|
170
|
-
'b: updateOneTradingPolicy(where: { alpacaAccountId: "a2" }, data: { killSwitchEnabled: { set: true } }) { id } }';
|
|
171
|
-
const NESTED_POLICY = 'mutation Nested { updateOneAlpacaAccount(where: { id: "a1" }, data: { tradingPolicy: { update: { data: { realtimeTradingEnabled: { set: true } } } } }) { id } }';
|
|
172
|
-
const STEAL_ACCOUNT = `mutation Steal { updateOneUser(where: { id: "${U_STRANGER}" }, data: { alpacaAccounts: { connect: [{ id: "a1" }] } }) { id } }`;
|
|
173
|
-
const CREATE_WITH_KEYS = `mutation Create { createOneAlpacaAccount(data: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${U_OWNER}" } } }) { id } }`;
|
|
174
|
-
const SELF_UPDATE = `mutation Self { updateOneUser(where: { id: "${U_OWNER}" }, data: { name: { set: "n" } }) { id } }`;
|
|
175
|
-
const BULK_POLICY = 'mutation Bulk { updateManyTradingPolicy(where: { killSwitchEnabled: { equals: false } }, data: { killSwitchEnabled: { set: true } }) { count } }';
|
|
176
|
-
const DELETE_ACCOUNT = 'mutation Del { deleteOneAlpacaAccount(where: { id: "a1" }) { id } }';
|
|
177
|
-
const ARM = '{ update: { data: { realtimeTradingEnabled: { set: true } } } }';
|
|
178
|
-
// Blocker 1: minting fund entitlement.
|
|
179
|
-
const NESTED_ASSIGNMENT = `mutation { updateOneUser(where: { id: "${U_FUND}" }, data: { fundAssignments: { create: [{ fund: { connect: { id: "${FUND_2}" } } }] } }) { id } }`;
|
|
180
|
-
const NESTED_MEMBERSHIP = `mutation { updateOneUser(where: { id: "${U_STRANGER}" }, data: { orgMemberships: { create: [{ organization: { connect: { id: "${ORG_2}" } } }] } }) { id } }`;
|
|
181
|
-
const ROOT_ASSIGNMENT_OTHER_FUND = `mutation { createOneFundAssignment(data: { fund: { connect: { id: "${FUND_2}" } }, user: { connect: { id: "${U_STRANGER}" } } }) { id } }`;
|
|
182
|
-
const ROOT_ASSIGNMENT_OWN_FUND = `mutation { createOneFundAssignment(data: { fund: { connect: { id: "${FUND_1}" } }, user: { connect: { id: "${U_FUND}" } } }) { id } }`;
|
|
183
|
-
const RETENANT_ASSIGNMENT = `mutation { updateOneFundAssignment(where: { id: "fa1" }, data: { fund: { connect: { id: "${FUND_2}" } } }) { id } }`;
|
|
184
|
-
const BROKER_LABEL = (id) => `mutation { updateOneBrokerageAccount(where: { id: "${id}" }, data: { label: { set: "x" } }) { id } }`;
|
|
185
|
-
const ARM_UNDER_USER = (userId, accountId) => `mutation { updateOneUser(where: { id: "${userId}" }, data: { alpacaAccounts: { update: [{ where: { id: "${accountId}" }, data: { tradingPolicy: ${ARM} } }] } }) { id } }`;
|
|
186
|
-
// Entitlement rows: who may write a membership or a fund assignment.
|
|
187
|
-
const SET_MEMBERSHIP_ROLE = (id, role) => `mutation { updateOneOrgMembership(where: { id: "${id}" }, data: { role: { set: ${role} } }) { id } }`;
|
|
188
|
-
const DELETE_MEMBERSHIP = (id) => `mutation { deleteOneOrgMembership(where: { id: "${id}" }) { id } }`;
|
|
189
|
-
const CREATE_MEMBERSHIP = (orgId, userId, role) => `mutation { createOneOrgMembership(data: { organization: { connect: { id: "${orgId}" } }, user: { connect: { id: "${userId}" } }, role: ${role} }) { id } }`;
|
|
190
|
-
const CREATE_ASSIGNMENT = (fundId, userId, role) => `mutation { createOneFundAssignment(data: { fund: { connect: { id: "${fundId}" } }, user: { connect: { id: "${userId}" } }, role: ${role} }) { id } }`;
|
|
191
|
-
const SET_ASSIGNMENT_ROLE = (id, role) => `mutation { updateOneFundAssignment(where: { id: "${id}" }, data: { role: { set: ${role} } }) { id } }`;
|
|
192
|
-
const SET_MEMBERSHIP_ROLE_BY_PAIR = (orgId, userId, role) => `mutation { updateOneOrgMembership(where: { organizationId_userId: { organizationId: "${orgId}", userId: "${userId}" } }, data: { role: { set: ${role} } }) { id } }`;
|
|
193
|
-
/** The platform's fund-creation payload: the creator as operator and as the fund's first MANAGER. */
|
|
194
|
-
const CREATE_FUND_WITH_MANAGER = (userId) => `mutation { createOneFund(data: { name: "F", slug: "f", organization: { connect: { id: "${ORG_1}" } }, operator: { connect: { id: "${userId}" } }, assignments: { create: [{ user: { connect: { id: "${userId}" } }, role: MANAGER }] } }) { id } }`;
|
|
195
|
-
// Blocker 2: walks that leave the root's rows.
|
|
196
|
-
const ACCOUNT_CHAIN = 'mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { brokerageAccount: { update: { data: { fund: { update: { data: { name: { set: "x" } } } } } } } }) { id } }';
|
|
197
|
-
const MANAGED_FUND_OPERATOR = `mutation { updateOneUser(where: { id: "${U_FUND}" }, data: { managedFunds: { update: [{ where: { id: "${FUND_1}" }, data: { operator: { update: { data: { role: { set: ADMIN } } } } } }] } }) { id } }`;
|
|
198
|
-
const OWNER_ROW_VIA_FUND = 'mutation { updateOneAlpacaAccount(where: { id: "a2" }, data: { user: { update: { data: { email: { set: "taken@example.test" } } } } }) { id } }';
|
|
199
|
-
const REPOINT_BROKER = 'mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { brokerageAccount: { connect: { id: "ba1" } } }) { id } }';
|
|
200
|
-
const NESTED_FUND_POLICY = 'mutation { updateOneAlpacaAccount(where: { id: "a2" }, data: { tradingPolicy: { update: { data: { killSwitchEnabled: { set: true } } } } }) { id } }';
|
|
201
|
-
// Blocker 3: nested policy writes attributed to the account they reach.
|
|
202
|
-
/** Root account a1 → its owner → a fund → that fund's broker ba2 → ba2's engine account (a3, reached to-one) → its policy. */
|
|
203
|
-
const ARM_FAR_FROM_ROOT = `mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { user: { update: { data: { fundAssignments: { update: [{ where: { id: "fa2" }, data: { fund: { update: { data: { brokerageAccounts: { update: [{ where: { id: "ba2" }, data: { engineAccount: { update: { data: { tradingPolicy: ${ARM} } } } } }] } } } } } }] } } } } }) { id } }`;
|
|
204
|
-
const ARM_VIA_BROKER = `mutation { updateOneBrokerageAccount(where: { id: "ba2" }, data: { engineAccount: { update: { data: { tradingPolicy: ${ARM} } } } }) { id } }`;
|
|
205
|
-
// Majors.
|
|
206
|
-
const SELF_ROLE = `mutation { updateOneUser(where: { id: "${U_OWNER}" }, data: { role: { set: ADMIN } }) { id } }`;
|
|
207
|
-
// Desk availability: a user sets their own; never another user's.
|
|
208
|
-
const SET_AVAILABILITY = (userId) => `mutation { updateOneUser(where: { id: "${userId}" }, data: { availability: { set: away }, availabilityUntil: { set: "2026-11-14T10:00:00.000Z" } }) { id } }`;
|
|
209
|
-
const AUDIT_ROW = (source) => `mutation { createOneAuditLog(data: { userId: "${U_OWNER}", operationType: UPDATE, modelName: "TradingPolicy", recordId: "p1", changedFields: {}, metadata: { source: "${source}" } }) { id } }`;
|
|
210
|
-
// A fund ledger entry: the engine's service principal writes it; no signed-in user may place one.
|
|
211
|
-
const AUDIT_LEDGER_ROW = (userId, fundId) => `mutation { createOneAuditLog(data: { userId: "${userId}", operationType: UPDATE, modelName: "Order", recordId: "o1", changedFields: {}, fundId: "${fundId}", metadata: { source: "platform" } }) { id } }`;
|
|
212
|
-
const CONFIG_UPSERT = (key) => `mutation { upsertOneConfiguration(where: { configKey: "${key}" }, create: { configKey: "${key}", configValue: {}, type: USER_PREFERENCE }, update: { configValue: {} }) { id } }`;
|
|
213
|
-
// Controls: the platform's own fund-operator writes stay admitted.
|
|
214
|
-
const BROKER_CREATE = `mutation { createOneBrokerageAccount(data: { fund: { connect: { id: "${FUND_1}" } }, engineAccount: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${U_FUND}" } } } } }) { id } }`;
|
|
215
|
-
const BROKER_CREATE_OTHER_OWNER = `mutation { createOneBrokerageAccount(data: { fund: { connect: { id: "${FUND_1}" } }, engineAccount: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${U_OTHER}" } } } } }) { id } }`;
|
|
216
|
-
const BROKER_BRIDGE_FOREIGN = `mutation { createOneBrokerageAccount(data: { fund: { connect: { id: "${FUND_1}" } }, engineAccount: { connect: { id: "a3" } } }) { id } }`;
|
|
217
|
-
/** The platform broker-credentials route's update branch: rotate keys on the fund's bound engine account. */
|
|
218
|
-
const BROKER_ROTATE = (userId) => `mutation { updateOneBrokerageAccount(where: { id: "ba1" }, data: { label: { set: "rotated" }, engineAccount: { upsert: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${userId}" } } }, update: { APIKey: { set: "${API_KEY}" } } } } }) { id } }`;
|
|
219
|
-
const SUSPEND_UPSERT = 'mutation { upsertOneTradingPolicy(where: { alpacaAccountId: "a2" }, create: { alpacaAccount: { connect: { id: "a2" } } }, update: { killSwitchEnabled: { set: true } }) { id } }';
|
|
220
|
-
const DISARM_LIVE = 'mutation Disarm { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: false } }) { id } }';
|
|
221
|
-
const DISARM_LIVE_WITH_LANES = 'mutation DisarmLanes { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: false }, intradayLanePrefs: { armed: false } }) { id } }';
|
|
222
|
-
const ARM_LANES_LIVE = 'mutation ArmLanes { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { intradayLanePrefs: { armed: true } }) { id } }';
|
|
223
|
-
// Credential predicates: a `where` over a stored credential must be refused
|
|
224
|
-
// before the guard reads a row with it, or the rows it matched land in the
|
|
225
|
-
// audit trail and the filter becomes an oracle over the credential.
|
|
226
|
-
const SECRET_PREFIX = '{ alpacaAccount: { is: { APISecret: { startsWith: "m" } } } }';
|
|
227
|
-
const ORACLE_BULK = `mutation { updateManyTradingPolicy(where: ${SECRET_PREFIX}, data: { killSwitchEnabled: { set: true } }) { count } }`;
|
|
228
|
-
const ORACLE_ONE = 'mutation { updateOneTradingPolicy(where: { alpacaAccountId: "a1", alpacaAccount: { is: { APIKey: { startsWith: "P" } } } }, data: { killSwitchEnabled: { set: true } }) { id } }';
|
|
229
|
-
const ORACLE_NESTED = 'mutation { updateOneAlpacaAccount(where: { id: "a1", APISecret: { startsWith: "m" } }, data: { tradingPolicy: { update: { data: { killSwitchEnabled: { set: true } } } } }) { id } }';
|
|
230
|
-
const ORACLE_NESTED_WHERE = `mutation { updateOneUser(where: { id: "${U_OWNER}" }, data: { alpacaAccounts: { update: [{ where: { id: "a1", APISecret: { startsWith: "m" } }, data: { tradingPolicy: ${ARM} } }] } }) { id } }`;
|
|
231
|
-
export const SCENARIOS = [
|
|
232
|
-
{ name: 'flip/none/enforce', query: FLIP_LIVE, principal: 'none', mode: 'enforce' },
|
|
233
|
-
{ name: 'flip/none/shadow', query: FLIP_LIVE, principal: 'none', mode: 'shadow' },
|
|
234
|
-
{ name: 'flip/none/shadow+escalated', query: FLIP_LIVE, principal: 'none', mode: 'shadow', enforcedModels: ['TradingPolicy'] },
|
|
235
|
-
{ name: 'flip/none/shadow+other-escalated', query: FLIP_LIVE, principal: 'none', mode: 'shadow', enforcedModels: ['User'] },
|
|
236
|
-
{ name: 'flip/none/off', query: FLIP_LIVE, principal: 'none', mode: 'off' },
|
|
237
|
-
{ name: 'flip/server/enforce', query: FLIP_LIVE, principal: 'server', mode: 'enforce' },
|
|
238
|
-
{ name: 'flip/staticServer/enforce', query: FLIP_LIVE, principal: 'staticServer', mode: 'enforce' },
|
|
239
|
-
{ name: 'flip/admin/enforce', query: FLIP_LIVE, principal: 'admin', mode: 'enforce' },
|
|
240
|
-
{ name: 'flip/owner/enforce', query: FLIP_LIVE, principal: 'owner', mode: 'enforce' },
|
|
241
|
-
{ name: 'flip/stranger/enforce', query: FLIP_LIVE, principal: 'stranger', mode: 'enforce' },
|
|
242
|
-
{ name: 'flip/stranger/shadow', query: FLIP_LIVE, principal: 'stranger', mode: 'shadow' },
|
|
243
|
-
{ name: 'flipFund/fundUser/enforce', query: FLIP_FUND, principal: 'fundUser', mode: 'enforce' },
|
|
244
|
-
{ name: 'flipFund/stranger/enforce', query: FLIP_FUND, principal: 'stranger', mode: 'enforce' },
|
|
245
|
-
{ name: 'aliased/none/enforce', query: ALIASED, principal: 'none', mode: 'enforce' },
|
|
246
|
-
{ name: 'aliased/owner/enforce', query: ALIASED, principal: 'owner', mode: 'enforce' },
|
|
247
|
-
{ name: 'nested/none/enforce', query: NESTED_POLICY, principal: 'none', mode: 'enforce' },
|
|
248
|
-
{ name: 'nested/owner/enforce', query: NESTED_POLICY, principal: 'owner', mode: 'enforce' },
|
|
249
|
-
{ name: 'nested/stranger/enforce', query: NESTED_POLICY, principal: 'stranger', mode: 'enforce' },
|
|
250
|
-
{ name: 'steal/stranger/enforce', query: STEAL_ACCOUNT, principal: 'stranger', mode: 'enforce' },
|
|
251
|
-
{ name: 'createKeys/none/enforce', query: CREATE_WITH_KEYS, principal: 'none', mode: 'enforce' },
|
|
252
|
-
{ name: 'createKeys/stranger/enforce', query: CREATE_WITH_KEYS, principal: 'stranger', mode: 'enforce' },
|
|
253
|
-
{ name: 'createKeys/owner/enforce', query: CREATE_WITH_KEYS, principal: 'owner', mode: 'enforce' },
|
|
254
|
-
{ name: 'self/owner/enforce', query: SELF_UPDATE, principal: 'owner', mode: 'enforce' },
|
|
255
|
-
{ name: 'self/stranger/enforce', query: SELF_UPDATE, principal: 'stranger', mode: 'enforce' },
|
|
256
|
-
{ name: 'bulk/owner/enforce', query: BULK_POLICY, principal: 'owner', mode: 'enforce' },
|
|
257
|
-
{ name: 'bulk/server/enforce', query: BULK_POLICY, principal: 'server', mode: 'enforce' },
|
|
258
|
-
{ name: 'delete/owner/enforce', query: DELETE_ACCOUNT, principal: 'owner', mode: 'enforce' },
|
|
259
|
-
{ name: 'auditDown/server/enforce', query: FLIP_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
|
|
260
|
-
{ name: 'auditDown/server/shadow', query: FLIP_LIVE, principal: 'server', mode: 'shadow', auditDown: true },
|
|
261
|
-
{ name: 'b1/nestedAssignment/fundUser/enforce', query: NESTED_ASSIGNMENT, principal: 'fundUser', mode: 'enforce' },
|
|
262
|
-
{ name: 'b1/nestedMembership/stranger/enforce', query: NESTED_MEMBERSHIP, principal: 'stranger', mode: 'enforce' },
|
|
263
|
-
{ name: 'b1/rootAssignment/stranger/enforce', query: ROOT_ASSIGNMENT_OTHER_FUND, principal: 'stranger', mode: 'enforce' },
|
|
264
|
-
{
|
|
265
|
-
name: 'b1/rootAssignment/stranger/shadow+accounts',
|
|
266
|
-
query: ROOT_ASSIGNMENT_OTHER_FUND,
|
|
267
|
-
principal: 'stranger',
|
|
268
|
-
mode: 'shadow',
|
|
269
|
-
enforcedModels: ['TradingPolicy', 'AlpacaAccount'],
|
|
270
|
-
},
|
|
271
|
-
{ name: 'b1/rootAssignment/fundUser/enforce', query: ROOT_ASSIGNMENT_OWN_FUND, principal: 'fundUser', mode: 'enforce' },
|
|
272
|
-
{ name: 'b1/rootAssignment/fundUser/shadow', query: ROOT_ASSIGNMENT_OWN_FUND, principal: 'fundUser', mode: 'shadow' },
|
|
273
|
-
// A member's own promotion, under both modes.
|
|
274
|
-
{ name: 'mem/promoteSelf/orgMember/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'OWNER'), principal: 'orgMember', mode: 'enforce' },
|
|
275
|
-
{ name: 'mem/promoteSelf/orgMember/shadow', query: SET_MEMBERSHIP_ROLE('om-member', 'OWNER'), principal: 'orgMember', mode: 'shadow' },
|
|
276
|
-
{ name: 'mem/promoteSelfByPair/orgMember/enforce', query: SET_MEMBERSHIP_ROLE_BY_PAIR(ORG_1, U_ORG_MEMBER, 'ADMIN'), principal: 'orgMember', mode: 'enforce' },
|
|
277
|
-
{ name: 'mem/selfManager/orgMember/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_ORG_MEMBER, 'MANAGER'), principal: 'orgMember', mode: 'enforce' },
|
|
278
|
-
{ name: 'mem/selfManager/orgMember/shadow', query: CREATE_ASSIGNMENT(FUND_1, U_ORG_MEMBER, 'MANAGER'), principal: 'orgMember', mode: 'shadow' },
|
|
279
|
-
{ name: 'mem/selfManager/fundUser/enforce', query: SET_ASSIGNMENT_ROLE('fa1', 'MANAGER'), principal: 'fundUser', mode: 'enforce' },
|
|
280
|
-
// OWNER and ADMIN manage the organization's memberships; only OWNER touches an OWNER row.
|
|
281
|
-
{ name: 'mem/ownerSetsRole/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'ADMIN'), principal: 'orgOwner', mode: 'enforce' },
|
|
282
|
-
{ name: 'mem/ownerGrantsOwner/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-admin', 'OWNER'), principal: 'orgOwner', mode: 'enforce' },
|
|
283
|
-
{ name: 'mem/ownerRemoves/orgOwner/enforce', query: DELETE_MEMBERSHIP('om-member'), principal: 'orgOwner', mode: 'enforce' },
|
|
284
|
-
{ name: 'mem/adminSetsRole/orgAdmin/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'AUDITOR'), principal: 'orgAdmin', mode: 'enforce' },
|
|
285
|
-
{ name: 'mem/adminGrantsOwner/orgAdmin/enforce', query: SET_MEMBERSHIP_ROLE('om-admin', 'OWNER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
286
|
-
{ name: 'mem/adminDemotesOwner/orgAdmin/enforce', query: SET_MEMBERSHIP_ROLE('om-owner', 'MEMBER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
287
|
-
{ name: 'mem/adminRemovesOwner/orgAdmin/enforce', query: DELETE_MEMBERSHIP('om-owner'), principal: 'orgAdmin', mode: 'enforce' },
|
|
288
|
-
{ name: 'mem/adminAddsMember/orgAdmin/enforce', query: CREATE_MEMBERSHIP(ORG_1, U_STRANGER, 'COMPLIANCE_OFFICER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
289
|
-
{ name: 'mem/otherOrg/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om2', 'OWNER'), principal: 'orgOwner', mode: 'enforce' },
|
|
290
|
-
{ name: 'mem/missingRow/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-none', 'ADMIN'), principal: 'orgOwner', mode: 'enforce' },
|
|
291
|
-
// Self-service: the creator of an empty organization. A domain join made as the
|
|
292
|
-
// joiner carries no proof the backend can read (the email is the caller's own column).
|
|
293
|
-
{ name: 'mem/firstOwner/founder/enforce', query: CREATE_MEMBERSHIP(ORG_NEW, U_FOUNDER, 'OWNER'), principal: 'founder', mode: 'enforce' },
|
|
294
|
-
{ name: 'mem/claimOccupied/founder/enforce', query: CREATE_MEMBERSHIP(ORG_1, U_FOUNDER, 'OWNER'), principal: 'founder', mode: 'enforce' },
|
|
295
|
-
{ name: 'mem/firstOwnerForOther/founder/enforce', query: CREATE_MEMBERSHIP(ORG_NEW, U_STRANGER, 'OWNER'), principal: 'founder', mode: 'enforce' },
|
|
296
|
-
{ name: 'mem/domainJoin/joiner/enforce', query: CREATE_MEMBERSHIP(ORG_DOMAIN, U_JOINER, 'MEMBER'), principal: 'joiner', mode: 'enforce' },
|
|
297
|
-
// An invitation's acceptance carries no proof the backend can read.
|
|
298
|
-
{ name: 'mem/inviteAccept/stranger/enforce', query: CREATE_MEMBERSHIP(ORG_1, U_STRANGER, 'ADMIN'), principal: 'stranger', mode: 'enforce' },
|
|
299
|
-
// Fund assignments: org OWNER/ADMIN, or the fund's own MANAGER.
|
|
300
|
-
{ name: 'mem/ownerAssigns/orgOwner/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'MANAGER'), principal: 'orgOwner', mode: 'enforce' },
|
|
301
|
-
{ name: 'mem/adminAssigns/orgAdmin/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'TRADER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
302
|
-
{ name: 'mem/managerAssigns/fundManager/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'ANALYST'), principal: 'fundManager', mode: 'enforce' },
|
|
303
|
-
{ name: 'mem/managerSetsRole/fundManager/enforce', query: SET_ASSIGNMENT_ROLE('fa1', 'ANALYST'), principal: 'fundManager', mode: 'enforce' },
|
|
304
|
-
{ name: 'mem/managerOtherFund/fundManager/enforce', query: CREATE_ASSIGNMENT(FUND_2, U_STRANGER, 'ANALYST'), principal: 'fundManager', mode: 'enforce' },
|
|
305
|
-
{ name: 'mem/managerOtherFundRow/fundManager/enforce', query: SET_ASSIGNMENT_ROLE('fa2', 'VIEWER'), principal: 'fundManager', mode: 'enforce' },
|
|
306
|
-
{ name: 'mem/traderAssigns/fundTrader/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'ANALYST'), principal: 'fundTrader', mode: 'enforce' },
|
|
307
|
-
// The authority read fails: refused, and only observed in shadow.
|
|
308
|
-
{ name: 'mem/readDown/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'ADMIN'), principal: 'orgOwner', mode: 'enforce', membershipReadsDown: true },
|
|
309
|
-
{ name: 'mem/readDown/orgOwner/shadow', query: SET_MEMBERSHIP_ROLE('om-member', 'ADMIN'), principal: 'orgOwner', mode: 'shadow', membershipReadsDown: true },
|
|
310
|
-
// The platform's fund creation writes the creator's MANAGER assignment nested.
|
|
311
|
-
{ name: 'mem/fundCreate/orgOwner/enforce', query: CREATE_FUND_WITH_MANAGER(U_ORG_OWNER), principal: 'orgOwner', mode: 'enforce' },
|
|
312
|
-
{ name: 'mem/ownerSetsRole/server/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'OWNER'), principal: 'server', mode: 'enforce' },
|
|
313
|
-
{ name: 'b1/retenantAssignment/fundUser/enforce', query: RETENANT_ASSIGNMENT, principal: 'fundUser', mode: 'enforce' },
|
|
314
|
-
{ name: 'b1/crossTenantBroker/stranger/enforce', query: BROKER_LABEL('ba2'), principal: 'stranger', mode: 'enforce' },
|
|
315
|
-
{ name: 'b1/tenantBroker/fundUser/enforce', query: BROKER_LABEL('ba1'), principal: 'fundUser', mode: 'enforce' },
|
|
316
|
-
{
|
|
317
|
-
name: 'b1/armUnderUser/none/shadow+policy',
|
|
318
|
-
query: ARM_UNDER_USER(U_OTHER, 'a3'),
|
|
319
|
-
principal: 'none',
|
|
320
|
-
mode: 'shadow',
|
|
321
|
-
enforcedModels: ['TradingPolicy'],
|
|
322
|
-
},
|
|
323
|
-
{
|
|
324
|
-
name: 'b1/stealAccountUnderUser/none/shadow+accounts',
|
|
325
|
-
query: `mutation { updateOneUser(where: { id: "${U_STRANGER}" }, data: { alpacaAccounts: { connect: [{ id: "a3" }] } }) { id } }`,
|
|
326
|
-
principal: 'none',
|
|
327
|
-
mode: 'shadow',
|
|
328
|
-
enforcedModels: ['AlpacaAccount'],
|
|
329
|
-
},
|
|
330
|
-
{
|
|
331
|
-
name: 'b1/connectAccountOntoPolicy/none/shadow+accounts',
|
|
332
|
-
query: 'mutation { createOneTradingPolicy(data: { alpacaAccount: { connect: { id: "a3" } } }) { id } }',
|
|
333
|
-
principal: 'none',
|
|
334
|
-
mode: 'shadow',
|
|
335
|
-
enforcedModels: ['AlpacaAccount'],
|
|
336
|
-
},
|
|
337
|
-
{ name: 'b2/accountChain/owner/enforce', query: ACCOUNT_CHAIN, principal: 'owner', mode: 'enforce' },
|
|
338
|
-
{ name: 'b2/managedFundOperator/fundUser/enforce', query: MANAGED_FUND_OPERATOR, principal: 'fundUser', mode: 'enforce' },
|
|
339
|
-
{ name: 'b2/ownerRowViaFund/fundUser/enforce', query: OWNER_ROW_VIA_FUND, principal: 'fundUser', mode: 'enforce' },
|
|
340
|
-
{ name: 'b2/armUnderUser/fundUser/enforce', query: ARM_UNDER_USER(U_FUND, 'a3'), principal: 'fundUser', mode: 'enforce' },
|
|
341
|
-
{ name: 'b2/repointBroker/owner/enforce', query: REPOINT_BROKER, principal: 'owner', mode: 'enforce' },
|
|
342
|
-
{ name: 'b2/nestedFundPolicy/fundUser/enforce', query: NESTED_FUND_POLICY, principal: 'fundUser', mode: 'enforce' },
|
|
343
|
-
{ name: 'b3/armUnderUser/server/enforce', query: ARM_UNDER_USER(U_OTHER, 'a3'), principal: 'server', mode: 'enforce' },
|
|
344
|
-
{ name: 'b3/armFarFromRoot/server/enforce', query: ARM_FAR_FROM_ROOT, principal: 'server', mode: 'enforce' },
|
|
345
|
-
{ name: 'b3/armViaBroker/server/enforce', query: ARM_VIA_BROKER, principal: 'server', mode: 'enforce' },
|
|
346
|
-
{ name: 'b3/armUnderUser/owner/enforce', query: ARM_UNDER_USER(U_OWNER, 'a1'), principal: 'owner', mode: 'enforce' },
|
|
347
|
-
{ name: 'm/selfRole/owner/enforce', query: SELF_ROLE, principal: 'owner', mode: 'enforce' },
|
|
348
|
-
{ name: 'm/availability/owner/enforce', query: SET_AVAILABILITY(U_OWNER), principal: 'owner', mode: 'enforce' },
|
|
349
|
-
{ name: 'm/availabilityOther/owner/enforce', query: SET_AVAILABILITY(U_STRANGER), principal: 'owner', mode: 'enforce' },
|
|
350
|
-
{ name: 'm/forgedAudit/owner/enforce', query: AUDIT_ROW('mutation-auth-guard'), principal: 'owner', mode: 'enforce' },
|
|
351
|
-
{ name: 'm/audit/owner/enforce', query: AUDIT_ROW('platform'), principal: 'owner', mode: 'enforce' },
|
|
352
|
-
{ name: 'm/ledgerOtherFund/owner/enforce', query: AUDIT_LEDGER_ROW(U_OWNER, FUND_2), principal: 'owner', mode: 'enforce' },
|
|
353
|
-
{ name: 'm/ledgerOwnFund/fundUser/enforce', query: AUDIT_LEDGER_ROW(U_FUND, FUND_1), principal: 'fundUser', mode: 'enforce' },
|
|
354
|
-
{ name: 'm/ledger/server/enforce', query: AUDIT_LEDGER_ROW(U_OWNER, FUND_2), principal: 'server', mode: 'enforce' },
|
|
355
|
-
{ name: 'm/ledgerOtherFund/owner/shadow', query: AUDIT_LEDGER_ROW(U_OWNER, FUND_2), principal: 'owner', mode: 'shadow' },
|
|
356
|
-
{ name: 'm/ledgerOtherFund/owner/off', query: AUDIT_LEDGER_ROW(U_OWNER, FUND_2), principal: 'owner', mode: 'off' },
|
|
357
|
-
{ name: 'm/audit/owner/shadow', query: AUDIT_ROW('platform'), principal: 'owner', mode: 'shadow' },
|
|
358
|
-
{ name: 'm/systemConfig/owner/enforce', query: CONFIG_UPSERT('llm.alias.routing'), principal: 'owner', mode: 'enforce' },
|
|
359
|
-
{
|
|
360
|
-
name: 'm/ownConfig/owner/enforce',
|
|
361
|
-
query: CONFIG_UPSERT(`platform.web.chart-preferences.user.${U_OWNER}`),
|
|
362
|
-
principal: 'owner',
|
|
363
|
-
mode: 'enforce',
|
|
364
|
-
},
|
|
365
|
-
{ name: 'm/disarmAuditDown/server/enforce', query: DISARM_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
|
|
366
|
-
{ name: 'm/disarmLanesAuditDown/server/enforce', query: DISARM_LIVE_WITH_LANES, principal: 'server', mode: 'enforce', auditDown: true },
|
|
367
|
-
{ name: 'm/armLanesAuditDown/server/enforce', query: ARM_LANES_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
|
|
368
|
-
{ name: 'ctl/brokerCreate/fundUser/enforce', query: BROKER_CREATE, principal: 'fundUser', mode: 'enforce' },
|
|
369
|
-
{ name: 'ctl/brokerCreateOtherOwner/fundUser/enforce', query: BROKER_CREATE_OTHER_OWNER, principal: 'fundUser', mode: 'enforce' },
|
|
370
|
-
{ name: 'ctl/brokerBridgeForeign/fundUser/enforce', query: BROKER_BRIDGE_FOREIGN, principal: 'fundUser', mode: 'enforce' },
|
|
371
|
-
{ name: 'ctl/suspendUpsert/fundUser/enforce', query: SUSPEND_UPSERT, principal: 'fundUser', mode: 'enforce' },
|
|
372
|
-
{ name: 'ctl/brokerRotate/fundUser/enforce', query: BROKER_ROTATE(U_FUND), principal: 'fundUser', mode: 'enforce' },
|
|
373
|
-
{ name: 'ctl/brokerRotate/stranger/enforce', query: BROKER_ROTATE(U_STRANGER), principal: 'stranger', mode: 'enforce' },
|
|
374
|
-
{ name: 'cred/bulk/none/shadow', query: ORACLE_BULK, principal: 'none', mode: 'shadow' },
|
|
375
|
-
{ name: 'cred/bulk/none/enforce', query: ORACLE_BULK, principal: 'none', mode: 'enforce' },
|
|
376
|
-
{ name: 'cred/bulk/none/off', query: ORACLE_BULK, principal: 'none', mode: 'off' },
|
|
377
|
-
{ name: 'cred/bulk/admin/enforce', query: ORACLE_BULK, principal: 'admin', mode: 'enforce' },
|
|
378
|
-
{ name: 'cred/bulk/owner/shadow', query: ORACLE_BULK, principal: 'owner', mode: 'shadow' },
|
|
379
|
-
{ name: 'cred/one/none/shadow', query: ORACLE_ONE, principal: 'none', mode: 'shadow' },
|
|
380
|
-
{ name: 'cred/one/none/enforce', query: ORACLE_ONE, principal: 'none', mode: 'enforce' },
|
|
381
|
-
{ name: 'cred/nested/none/shadow', query: ORACLE_NESTED, principal: 'none', mode: 'shadow' },
|
|
382
|
-
{ name: 'cred/nestedWhere/none/shadow', query: ORACLE_NESTED_WHERE, principal: 'none', mode: 'shadow' },
|
|
383
|
-
{ name: 'cred/nested/owner/enforce', query: ORACLE_NESTED, principal: 'owner', mode: 'enforce' },
|
|
384
|
-
{ name: 'cred/bulk/server/enforce', query: ORACLE_BULK, principal: 'server', mode: 'enforce' },
|
|
385
|
-
{ name: 'cred/bulk/none/shadow+credShadow', query: ORACLE_BULK, principal: 'none', mode: 'shadow', credentialMode: 'shadow' },
|
|
386
|
-
];
|
|
387
|
-
async function counterSnapshot() {
|
|
388
|
-
const metric = await mutationAuthorizationTotal.get();
|
|
389
|
-
const out = {};
|
|
390
|
-
for (const v of metric.values) {
|
|
391
|
-
const key = `${v.labels.mutation}|${v.labels.principal_kind}|${v.labels.decision}|${v.labels.reason}`;
|
|
392
|
-
out[key] = (out[key] ?? 0) + v.value;
|
|
393
|
-
}
|
|
394
|
-
return out;
|
|
395
|
-
}
|
|
396
|
-
async function auditFailures() {
|
|
397
|
-
const metric = await mutationAuditWriteFailuresTotal.get();
|
|
398
|
-
return metric.values.reduce((sum, v) => sum + v.value, 0);
|
|
399
|
-
}
|
|
400
|
-
async function auditBypasses() {
|
|
401
|
-
const metric = await mutationAuditBypassedTotal.get();
|
|
402
|
-
return metric.values.reduce((sum, v) => sum + v.value, 0);
|
|
403
|
-
}
|
|
404
|
-
function policyBy(where) {
|
|
405
|
-
return Object.values(POLICIES).find((p) => (where.id !== undefined && p.id === where.id) || (where.alpacaAccountId !== undefined && p.alpacaAccountId === where.alpacaAccountId));
|
|
406
|
-
}
|
|
407
|
-
function policyFacts(p) {
|
|
408
|
-
return {
|
|
409
|
-
...p,
|
|
410
|
-
realtimeTradingEnabled: false,
|
|
411
|
-
paperTradingOnly: false,
|
|
412
|
-
killSwitchEnabled: false,
|
|
413
|
-
autonomyMode: 'ADVISORY_ONLY',
|
|
414
|
-
intradayLanePrefs: null,
|
|
415
|
-
alpacaAccount: ACCOUNTS[p.alpacaAccountId],
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Fake delegates for the tenancy models: `findMany` / `findUnique` over the
|
|
420
|
-
* fixture rows (the entitlement read and the guard's scope check), and
|
|
421
|
-
* recording reads and writes.
|
|
422
|
-
*/
|
|
423
|
-
function tenancyDelegates(write, read, reads, membershipReadsDown) {
|
|
424
|
-
const out = {};
|
|
425
|
-
for (const [delegate, rows] of Object.entries(TENANCY)) {
|
|
426
|
-
out[delegate] = {
|
|
427
|
-
findMany: ({ where }) => read(`${delegate}.findMany`, rows.filter((r) => matches(r, where))),
|
|
428
|
-
findUnique: ({ where, select }) => {
|
|
429
|
-
if (membershipReadsDown() && (delegate === 'orgMembership' || delegate === 'fundAssignment')) {
|
|
430
|
-
reads.push(`${delegate}.findUnique`);
|
|
431
|
-
return Promise.reject(new Error('membership table unavailable'));
|
|
432
|
-
}
|
|
433
|
-
const row = rows.find((r) => matches(r, where));
|
|
434
|
-
return read(`${delegate}.findUnique`, row ? project(delegate, row, select) : null);
|
|
435
|
-
},
|
|
436
|
-
create: () => write(`${delegate}.create`, { id: `${delegate}-new` }),
|
|
437
|
-
update: ({ where }) => write(`${delegate}.update`, { id: where.id }),
|
|
438
|
-
upsert: ({ where }) => write(`${delegate}.upsert`, { id: where.id }),
|
|
439
|
-
delete: ({ where }) => write(`${delegate}.delete`, { id: where.id }),
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
return out;
|
|
443
|
-
}
|
|
444
|
-
async function main() {
|
|
445
|
-
let mode = 'enforce';
|
|
446
|
-
let enforcedModels = new Set();
|
|
447
|
-
let auditDown = false;
|
|
448
|
-
let credentialMode = 'enforce';
|
|
449
|
-
let membershipReadsDown = false;
|
|
450
|
-
let writes = [];
|
|
451
|
-
let reads = [];
|
|
452
|
-
let audit = [];
|
|
453
|
-
const write = (name, value) => {
|
|
454
|
-
writes.push(name);
|
|
455
|
-
return Promise.resolve(value);
|
|
456
|
-
};
|
|
457
|
-
const read = (name, value) => {
|
|
458
|
-
reads.push(name);
|
|
459
|
-
return Promise.resolve(value);
|
|
460
|
-
};
|
|
461
|
-
const prisma = {
|
|
462
|
-
tradingPolicy: {
|
|
463
|
-
findUnique: ({ where }) => {
|
|
464
|
-
const p = policyBy(where);
|
|
465
|
-
return read('tradingPolicy.findUnique', p ? policyFacts(p) : null);
|
|
466
|
-
},
|
|
467
|
-
findMany: () => read('tradingPolicy.findMany', Object.values(POLICIES).map(policyFacts)),
|
|
468
|
-
update: ({ where }) => write('tradingPolicy.update', { ...policyBy(where), realtimeTradingEnabled: true }),
|
|
469
|
-
updateMany: () => write('tradingPolicy.updateMany', { count: 2 }),
|
|
470
|
-
upsert: ({ where }) => write('tradingPolicy.upsert', { ...policyBy(where) }),
|
|
471
|
-
},
|
|
472
|
-
alpacaAccount: {
|
|
473
|
-
findUnique: ({ where }) => read('alpacaAccount.findUnique', typeof where.id === 'string' ? (ACCOUNTS[where.id] ?? null) : null),
|
|
474
|
-
update: () => write('alpacaAccount.update', { id: 'a1', type: 'LIVE' }),
|
|
475
|
-
create: () => write('alpacaAccount.create', { id: 'a9', type: 'PAPER' }),
|
|
476
|
-
delete: () => write('alpacaAccount.delete', { id: 'a1', type: 'LIVE' }),
|
|
477
|
-
},
|
|
478
|
-
user: {
|
|
479
|
-
update: ({ where }) => write('user.update', { id: where.id }),
|
|
480
|
-
},
|
|
481
|
-
...tenancyDelegates(write, read, { push: (name) => reads.push(name) }, () => membershipReadsDown),
|
|
482
|
-
auditLog: {
|
|
483
|
-
create: ({ data }) => {
|
|
484
|
-
if (auditDown)
|
|
485
|
-
return Promise.reject(new Error('audit table unavailable'));
|
|
486
|
-
audit.push(data);
|
|
487
|
-
if (data.metadata === null || typeof data.metadata !== 'object' || data.metadata.source !== 'mutation-auth-guard') {
|
|
488
|
-
writes.push('auditLog.create');
|
|
489
|
-
}
|
|
490
|
-
return Promise.resolve({ id: `audit-${audit.length}` });
|
|
491
|
-
},
|
|
492
|
-
},
|
|
493
|
-
configuration: {
|
|
494
|
-
upsert: ({ where }) => write('configuration.upsert', { id: `c-${String(where.configKey)}` }),
|
|
495
|
-
},
|
|
496
|
-
};
|
|
497
|
-
const schema = await buildSchema({
|
|
498
|
-
resolvers: [
|
|
499
|
-
TradingPolicyCrudResolver,
|
|
500
|
-
AlpacaAccountCrudResolver,
|
|
501
|
-
UserCrudResolver,
|
|
502
|
-
OrganizationCrudResolver,
|
|
503
|
-
OrgMembershipCrudResolver,
|
|
504
|
-
FundCrudResolver,
|
|
505
|
-
FundAssignmentCrudResolver,
|
|
506
|
-
BrokerageAccountCrudResolver,
|
|
507
|
-
AuditLogCrudResolver,
|
|
508
|
-
ConfigurationCrudResolver,
|
|
509
|
-
],
|
|
510
|
-
validate: false,
|
|
511
|
-
});
|
|
512
|
-
const guardedMutations = installMutationAuthGuard(schema, {
|
|
513
|
-
modeProvider: () => mode,
|
|
514
|
-
enforcedModelsProvider: () => enforcedModels,
|
|
515
|
-
credentialGuardModeProvider: () => credentialMode,
|
|
516
|
-
});
|
|
517
|
-
// Installing twice must not double-guard (each decision would count twice).
|
|
518
|
-
installMutationAuthGuard(schema, { modeProvider: () => mode, enforcedModelsProvider: () => enforcedModels });
|
|
519
|
-
const mutationFieldCount = Object.keys(schema.getMutationType()?.getFields() ?? {}).length;
|
|
520
|
-
const server = new ApolloServer({ schema, plugins: [createHttpStatusMapperPlugin()] });
|
|
521
|
-
await server.start();
|
|
522
|
-
const results = {};
|
|
523
|
-
for (const scenario of SCENARIOS) {
|
|
524
|
-
mode = scenario.mode;
|
|
525
|
-
enforcedModels = new Set(scenario.enforcedModels ?? []);
|
|
526
|
-
auditDown = scenario.auditDown === true;
|
|
527
|
-
credentialMode = scenario.credentialMode ?? 'enforce';
|
|
528
|
-
membershipReadsDown = scenario.membershipReadsDown === true;
|
|
529
|
-
writes = [];
|
|
530
|
-
reads = [];
|
|
531
|
-
audit = [];
|
|
532
|
-
resetMutationAuthLogThrottle();
|
|
533
|
-
const before = await counterSnapshot();
|
|
534
|
-
const failuresBefore = await auditFailures();
|
|
535
|
-
const bypassesBefore = await auditBypasses();
|
|
536
|
-
const response = await server.executeOperation({ query: scenario.query }, {
|
|
537
|
-
contextValue: {
|
|
538
|
-
prisma,
|
|
539
|
-
principal: PRINCIPALS[scenario.principal],
|
|
540
|
-
req: {
|
|
541
|
-
ip: '203.0.113.7',
|
|
542
|
-
headers: { 'user-agent': 'mutation-guard-harness', 'x-adaptic-change-reason': 'harness: arm LIVE' },
|
|
543
|
-
},
|
|
544
|
-
},
|
|
545
|
-
});
|
|
546
|
-
const after = await counterSnapshot();
|
|
547
|
-
const counterDelta = {};
|
|
548
|
-
for (const [key, value] of Object.entries(after)) {
|
|
549
|
-
const delta = value - (before[key] ?? 0);
|
|
550
|
-
if (delta !== 0)
|
|
551
|
-
counterDelta[key] = delta;
|
|
552
|
-
}
|
|
553
|
-
const body = response.body.kind === 'single' ? response.body.singleResult : null;
|
|
554
|
-
const errors = body?.errors ?? [];
|
|
555
|
-
results[scenario.name] = {
|
|
556
|
-
status: response.http.status ?? 200,
|
|
557
|
-
codes: errors.map((e) => String(e.extensions?.code)),
|
|
558
|
-
reasons: errors.map((e) => String(e.extensions?.reason)),
|
|
559
|
-
json: JSON.stringify(body),
|
|
560
|
-
writes,
|
|
561
|
-
reads,
|
|
562
|
-
audit: JSON.parse(JSON.stringify(audit)),
|
|
563
|
-
counterDelta,
|
|
564
|
-
auditFailureDelta: (await auditFailures()) - failuresBefore,
|
|
565
|
-
auditBypassDelta: (await auditBypasses()) - bypassesBefore,
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
await server.stop();
|
|
569
|
-
process.stdout.write(`<<<RESULTS>>>${JSON.stringify({ guardedMutations, mutationFieldCount, results })}<<<END>>>\n`);
|
|
570
|
-
}
|
|
571
|
-
main().catch((error) => {
|
|
572
|
-
process.stderr.write(`harness failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
|
573
|
-
process.exit(1);
|
|
574
|
-
});
|
|
575
|
-
//# sourceMappingURL=mutation-auth-guard.harness.js.map
|