@memberjunction/server 5.51.3 → 5.51.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/README.md +34 -1
  2. package/dist/agentSessions/SessionManager.d.ts +5 -2
  3. package/dist/agentSessions/SessionManager.d.ts.map +1 -1
  4. package/dist/agentSessions/SessionManager.js +17 -8
  5. package/dist/agentSessions/SessionManager.js.map +1 -1
  6. package/dist/agentSessions/SessionRunIDVerifier.d.ts +63 -0
  7. package/dist/agentSessions/SessionRunIDVerifier.d.ts.map +1 -0
  8. package/dist/agentSessions/SessionRunIDVerifier.js +136 -0
  9. package/dist/agentSessions/SessionRunIDVerifier.js.map +1 -0
  10. package/dist/agentSessions/index.d.ts +1 -0
  11. package/dist/agentSessions/index.d.ts.map +1 -1
  12. package/dist/agentSessions/index.js +1 -0
  13. package/dist/agentSessions/index.js.map +1 -1
  14. package/dist/auth/actionAuthorization.d.ts +40 -0
  15. package/dist/auth/actionAuthorization.d.ts.map +1 -0
  16. package/dist/auth/actionAuthorization.js +94 -0
  17. package/dist/auth/actionAuthorization.js.map +1 -0
  18. package/dist/auth/index.d.ts +1 -0
  19. package/dist/auth/index.d.ts.map +1 -1
  20. package/dist/auth/index.js +1 -0
  21. package/dist/auth/index.js.map +1 -1
  22. package/dist/auth/scopeLimitedPrincipal.d.ts +39 -0
  23. package/dist/auth/scopeLimitedPrincipal.d.ts.map +1 -0
  24. package/dist/auth/scopeLimitedPrincipal.js +49 -0
  25. package/dist/auth/scopeLimitedPrincipal.js.map +1 -0
  26. package/dist/config.d.ts +53 -0
  27. package/dist/config.d.ts.map +1 -1
  28. package/dist/config.js +34 -1
  29. package/dist/config.js.map +1 -1
  30. package/dist/context.d.ts +6 -0
  31. package/dist/context.d.ts.map +1 -1
  32. package/dist/context.js +24 -34
  33. package/dist/context.js.map +1 -1
  34. package/dist/generated/generated.d.ts.map +1 -1
  35. package/dist/generated/generated.js +3262 -3273
  36. package/dist/generated/generated.js.map +1 -1
  37. package/dist/generic/CacheInvalidationResolver.d.ts +124 -4
  38. package/dist/generic/CacheInvalidationResolver.d.ts.map +1 -1
  39. package/dist/generic/CacheInvalidationResolver.js +170 -15
  40. package/dist/generic/CacheInvalidationResolver.js.map +1 -1
  41. package/dist/generic/FireAndForgetHeartbeat.d.ts +5 -0
  42. package/dist/generic/FireAndForgetHeartbeat.d.ts.map +1 -1
  43. package/dist/generic/FireAndForgetHeartbeat.js +5 -4
  44. package/dist/generic/FireAndForgetHeartbeat.js.map +1 -1
  45. package/dist/generic/PushStatusResolver.d.ts +58 -0
  46. package/dist/generic/PushStatusResolver.d.ts.map +1 -1
  47. package/dist/generic/PushStatusResolver.js +42 -3
  48. package/dist/generic/PushStatusResolver.js.map +1 -1
  49. package/dist/generic/ResolverBase.d.ts +148 -3
  50. package/dist/generic/ResolverBase.d.ts.map +1 -1
  51. package/dist/generic/ResolverBase.js +287 -30
  52. package/dist/generic/ResolverBase.js.map +1 -1
  53. package/dist/generic/RunViewResolver.d.ts.map +1 -1
  54. package/dist/generic/RunViewResolver.js +12 -0
  55. package/dist/generic/RunViewResolver.js.map +1 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +56 -48
  58. package/dist/index.js.map +1 -1
  59. package/dist/multiTenancy/index.d.ts.map +1 -1
  60. package/dist/multiTenancy/index.js +22 -2
  61. package/dist/multiTenancy/index.js.map +1 -1
  62. package/dist/postgresqlCompat.d.ts +8 -0
  63. package/dist/postgresqlCompat.d.ts.map +1 -0
  64. package/dist/postgresqlCompat.js +19 -0
  65. package/dist/postgresqlCompat.js.map +1 -0
  66. package/dist/postgresqlPoolSettings.d.ts +108 -0
  67. package/dist/postgresqlPoolSettings.d.ts.map +1 -0
  68. package/dist/postgresqlPoolSettings.js +134 -0
  69. package/dist/postgresqlPoolSettings.js.map +1 -0
  70. package/dist/realtimeWidget/widgetGuestElevation.d.ts +2 -2
  71. package/dist/realtimeWidget/widgetGuestElevation.js +2 -2
  72. package/dist/resolvers/ActionResolver.d.ts +31 -5
  73. package/dist/resolvers/ActionResolver.d.ts.map +1 -1
  74. package/dist/resolvers/ActionResolver.js +75 -14
  75. package/dist/resolvers/ActionResolver.js.map +1 -1
  76. package/dist/resolvers/AdhocQueryResolver.d.ts +39 -17
  77. package/dist/resolvers/AdhocQueryResolver.d.ts.map +1 -1
  78. package/dist/resolvers/AdhocQueryResolver.js +97 -157
  79. package/dist/resolvers/AdhocQueryResolver.js.map +1 -1
  80. package/dist/resolvers/DatasetResolver.d.ts +24 -3
  81. package/dist/resolvers/DatasetResolver.d.ts.map +1 -1
  82. package/dist/resolvers/DatasetResolver.js +57 -8
  83. package/dist/resolvers/DatasetResolver.js.map +1 -1
  84. package/dist/resolvers/EntityRecordNameResolver.d.ts +14 -4
  85. package/dist/resolvers/EntityRecordNameResolver.d.ts.map +1 -1
  86. package/dist/resolvers/EntityRecordNameResolver.js +18 -6
  87. package/dist/resolvers/EntityRecordNameResolver.js.map +1 -1
  88. package/dist/resolvers/GetDataContextDataResolver.d.ts +33 -7
  89. package/dist/resolvers/GetDataContextDataResolver.d.ts.map +1 -1
  90. package/dist/resolvers/GetDataContextDataResolver.js +117 -38
  91. package/dist/resolvers/GetDataContextDataResolver.js.map +1 -1
  92. package/dist/resolvers/GetDataResolver.d.ts.map +1 -1
  93. package/dist/resolvers/GetDataResolver.js +13 -1
  94. package/dist/resolvers/GetDataResolver.js.map +1 -1
  95. package/dist/resolvers/MCPResolver.d.ts.map +1 -1
  96. package/dist/resolvers/MCPResolver.js +13 -16
  97. package/dist/resolvers/MCPResolver.js.map +1 -1
  98. package/dist/resolvers/RealtimeClientSessionResolver.d.ts +26 -14
  99. package/dist/resolvers/RealtimeClientSessionResolver.d.ts.map +1 -1
  100. package/dist/resolvers/RealtimeClientSessionResolver.js +63 -46
  101. package/dist/resolvers/RealtimeClientSessionResolver.js.map +1 -1
  102. package/dist/resolvers/RemoteBrowserActionResolver.d.ts +2 -0
  103. package/dist/resolvers/RemoteBrowserActionResolver.d.ts.map +1 -1
  104. package/dist/resolvers/RemoteBrowserActionResolver.js +24 -27
  105. package/dist/resolvers/RemoteBrowserActionResolver.js.map +1 -1
  106. package/dist/resolvers/RunAIAgentResolver.d.ts.map +1 -1
  107. package/dist/resolvers/RunAIAgentResolver.js +30 -40
  108. package/dist/resolvers/RunAIAgentResolver.js.map +1 -1
  109. package/dist/resolvers/RunTemplateResolver.d.ts.map +1 -1
  110. package/dist/resolvers/RunTemplateResolver.js +12 -11
  111. package/dist/resolvers/RunTemplateResolver.js.map +1 -1
  112. package/dist/resolvers/RunTestResolver.d.ts.map +1 -1
  113. package/dist/resolvers/RunTestResolver.js +90 -112
  114. package/dist/resolvers/RunTestResolver.js.map +1 -1
  115. package/dist/resolvers/SyncRolesUsersResolver.d.ts.map +1 -1
  116. package/dist/resolvers/SyncRolesUsersResolver.js +11 -2
  117. package/dist/resolvers/SyncRolesUsersResolver.js.map +1 -1
  118. package/dist/resolvers/VersionHistoryResolver.d.ts.map +1 -1
  119. package/dist/resolvers/VersionHistoryResolver.js +8 -12
  120. package/dist/resolvers/VersionHistoryResolver.js.map +1 -1
  121. package/dist/resolvers/adhocTimeout.d.ts +7 -0
  122. package/dist/resolvers/adhocTimeout.d.ts.map +1 -0
  123. package/dist/resolvers/adhocTimeout.js +12 -0
  124. package/dist/resolvers/adhocTimeout.js.map +1 -0
  125. package/dist/rest/ViewOperationsHandler.d.ts +3 -1
  126. package/dist/rest/ViewOperationsHandler.d.ts.map +1 -1
  127. package/dist/rest/ViewOperationsHandler.js +29 -17
  128. package/dist/rest/ViewOperationsHandler.js.map +1 -1
  129. package/dist/services/TaskOrchestrator.d.ts.map +1 -1
  130. package/dist/services/TaskOrchestrator.js +17 -15
  131. package/dist/services/TaskOrchestrator.js.map +1 -1
  132. package/package.json +90 -89
  133. package/src/__tests__/ActionResolver.authorization.test.ts +353 -0
  134. package/src/__tests__/AdhocQueryResolver.bugs.test.ts +14 -35
  135. package/src/__tests__/AdhocQueryResolver.pagination.test.ts +6 -2
  136. package/src/__tests__/AdhocQueryResolver.scopeGuard.test.ts +84 -0
  137. package/src/__tests__/AdhocQueryResolver.sqlAuthorizer.test.ts +104 -0
  138. package/src/__tests__/DatasetResolver.itemFilters.test.ts +201 -0
  139. package/src/__tests__/EntityRecordNameResolver.rowSecurity.test.ts +152 -0
  140. package/src/__tests__/GetDataContextDataResolver.sqlItems.test.ts +416 -0
  141. package/src/__tests__/ListOperationsResolver.adhocScreen.test.ts +136 -0
  142. package/src/__tests__/RealtimeClientSessionResolver.configTamper.test.ts +318 -0
  143. package/src/__tests__/RealtimeClientSessionResolver.test.ts +66 -27
  144. package/src/__tests__/RemoteBrowserActionResolver.goalRunLink.test.ts +134 -0
  145. package/src/__tests__/ResolverBase.adhocReadScope.test.ts +221 -0
  146. package/src/__tests__/ResolverBase.aggregateScreen.test.ts +173 -0
  147. package/src/__tests__/ResolverBase.balancedClause.test.ts +155 -0
  148. package/src/__tests__/ResolverBase.clauseUnscopedRead.test.ts +116 -0
  149. package/src/__tests__/ResolverBase.filterEscaping.test.ts +351 -0
  150. package/src/__tests__/RunTemplateResolver.test.ts +132 -0
  151. package/src/__tests__/RunViewResolver.cacheCheckScreen.test.ts +164 -0
  152. package/src/__tests__/SessionManager.test.ts +88 -13
  153. package/src/__tests__/SessionRunIDVerifier.test.ts +255 -0
  154. package/src/__tests__/UpdateMJDataContextItem.oldValues.test.ts +220 -0
  155. package/src/__tests__/ViewOperationsHandler.clauseScreen.test.ts +155 -0
  156. package/src/__tests__/actionAuthorization.test.ts +130 -0
  157. package/src/__tests__/adhocTimeoutClamp.test.ts +26 -0
  158. package/src/__tests__/cacheInvalidationRecordData.test.ts +241 -0
  159. package/src/__tests__/multiTenancy.postgresRewrite.test.ts +180 -0
  160. package/src/__tests__/multiTenancy.security.test.ts +51 -0
  161. package/src/__tests__/multiTenancy.test.ts +1 -1
  162. package/src/__tests__/newUserRolesDefault.test.ts +81 -0
  163. package/src/__tests__/postgresqlPoolSettings.test.ts +131 -0
  164. package/src/__tests__/pushStatusResolver.filter.test.ts +56 -0
  165. package/src/__tests__/resolverBase.refusalMessage.test.ts +88 -0
  166. package/src/__tests__/resolverBase.rls.test.ts +2 -0
  167. package/src/__tests__/translateBracketsToPG.test.ts +20 -0
  168. package/src/agentSessions/SessionManager.ts +24 -25
  169. package/src/agentSessions/SessionRunIDVerifier.ts +179 -0
  170. package/src/agentSessions/index.ts +1 -0
  171. package/src/auth/actionAuthorization.ts +119 -0
  172. package/src/auth/index.ts +1 -0
  173. package/src/auth/scopeLimitedPrincipal.ts +50 -0
  174. package/src/config.ts +34 -1
  175. package/src/context.ts +25 -34
  176. package/src/generated/generated.ts +3262 -3273
  177. package/src/generic/CacheInvalidationResolver.ts +206 -15
  178. package/src/generic/FireAndForgetHeartbeat.ts +10 -4
  179. package/src/generic/PushStatusResolver.ts +79 -4
  180. package/src/generic/ResolverBase.ts +339 -31
  181. package/src/generic/RunViewResolver.ts +17 -0
  182. package/src/index.ts +63 -50
  183. package/src/multiTenancy/index.ts +24 -2
  184. package/src/postgresqlCompat.ts +21 -0
  185. package/src/postgresqlPoolSettings.ts +213 -0
  186. package/src/realtimeWidget/widgetGuestElevation.ts +2 -2
  187. package/src/resolvers/ActionResolver.ts +85 -22
  188. package/src/resolvers/AdhocQueryResolver.ts +110 -177
  189. package/src/resolvers/DatasetResolver.ts +70 -10
  190. package/src/resolvers/EntityRecordNameResolver.ts +24 -7
  191. package/src/resolvers/GetDataContextDataResolver.ts +139 -41
  192. package/src/resolvers/GetDataResolver.ts +14 -1
  193. package/src/resolvers/MCPResolver.ts +13 -15
  194. package/src/resolvers/RealtimeClientSessionResolver.ts +82 -50
  195. package/src/resolvers/RemoteBrowserActionResolver.ts +30 -26
  196. package/src/resolvers/RunAIAgentResolver.ts +30 -40
  197. package/src/resolvers/RunTemplateResolver.ts +13 -12
  198. package/src/resolvers/RunTestResolver.ts +90 -112
  199. package/src/resolvers/SyncRolesUsersResolver.ts +11 -2
  200. package/src/resolvers/VersionHistoryResolver.ts +10 -13
  201. package/src/resolvers/__tests__/GetDataResolver.validation.test.ts +95 -0
  202. package/src/resolvers/__tests__/ReportResolver.test.ts +2 -0
  203. package/src/resolvers/adhocTimeout.ts +12 -0
  204. package/src/rest/ViewOperationsHandler.ts +37 -18
  205. package/src/services/TaskOrchestrator.ts +17 -17
  206. package/dist/resolvers/adhoc-query-helpers.d.ts +0 -27
  207. package/dist/resolvers/adhoc-query-helpers.d.ts.map +0 -1
  208. package/dist/resolvers/adhoc-query-helpers.js +0 -42
  209. package/dist/resolvers/adhoc-query-helpers.js.map +0 -1
  210. package/src/__tests__/adhoc-query-helpers.test.ts +0 -50
  211. package/src/resolvers/adhoc-query-helpers.ts +0 -50
