@adaptic/backend-legacy 0.0.1055 → 0.0.1056
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/esm/auth/membership-write-authority.d.ts +110 -0
- package/esm/auth/membership-write-authority.mjs +125 -0
- package/esm/auth/mutation-authorization.d.ts +19 -3
- package/esm/auth/mutation-authorization.mjs +21 -2
- package/esm/auth/nested-write-policy.d.ts +4 -0
- package/esm/auth/nested-write-policy.mjs +19 -0
- package/esm/auth/tenancy-scope.d.ts +2 -1
- package/esm/auth/tenancy-scope.mjs +2 -1
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +2 -0
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +136 -10
- package/esm/middleware/mutation-auth-guard.d.ts +4 -2
- package/esm/middleware/mutation-auth-guard.mjs +20 -2
- package/esm/middleware/mutation-membership-facts.d.ts +133 -0
- package/esm/middleware/mutation-membership-facts.mjs +271 -0
- package/esm/middleware/mutation-tenant-facts.d.ts +4 -2
- package/esm/middleware/mutation-tenant-facts.mjs +4 -2
- package/package.json +1 -1
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may write an entitlement row — pure decision logic.
|
|
3
|
+
*
|
|
4
|
+
* `OrgMembership.role` and `FundAssignment.role` are the authority the rest of
|
|
5
|
+
* the system reads: the platform derives a person's personas from them at
|
|
6
|
+
* sign-in, the tenancy scope derives which organizations and funds they reach,
|
|
7
|
+
* and fund entitlement admits writes to every brokerage account bridged to a
|
|
8
|
+
* fund. Being inside a tenant is therefore not enough to write one of these
|
|
9
|
+
* rows. A plain member who could write them could make themselves OWNER of
|
|
10
|
+
* their organization, or MANAGER of any fund in it, and every downstream
|
|
11
|
+
* authority would follow.
|
|
12
|
+
*
|
|
13
|
+
* A user principal may write an entitlement row only with authority over the
|
|
14
|
+
* tenant the row belongs to:
|
|
15
|
+
*
|
|
16
|
+
* - **OrgMembership** — the caller holds OWNER or ADMIN in that organization.
|
|
17
|
+
* A row whose role is OWNER, before or after the write, needs OWNER: an
|
|
18
|
+
* ADMIN who could grant OWNER could grant it to themselves, and an ADMIN who
|
|
19
|
+
* could demote or remove an OWNER could take the organization from them.
|
|
20
|
+
* - **FundAssignment** — the caller holds OWNER or ADMIN in the fund's
|
|
21
|
+
* organization, or a MANAGER assignment on that same fund. MANAGER is the
|
|
22
|
+
* highest fund role and is the role that runs the fund's team, so admitting
|
|
23
|
+
* it lets no one rise above what they already hold, and it confers nothing
|
|
24
|
+
* on any other fund.
|
|
25
|
+
*
|
|
26
|
+
* One self-service write is admitted without that authority, because the
|
|
27
|
+
* backend can prove from its own rows that nothing is being taken from
|
|
28
|
+
* anyone: the **first owner**. A caller makes themselves OWNER of an
|
|
29
|
+
* organization that is not deleted and has no members and no funds. That is
|
|
30
|
+
* the state an organization is in the moment its creator has written it; once
|
|
31
|
+
* anyone holds a membership, or the organization holds a fund, the exception
|
|
32
|
+
* closes, and an organization with neither has nothing in it to claim.
|
|
33
|
+
*
|
|
34
|
+
* Joining an organization any other way (an invitation, an email-domain
|
|
35
|
+
* match) rests on proof the backend cannot verify from rows the caller is
|
|
36
|
+
* unable to write — an invitation is a single-use token, and a user's email
|
|
37
|
+
* address is a column of their own row — so those memberships are written by
|
|
38
|
+
* a service principal after the platform has checked the proof.
|
|
39
|
+
*
|
|
40
|
+
* Everything here is decided from facts read from the database for this
|
|
41
|
+
* mutation (`src/middleware/mutation-membership-facts.ts`), never from the
|
|
42
|
+
* token's claims.
|
|
43
|
+
*
|
|
44
|
+
* @module auth/membership-write-authority
|
|
45
|
+
*/
|
|
46
|
+
/** An entitlement model. */
|
|
47
|
+
export type MembershipModel = 'OrgMembership' | 'FundAssignment';
|
|
48
|
+
/** Whether a model is one of the entitlement models this module decides. */
|
|
49
|
+
export declare function isMembershipModel(model: string): model is MembershipModel;
|
|
50
|
+
/** The organization role that owns an organization. */
|
|
51
|
+
export declare const ORG_OWNER_ROLE = "OWNER";
|
|
52
|
+
/** Organization roles that may manage memberships and fund assignments. */
|
|
53
|
+
export declare const ORG_MANAGEMENT_ROLES: ReadonlySet<string>;
|
|
54
|
+
/** The fund role that may manage its own fund's assignments. */
|
|
55
|
+
export declare const FUND_MANAGER_ROLE = "MANAGER";
|
|
56
|
+
/** What one side of an entitlement write does to one row. */
|
|
57
|
+
export interface MembershipRowWrite {
|
|
58
|
+
/** Whether the row is being created, or an existing row changed or removed. */
|
|
59
|
+
readonly side: 'create' | 'existing';
|
|
60
|
+
/** The organization the row belongs to (for a fund assignment, its fund's). */
|
|
61
|
+
readonly organizationId: string;
|
|
62
|
+
/** For a fund assignment: the fund. */
|
|
63
|
+
readonly fundId?: string;
|
|
64
|
+
/** The person the row is for. */
|
|
65
|
+
readonly memberUserId: string;
|
|
66
|
+
/**
|
|
67
|
+
* Every role the row holds before or after the write: the payload's role
|
|
68
|
+
* (or the column default) for a create; the stored role, and the new one
|
|
69
|
+
* if the write sets it, for an existing row.
|
|
70
|
+
*/
|
|
71
|
+
readonly rolesTouched: readonly string[];
|
|
72
|
+
/** Whether the write sets the row's free-form `permissions`. */
|
|
73
|
+
readonly setsPermissions: boolean;
|
|
74
|
+
}
|
|
75
|
+
/** What the caller holds in the row's tenant, read from the database. */
|
|
76
|
+
export interface CallerStanding {
|
|
77
|
+
/** The caller's OrgMembership role in the row's organization, or `null`. */
|
|
78
|
+
readonly orgRole: string | null;
|
|
79
|
+
/** For a fund assignment: the caller's FundAssignment role on that fund, or `null`. */
|
|
80
|
+
readonly fundRole: string | null;
|
|
81
|
+
}
|
|
82
|
+
/** The facts a first-owner OrgMembership create is decided on. */
|
|
83
|
+
export interface FirstOwnerFacts {
|
|
84
|
+
readonly organizationDeleted: boolean;
|
|
85
|
+
readonly organizationMemberCount: number;
|
|
86
|
+
readonly organizationFundCount: number;
|
|
87
|
+
}
|
|
88
|
+
/** Why an entitlement write was admitted or refused. */
|
|
89
|
+
export type MembershipVerdict = 'membership_org_admin' | 'membership_fund_manager' | 'membership_first_owner' | 'tenant_out_of_scope' | 'membership_role_insufficient' | 'membership_owner_requires_owner';
|
|
90
|
+
/** The verdicts that admit the write. */
|
|
91
|
+
export declare const ADMITTING_MEMBERSHIP_VERDICTS: ReadonlySet<MembershipVerdict>;
|
|
92
|
+
/**
|
|
93
|
+
* Whether a write could be a first-owner create: the caller making
|
|
94
|
+
* themselves a member of an organization they do not belong to. The
|
|
95
|
+
* first-owner facts are read only for this shape.
|
|
96
|
+
*/
|
|
97
|
+
export declare function isFirstOwnerCandidate(model: MembershipModel, write: MembershipRowWrite, callerId: string, standing: CallerStanding): boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Decide one side of an entitlement write. Pure; performs no I/O.
|
|
100
|
+
*
|
|
101
|
+
* @param model - The entitlement model written.
|
|
102
|
+
* @param write - What the write does to the row.
|
|
103
|
+
* @param callerId - The user principal's subject.
|
|
104
|
+
* @param standing - What the caller holds in the row's tenant.
|
|
105
|
+
* @param firstOwner - The first-owner facts, read only for an
|
|
106
|
+
* {@link isFirstOwnerCandidate} write; `null` otherwise.
|
|
107
|
+
* @returns The verdict.
|
|
108
|
+
*/
|
|
109
|
+
export declare function decideMembershipWrite(model: MembershipModel, write: MembershipRowWrite, callerId: string, standing: CallerStanding, firstOwner: FirstOwnerFacts | null): MembershipVerdict;
|
|
110
|
+
//# sourceMappingURL=membership-write-authority.d.ts.map
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may write an entitlement row — pure decision logic.
|
|
3
|
+
*
|
|
4
|
+
* `OrgMembership.role` and `FundAssignment.role` are the authority the rest of
|
|
5
|
+
* the system reads: the platform derives a person's personas from them at
|
|
6
|
+
* sign-in, the tenancy scope derives which organizations and funds they reach,
|
|
7
|
+
* and fund entitlement admits writes to every brokerage account bridged to a
|
|
8
|
+
* fund. Being inside a tenant is therefore not enough to write one of these
|
|
9
|
+
* rows. A plain member who could write them could make themselves OWNER of
|
|
10
|
+
* their organization, or MANAGER of any fund in it, and every downstream
|
|
11
|
+
* authority would follow.
|
|
12
|
+
*
|
|
13
|
+
* A user principal may write an entitlement row only with authority over the
|
|
14
|
+
* tenant the row belongs to:
|
|
15
|
+
*
|
|
16
|
+
* - **OrgMembership** — the caller holds OWNER or ADMIN in that organization.
|
|
17
|
+
* A row whose role is OWNER, before or after the write, needs OWNER: an
|
|
18
|
+
* ADMIN who could grant OWNER could grant it to themselves, and an ADMIN who
|
|
19
|
+
* could demote or remove an OWNER could take the organization from them.
|
|
20
|
+
* - **FundAssignment** — the caller holds OWNER or ADMIN in the fund's
|
|
21
|
+
* organization, or a MANAGER assignment on that same fund. MANAGER is the
|
|
22
|
+
* highest fund role and is the role that runs the fund's team, so admitting
|
|
23
|
+
* it lets no one rise above what they already hold, and it confers nothing
|
|
24
|
+
* on any other fund.
|
|
25
|
+
*
|
|
26
|
+
* One self-service write is admitted without that authority, because the
|
|
27
|
+
* backend can prove from its own rows that nothing is being taken from
|
|
28
|
+
* anyone: the **first owner**. A caller makes themselves OWNER of an
|
|
29
|
+
* organization that is not deleted and has no members and no funds. That is
|
|
30
|
+
* the state an organization is in the moment its creator has written it; once
|
|
31
|
+
* anyone holds a membership, or the organization holds a fund, the exception
|
|
32
|
+
* closes, and an organization with neither has nothing in it to claim.
|
|
33
|
+
*
|
|
34
|
+
* Joining an organization any other way (an invitation, an email-domain
|
|
35
|
+
* match) rests on proof the backend cannot verify from rows the caller is
|
|
36
|
+
* unable to write — an invitation is a single-use token, and a user's email
|
|
37
|
+
* address is a column of their own row — so those memberships are written by
|
|
38
|
+
* a service principal after the platform has checked the proof.
|
|
39
|
+
*
|
|
40
|
+
* Everything here is decided from facts read from the database for this
|
|
41
|
+
* mutation (`src/middleware/mutation-membership-facts.ts`), never from the
|
|
42
|
+
* token's claims.
|
|
43
|
+
*
|
|
44
|
+
* @module auth/membership-write-authority
|
|
45
|
+
*/
|
|
46
|
+
/** Whether a model is one of the entitlement models this module decides. */
|
|
47
|
+
export function isMembershipModel(model) {
|
|
48
|
+
return model === 'OrgMembership' || model === 'FundAssignment';
|
|
49
|
+
}
|
|
50
|
+
/** The organization role that owns an organization. */
|
|
51
|
+
export const ORG_OWNER_ROLE = 'OWNER';
|
|
52
|
+
/** Organization roles that may manage memberships and fund assignments. */
|
|
53
|
+
export const ORG_MANAGEMENT_ROLES = new Set([
|
|
54
|
+
ORG_OWNER_ROLE,
|
|
55
|
+
'ADMIN',
|
|
56
|
+
]);
|
|
57
|
+
/** The fund role that may manage its own fund's assignments. */
|
|
58
|
+
export const FUND_MANAGER_ROLE = 'MANAGER';
|
|
59
|
+
/** The verdicts that admit the write. */
|
|
60
|
+
export const ADMITTING_MEMBERSHIP_VERDICTS = new Set([
|
|
61
|
+
'membership_org_admin',
|
|
62
|
+
'membership_fund_manager',
|
|
63
|
+
'membership_first_owner',
|
|
64
|
+
]);
|
|
65
|
+
/**
|
|
66
|
+
* Whether a write could be a first-owner create: the caller making
|
|
67
|
+
* themselves a member of an organization they do not belong to. The
|
|
68
|
+
* first-owner facts are read only for this shape.
|
|
69
|
+
*/
|
|
70
|
+
export function isFirstOwnerCandidate(model, write, callerId, standing) {
|
|
71
|
+
return (model === 'OrgMembership' &&
|
|
72
|
+
write.side === 'create' &&
|
|
73
|
+
write.memberUserId === callerId &&
|
|
74
|
+
standing.orgRole === null);
|
|
75
|
+
}
|
|
76
|
+
/** Whether a create makes the caller the plain first OWNER of an empty organization. */
|
|
77
|
+
function isFirstOwner(write, facts) {
|
|
78
|
+
return (write.rolesTouched.length === 1 &&
|
|
79
|
+
write.rolesTouched[0] === ORG_OWNER_ROLE &&
|
|
80
|
+
!write.setsPermissions &&
|
|
81
|
+
!facts.organizationDeleted &&
|
|
82
|
+
facts.organizationMemberCount === 0 &&
|
|
83
|
+
facts.organizationFundCount === 0);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Decide one side of an entitlement write. Pure; performs no I/O.
|
|
87
|
+
*
|
|
88
|
+
* @param model - The entitlement model written.
|
|
89
|
+
* @param write - What the write does to the row.
|
|
90
|
+
* @param callerId - The user principal's subject.
|
|
91
|
+
* @param standing - What the caller holds in the row's tenant.
|
|
92
|
+
* @param firstOwner - The first-owner facts, read only for an
|
|
93
|
+
* {@link isFirstOwnerCandidate} write; `null` otherwise.
|
|
94
|
+
* @returns The verdict.
|
|
95
|
+
*/
|
|
96
|
+
export function decideMembershipWrite(model, write, callerId, standing, firstOwner) {
|
|
97
|
+
const { orgRole, fundRole } = standing;
|
|
98
|
+
if (model === 'OrgMembership') {
|
|
99
|
+
if (orgRole === ORG_OWNER_ROLE)
|
|
100
|
+
return 'membership_org_admin';
|
|
101
|
+
if (orgRole !== null && ORG_MANAGEMENT_ROLES.has(orgRole)) {
|
|
102
|
+
return write.rolesTouched.includes(ORG_OWNER_ROLE)
|
|
103
|
+
? 'membership_owner_requires_owner'
|
|
104
|
+
: 'membership_org_admin';
|
|
105
|
+
}
|
|
106
|
+
if (orgRole !== null)
|
|
107
|
+
return 'membership_role_insufficient';
|
|
108
|
+
if (firstOwner !== null &&
|
|
109
|
+
isFirstOwnerCandidate(model, write, callerId, standing) &&
|
|
110
|
+
isFirstOwner(write, firstOwner)) {
|
|
111
|
+
return 'membership_first_owner';
|
|
112
|
+
}
|
|
113
|
+
return 'tenant_out_of_scope';
|
|
114
|
+
}
|
|
115
|
+
if (orgRole !== null && ORG_MANAGEMENT_ROLES.has(orgRole)) {
|
|
116
|
+
return 'membership_org_admin';
|
|
117
|
+
}
|
|
118
|
+
if (fundRole === FUND_MANAGER_ROLE)
|
|
119
|
+
return 'membership_fund_manager';
|
|
120
|
+
if (orgRole !== null || fundRole !== null) {
|
|
121
|
+
return 'membership_role_insufficient';
|
|
122
|
+
}
|
|
123
|
+
return 'tenant_out_of_scope';
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=membership-write-authority.js.map
|
|
@@ -30,7 +30,15 @@
|
|
|
30
30
|
* accounts has no single owner to check.
|
|
31
31
|
* - `self` — `User`: only the caller's own row, and only its profile and
|
|
32
32
|
* onboarding fields (`./user-write-content.ts`).
|
|
33
|
-
* - `
|
|
33
|
+
* - `membership_authority` — `OrgMembership` and `FundAssignment`, the rows
|
|
34
|
+
* every other entitlement is read from: the caller must hold OWNER or
|
|
35
|
+
* ADMIN in the row's organization (OWNER for a row whose role is OWNER),
|
|
36
|
+
* or MANAGER on the assignment's own fund; or the write makes the caller
|
|
37
|
+
* the first owner of an empty organization, the one self-service create
|
|
38
|
+
* the backend can verify from rows the caller cannot write
|
|
39
|
+
* (`./membership-write-authority.ts`). Roles are read from the database
|
|
40
|
+
* for the mutation, never from the token.
|
|
41
|
+
* - `tenant_scoped` — the other tenancy-governed models: the row (for an update,
|
|
34
42
|
* upsert or delete) or the payload's tenant (for a create) must lie in the
|
|
35
43
|
* caller's OrgMembership / FundAssignment entitlement. The guard checks
|
|
36
44
|
* this itself, whatever `TENANCY_SCOPING_MODE` says, because fund
|
|
@@ -81,6 +89,7 @@
|
|
|
81
89
|
*
|
|
82
90
|
* @module auth/mutation-authorization
|
|
83
91
|
*/
|
|
92
|
+
import { type MembershipVerdict } from './membership-write-authority';
|
|
84
93
|
import type { BackendPrincipal } from './token-verifier';
|
|
85
94
|
/** Operating mode of the mutation guard. See the module doc. */
|
|
86
95
|
export type MutationAuthMode = 'off' | 'shadow' | 'enforce';
|
|
@@ -173,7 +182,7 @@ export interface MutationTarget {
|
|
|
173
182
|
*/
|
|
174
183
|
export declare function classifyMutationField(fieldName: string, models: ReadonlySet<string>): MutationTarget;
|
|
175
184
|
/** How a `user` principal may write a model. See the module doc. */
|
|
176
|
-
export type UserWritePolicy = 'service_only' | 'account_owned' | 'self' | 'tenant_scoped' | 'mandate_tenant' | 'authenticated' | 'resolver_authorized';
|
|
185
|
+
export type UserWritePolicy = 'service_only' | 'account_owned' | 'self' | 'tenant_scoped' | 'membership_authority' | 'mandate_tenant' | 'authenticated' | 'resolver_authorized';
|
|
177
186
|
/** A model's user policy plus the actions a user may perform under it. */
|
|
178
187
|
export interface ModelWriteRule {
|
|
179
188
|
readonly policy: UserWritePolicy;
|
|
@@ -196,7 +205,7 @@ export declare const MODEL_WRITE_RULES: ReadonlyMap<string, ModelWriteRule>;
|
|
|
196
205
|
/** The write rule for a model. */
|
|
197
206
|
export declare function ruleFor(model: string): ModelWriteRule;
|
|
198
207
|
/** Why a mutation was admitted or refused. A bounded metric label. */
|
|
199
|
-
export type MutationAuthReason = 'guard_off' | 'guard_error' | 'service_principal' | 'admin_principal' | 'account_owner' | 'account_fund_entitled' | 'self' | 'tenant_scoped' | 'authenticated_user_model' | 'resolver_authorized' | 'unauthenticated' | 'service_principal_only' | 'model_not_user_writable' | 'action_not_user_writable' | 'bulk_not_user_writable' | 'not_account_owner' | 'account_unresolved' | 'not_self' | 'tenant_out_of_scope' | 'tenant_unresolved' | 'field_not_user_writable' | 'reserved_audit_source' | 'audit_actor_mismatch' | 'ledger_fund_reserved' | 'config_key_not_user_scoped' | 'nested_write_not_user_writable' | 'nested_entitlement_write';
|
|
208
|
+
export type MutationAuthReason = 'guard_off' | 'guard_error' | 'service_principal' | 'admin_principal' | 'account_owner' | 'account_fund_entitled' | 'self' | 'tenant_scoped' | 'authenticated_user_model' | 'resolver_authorized' | 'unauthenticated' | 'service_principal_only' | 'model_not_user_writable' | 'action_not_user_writable' | 'bulk_not_user_writable' | 'not_account_owner' | 'account_unresolved' | 'not_self' | 'tenant_out_of_scope' | 'tenant_unresolved' | 'membership_org_admin' | 'membership_fund_manager' | 'membership_first_owner' | 'membership_role_insufficient' | 'membership_owner_requires_owner' | 'membership_authority_unresolved' | 'field_not_user_writable' | 'reserved_audit_source' | 'audit_actor_mismatch' | 'ledger_fund_reserved' | 'config_key_not_user_scoped' | 'nested_write_not_user_writable' | 'nested_entitlement_write';
|
|
200
209
|
/** Ownership facts the middleware resolved for an `account_owned` write. */
|
|
201
210
|
export type AccountOwnership = {
|
|
202
211
|
readonly kind: 'owner';
|
|
@@ -209,6 +218,11 @@ export type AccountOwnership = {
|
|
|
209
218
|
};
|
|
210
219
|
/** For a `tenant_scoped` write: whether the row or payload lies in the caller's entitlement. */
|
|
211
220
|
export type TenantScope = 'in_scope' | 'out_of_scope';
|
|
221
|
+
/**
|
|
222
|
+
* For a `membership_authority` write: the verdict read from the database, or
|
|
223
|
+
* `unresolved` when the rows it reaches could not be identified or read.
|
|
224
|
+
*/
|
|
225
|
+
export type MembershipAuthority = MembershipVerdict | 'unresolved';
|
|
212
226
|
/** Everything the decision needs beyond the principal and target. */
|
|
213
227
|
export interface MutationFacts {
|
|
214
228
|
/** For `account_owned`: whether the caller owns every account touched. */
|
|
@@ -217,6 +231,8 @@ export interface MutationFacts {
|
|
|
217
231
|
readonly targetsSelf?: boolean;
|
|
218
232
|
/** For `tenant_scoped`: the guard's own scope check; absent = not yet resolved. */
|
|
219
233
|
readonly tenantScope?: TenantScope;
|
|
234
|
+
/** For `membership_authority`: the caller's authority over the row; absent = not yet resolved. */
|
|
235
|
+
readonly membershipAuthority?: MembershipAuthority;
|
|
220
236
|
/**
|
|
221
237
|
* Every model the mutation's nested writes reach. A non-service principal is
|
|
222
238
|
* refused when one is service-principal only, whatever its root.
|
|
@@ -30,7 +30,15 @@
|
|
|
30
30
|
* accounts has no single owner to check.
|
|
31
31
|
* - `self` — `User`: only the caller's own row, and only its profile and
|
|
32
32
|
* onboarding fields (`./user-write-content.ts`).
|
|
33
|
-
* - `
|
|
33
|
+
* - `membership_authority` — `OrgMembership` and `FundAssignment`, the rows
|
|
34
|
+
* every other entitlement is read from: the caller must hold OWNER or
|
|
35
|
+
* ADMIN in the row's organization (OWNER for a row whose role is OWNER),
|
|
36
|
+
* or MANAGER on the assignment's own fund; or the write makes the caller
|
|
37
|
+
* the first owner of an empty organization, the one self-service create
|
|
38
|
+
* the backend can verify from rows the caller cannot write
|
|
39
|
+
* (`./membership-write-authority.ts`). Roles are read from the database
|
|
40
|
+
* for the mutation, never from the token.
|
|
41
|
+
* - `tenant_scoped` — the other tenancy-governed models: the row (for an update,
|
|
34
42
|
* upsert or delete) or the payload's tenant (for a create) must lie in the
|
|
35
43
|
* caller's OrgMembership / FundAssignment entitlement. The guard checks
|
|
36
44
|
* this itself, whatever `TENANCY_SCOPING_MODE` says, because fund
|
|
@@ -81,6 +89,7 @@
|
|
|
81
89
|
*
|
|
82
90
|
* @module auth/mutation-authorization
|
|
83
91
|
*/
|
|
92
|
+
import { ADMITTING_MEMBERSHIP_VERDICTS, isMembershipModel, } from './membership-write-authority.mjs';
|
|
84
93
|
import { DESK_MODELS, GOVERNED_MODELS } from './tenancy-scope.mjs';
|
|
85
94
|
/** Environment variable selecting the global mode. */
|
|
86
95
|
export const MUTATION_AUTH_MODE_ENV = 'MUTATION_AUTH_MODE';
|
|
@@ -246,7 +255,11 @@ export const MODEL_WRITE_RULES = new Map([
|
|
|
246
255
|
['TradingPolicy', { policy: 'account_owned', userActions: ONLY('create', 'update', 'upsert') }],
|
|
247
256
|
['AlpacaAccount', { policy: 'account_owned', userActions: ONLY('create', 'update') }],
|
|
248
257
|
['User', { policy: 'self', userActions: ONLY('update') }],
|
|
249
|
-
...GOVERNED_MODELS.map((model) => [model, { policy: 'tenant_scoped' }]),
|
|
258
|
+
...GOVERNED_MODELS.filter((model) => !isMembershipModel(model)).map((model) => [model, { policy: 'tenant_scoped' }]),
|
|
259
|
+
// The entitlement rows: being inside the tenant is not enough to write the
|
|
260
|
+
// role that decides what everyone in it may do.
|
|
261
|
+
['OrgMembership', { policy: 'membership_authority' }],
|
|
262
|
+
['FundAssignment', { policy: 'membership_authority' }],
|
|
250
263
|
['Configuration', { policy: 'authenticated', userActions: ONLY('upsert') }],
|
|
251
264
|
['DashboardLayout', { policy: 'authenticated', userActions: ONLY('upsert') }],
|
|
252
265
|
['Mandate', { policy: 'authenticated', userActions: ONLY('create', 'update') }],
|
|
@@ -326,6 +339,12 @@ export function evaluateMutationAccess(principal, target, facts = {}) {
|
|
|
326
339
|
}
|
|
327
340
|
case 'self':
|
|
328
341
|
return facts.targetsSelf === true ? allow('self') : forbid('not_self');
|
|
342
|
+
case 'membership_authority': {
|
|
343
|
+
const authority = facts.membershipAuthority;
|
|
344
|
+
if (authority === undefined || authority === 'unresolved')
|
|
345
|
+
return forbid('membership_authority_unresolved');
|
|
346
|
+
return ADMITTING_MEMBERSHIP_VERDICTS.has(authority) ? allow(authority) : forbid(authority);
|
|
347
|
+
}
|
|
329
348
|
case 'tenant_scoped':
|
|
330
349
|
case 'mandate_tenant':
|
|
331
350
|
if (facts.tenantScope === 'in_scope')
|
|
@@ -33,6 +33,10 @@
|
|
|
33
33
|
* root's tenant check reads exactly that connect); re-tenanting an
|
|
34
34
|
* existing row is refused;
|
|
35
35
|
* - into the caller's own `User` row while the parent is being created;
|
|
36
|
+
* - into any `User` row as the member of a root `OrgMembership` or
|
|
37
|
+
* `FundAssignment` create: adding a person to a team is what those
|
|
38
|
+
* creates are for, and the root decision reads that connect and requires
|
|
39
|
+
* authority over the tenant (`./membership-write-authority.ts`);
|
|
36
40
|
* - into `AlpacaAccount` only as the policy's own account on a root
|
|
37
41
|
* TradingPolicy create, whose ownership check reads that connect.
|
|
38
42
|
* - **Content writes into an owned model** (account, policy, user row) are
|
|
@@ -33,6 +33,10 @@
|
|
|
33
33
|
* root's tenant check reads exactly that connect); re-tenanting an
|
|
34
34
|
* existing row is refused;
|
|
35
35
|
* - into the caller's own `User` row while the parent is being created;
|
|
36
|
+
* - into any `User` row as the member of a root `OrgMembership` or
|
|
37
|
+
* `FundAssignment` create: adding a person to a team is what those
|
|
38
|
+
* creates are for, and the root decision reads that connect and requires
|
|
39
|
+
* authority over the tenant (`./membership-write-authority.ts`);
|
|
36
40
|
* - into `AlpacaAccount` only as the policy's own account on a root
|
|
37
41
|
* TradingPolicy create, whose ownership check reads that connect.
|
|
38
42
|
* - **Content writes into an owned model** (account, policy, user row) are
|
|
@@ -76,12 +80,27 @@ function nestedPolicyOf(model) {
|
|
|
76
80
|
const policy = ruleFor(model).policy;
|
|
77
81
|
return policy === 'mandate_tenant' ? 'authenticated' : policy;
|
|
78
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Whether a connect names the member of a root entitlement-row create. The
|
|
85
|
+
* root's own decision reads the member from this connect and holds the
|
|
86
|
+
* caller to authority over the tenant, so the hop needs no check of its own.
|
|
87
|
+
*/
|
|
88
|
+
function isRootMemberConnect(write) {
|
|
89
|
+
return (write.depth === 1 &&
|
|
90
|
+
write.parentMode === 'create' &&
|
|
91
|
+
write.relation === 'user' &&
|
|
92
|
+
ENTITLEMENT_MODELS.has(write.parentModel) &&
|
|
93
|
+
write.connectIds !== null &&
|
|
94
|
+
write.connectIds.length === 1);
|
|
95
|
+
}
|
|
79
96
|
function connectAllowed(write, callerId, relations) {
|
|
80
97
|
if (relations.fkOnParent(write.parentModel, write.relation) !== true)
|
|
81
98
|
return false;
|
|
82
99
|
const policy = nestedPolicyOf(write.model);
|
|
83
100
|
switch (policy) {
|
|
84
101
|
case 'self':
|
|
102
|
+
if (isRootMemberConnect(write))
|
|
103
|
+
return true;
|
|
85
104
|
return (write.parentMode === 'create' &&
|
|
86
105
|
write.connectIds !== null &&
|
|
87
106
|
write.connectIds.length > 0 &&
|
|
@@ -84,7 +84,8 @@ export declare const DESK_MODELS: readonly ["Follow", "AutoFollowRule", "PushSub
|
|
|
84
84
|
* (`src/resolvers/custom/strategy-draft-service.ts`, through
|
|
85
85
|
* {@link buildWriteScopeWhere}). The model is kept out of
|
|
86
86
|
* {@link GOVERNED_MODELS} on purpose: that list also gives each model a
|
|
87
|
-
*
|
|
87
|
+
* user-write rule (`tenant_scoped`, or `membership_authority` for the
|
|
88
|
+
* entitlement rows; `src/auth/mutation-authorization.ts`),
|
|
88
89
|
* which would make the generated `Strategy` writes user-writable.
|
|
89
90
|
*
|
|
90
91
|
* Scoped in every mode ({@link ALWAYS_ENFORCED_MODELS}): the predicate leaves
|
|
@@ -89,7 +89,8 @@ export const DESK_MODELS = [
|
|
|
89
89
|
* (`src/resolvers/custom/strategy-draft-service.ts`, through
|
|
90
90
|
* {@link buildWriteScopeWhere}). The model is kept out of
|
|
91
91
|
* {@link GOVERNED_MODELS} on purpose: that list also gives each model a
|
|
92
|
-
*
|
|
92
|
+
* user-write rule (`tenant_scoped`, or `membership_authority` for the
|
|
93
|
+
* entitlement rows; `src/auth/mutation-authorization.ts`),
|
|
93
94
|
* which would make the generated `Strategy` writes user-writable.
|
|
94
95
|
*
|
|
95
96
|
* Scoped in every mode ({@link ALWAYS_ENFORCED_MODELS}): the predicate leaves
|
|
@@ -34,6 +34,8 @@ export interface Scenario {
|
|
|
34
34
|
auditDown?: boolean;
|
|
35
35
|
/** The credential-field guard's mode; defaults to `enforce`, production's setting. */
|
|
36
36
|
credentialMode?: CredentialFieldGuardMode;
|
|
37
|
+
/** Make every OrgMembership and FundAssignment `findUnique` fail. */
|
|
38
|
+
membershipReadsDown?: boolean;
|
|
37
39
|
}
|
|
38
40
|
export declare const SCENARIOS: Scenario[];
|
|
39
41
|
/** What the harness reports per scenario. */
|
|
@@ -42,6 +42,18 @@ const U_OTHER = '44444444-4444-4444-8444-444444444444';
|
|
|
42
42
|
const FUND_1 = '55555555-5555-4555-8555-555555555555';
|
|
43
43
|
const FUND_2 = '77777777-7777-4777-8777-777777777777';
|
|
44
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';
|
|
45
57
|
const ACCOUNTS = {
|
|
46
58
|
a1: { id: 'a1', userId: U_OWNER, type: 'LIVE', brokerageAccount: null },
|
|
47
59
|
a2: { id: 'a2', userId: U_OTHER, type: 'PAPER', brokerageAccount: { fundId: FUND_1 } },
|
|
@@ -52,17 +64,34 @@ const POLICIES = {
|
|
|
52
64
|
p2: { id: 'p2', alpacaAccountId: 'a2' },
|
|
53
65
|
p3: { id: 'p3', alpacaAccountId: 'a3' },
|
|
54
66
|
};
|
|
55
|
-
/**
|
|
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
|
+
*/
|
|
56
72
|
const TENANCY = {
|
|
57
|
-
organization: [
|
|
58
|
-
|
|
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
|
+
],
|
|
59
86
|
fund: [
|
|
60
|
-
{ id: FUND_1, organizationId:
|
|
87
|
+
{ id: FUND_1, organizationId: ORG_1 },
|
|
61
88
|
{ id: FUND_2, organizationId: ORG_2 },
|
|
62
89
|
],
|
|
63
90
|
fundAssignment: [
|
|
64
|
-
{ id: 'fa1', fundId: FUND_1, userId: U_FUND },
|
|
65
|
-
{ id: 'fa2', fundId: FUND_2, userId: U_OTHER },
|
|
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' },
|
|
66
95
|
],
|
|
67
96
|
brokerageAccount: [
|
|
68
97
|
{ id: 'ba1', fundId: FUND_1, engineAccountId: 'a2' },
|
|
@@ -82,9 +111,41 @@ function matches(row, where) {
|
|
|
82
111
|
if (condition !== null && typeof condition === 'object' && 'in' in condition) {
|
|
83
112
|
return condition.in.includes(row[key]);
|
|
84
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
|
+
}
|
|
85
121
|
return row[key] === condition;
|
|
86
122
|
});
|
|
87
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
|
+
}
|
|
88
149
|
const PRINCIPALS = {
|
|
89
150
|
none: null,
|
|
90
151
|
server: { kind: 'server', sub: 'adaptic-engine:host-1:42' },
|
|
@@ -93,6 +154,15 @@ const PRINCIPALS = {
|
|
|
93
154
|
owner: { kind: 'user', sub: U_OWNER, email: 'owner@example.test', roles: [] },
|
|
94
155
|
stranger: { kind: 'user', sub: U_STRANGER, roles: [] },
|
|
95
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: [] },
|
|
96
166
|
};
|
|
97
167
|
const FLIP_LIVE = 'mutation Flip { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: true } }) { id realtimeTradingEnabled } }';
|
|
98
168
|
const FLIP_FUND = 'mutation FlipFund { updateOneTradingPolicy(where: { alpacaAccountId: "a2" }, data: { killSwitchEnabled: { set: true } }) { id } }';
|
|
@@ -113,6 +183,15 @@ const ROOT_ASSIGNMENT_OWN_FUND = `mutation { createOneFundAssignment(data: { fun
|
|
|
113
183
|
const RETENANT_ASSIGNMENT = `mutation { updateOneFundAssignment(where: { id: "fa1" }, data: { fund: { connect: { id: "${FUND_2}" } } }) { id } }`;
|
|
114
184
|
const BROKER_LABEL = (id) => `mutation { updateOneBrokerageAccount(where: { id: "${id}" }, data: { label: { set: "x" } }) { id } }`;
|
|
115
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 } }`;
|
|
116
195
|
// Blocker 2: walks that leave the root's rows.
|
|
117
196
|
const ACCOUNT_CHAIN = 'mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { brokerageAccount: { update: { data: { fund: { update: { data: { name: { set: "x" } } } } } } } }) { id } }';
|
|
118
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 } }`;
|
|
@@ -188,6 +267,47 @@ export const SCENARIOS = [
|
|
|
188
267
|
enforcedModels: ['TradingPolicy', 'AlpacaAccount'],
|
|
189
268
|
},
|
|
190
269
|
{ name: 'b1/rootAssignment/fundUser/enforce', query: ROOT_ASSIGNMENT_OWN_FUND, principal: 'fundUser', mode: 'enforce' },
|
|
270
|
+
{ name: 'b1/rootAssignment/fundUser/shadow', query: ROOT_ASSIGNMENT_OWN_FUND, principal: 'fundUser', mode: 'shadow' },
|
|
271
|
+
// A member's own promotion, under both modes.
|
|
272
|
+
{ name: 'mem/promoteSelf/orgMember/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'OWNER'), principal: 'orgMember', mode: 'enforce' },
|
|
273
|
+
{ name: 'mem/promoteSelf/orgMember/shadow', query: SET_MEMBERSHIP_ROLE('om-member', 'OWNER'), principal: 'orgMember', mode: 'shadow' },
|
|
274
|
+
{ name: 'mem/promoteSelfByPair/orgMember/enforce', query: SET_MEMBERSHIP_ROLE_BY_PAIR(ORG_1, U_ORG_MEMBER, 'ADMIN'), principal: 'orgMember', mode: 'enforce' },
|
|
275
|
+
{ name: 'mem/selfManager/orgMember/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_ORG_MEMBER, 'MANAGER'), principal: 'orgMember', mode: 'enforce' },
|
|
276
|
+
{ name: 'mem/selfManager/orgMember/shadow', query: CREATE_ASSIGNMENT(FUND_1, U_ORG_MEMBER, 'MANAGER'), principal: 'orgMember', mode: 'shadow' },
|
|
277
|
+
{ name: 'mem/selfManager/fundUser/enforce', query: SET_ASSIGNMENT_ROLE('fa1', 'MANAGER'), principal: 'fundUser', mode: 'enforce' },
|
|
278
|
+
// OWNER and ADMIN manage the organization's memberships; only OWNER touches an OWNER row.
|
|
279
|
+
{ name: 'mem/ownerSetsRole/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'ADMIN'), principal: 'orgOwner', mode: 'enforce' },
|
|
280
|
+
{ name: 'mem/ownerGrantsOwner/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-admin', 'OWNER'), principal: 'orgOwner', mode: 'enforce' },
|
|
281
|
+
{ name: 'mem/ownerRemoves/orgOwner/enforce', query: DELETE_MEMBERSHIP('om-member'), principal: 'orgOwner', mode: 'enforce' },
|
|
282
|
+
{ name: 'mem/adminSetsRole/orgAdmin/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'AUDITOR'), principal: 'orgAdmin', mode: 'enforce' },
|
|
283
|
+
{ name: 'mem/adminGrantsOwner/orgAdmin/enforce', query: SET_MEMBERSHIP_ROLE('om-admin', 'OWNER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
284
|
+
{ name: 'mem/adminDemotesOwner/orgAdmin/enforce', query: SET_MEMBERSHIP_ROLE('om-owner', 'MEMBER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
285
|
+
{ name: 'mem/adminRemovesOwner/orgAdmin/enforce', query: DELETE_MEMBERSHIP('om-owner'), principal: 'orgAdmin', mode: 'enforce' },
|
|
286
|
+
{ name: 'mem/adminAddsMember/orgAdmin/enforce', query: CREATE_MEMBERSHIP(ORG_1, U_STRANGER, 'COMPLIANCE_OFFICER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
287
|
+
{ name: 'mem/otherOrg/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om2', 'OWNER'), principal: 'orgOwner', mode: 'enforce' },
|
|
288
|
+
{ name: 'mem/missingRow/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-none', 'ADMIN'), principal: 'orgOwner', mode: 'enforce' },
|
|
289
|
+
// Self-service: the creator of an empty organization. A domain join made as the
|
|
290
|
+
// joiner carries no proof the backend can read (the email is the caller's own column).
|
|
291
|
+
{ name: 'mem/firstOwner/founder/enforce', query: CREATE_MEMBERSHIP(ORG_NEW, U_FOUNDER, 'OWNER'), principal: 'founder', mode: 'enforce' },
|
|
292
|
+
{ name: 'mem/claimOccupied/founder/enforce', query: CREATE_MEMBERSHIP(ORG_1, U_FOUNDER, 'OWNER'), principal: 'founder', mode: 'enforce' },
|
|
293
|
+
{ name: 'mem/firstOwnerForOther/founder/enforce', query: CREATE_MEMBERSHIP(ORG_NEW, U_STRANGER, 'OWNER'), principal: 'founder', mode: 'enforce' },
|
|
294
|
+
{ name: 'mem/domainJoin/joiner/enforce', query: CREATE_MEMBERSHIP(ORG_DOMAIN, U_JOINER, 'MEMBER'), principal: 'joiner', mode: 'enforce' },
|
|
295
|
+
// An invitation's acceptance carries no proof the backend can read.
|
|
296
|
+
{ name: 'mem/inviteAccept/stranger/enforce', query: CREATE_MEMBERSHIP(ORG_1, U_STRANGER, 'ADMIN'), principal: 'stranger', mode: 'enforce' },
|
|
297
|
+
// Fund assignments: org OWNER/ADMIN, or the fund's own MANAGER.
|
|
298
|
+
{ name: 'mem/ownerAssigns/orgOwner/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'MANAGER'), principal: 'orgOwner', mode: 'enforce' },
|
|
299
|
+
{ name: 'mem/adminAssigns/orgAdmin/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'TRADER'), principal: 'orgAdmin', mode: 'enforce' },
|
|
300
|
+
{ name: 'mem/managerAssigns/fundManager/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'ANALYST'), principal: 'fundManager', mode: 'enforce' },
|
|
301
|
+
{ name: 'mem/managerSetsRole/fundManager/enforce', query: SET_ASSIGNMENT_ROLE('fa1', 'ANALYST'), principal: 'fundManager', mode: 'enforce' },
|
|
302
|
+
{ name: 'mem/managerOtherFund/fundManager/enforce', query: CREATE_ASSIGNMENT(FUND_2, U_STRANGER, 'ANALYST'), principal: 'fundManager', mode: 'enforce' },
|
|
303
|
+
{ name: 'mem/managerOtherFundRow/fundManager/enforce', query: SET_ASSIGNMENT_ROLE('fa2', 'VIEWER'), principal: 'fundManager', mode: 'enforce' },
|
|
304
|
+
{ name: 'mem/traderAssigns/fundTrader/enforce', query: CREATE_ASSIGNMENT(FUND_1, U_STRANGER, 'ANALYST'), principal: 'fundTrader', mode: 'enforce' },
|
|
305
|
+
// The authority read fails: refused, and only observed in shadow.
|
|
306
|
+
{ name: 'mem/readDown/orgOwner/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'ADMIN'), principal: 'orgOwner', mode: 'enforce', membershipReadsDown: true },
|
|
307
|
+
{ name: 'mem/readDown/orgOwner/shadow', query: SET_MEMBERSHIP_ROLE('om-member', 'ADMIN'), principal: 'orgOwner', mode: 'shadow', membershipReadsDown: true },
|
|
308
|
+
// The platform's fund creation writes the creator's MANAGER assignment nested.
|
|
309
|
+
{ name: 'mem/fundCreate/orgOwner/enforce', query: CREATE_FUND_WITH_MANAGER(U_ORG_OWNER), principal: 'orgOwner', mode: 'enforce' },
|
|
310
|
+
{ name: 'mem/ownerSetsRole/server/enforce', query: SET_MEMBERSHIP_ROLE('om-member', 'OWNER'), principal: 'server', mode: 'enforce' },
|
|
191
311
|
{ name: 'b1/retenantAssignment/fundUser/enforce', query: RETENANT_ASSIGNMENT, principal: 'fundUser', mode: 'enforce' },
|
|
192
312
|
{ name: 'b1/crossTenantBroker/stranger/enforce', query: BROKER_LABEL('ba2'), principal: 'stranger', mode: 'enforce' },
|
|
193
313
|
{ name: 'b1/tenantBroker/fundUser/enforce', query: BROKER_LABEL('ba1'), principal: 'fundUser', mode: 'enforce' },
|
|
@@ -295,14 +415,18 @@ function policyFacts(p) {
|
|
|
295
415
|
* fixture rows (the entitlement read and the guard's scope check), and
|
|
296
416
|
* recording reads and writes.
|
|
297
417
|
*/
|
|
298
|
-
function tenancyDelegates(write, read) {
|
|
418
|
+
function tenancyDelegates(write, read, reads, membershipReadsDown) {
|
|
299
419
|
const out = {};
|
|
300
420
|
for (const [delegate, rows] of Object.entries(TENANCY)) {
|
|
301
421
|
out[delegate] = {
|
|
302
422
|
findMany: ({ where }) => read(`${delegate}.findMany`, rows.filter((r) => matches(r, where))),
|
|
303
|
-
findUnique: ({ where }) => {
|
|
423
|
+
findUnique: ({ where, select }) => {
|
|
424
|
+
if (membershipReadsDown() && (delegate === 'orgMembership' || delegate === 'fundAssignment')) {
|
|
425
|
+
reads.push(`${delegate}.findUnique`);
|
|
426
|
+
return Promise.reject(new Error('membership table unavailable'));
|
|
427
|
+
}
|
|
304
428
|
const row = rows.find((r) => matches(r, where));
|
|
305
|
-
return read(`${delegate}.findUnique`, row ?
|
|
429
|
+
return read(`${delegate}.findUnique`, row ? project(delegate, row, select) : null);
|
|
306
430
|
},
|
|
307
431
|
create: () => write(`${delegate}.create`, { id: `${delegate}-new` }),
|
|
308
432
|
update: ({ where }) => write(`${delegate}.update`, { id: where.id }),
|
|
@@ -317,6 +441,7 @@ async function main() {
|
|
|
317
441
|
let enforcedModels = new Set();
|
|
318
442
|
let auditDown = false;
|
|
319
443
|
let credentialMode = 'enforce';
|
|
444
|
+
let membershipReadsDown = false;
|
|
320
445
|
let writes = [];
|
|
321
446
|
let reads = [];
|
|
322
447
|
let audit = [];
|
|
@@ -348,7 +473,7 @@ async function main() {
|
|
|
348
473
|
user: {
|
|
349
474
|
update: ({ where }) => write('user.update', { id: where.id }),
|
|
350
475
|
},
|
|
351
|
-
...tenancyDelegates(write, read),
|
|
476
|
+
...tenancyDelegates(write, read, { push: (name) => reads.push(name) }, () => membershipReadsDown),
|
|
352
477
|
auditLog: {
|
|
353
478
|
create: ({ data }) => {
|
|
354
479
|
if (auditDown)
|
|
@@ -395,6 +520,7 @@ async function main() {
|
|
|
395
520
|
enforcedModels = new Set(scenario.enforcedModels ?? []);
|
|
396
521
|
auditDown = scenario.auditDown === true;
|
|
397
522
|
credentialMode = scenario.credentialMode ?? 'enforce';
|
|
523
|
+
membershipReadsDown = scenario.membershipReadsDown === true;
|
|
398
524
|
writes = [];
|
|
399
525
|
reads = [];
|
|
400
526
|
audit = [];
|
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* policy or account row, that account.
|
|
5
5
|
*
|
|
6
6
|
* The decision itself lives in `src/auth/mutation-authorization.ts` (pure);
|
|
7
|
-
* this module installs it on the built schema, resolves the ownership
|
|
8
|
-
* user principal's write needs
|
|
7
|
+
* this module installs it on the built schema, resolves the ownership,
|
|
8
|
+
* tenancy and membership-role facts a user principal's write needs (read
|
|
9
|
+
* from the database for the mutation, never from the token), counts and logs
|
|
10
|
+
* every decision, and writes the
|
|
9
11
|
* attributed TradingPolicy audit rows (`./trading-policy-audit.ts`).
|
|
10
12
|
*
|
|
11
13
|
* ## Why it wraps the Mutation fields instead of being a global middleware
|
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* policy or account row, that account.
|
|
5
5
|
*
|
|
6
6
|
* The decision itself lives in `src/auth/mutation-authorization.ts` (pure);
|
|
7
|
-
* this module installs it on the built schema, resolves the ownership
|
|
8
|
-
* user principal's write needs
|
|
7
|
+
* this module installs it on the built schema, resolves the ownership,
|
|
8
|
+
* tenancy and membership-role facts a user principal's write needs (read
|
|
9
|
+
* from the database for the mutation, never from the token), counts and logs
|
|
10
|
+
* every decision, and writes the
|
|
9
11
|
* attributed TradingPolicy audit rows (`./trading-policy-audit.ts`).
|
|
10
12
|
*
|
|
11
13
|
* ## Why it wraps the Mutation fields instead of being a global middleware
|
|
@@ -53,6 +55,7 @@ import { defaultFieldResolver, GraphQLError, } from 'graphql';
|
|
|
53
55
|
import { Counter } from 'prom-client';
|
|
54
56
|
import { redactCredentials } from '../auth/credential-redaction.mjs';
|
|
55
57
|
import { classifyMutationField, effectiveModeFor, evaluateMutationAccess, getEnforcedModels, getMutationAuthMode, touchesAlwaysEnforced, } from '../auth/mutation-authorization.mjs';
|
|
58
|
+
import { isMembershipModel } from '../auth/membership-write-authority.mjs';
|
|
56
59
|
import { findNestedWrites } from '../auth/nested-write-inspector.mjs';
|
|
57
60
|
import { firstNestedRefusal, writesNestedModelRows } from '../auth/nested-write-policy.mjs';
|
|
58
61
|
import { GOVERNED_MODELS } from '../auth/tenancy-scope.mjs';
|
|
@@ -61,6 +64,7 @@ import { metricsRegistry } from '../config/metrics.mjs';
|
|
|
61
64
|
import { logger } from '../utils/logger.mjs';
|
|
62
65
|
import { credentialAccessForbidden, credentialFieldAccessTotal, findCredentialArgumentReferences, getCredentialFieldGuardMode, } from './credential-field-guard.mjs';
|
|
63
66
|
import { loadTouchedAccounts, ownershipOf, resolveNestedPolicyRows, } from './mutation-account-facts.mjs';
|
|
67
|
+
import { membershipWriteVerdict } from './mutation-membership-facts.mjs';
|
|
64
68
|
import { mandateVersionScopeOf, tenantScopeOf } from './mutation-tenant-facts.mjs';
|
|
65
69
|
import { actorFor, changeReasonFor, isDisarmOnlyPolicyWrite, mayTouchLiveAccount, mutationAuditBypassedTotal, touchesTradingSwitch, writeAttemptRow, writeResultRow, } from './trading-policy-audit.mjs';
|
|
66
70
|
/**
|
|
@@ -213,6 +217,20 @@ async function decide(principal, target, nested, args, touched, prisma, relation
|
|
|
213
217
|
return first;
|
|
214
218
|
}
|
|
215
219
|
}
|
|
220
|
+
if (first.reason === 'membership_authority_unresolved' && isMembershipModel(target.model)) {
|
|
221
|
+
try {
|
|
222
|
+
const membership = await membershipWriteVerdict(prisma, target.model, target, args, principal.sub);
|
|
223
|
+
const membershipAuthority = membership.kind === 'decided' ? membership.verdict : 'unresolved';
|
|
224
|
+
return evaluateMutationAccess(principal, target, { ...facts, membershipAuthority });
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
logger.error('[mutation-auth] membership authority could not be read; refusing as unresolved', {
|
|
228
|
+
mutation: target.fieldName,
|
|
229
|
+
error: error instanceof Error ? error.message : String(error),
|
|
230
|
+
});
|
|
231
|
+
return first;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
216
234
|
if (first.reason === 'tenant_unresolved' && (isGovernedModel(target.model) || target.model === 'MandateVersion')) {
|
|
217
235
|
try {
|
|
218
236
|
const tenantScope = isGovernedModel(target.model)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The database facts a user principal's OrgMembership or FundAssignment write
|
|
3
|
+
* is decided on (`src/auth/membership-write-authority.ts`).
|
|
4
|
+
*
|
|
5
|
+
* For each row the write reaches — the payload's row for a create, the row the
|
|
6
|
+
* caller's `where` addresses for an update or delete, both for an upsert — it
|
|
7
|
+
* reads the row's organization (and fund), and what the CALLER holds there:
|
|
8
|
+
* their OrgMembership role in that organization and, for a fund assignment,
|
|
9
|
+
* their FundAssignment role on that fund. Roles come from these rows, never
|
|
10
|
+
* from the token's claims, because the token's roles are the platform's
|
|
11
|
+
* persona for the caller and are themselves derived from these rows. Each
|
|
12
|
+
* organization's and fund's standing is read once per mutation.
|
|
13
|
+
*
|
|
14
|
+
* A row that does not exist (an addressed membership, or the fund a payload
|
|
15
|
+
* names) is decided as outside the caller's tenant, the same answer a row in
|
|
16
|
+
* another tenant gets, so the refusal says nothing about which ids exist.
|
|
17
|
+
* Arguments that identify no row at all (no `where`, a payload naming no
|
|
18
|
+
* organization, fund or member) are {@link MembershipFacts} `unresolvable`;
|
|
19
|
+
* a database failure propagates. The guard refuses on both.
|
|
20
|
+
*
|
|
21
|
+
* @module middleware/mutation-membership-facts
|
|
22
|
+
*/
|
|
23
|
+
import type { MutationTarget } from '../auth/mutation-authorization';
|
|
24
|
+
import { type MembershipModel, type MembershipVerdict } from '../auth/membership-write-authority';
|
|
25
|
+
type Where = Record<string, unknown>;
|
|
26
|
+
declare const MEMBERSHIP_SELECT: {
|
|
27
|
+
readonly organizationId: true;
|
|
28
|
+
readonly userId: true;
|
|
29
|
+
readonly role: true;
|
|
30
|
+
};
|
|
31
|
+
declare const ASSIGNMENT_SELECT: {
|
|
32
|
+
readonly fundId: true;
|
|
33
|
+
readonly userId: true;
|
|
34
|
+
readonly role: true;
|
|
35
|
+
readonly fund: {
|
|
36
|
+
readonly select: {
|
|
37
|
+
readonly organizationId: true;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
declare const MEMBERSHIP_ROLE_SELECT: {
|
|
42
|
+
readonly role: true;
|
|
43
|
+
};
|
|
44
|
+
declare const ASSIGNMENT_ROLE_SELECT: {
|
|
45
|
+
readonly role: true;
|
|
46
|
+
};
|
|
47
|
+
declare const FUND_SELECT: {
|
|
48
|
+
readonly organizationId: true;
|
|
49
|
+
};
|
|
50
|
+
declare const ORGANIZATION_SELECT: {
|
|
51
|
+
readonly deletedAt: true;
|
|
52
|
+
readonly _count: {
|
|
53
|
+
readonly select: {
|
|
54
|
+
readonly members: true;
|
|
55
|
+
readonly funds: true;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The slice of the Prisma client the facts are read through. Declared
|
|
61
|
+
* structurally so the decision can be exercised against a fake; the guard
|
|
62
|
+
* passes the server's PrismaClient.
|
|
63
|
+
*/
|
|
64
|
+
export interface MembershipFactsPrisma {
|
|
65
|
+
orgMembership: {
|
|
66
|
+
findUnique(args: {
|
|
67
|
+
where: Where;
|
|
68
|
+
select: typeof MEMBERSHIP_SELECT | typeof MEMBERSHIP_ROLE_SELECT;
|
|
69
|
+
}): Promise<{
|
|
70
|
+
organizationId?: string;
|
|
71
|
+
userId?: string;
|
|
72
|
+
role: string;
|
|
73
|
+
} | null>;
|
|
74
|
+
};
|
|
75
|
+
fundAssignment: {
|
|
76
|
+
findUnique(args: {
|
|
77
|
+
where: Where;
|
|
78
|
+
select: typeof ASSIGNMENT_SELECT | typeof ASSIGNMENT_ROLE_SELECT;
|
|
79
|
+
}): Promise<{
|
|
80
|
+
fundId?: string;
|
|
81
|
+
userId?: string;
|
|
82
|
+
role: string;
|
|
83
|
+
fund?: {
|
|
84
|
+
organizationId: string;
|
|
85
|
+
};
|
|
86
|
+
} | null>;
|
|
87
|
+
};
|
|
88
|
+
fund: {
|
|
89
|
+
findUnique(args: {
|
|
90
|
+
where: {
|
|
91
|
+
id: string;
|
|
92
|
+
};
|
|
93
|
+
select: typeof FUND_SELECT;
|
|
94
|
+
}): Promise<{
|
|
95
|
+
organizationId: string;
|
|
96
|
+
} | null>;
|
|
97
|
+
};
|
|
98
|
+
organization: {
|
|
99
|
+
findUnique(args: {
|
|
100
|
+
where: {
|
|
101
|
+
id: string;
|
|
102
|
+
};
|
|
103
|
+
select: typeof ORGANIZATION_SELECT;
|
|
104
|
+
}): Promise<{
|
|
105
|
+
deletedAt: Date | null;
|
|
106
|
+
_count: {
|
|
107
|
+
members: number;
|
|
108
|
+
funds: number;
|
|
109
|
+
};
|
|
110
|
+
} | null>;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** The outcome of {@link membershipWriteVerdict}. */
|
|
114
|
+
export type MembershipFacts = {
|
|
115
|
+
readonly kind: 'decided';
|
|
116
|
+
readonly verdict: MembershipVerdict;
|
|
117
|
+
} | {
|
|
118
|
+
readonly kind: 'unresolvable';
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Decide a user principal's write to an entitlement row from the database.
|
|
122
|
+
* Every row the write reaches must be admitted; the first refusal is returned.
|
|
123
|
+
*
|
|
124
|
+
* @param prisma - A client exposing {@link MembershipFactsPrisma}.
|
|
125
|
+
* @param model - The entitlement model written.
|
|
126
|
+
* @param target - The classified root mutation (`one` cardinality).
|
|
127
|
+
* @param args - The mutation's arguments.
|
|
128
|
+
* @param callerId - The user principal's subject.
|
|
129
|
+
* @throws Whatever the database raised; the caller refuses on it.
|
|
130
|
+
*/
|
|
131
|
+
export declare function membershipWriteVerdict(prisma: MembershipFactsPrisma, model: MembershipModel, target: MutationTarget, args: Record<string, unknown>, callerId: string): Promise<MembershipFacts>;
|
|
132
|
+
export {};
|
|
133
|
+
//# sourceMappingURL=mutation-membership-facts.d.ts.map
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The database facts a user principal's OrgMembership or FundAssignment write
|
|
3
|
+
* is decided on (`src/auth/membership-write-authority.ts`).
|
|
4
|
+
*
|
|
5
|
+
* For each row the write reaches — the payload's row for a create, the row the
|
|
6
|
+
* caller's `where` addresses for an update or delete, both for an upsert — it
|
|
7
|
+
* reads the row's organization (and fund), and what the CALLER holds there:
|
|
8
|
+
* their OrgMembership role in that organization and, for a fund assignment,
|
|
9
|
+
* their FundAssignment role on that fund. Roles come from these rows, never
|
|
10
|
+
* from the token's claims, because the token's roles are the platform's
|
|
11
|
+
* persona for the caller and are themselves derived from these rows. Each
|
|
12
|
+
* organization's and fund's standing is read once per mutation.
|
|
13
|
+
*
|
|
14
|
+
* A row that does not exist (an addressed membership, or the fund a payload
|
|
15
|
+
* names) is decided as outside the caller's tenant, the same answer a row in
|
|
16
|
+
* another tenant gets, so the refusal says nothing about which ids exist.
|
|
17
|
+
* Arguments that identify no row at all (no `where`, a payload naming no
|
|
18
|
+
* organization, fund or member) are {@link MembershipFacts} `unresolvable`;
|
|
19
|
+
* a database failure propagates. The guard refuses on both.
|
|
20
|
+
*
|
|
21
|
+
* @module middleware/mutation-membership-facts
|
|
22
|
+
*/
|
|
23
|
+
import { ADMITTING_MEMBERSHIP_VERDICTS, decideMembershipWrite, isFirstOwnerCandidate, } from '../auth/membership-write-authority.mjs';
|
|
24
|
+
// Each selection and unique selector is pinned to the generated Prisma types,
|
|
25
|
+
// so a renamed column, relation or compound key fails the build rather than
|
|
26
|
+
// failing every membership write at run time.
|
|
27
|
+
const MEMBERSHIP_SELECT = {
|
|
28
|
+
organizationId: true,
|
|
29
|
+
userId: true,
|
|
30
|
+
role: true,
|
|
31
|
+
};
|
|
32
|
+
const ASSIGNMENT_SELECT = {
|
|
33
|
+
fundId: true,
|
|
34
|
+
userId: true,
|
|
35
|
+
role: true,
|
|
36
|
+
fund: { select: { organizationId: true } },
|
|
37
|
+
};
|
|
38
|
+
const MEMBERSHIP_ROLE_SELECT = {
|
|
39
|
+
role: true,
|
|
40
|
+
};
|
|
41
|
+
const ASSIGNMENT_ROLE_SELECT = {
|
|
42
|
+
role: true,
|
|
43
|
+
};
|
|
44
|
+
const FUND_SELECT = {
|
|
45
|
+
organizationId: true,
|
|
46
|
+
};
|
|
47
|
+
const ORGANIZATION_SELECT = {
|
|
48
|
+
deletedAt: true,
|
|
49
|
+
_count: { select: { members: true, funds: true } },
|
|
50
|
+
};
|
|
51
|
+
/** The caller's own membership in an organization, by its compound unique key. */
|
|
52
|
+
function callerMembershipWhere(organizationId, userId) {
|
|
53
|
+
return { organizationId_userId: { organizationId, userId } };
|
|
54
|
+
}
|
|
55
|
+
/** The caller's own assignment on a fund, by its compound unique key. */
|
|
56
|
+
function callerAssignmentWhere(fundId, userId) {
|
|
57
|
+
return { fundId_userId: { fundId, userId } };
|
|
58
|
+
}
|
|
59
|
+
/** The column default for each model's `role` (`prisma/schema.prisma`). */
|
|
60
|
+
const DEFAULT_ROLE = {
|
|
61
|
+
OrgMembership: 'MEMBER',
|
|
62
|
+
FundAssignment: 'VIEWER',
|
|
63
|
+
};
|
|
64
|
+
function asRecord(value) {
|
|
65
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
66
|
+
? value
|
|
67
|
+
: undefined;
|
|
68
|
+
}
|
|
69
|
+
/** A foreign key from a create payload, in its scalar or `relation.connect.id` form. */
|
|
70
|
+
function connectIdOf(data, scalar, relation) {
|
|
71
|
+
const direct = data[scalar];
|
|
72
|
+
if (typeof direct === 'string' && direct.length > 0)
|
|
73
|
+
return direct;
|
|
74
|
+
const id = asRecord(asRecord(data[relation])?.connect)?.id;
|
|
75
|
+
return typeof id === 'string' && id.length > 0 ? id : undefined;
|
|
76
|
+
}
|
|
77
|
+
/** An enum value written either bare (`OWNER`) or as `{ set: OWNER }`. */
|
|
78
|
+
function enumValueOf(value) {
|
|
79
|
+
if (typeof value === 'string')
|
|
80
|
+
return value;
|
|
81
|
+
const set = asRecord(value)?.set;
|
|
82
|
+
return typeof set === 'string' ? set : undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Whether a payload writes the `permissions` list at all. */
|
|
85
|
+
function setsPermissions(data) {
|
|
86
|
+
return data.permissions !== undefined && data.permissions !== null;
|
|
87
|
+
}
|
|
88
|
+
/** The row a create payload would write. */
|
|
89
|
+
async function createdRow(prisma, model, payload) {
|
|
90
|
+
const data = asRecord(payload);
|
|
91
|
+
if (!data)
|
|
92
|
+
return 'malformed';
|
|
93
|
+
const memberUserId = connectIdOf(data, 'userId', 'user');
|
|
94
|
+
if (memberUserId === undefined)
|
|
95
|
+
return 'malformed';
|
|
96
|
+
const role = data.role === undefined ? DEFAULT_ROLE[model] : enumValueOf(data.role);
|
|
97
|
+
if (role === undefined)
|
|
98
|
+
return 'malformed';
|
|
99
|
+
const base = {
|
|
100
|
+
side: 'create',
|
|
101
|
+
memberUserId,
|
|
102
|
+
rolesTouched: [role],
|
|
103
|
+
setsPermissions: setsPermissions(data),
|
|
104
|
+
};
|
|
105
|
+
if (model === 'OrgMembership') {
|
|
106
|
+
const organizationId = connectIdOf(data, 'organizationId', 'organization');
|
|
107
|
+
return organizationId === undefined
|
|
108
|
+
? 'malformed'
|
|
109
|
+
: { ...base, organizationId };
|
|
110
|
+
}
|
|
111
|
+
const fundId = connectIdOf(data, 'fundId', 'fund');
|
|
112
|
+
if (fundId === undefined)
|
|
113
|
+
return 'malformed';
|
|
114
|
+
const fund = await prisma.fund.findUnique({
|
|
115
|
+
where: { id: fundId },
|
|
116
|
+
select: FUND_SELECT,
|
|
117
|
+
});
|
|
118
|
+
return fund
|
|
119
|
+
? { ...base, organizationId: fund.organizationId, fundId }
|
|
120
|
+
: 'missing';
|
|
121
|
+
}
|
|
122
|
+
/** The row an update, upsert or delete addresses. */
|
|
123
|
+
async function existingRow(prisma, model, where, update) {
|
|
124
|
+
const newRole = update?.role === undefined ? undefined : enumValueOf(update.role);
|
|
125
|
+
const extra = {
|
|
126
|
+
side: 'existing',
|
|
127
|
+
setsPermissions: update !== undefined && setsPermissions(update),
|
|
128
|
+
};
|
|
129
|
+
if (model === 'OrgMembership') {
|
|
130
|
+
const row = await prisma.orgMembership.findUnique({
|
|
131
|
+
where,
|
|
132
|
+
select: MEMBERSHIP_SELECT,
|
|
133
|
+
});
|
|
134
|
+
if (!row?.organizationId || !row.userId)
|
|
135
|
+
return 'missing';
|
|
136
|
+
return {
|
|
137
|
+
...extra,
|
|
138
|
+
organizationId: row.organizationId,
|
|
139
|
+
memberUserId: row.userId,
|
|
140
|
+
rolesTouched: newRole === undefined ? [row.role] : [row.role, newRole],
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const row = await prisma.fundAssignment.findUnique({
|
|
144
|
+
where,
|
|
145
|
+
select: ASSIGNMENT_SELECT,
|
|
146
|
+
});
|
|
147
|
+
if (!row?.fundId || !row.userId || !row.fund)
|
|
148
|
+
return 'missing';
|
|
149
|
+
return {
|
|
150
|
+
...extra,
|
|
151
|
+
organizationId: row.fund.organizationId,
|
|
152
|
+
fundId: row.fundId,
|
|
153
|
+
memberUserId: row.userId,
|
|
154
|
+
rolesTouched: newRole === undefined ? [row.role] : [row.role, newRole],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* The rows a write reaches. An upsert reaches the existing row when there is
|
|
159
|
+
* one (the update branch) and always the create payload's row (the branch
|
|
160
|
+
* taken when there is none).
|
|
161
|
+
*/
|
|
162
|
+
async function rowsWritten(prisma, model, target, args) {
|
|
163
|
+
if (target.action === 'create') {
|
|
164
|
+
const row = await createdRow(prisma, model, args.data);
|
|
165
|
+
return row === 'malformed' ? row : [row];
|
|
166
|
+
}
|
|
167
|
+
const where = asRecord(args.where);
|
|
168
|
+
if (!where)
|
|
169
|
+
return 'malformed';
|
|
170
|
+
if (target.action === 'upsert') {
|
|
171
|
+
const created = await createdRow(prisma, model, args.create);
|
|
172
|
+
if (created === 'malformed')
|
|
173
|
+
return created;
|
|
174
|
+
const existing = await existingRow(prisma, model, where, asRecord(args.update));
|
|
175
|
+
return existing === 'missing' ? [created] : [existing, created];
|
|
176
|
+
}
|
|
177
|
+
const update = target.action === 'update' ? asRecord(args.data) : undefined;
|
|
178
|
+
return [await existingRow(prisma, model, where, update)];
|
|
179
|
+
}
|
|
180
|
+
/** Reads what the caller holds in an organization and fund, once each per mutation. */
|
|
181
|
+
function standingReader(prisma, callerId) {
|
|
182
|
+
const orgRoles = new Map();
|
|
183
|
+
const fundRoles = new Map();
|
|
184
|
+
const orgRole = (organizationId) => {
|
|
185
|
+
let role = orgRoles.get(organizationId);
|
|
186
|
+
if (!role) {
|
|
187
|
+
role = prisma.orgMembership
|
|
188
|
+
.findUnique({
|
|
189
|
+
where: callerMembershipWhere(organizationId, callerId),
|
|
190
|
+
select: MEMBERSHIP_ROLE_SELECT,
|
|
191
|
+
})
|
|
192
|
+
.then((row) => row?.role ?? null);
|
|
193
|
+
orgRoles.set(organizationId, role);
|
|
194
|
+
}
|
|
195
|
+
return role;
|
|
196
|
+
};
|
|
197
|
+
const fundRole = (fundId) => {
|
|
198
|
+
let role = fundRoles.get(fundId);
|
|
199
|
+
if (!role) {
|
|
200
|
+
role = prisma.fundAssignment
|
|
201
|
+
.findUnique({
|
|
202
|
+
where: callerAssignmentWhere(fundId, callerId),
|
|
203
|
+
select: ASSIGNMENT_ROLE_SELECT,
|
|
204
|
+
})
|
|
205
|
+
.then((row) => row?.role ?? null);
|
|
206
|
+
fundRoles.set(fundId, role);
|
|
207
|
+
}
|
|
208
|
+
return role;
|
|
209
|
+
};
|
|
210
|
+
return async (write) => {
|
|
211
|
+
const [org, fund] = await Promise.all([
|
|
212
|
+
orgRole(write.organizationId),
|
|
213
|
+
write.fundId === undefined
|
|
214
|
+
? Promise.resolve(null)
|
|
215
|
+
: fundRole(write.fundId),
|
|
216
|
+
]);
|
|
217
|
+
return { orgRole: org, fundRole: fund };
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** The facts a first-owner create is decided on, or `null` when the organization does not exist. */
|
|
221
|
+
async function firstOwnerFactsOf(prisma, organizationId) {
|
|
222
|
+
const organization = await prisma.organization.findUnique({
|
|
223
|
+
where: { id: organizationId },
|
|
224
|
+
select: ORGANIZATION_SELECT,
|
|
225
|
+
});
|
|
226
|
+
if (!organization)
|
|
227
|
+
return null;
|
|
228
|
+
return {
|
|
229
|
+
organizationDeleted: organization.deletedAt !== null,
|
|
230
|
+
organizationMemberCount: organization._count.members,
|
|
231
|
+
organizationFundCount: organization._count.funds,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Decide a user principal's write to an entitlement row from the database.
|
|
236
|
+
* Every row the write reaches must be admitted; the first refusal is returned.
|
|
237
|
+
*
|
|
238
|
+
* @param prisma - A client exposing {@link MembershipFactsPrisma}.
|
|
239
|
+
* @param model - The entitlement model written.
|
|
240
|
+
* @param target - The classified root mutation (`one` cardinality).
|
|
241
|
+
* @param args - The mutation's arguments.
|
|
242
|
+
* @param callerId - The user principal's subject.
|
|
243
|
+
* @throws Whatever the database raised; the caller refuses on it.
|
|
244
|
+
*/
|
|
245
|
+
export async function membershipWriteVerdict(prisma, model, target, args, callerId) {
|
|
246
|
+
const rows = await rowsWritten(prisma, model, target, args);
|
|
247
|
+
if (rows === 'malformed')
|
|
248
|
+
return { kind: 'unresolvable' };
|
|
249
|
+
const standingOf = standingReader(prisma, callerId);
|
|
250
|
+
let admitted = null;
|
|
251
|
+
for (const row of rows) {
|
|
252
|
+
if (row === 'missing' || row === 'malformed') {
|
|
253
|
+
return row === 'missing'
|
|
254
|
+
? { kind: 'decided', verdict: 'tenant_out_of_scope' }
|
|
255
|
+
: { kind: 'unresolvable' };
|
|
256
|
+
}
|
|
257
|
+
const standing = await standingOf(row);
|
|
258
|
+
const firstOwner = isFirstOwnerCandidate(model, row, callerId, standing)
|
|
259
|
+
? await firstOwnerFactsOf(prisma, row.organizationId)
|
|
260
|
+
: null;
|
|
261
|
+
const verdict = decideMembershipWrite(model, row, callerId, standing, firstOwner);
|
|
262
|
+
if (!ADMITTING_MEMBERSHIP_VERDICTS.has(verdict)) {
|
|
263
|
+
return { kind: 'decided', verdict };
|
|
264
|
+
}
|
|
265
|
+
admitted ??= verdict;
|
|
266
|
+
}
|
|
267
|
+
return admitted === null
|
|
268
|
+
? { kind: 'unresolvable' }
|
|
269
|
+
: { kind: 'decided', verdict: admitted };
|
|
270
|
+
}
|
|
271
|
+
//# sourceMappingURL=mutation-membership-facts.js.map
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The mutation guard's own tenancy check for a user principal's write to a
|
|
3
|
-
* tenancy-governed model (Organization,
|
|
4
|
-
*
|
|
3
|
+
* tenancy-governed model (Organization, Fund, BrokerageAccount,
|
|
4
|
+
* Notification*, the desk models). The entitlement rows themselves,
|
|
5
|
+
* OrgMembership and FundAssignment, need more than tenancy: the guard decides
|
|
6
|
+
* them on the caller's role (`./mutation-membership-facts.ts`).
|
|
5
7
|
*
|
|
6
8
|
* The tenancy-scoping middleware applies the same scope, but only as strongly
|
|
7
9
|
* as `TENANCY_SCOPING_MODE` (default `shadow`) and only on root fields. The
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The mutation guard's own tenancy check for a user principal's write to a
|
|
3
|
-
* tenancy-governed model (Organization,
|
|
4
|
-
*
|
|
3
|
+
* tenancy-governed model (Organization, Fund, BrokerageAccount,
|
|
4
|
+
* Notification*, the desk models). The entitlement rows themselves,
|
|
5
|
+
* OrgMembership and FundAssignment, need more than tenancy: the guard decides
|
|
6
|
+
* them on the caller's role (`./mutation-membership-facts.ts`).
|
|
5
7
|
*
|
|
6
8
|
* The tenancy-scoping middleware applies the same scope, but only as strongly
|
|
7
9
|
* as `TENANCY_SCOPING_MODE` (default `shadow`) and only on root fields. The
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adaptic/backend-legacy",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.1056",
|
|
4
4
|
"description": "Backend executable CRUD functions with dynamic variables construction, and type definitions for the Adaptic AI platform.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "index.d.ts",
|