@@ -0,0 +1,353 @@
1
+ // type-graphql decorators call `Reflect.getMetadata`, which only exists once this polyfill is
2
+ // loaded. MUST precede any import that pulls in the resolver file.
3
+ import 'reflect-metadata';
4
+
5
+ /**
6
+ * `RunAction` is a public mutation: any authenticated principal can call it with any action ID.
7
+ * These tests pin who may run an action through it, and that the client cannot switch off the
8
+ * action execution log.
9
+ *
10
+ * Policy under test:
11
+ * - scope-limited sessions (anonymous magic-link guests, widget guests, resource-scoped links)
12
+ * are refused before anything loads;
13
+ * - an Owner may run any action, decided before anything is read;
14
+ * - any other user must hold one of the authorizations linked to the action through
15
+ * `MJ: Action Authorizations`; an action with none runs only when its class authorizes its
16
+ * caller itself (`BaseAction.AuthorizesCaller`), and is refused otherwise;
17
+ * - the links, the authorization tree and the role grants all come from the request's provider,
18
+ * or all from the global provider when the request carries none.
19
+ */
20
+ import { describe, it, expect, vi, beforeEach, type MockInstance } from 'vitest';
21
+
22
+ // As in RunDecisionResolver.test.ts: vitest's esbuild transform does not apply
23
+ // `emitDecoratorMetadata`, so the decorators are no-ops and the resolver runs as a plain class.
24
+ vi.mock('type-graphql', () => {
25
+ const noopDecorator = () => () => undefined;
26
+ return {
27
+ Resolver: noopDecorator, Mutation: noopDecorator, Query: noopDecorator, Subscription: noopDecorator,
28
+ ObjectType: noopDecorator, InputType: noopDecorator, Field: noopDecorator, Arg: noopDecorator,
29
+ Args: noopDecorator, Ctx: noopDecorator, PubSub: noopDecorator, Root: noopDecorator,
30
+ Directive: noopDecorator, Authorized: noopDecorator, UseMiddleware: noopDecorator,
31
+ createUnionType: () => class {},
32
+ AuthorizationError: class AuthorizationError extends Error {
33
+ constructor(message?: string) {
34
+ super(message);
35
+ this.name = 'AuthorizationError';
36
+ }
37
+ },
38
+ Float: class {}, Int: class {}, ID: class {},
39
+ };
40
+ });
41
+
42
+ import {
43
+ AuthorizationInfo,
44
+ AuthorizationRoleInfo,
45
+ EntityInfo,
46
+ Metadata,
47
+ RunView,
48
+ UserInfo,
49
+ UserRoleInfo,
50
+ type DatabaseProviderBase,
51
+ type IMetadataProvider,
52
+ type RunViewParams,
53
+ type RunViewResult,
54
+ } from '@memberjunction/core';
55
+ import { UserCache } from '@memberjunction/sqlserver-dataprovider';
56
+ import { MJGlobal } from '@memberjunction/global';
57
+ import { ActionEngineServer, BaseAction } from '@memberjunction/actions';
58
+ import { MJActionEntityExtended, type ActionResult, type ActionResultSimple, type RunActionParams } from '@memberjunction/actions-base';
59
+ import { ActionResolver, type RunActionInput } from '../resolvers/ActionResolver.js';
60
+ import type { AppContext, ProviderInfo, UserPayload } from '../types.js';
61
+
62
+ // ─── Fixtures ────────────────────────────────────────────────────────────────
63
+
64
+ const ACTION_ENTITY = new EntityInfo({
65
+ ID: 'entity-actions', Name: 'MJ: Actions', SchemaName: '__mj', BaseTable: 'Action', BaseView: 'vwActions',
66
+ Fields: ['ID', 'Name', 'Type', 'DriverClass'].map((field, index) => ({
67
+ ID: `entity-actions-${field}`, EntityID: 'entity-actions', Sequence: index + 1, Name: field, Entity: 'MJ: Actions',
68
+ Type: field === 'ID' ? 'uniqueidentifier' : 'nvarchar', IsPrimaryKey: field === 'ID',
69
+ })),
70
+ });
71
+
72
+ const makeAction = (fields: Pick<MJActionEntityExtended, 'ID' | 'Name'>): MJActionEntityExtended => {
73
+ const action = new MJActionEntityExtended(ACTION_ENTITY);
74
+ action.Hydrate({ Type: 'Custom', DriverClass: null, ...fields });
75
+ return action;
76
+ };
77
+
78
+ /** The "Calculate Expression" action from metadata/actions: no Action Authorization rows ship for it. */
79
+ const UNGRANTED_ACTION = makeAction({ ID: '22F9505E-3BEB-400E-A49F-A74D135C5A93', Name: 'Calculate Expression' });
80
+ /** An action an administrator linked to the "Run Audience Actions" authorization. */
81
+ const GRANTED_ACTION = makeAction({ ID: 'A11C0000-0000-4000-8000-000000000002', Name: 'Send To Audience' });
82
+ /** An action linked only to an authorization that has been switched off. */
83
+ const INACTIVE_GRANT_ACTION = makeAction({ ID: 'A11C0000-0000-4000-8000-000000000003', Name: 'Archive Audience' });
84
+ /** The Database Designer's "Create Entity" from metadata/actions: no Action Authorization rows ship for it. */
85
+ const SELF_AUTHORIZING_ACTION = makeAction({ ID: 'F4CBD4ED-C258-468B-8F50-F12E4C74A431', Name: 'Create Entity' });
86
+ /** An action an administrator linked to "Run Reports", a child of the "Reporting" authorization. */
87
+ const REPORT_ACTION = makeAction({ ID: 'A11C0000-0000-4000-8000-000000000004', Name: 'Export Report' });
88
+
89
+ /**
90
+ * Stands in for the Database Designer's Create Entity class, which checks the caller's Schema
91
+ * Management authorization itself. Registered the way `@RegisterClass` registers the real one.
92
+ */
93
+ class SelfAuthorizingCreateEntity extends BaseAction {
94
+ public static readonly AuthorizesCaller = true;
95
+ protected async InternalRunAction(): Promise<ActionResultSimple> {
96
+ return { Success: true, ResultCode: 'SUCCESS' };
97
+ }
98
+ }
99
+ MJGlobal.Instance.ClassFactory.Register(BaseAction, SelfAuthorizingCreateEntity, 'Create Entity');
100
+
101
+ const UI_ROLE_ID = 'E0AFCCEC-6A37-EF11-86D4-000D3A4E707E';
102
+ const DEVELOPER_ROLE_ID = 'DEAFCCEC-6A37-EF11-86D4-000D3A4E707E';
103
+ const OTHER_ROLE_ID = 'A11C0000-0000-4000-8000-0000000000F1';
104
+ const BLOCKED_ROLE_ID = 'A11C0000-0000-4000-8000-0000000000F2';
105
+
106
+ const AUDIENCE_AUTH = new AuthorizationInfo({ ID: 'A11C0000-0000-4000-8000-0000000000A1', Name: 'Run Audience Actions', IsActive: true });
107
+ const INACTIVE_AUTH = new AuthorizationInfo({ ID: 'A11C0000-0000-4000-8000-0000000000A2', Name: 'Archive Audiences', IsActive: false });
108
+ const REPORTING_AUTH = new AuthorizationInfo({ ID: 'A11C0000-0000-4000-8000-0000000000A3', Name: 'Reporting', IsActive: true });
109
+ const RUN_REPORTS_AUTH = new AuthorizationInfo({ ID: 'A11C0000-0000-4000-8000-0000000000A4', Name: 'Run Reports', IsActive: true, ParentID: REPORTING_AUTH.ID });
110
+
111
+ const grant = (type: 'Allow' | 'Deny', authorization: AuthorizationInfo, roleID: string): AuthorizationRoleInfo =>
112
+ new AuthorizationRoleInfo({ ID: `${type}-${authorization.ID}-${roleID}`, AuthorizationID: authorization.ID, RoleID: roleID, Type: type });
113
+
114
+ const AUTHORIZATION_ROLES = [
115
+ grant('Allow', AUDIENCE_AUTH, UI_ROLE_ID),
116
+ grant('Allow', INACTIVE_AUTH, UI_ROLE_ID),
117
+ ];
118
+
119
+ /** `MJ: Action Authorizations`, as ActionID → AuthorizationIDs. */
120
+ const ACTION_AUTHORIZATIONS: Record<string, string[]> = {
121
+ [GRANTED_ACTION.ID]: [AUDIENCE_AUTH.ID],
122
+ [INACTIVE_GRANT_ACTION.ID]: [INACTIVE_AUTH.ID],
123
+ [REPORT_ACTION.ID]: [RUN_REPORTS_AUTH.ID],
124
+ };
125
+
126
+ /** A provider's authorization tree and role grants, as a stand-in metadata provider. */
127
+ const authorizationMetadata = (authorizations: AuthorizationInfo[], grants: AuthorizationRoleInfo[]) =>
128
+ ({ Authorizations: authorizations, AuthorizationRoles: grants }) as unknown as IMetadataProvider & DatabaseProviderBase;
129
+
130
+ /** The request-scoped provider MJServer puts in the GraphQL context. */
131
+ const requestProvider = (authorizations: AuthorizationInfo[], grants: AuthorizationRoleInfo[]): ProviderInfo => ({
132
+ type: 'Read-Write',
133
+ provider: authorizationMetadata(authorizations, grants),
134
+ });
135
+
136
+ const makeUser = (fields: Pick<UserInfo, 'ID' | 'Name' | 'Email' | 'Type'>, roleIDs: string[]): UserInfo =>
137
+ new UserInfo(null, {
138
+ ...fields,
139
+ UserRoles: roleIDs.map((RoleID) => new UserRoleInfo({ UserID: fields.ID, RoleID })),
140
+ });
141
+
142
+ const UI_USER = makeUser({ ID: 'user-ui', Name: 'Pat', Email: 'pat@example.com', Type: 'User' }, [UI_ROLE_ID]);
143
+ const OTHER_USER = makeUser({ ID: 'user-other', Name: 'Sam', Email: 'sam@example.com', Type: 'User' }, [OTHER_ROLE_ID]);
144
+ const BLOCKED_UI_USER = makeUser({ ID: 'user-blocked', Name: 'Lee', Email: 'lee@example.com', Type: 'User' }, [UI_ROLE_ID, BLOCKED_ROLE_ID]);
145
+ const DEVELOPER = makeUser({ ID: 'user-dev', Name: 'Dana', Email: 'dana@example.com', Type: 'User' }, [DEVELOPER_ROLE_ID]);
146
+ // `Type` is an nchar column, so the database pads it.
147
+ const OWNER = makeUser({ ID: 'user-owner', Name: 'Olive', Email: 'olive@example.com', Type: 'Owner ' }, []);
148
+ const SYSTEM_USER = makeUser({ ID: 'user-system', Name: 'System', Email: 'system@example.com', Type: 'Owner' }, []);
149
+
150
+ const payloadFor = (user: UserInfo): UserPayload => ({ email: user.Email, userRecord: user, sessionId: `session-${user.ID}` });
151
+
152
+ /** The context the resolver reads: `userPayload` and `providers`. With no providers, it uses the global one. */
153
+ function context(user: UserInfo, providers: ProviderInfo[]): AppContext {
154
+ const partial: Pick<AppContext, 'userPayload' | 'providers'> = { userPayload: payloadFor(user), providers };
155
+ return partial as AppContext;
156
+ }
157
+
158
+ const runAction = (user: UserInfo, input: Partial<RunActionInput> & Pick<RunActionInput, 'ActionID'>, providers: ProviderInfo[] = []) =>
159
+ new ActionResolver().RunAction({ Params: [], ...input } as RunActionInput, context(user, providers));
160
+
161
+ const ENGINE_RESULT: ActionResult = { Success: true, Message: 'ran', RunParams: null, Params: [] };
162
+
163
+ let engineRun: MockInstance<ActionEngineServer['RunAction']>;
164
+ let engineConfig: MockInstance<ActionEngineServer['Config']>;
165
+ let viewRun: MockInstance<RunView['RunView']>;
166
+ let globalProvider: MockInstance<() => IMetadataProvider>;
167
+ const sentParams = (): RunActionParams => engineRun.mock.calls[0][0];
168
+
169
+ beforeEach(() => {
170
+ vi.restoreAllMocks();
171
+ engineConfig = vi.spyOn(ActionEngineServer.prototype, 'Config').mockResolvedValue(undefined);
172
+ vi.spyOn(ActionEngineServer.prototype, 'Actions', 'get').mockReturnValue([UNGRANTED_ACTION, GRANTED_ACTION, INACTIVE_GRANT_ACTION, SELF_AUTHORIZING_ACTION, REPORT_ACTION]);
173
+ engineRun = vi.spyOn(ActionEngineServer.prototype, 'RunAction').mockResolvedValue(ENGINE_RESULT);
174
+ vi.spyOn(UserCache.prototype, 'GetSystemUser').mockReturnValue(SYSTEM_USER);
175
+ globalProvider = vi.spyOn(Metadata, 'Provider', 'get').mockReturnValue(authorizationMetadata([AUDIENCE_AUTH, INACTIVE_AUTH], AUTHORIZATION_ROLES));
176
+ // No database: answer the `MJ: Action Authorizations` lookup from the fixture above.
177
+ viewRun = vi.spyOn(RunView.prototype, 'RunView').mockImplementation(async <T>(params: RunViewParams): Promise<RunViewResult<T>> => {
178
+ const actionID = Object.keys(ACTION_AUTHORIZATIONS).find((id) => typeof params.ExtraFilter === 'string' && params.ExtraFilter.includes(id));
179
+ const rows = params.EntityName === 'MJ: Action Authorizations' && actionID
180
+ ? ACTION_AUTHORIZATIONS[actionID].map((AuthorizationID) => ({ ActionID: actionID, AuthorizationID }))
181
+ : [];
182
+ return { Success: true, Results: rows as T[], RowCount: rows.length, TotalRowCount: rows.length, ExecutionTime: 0, ErrorMessage: '' };
183
+ });
184
+ });
185
+
186
+ // ─── Scope-limited sessions ──────────────────────────────────────────────────
187
+
188
+ describe('RunAction: scope-limited sessions', () => {
189
+ it.each([
190
+ ['an anonymous magic-link or widget guest', { IsMagicLinkAnonymous: true, MagicLinkScope: { ResourceID: 'widget-session-1', ResourceType: 'Widget Session' } }],
191
+ ['a resource-scoped magic-link session', { IsMagicLinkAnonymous: false, MagicLinkScope: { ResourceID: 'dashboard-1', ResourceType: 'Dashboards' } }],
192
+ ])('refuses %s before the action engine loads or runs anything', async (_label, limit) => {
193
+ const guest = Object.assign(makeUser({ ID: 'user-guest', Name: 'Guest', Email: 'guest@example.com', Type: 'User' }, [UI_ROLE_ID]), limit);
194
+
195
+ const result = await runAction(guest, { ActionID: GRANTED_ACTION.ID });
196
+
197
+ expect(result.Success).toBe(false);
198
+ expect(result.Message).toMatch(/not permitted for scope-limited sessions/);
199
+ expect(engineConfig).not.toHaveBeenCalled();
200
+ expect(engineRun).not.toHaveBeenCalled();
201
+ });
202
+ });
203
+
204
+ // ─── Per-action authorization ────────────────────────────────────────────────
205
+
206
+ describe('RunAction: per-action authorization', () => {
207
+ it('refuses an ordinary user for an action that no Action Authorization grants', async () => {
208
+ const result = await runAction(UI_USER, {
209
+ ActionID: UNGRANTED_ACTION.ID,
210
+ Params: [{ Name: 'Expression', Type: 'Input', Value: '6*7' }],
211
+ });
212
+
213
+ expect(result.Success).toBe(false);
214
+ expect(result.Message).toMatch(/not authorized to run action/i);
215
+ expect(engineRun).not.toHaveBeenCalled();
216
+ });
217
+
218
+ it('refuses a user whose roles hold none of the action\'s authorizations', async () => {
219
+ const result = await runAction(OTHER_USER, { ActionID: GRANTED_ACTION.ID });
220
+
221
+ expect(result.Success).toBe(false);
222
+ expect(result.Message).toMatch(/not authorized to run action/i);
223
+ expect(engineRun).not.toHaveBeenCalled();
224
+ });
225
+
226
+ it('refuses when the only linked authorization is inactive', async () => {
227
+ const result = await runAction(UI_USER, { ActionID: INACTIVE_GRANT_ACTION.ID });
228
+
229
+ expect(result.Success).toBe(false);
230
+ expect(engineRun).not.toHaveBeenCalled();
231
+ });
232
+
233
+ it('runs the action for a user whose role holds a linked authorization', async () => {
234
+ const result = await runAction(UI_USER, { ActionID: GRANTED_ACTION.ID });
235
+
236
+ expect(result.Success).toBe(true);
237
+ expect(sentParams().Action).toBe(GRANTED_ACTION);
238
+ expect(sentParams().ContextUser).toBe(UI_USER);
239
+ });
240
+
241
+ it('runs any action for an Owner, deciding before reading any Action Authorization', async () => {
242
+ const result = await runAction(OWNER, { ActionID: UNGRANTED_ACTION.ID });
243
+
244
+ expect(result.Success).toBe(true);
245
+ expect(sentParams().Action).toBe(UNGRANTED_ACTION);
246
+ expect(viewRun).not.toHaveBeenCalled();
247
+ });
248
+
249
+ it('runs an unlinked action whose class authorizes its caller, so the action decides: a Developer may run Create Entity', async () => {
250
+ const result = await runAction(DEVELOPER, { ActionID: SELF_AUTHORIZING_ACTION.ID });
251
+
252
+ expect(result.Success).toBe(true);
253
+ expect(sentParams().Action).toBe(SELF_AUTHORIZING_ACTION);
254
+ expect(sentParams().ContextUser).toBe(DEVELOPER);
255
+ });
256
+
257
+ it('still refuses that Developer an unlinked action whose class does not authorize its caller', async () => {
258
+ const result = await runAction(DEVELOPER, { ActionID: UNGRANTED_ACTION.ID });
259
+
260
+ expect(result.Success).toBe(false);
261
+ expect(result.Message).toMatch(/not authorized to run action/i);
262
+ expect(engineRun).not.toHaveBeenCalled();
263
+ });
264
+
265
+ it('still reports an unknown action ID as not found', async () => {
266
+ const result = await runAction(OWNER, { ActionID: 'A11C0000-0000-4000-8000-0000000000FF' });
267
+
268
+ expect(result.Success).toBe(false);
269
+ expect(result.Message).toMatch(/not found/);
270
+ expect(engineRun).not.toHaveBeenCalled();
271
+ });
272
+ });
273
+
274
+ // ─── The request's provider decides ──────────────────────────────────────────
275
+
276
+ describe('RunAction: role grants come from the request provider, not the global provider', () => {
277
+ /** Gives the global provider the same authorizations as the request, with its own role grants. */
278
+ const globalGrants = (authorizations: AuthorizationInfo[], grants: AuthorizationRoleInfo[]) =>
279
+ globalProvider.mockReturnValue(authorizationMetadata(authorizations, grants));
280
+
281
+ it('refuses when the request provider has the linked authorization but no Allow for the caller, even though the global provider has one', async () => {
282
+ globalGrants([AUDIENCE_AUTH], [grant('Allow', AUDIENCE_AUTH, UI_ROLE_ID)]);
283
+
284
+ const result = await runAction(UI_USER, { ActionID: GRANTED_ACTION.ID }, [requestProvider([AUDIENCE_AUTH], [])]);
285
+
286
+ expect(result.Success).toBe(false);
287
+ expect(result.Message).toMatch(/not authorized to run action/i);
288
+ expect(engineRun).not.toHaveBeenCalled();
289
+ });
290
+
291
+ it('runs when the request provider has an Allow for the caller and the global provider does not', async () => {
292
+ globalGrants([AUDIENCE_AUTH], []);
293
+
294
+ const result = await runAction(OTHER_USER, { ActionID: GRANTED_ACTION.ID }, [
295
+ requestProvider([AUDIENCE_AUTH], [grant('Allow', AUDIENCE_AUTH, OTHER_ROLE_ID)]),
296
+ ]);
297
+
298
+ expect(result.Success).toBe(true);
299
+ expect(sentParams().ContextUser).toBe(OTHER_USER);
300
+ });
301
+
302
+ it('refuses when the request provider denies one of the caller\'s roles, even though the global provider has only an Allow', async () => {
303
+ globalGrants([AUDIENCE_AUTH], [grant('Allow', AUDIENCE_AUTH, UI_ROLE_ID)]);
304
+
305
+ const result = await runAction(BLOCKED_UI_USER, { ActionID: GRANTED_ACTION.ID }, [
306
+ requestProvider([AUDIENCE_AUTH], [grant('Allow', AUDIENCE_AUTH, UI_ROLE_ID), grant('Deny', AUDIENCE_AUTH, BLOCKED_ROLE_ID)]),
307
+ ]);
308
+
309
+ expect(result.Success).toBe(false);
310
+ expect(result.Message).toMatch(/not authorized to run action/i);
311
+ expect(engineRun).not.toHaveBeenCalled();
312
+ });
313
+
314
+ it('runs when only the request provider grants the parent of the linked authorization', async () => {
315
+ globalGrants([REPORTING_AUTH, RUN_REPORTS_AUTH], []);
316
+
317
+ const result = await runAction(OTHER_USER, { ActionID: REPORT_ACTION.ID }, [
318
+ requestProvider([REPORTING_AUTH, RUN_REPORTS_AUTH], [grant('Allow', REPORTING_AUTH, OTHER_ROLE_ID)]),
319
+ ]);
320
+
321
+ expect(result.Success).toBe(true);
322
+ expect(sentParams().Action).toBe(REPORT_ACTION);
323
+ });
324
+
325
+ it('refuses when only the global provider grants the parent of the linked authorization', async () => {
326
+ globalGrants([REPORTING_AUTH, RUN_REPORTS_AUTH], [grant('Allow', REPORTING_AUTH, OTHER_ROLE_ID)]);
327
+
328
+ const result = await runAction(OTHER_USER, { ActionID: REPORT_ACTION.ID }, [requestProvider([REPORTING_AUTH, RUN_REPORTS_AUTH], [])]);
329
+
330
+ expect(result.Success).toBe(false);
331
+ expect(engineRun).not.toHaveBeenCalled();
332
+ });
333
+
334
+ it('reads the Action Authorization links through the request provider too', async () => {
335
+ const request = requestProvider([AUDIENCE_AUTH], [grant('Allow', AUDIENCE_AUTH, UI_ROLE_ID)]);
336
+
337
+ await runAction(UI_USER, { ActionID: GRANTED_ACTION.ID }, [request]);
338
+
339
+ const [view] = viewRun.mock.contexts;
340
+ expect(view instanceof RunView && view.ProviderToUse).toBe(request.provider);
341
+ });
342
+ });
343
+
344
+ // ─── Action execution log ────────────────────────────────────────────────────
345
+
346
+ describe('RunAction: action execution log', () => {
347
+ it('writes the execution log even when the client asks to skip it', async () => {
348
+ const result = await runAction(OWNER, { ActionID: UNGRANTED_ACTION.ID, SkipActionLog: true });
349
+
350
+ expect(result.Success).toBe(true);
351
+ expect(sentParams().SkipActionLog).toBe(false);
352
+ });
353
+ });
@@ -60,20 +60,15 @@ function stubMetadata(): void {
60
60
 
61
61
  describe('AdhocQueryResolver source-shape contract', () => {
62
62
 
63
- it('Bug #2: AdhocQueryResolver must import RenderPipeline (currently does not)', () => {
63
+ it('Bug #2: AdhocQueryResolver must hand the SQL to the provider ad-hoc path, authorizing the rendered SQL first', () => {
64
64
  const src = readResolverSource();
65
- // After the fix, the resolver should delegate composition + Nunjucks +
66
- // MaxRows handling to the canonical pipeline rather than re-implementing
67
- // a partial subset.
68
- const importsRenderPipeline =
69
- /import\s*\{[^}]*\bRenderPipeline\b[^}]*\}\s*from\s*['"]@memberjunction\/generic-database-provider['"]/.test(src);
70
- expect(importsRenderPipeline).toBe(true);
71
- });
72
-
73
- it('Bug #2: AdhocQueryResolver must call RenderPipeline.Run() somewhere (currently does not)', () => {
74
- const src = readResolverSource();
75
- const callsRenderPipelineRun = /\bRenderPipeline\.Run\s*\(/.test(src);
76
- expect(callsRenderPipelineRun).toBe(true);
65
+ // Composition, comment removal, the single-read rule and the row cap all happen in the
66
+ // provider's ad-hoc path (RenderPipeline), shared with in-process callers. The resolver must
67
+ // delegate there rather than re-implement a partial subset.
68
+ expect(/\.RunQuery\(\{[\s\S]*SQL: input\.SQL/.test(src)).toBe(true);
69
+ // It renders only to authorize what will be read, never to run it.
70
+ expect(/RenderPipeline\.Run\(/.test(src)).toBe(true);
71
+ expect(/assertFullQueryUsesReadableEntityViews\(rendered\.Trace\.AfterTemplates/.test(src)).toBe(true);
77
72
  });
78
73
 
79
74
  it('Bug #3: AdhocQueryResolver must NOT contain the manual `SELECT TOP N * FROM (...)` wrap', () => {
@@ -126,29 +121,13 @@ ORDER BY JoinYear DESC`;
126
121
  // success/failure, the resolver should never hand a string containing
127
122
  // "{{query:" to SQL Server.
128
123
  //
129
- // We encode this as a contract on the resolver source: it must call
130
- // into RenderPipeline whenever composition tokens are present, OR
131
- // reject early with a clear error. Either way, the literal text
132
- // "{{query:" must not reach `request.query(...)`.
124
+ // We encode this as a contract on the resolver source: it must not execute SQL itself.
125
+ // It hands input.SQL to the read-only provider's ad-hoc path, which renders it through
126
+ // RenderPipeline (resolving composition tokens) before anything reaches the database.
133
127
  const src = readResolverSource();
134
-
135
- // Acceptable post-fix shape: source mentions RenderPipeline.Run and
136
- // passes input.SQL through it. We've already asserted the import +
137
- // call above; here we additionally require that input.SQL flows
138
- // through RenderPipeline.Run rather than directly to request.query.
139
- //
140
- // The current code contains `request.query(executableSql)` where
141
- // `executableSql` is derived from input.SQL via a string concat —
142
- // bypassing the pipeline entirely.
143
- const directlyExecutesInputSQL = /request\.query\s*\(\s*input\.SQL\s*\)/.test(src);
144
- expect(directlyExecutesInputSQL).toBe(false);
145
-
146
- // And — the executable string must be derived from a pipeline result,
147
- // not from an inline template literal that just concatenates input.SQL.
148
- // Heuristic: the file should reference `FinalSQL` (the pipeline's
149
- // output field) somewhere — this is what gets sent to the DB.
150
- const referencesFinalSQL = /\bFinalSQL\b/.test(src);
151
- expect(referencesFinalSQL).toBe(true);
128
+ const executesSQLItself = /request\.query\s*\(|\.ExecuteSQL\s*\(|new sql\.Request/.test(src);
129
+ expect(executesSQLItself).toBe(false);
130
+ expect(/\.RunQuery\(\{[\s\S]*SQL: input\.SQL/.test(src)).toBe(true);
152
131
  });
153
132
  });
154
133
 
@@ -79,9 +79,13 @@ describe('AdhocQueryResolver pagination source-shape contract', () => {
79
79
  expect(/TotalRowCount:\s*recordset\.length/.test(src)).toBe(false);
80
80
  });
81
81
 
82
- it('must consume the RenderPipeline PagingResult.CountSQL', () => {
82
+ it('must page through the read-only provider, passing MaxRows, StartRow and the timeout', () => {
83
83
  const src = readResolverSource();
84
- expect(/PagingResult\??\.CountSQL/.test(src)).toBe(true);
84
+ // The provider's ad-hoc path renders, pages in the database and counts; the resolver
85
+ // must hand it the paging inputs rather than run SQL itself.
86
+ expect(/GetReadOnlyProvider\(/.test(src)).toBe(true);
87
+ expect(/\.RunQuery\(\{[\s\S]*SQL: input\.SQL[\s\S]*MaxRows: input\.MaxRows[\s\S]*StartRow: startRow[\s\S]*TimeoutSeconds/.test(src)).toBe(true);
88
+ expect(/from 'mssql'|new sql\.Request/.test(src)).toBe(false);
85
89
  });
86
90
  });
87
91
 
@@ -0,0 +1,84 @@
1
+ /**
2
+ * `ExecuteAdhocQuery` runs a raw `SELECT` straight on the read-only pool: no `RunView`, no
3
+ * entity permissions, no row-level security, and therefore no magic-link scope. The
4
+ * confinement a scope-limited session relies on is expressed purely as RLS filter tokens
5
+ * substituted on the entity-read path, so on this path it simply does not exist — a
6
+ * scope-limited principal reaching it would read the whole database.
7
+ *
8
+ * These tests pin the predicate that classifies such principals, and that the resolver
9
+ * consults it before it touches a data source. The resolver itself needs a very heavy mock
10
+ * graph to instantiate (type-graphql decorators, mssql, AppContext, config, providers), so
11
+ * the ordering assertion is a source-shape test — the same hybrid strategy the existing
12
+ * `AdhocQueryResolver.bugs.test.ts` uses for this resolver.
13
+ */
14
+ import { describe, it, expect } from 'vitest';
15
+ import { readFileSync } from 'fs';
16
+ import { resolve } from 'path';
17
+ import { UserInfo } from '@memberjunction/core';
18
+ import { IsScopeLimitedPrincipal } from '../auth/scopeLimitedPrincipal.js';
19
+
20
+ const ADHOC_RESOLVER_PATH = resolve(__dirname, '../resolvers/AdhocQueryResolver.ts');
21
+
22
+ /** A principal with nothing set — the shape of an ordinary authenticated user. */
23
+ function plainUser(): UserInfo {
24
+ const u = new UserInfo();
25
+ u.ID = 'D1F1A0C4-0000-4000-8000-000000000001';
26
+ u.Email = 'user@example.com';
27
+ return u;
28
+ }
29
+
30
+ describe('IsScopeLimitedPrincipal', () => {
31
+ it('does not limit an ordinary authenticated user', () => {
32
+ expect(IsScopeLimitedPrincipal(plainUser())).toBe(false);
33
+ });
34
+
35
+ it('limits an anonymous magic-link guest', () => {
36
+ const guest = plainUser();
37
+ guest.IsMagicLinkAnonymous = true;
38
+ expect(IsScopeLimitedPrincipal(guest)).toBe(true);
39
+ });
40
+
41
+ it('limits a resource-scoped magic-link session (ResourceID)', () => {
42
+ const scoped = plainUser();
43
+ scoped.MagicLinkScope = { ResourceID: 'A0000000-0000-4000-8000-000000000009' };
44
+ expect(IsScopeLimitedPrincipal(scoped)).toBe(true);
45
+ });
46
+
47
+ it('limits a resource-scoped magic-link session carrying only a ResourceType', () => {
48
+ const scoped = plainUser();
49
+ scoped.MagicLinkScope = { ResourceType: 'Dashboards' };
50
+ expect(IsScopeLimitedPrincipal(scoped)).toBe(true);
51
+ });
52
+
53
+ it('does NOT limit a session whose scope object is empty', () => {
54
+ // An empty object carries no confinement. Testing the object's truthiness rather
55
+ // than its contents would lock out a session that is not actually scoped.
56
+ const notReallyScoped = plainUser();
57
+ notReallyScoped.MagicLinkScope = {};
58
+ expect(IsScopeLimitedPrincipal(notReallyScoped)).toBe(false);
59
+ });
60
+
61
+ it('fails closed when there is no principal at all', () => {
62
+ expect(IsScopeLimitedPrincipal(undefined)).toBe(true);
63
+ expect(IsScopeLimitedPrincipal(null)).toBe(true);
64
+ });
65
+ });
66
+
67
+ describe('AdhocQueryResolver scope guard placement', () => {
68
+ const src = readFileSync(ADHOC_RESOLVER_PATH, 'utf8');
69
+
70
+ it('consults IsScopeLimitedPrincipal', () => {
71
+ expect(/\bIsScopeLimitedPrincipal\s*\(/.test(src)).toBe(true);
72
+ });
73
+
74
+ it('refuses the principal BEFORE acquiring the read-only provider', () => {
75
+ // Authorization must gate the work, not run alongside it: if the guard landed after
76
+ // the provider were acquired (or the SQL executed), a scope-limited caller would already
77
+ // have reached the database.
78
+ const guardAt = src.indexOf('IsScopeLimitedPrincipal(');
79
+ const dataSourceAt = src.indexOf('GetReadOnlyProvider(');
80
+ expect(guardAt).toBeGreaterThan(-1);
81
+ expect(dataSourceAt).toBeGreaterThan(-1);
82
+ expect(guardAt).toBeLessThan(dataSourceAt);
83
+ });
84
+ });
@@ -0,0 +1,104 @@
1
+ // type-graphql decorators call `Reflect.getMetadata`, which only exists once this polyfill is
2
+ // loaded. MUST precede any import that pulls in the resolver file.
3
+ import 'reflect-metadata';
4
+
5
+ /**
6
+ * MJServer registers an ad-hoc SQL authorizer with the action engine so that Run Ad-hoc Query, which
7
+ * agents run as the calling user, applies the same checks as the ExecuteAdhocQuery resolver: the
8
+ * rendered SQL must be one read statement, every table it reads must be an entity base view the
9
+ * caller may read in full (no row-level filter, no denied field), and the timeout is limited by the
10
+ * server's request timeout.
11
+ *
12
+ * Every SQL statement below is harmless.
13
+ */
14
+ import { describe, it, expect, vi } from 'vitest';
15
+ import { readFileSync } from 'fs';
16
+ import { resolve } from 'path';
17
+
18
+ vi.mock('type-graphql', () => {
19
+ const noopDecorator = () => () => undefined;
20
+ return {
21
+ Resolver: noopDecorator, Mutation: noopDecorator, Query: noopDecorator, Subscription: noopDecorator,
22
+ ObjectType: noopDecorator, InputType: noopDecorator, Field: noopDecorator, Arg: noopDecorator,
23
+ Args: noopDecorator, Ctx: noopDecorator, PubSub: noopDecorator, Root: noopDecorator,
24
+ Directive: noopDecorator, Authorized: noopDecorator, UseMiddleware: noopDecorator,
25
+ createUnionType: () => class {},
26
+ AuthorizationError: class AuthorizationError extends Error {},
27
+ Float: class {}, Int: class {}, ID: class {},
28
+ };
29
+ });
30
+
31
+ // The server config is read from mj.config at import; the authorizer takes its timeout as an argument.
32
+ vi.mock('../config.js', () => ({ configInfo: { databaseSettings: { requestTimeout: 120_000 } } }));
33
+
34
+ import type { DatabaseProviderBase, UserInfo } from '@memberjunction/core';
35
+ import { CreateAdhocSQLAuthorizer } from '../resolvers/AdhocQueryResolver.js';
36
+ import { ClampAdhocTimeoutSeconds } from '../resolvers/adhocTimeout.js';
37
+
38
+ type EntityShape = { Name: string; SchemaName: string; BaseView: string; rowFilter?: string };
39
+
40
+ /** A read-only provider with the entity metadata the table check reads. */
41
+ function readOnlyProvider(entities: EntityShape[]): DatabaseProviderBase {
42
+ return {
43
+ PlatformKey: 'sqlserver',
44
+ Entities: entities.map((e) => ({
45
+ Name: e.Name,
46
+ SchemaName: e.SchemaName,
47
+ BaseView: e.BaseView,
48
+ GetUserPermisions: () => ({ CanRead: true }),
49
+ // lts/5: row-level security is the line's only read narrowing (no field-level security).
50
+ GetUserRowLevelSecurityWhereClause: () => e.rowFilter ?? '',
51
+ })),
52
+ } as unknown as DatabaseProviderBase;
53
+ }
54
+
55
+ const USER = { ID: 'user-1', Email: 'user@example.com' } as unknown as UserInfo;
56
+ const RUBRIC_EVALUATIONS: EntityShape = { Name: 'MJ: Rubric Evaluations', SchemaName: '__mj', BaseView: 'vwRubricEvaluations' };
57
+ const REQUEST_TIMEOUT_MS = 120_000;
58
+
59
+ describe('CreateAdhocSQLAuthorizer', () => {
60
+ const authorizer = CreateAdhocSQLAuthorizer(REQUEST_TIMEOUT_MS);
61
+
62
+ it('admits SQL that reads only entity views the user may read in full', () => {
63
+ const refusal = authorizer.Authorize('SELECT ID FROM [__mj].[vwRubricEvaluations]', readOnlyProvider([RUBRIC_EVALUATIONS]), USER);
64
+
65
+ expect(refusal).toBeNull();
66
+ });
67
+
68
+ it('refuses SQL that reads an entity the user may read only through a row filter', () => {
69
+ const filtered = { ...RUBRIC_EVALUATIONS, rowFilter: "EvaluatorUserID='user-1'" };
70
+
71
+ const refusal = authorizer.Authorize('SELECT * FROM __mj.vwRubricEvaluations', readOnlyProvider([filtered]), USER);
72
+
73
+ expect(refusal).toMatch(/row-level-security filtered/);
74
+ });
75
+
76
+ it('refuses SQL that reads a table that is not an entity view', () => {
77
+ const refusal = authorizer.Authorize('SELECT * FROM [__mj].[User]', readOnlyProvider([RUBRIC_EVALUATIONS]), USER);
78
+
79
+ expect(refusal).toMatch(/entity base view/);
80
+ });
81
+
82
+ it('refuses a stacked batch hidden behind a bracket identifier', () => {
83
+ const refusal = authorizer.Authorize("SELECT 1 AS [a'] ; SELECT 2 AS [b']", readOnlyProvider([RUBRIC_EVALUATIONS]), USER);
84
+
85
+ expect(refusal).toMatch(/single read query/);
86
+ });
87
+
88
+ it('limits the timeout the way ExecuteAdhocQuery does', () => {
89
+ for (const requested of [undefined, 5, 600]) {
90
+ expect(authorizer.ClampTimeoutSeconds(requested)).toBe(ClampAdhocTimeoutSeconds(requested, REQUEST_TIMEOUT_MS));
91
+ }
92
+ expect(authorizer.ClampTimeoutSeconds(600)).toBe(120);
93
+ });
94
+ });
95
+
96
+ describe('MJServer startup', () => {
97
+ // Startup needs a database, so this one assertion reads the source.
98
+ it('registers the read-only provider factory and this authorizer with the action engine', () => {
99
+ const src = readFileSync(resolve(__dirname, '../index.ts'), 'utf8');
100
+
101
+ expect(/ActionEngineServer\.Instance\.SetReadOnlyProviderFactory\(\s*\(\)\s*=>\s*CreateReadOnlyProvider\(dataSources\)\s*\)/.test(src)).toBe(true);
102
+ expect(/ActionEngineServer\.Instance\.SetAdhocSQLAuthorizer\(\s*CreateAdhocSQLAuthorizer\(configInfo\.databaseSettings\.requestTimeout\)\s*\)/.test(src)).toBe(true);
103
+ });
104
+ });