@memberjunction/core-actions 6.2.0 → 6.3.0-edge.0
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/README.md +28 -2
- package/dist/custom/ai/base-find-skills.action.d.ts +56 -0
- package/dist/custom/ai/base-find-skills.action.d.ts.map +1 -0
- package/dist/custom/ai/base-find-skills.action.js +237 -0
- package/dist/custom/ai/base-find-skills.action.js.map +1 -0
- package/dist/custom/ai/configure-agent-user-policy.action.d.ts.map +1 -1
- package/dist/custom/ai/configure-agent-user-policy.action.js +96 -15
- package/dist/custom/ai/configure-agent-user-policy.action.js.map +1 -1
- package/dist/custom/ai/find-best-skill.action.d.ts +13 -0
- package/dist/custom/ai/find-best-skill.action.d.ts.map +1 -0
- package/dist/custom/ai/find-best-skill.action.js +29 -0
- package/dist/custom/ai/find-best-skill.action.js.map +1 -0
- package/dist/custom/ai/find-candidate-skills.action.d.ts +21 -0
- package/dist/custom/ai/find-candidate-skills.action.d.ts.map +1 -0
- package/dist/custom/ai/find-candidate-skills.action.js +35 -0
- package/dist/custom/ai/find-candidate-skills.action.js.map +1 -0
- package/dist/custom/ai/get-skill-details.action.d.ts +40 -0
- package/dist/custom/ai/get-skill-details.action.d.ts.map +1 -0
- package/dist/custom/ai/get-skill-details.action.js +133 -0
- package/dist/custom/ai/get-skill-details.action.js.map +1 -0
- package/dist/custom/ai/prepare-outbound-call-brief.action.d.ts.map +1 -1
- package/dist/custom/ai/prepare-outbound-call-brief.action.js +10 -1
- package/dist/custom/ai/prepare-outbound-call-brief.action.js.map +1 -1
- package/dist/custom/ai/schedule-next-agent-wake.action.d.ts +16 -0
- package/dist/custom/ai/schedule-next-agent-wake.action.d.ts.map +1 -1
- package/dist/custom/ai/schedule-next-agent-wake.action.js +100 -17
- package/dist/custom/ai/schedule-next-agent-wake.action.js.map +1 -1
- package/dist/custom/ai/semantic-entity-search.helper.d.ts +1 -1
- package/dist/custom/ai/semantic-entity-search.helper.d.ts.map +1 -1
- package/dist/custom/ai/send-inter-agent-request.action.d.ts +17 -6
- package/dist/custom/ai/send-inter-agent-request.action.d.ts.map +1 -1
- package/dist/custom/ai/send-inter-agent-request.action.js +227 -29
- package/dist/custom/ai/send-inter-agent-request.action.js.map +1 -1
- package/dist/custom/ai/trigger-agent-wake.action.d.ts +19 -0
- package/dist/custom/ai/trigger-agent-wake.action.d.ts.map +1 -0
- package/dist/custom/ai/trigger-agent-wake.action.js +134 -0
- package/dist/custom/ai/trigger-agent-wake.action.js.map +1 -0
- package/dist/custom/ai/user-scoped-communication.action.d.ts +1 -1
- package/dist/custom/ai/user-scoped-communication.action.d.ts.map +1 -1
- package/dist/custom/ai/user-scoped-communication.action.js +13 -7
- package/dist/custom/ai/user-scoped-communication.action.js.map +1 -1
- package/dist/custom/communication/teams-webhook.action.d.ts +5 -0
- package/dist/custom/communication/teams-webhook.action.d.ts.map +1 -1
- package/dist/custom/communication/teams-webhook.action.js +15 -1
- package/dist/custom/communication/teams-webhook.action.js.map +1 -1
- package/dist/custom/crud/agent-data-policy-guard.d.ts +155 -0
- package/dist/custom/crud/agent-data-policy-guard.d.ts.map +1 -0
- package/dist/custom/crud/agent-data-policy-guard.js +898 -0
- package/dist/custom/crud/agent-data-policy-guard.js.map +1 -0
- package/dist/custom/crud/create-record.action.d.ts.map +1 -1
- package/dist/custom/crud/create-record.action.js +25 -0
- package/dist/custom/crud/create-record.action.js.map +1 -1
- package/dist/custom/crud/delete-record.action.d.ts.map +1 -1
- package/dist/custom/crud/delete-record.action.js +36 -1
- package/dist/custom/crud/delete-record.action.js.map +1 -1
- package/dist/custom/crud/get-record.action.d.ts.map +1 -1
- package/dist/custom/crud/get-record.action.js +36 -1
- package/dist/custom/crud/get-record.action.js.map +1 -1
- package/dist/custom/crud/get-records.action.d.ts +3 -3
- package/dist/custom/crud/get-records.action.d.ts.map +1 -1
- package/dist/custom/crud/get-records.action.js +55 -6
- package/dist/custom/crud/get-records.action.js.map +1 -1
- package/dist/custom/crud/update-record.action.d.ts.map +1 -1
- package/dist/custom/crud/update-record.action.js +82 -0
- package/dist/custom/crud/update-record.action.js.map +1 -1
- package/dist/custom/crud/write-entity-fields.action.d.ts.map +1 -1
- package/dist/custom/crud/write-entity-fields.action.js +73 -0
- package/dist/custom/crud/write-entity-fields.action.js.map +1 -1
- package/dist/custom/data/get-entity-details.action.d.ts.map +1 -1
- package/dist/custom/data/get-entity-details.action.js +33 -2
- package/dist/custom/data/get-entity-details.action.js.map +1 -1
- package/dist/custom/data/get-graph-context.action.d.ts +39 -0
- package/dist/custom/data/get-graph-context.action.d.ts.map +1 -0
- package/dist/custom/data/get-graph-context.action.js +303 -0
- package/dist/custom/data/get-graph-context.action.js.map +1 -0
- package/dist/custom/data/run-adhoc-query.action.d.ts.map +1 -1
- package/dist/custom/data/run-adhoc-query.action.js +6 -1
- package/dist/custom/data/run-adhoc-query.action.js.map +1 -1
- package/dist/custom/data/run-stored-query.action.d.ts.map +1 -1
- package/dist/custom/data/run-stored-query.action.js +8 -2
- package/dist/custom/data/run-stored-query.action.js.map +1 -1
- package/dist/custom/github/base-github.action.d.ts +51 -0
- package/dist/custom/github/base-github.action.d.ts.map +1 -0
- package/dist/custom/github/base-github.action.js +220 -0
- package/dist/custom/github/base-github.action.js.map +1 -0
- package/dist/custom/github/github-actions.d.ts +66 -0
- package/dist/custom/github/github-actions.d.ts.map +1 -0
- package/dist/custom/github/github-actions.js +715 -0
- package/dist/custom/github/github-actions.js.map +1 -0
- package/dist/custom/github/github-app-auth.d.ts +122 -0
- package/dist/custom/github/github-app-auth.d.ts.map +1 -0
- package/dist/custom/github/github-app-auth.js +396 -0
- package/dist/custom/github/github-app-auth.js.map +1 -0
- package/dist/custom/github/github-client.d.ts +288 -0
- package/dist/custom/github/github-client.d.ts.map +1 -0
- package/dist/custom/github/github-client.js +891 -0
- package/dist/custom/github/github-client.js.map +1 -0
- package/dist/custom/github/github-credential-resolver.d.ts +73 -0
- package/dist/custom/github/github-credential-resolver.d.ts.map +1 -0
- package/dist/custom/github/github-credential-resolver.js +330 -0
- package/dist/custom/github/github-credential-resolver.js.map +1 -0
- package/dist/custom/github/github-types.d.ts +216 -0
- package/dist/custom/github/github-types.d.ts.map +1 -0
- package/dist/custom/github/github-types.js +11 -0
- package/dist/custom/github/github-types.js.map +1 -0
- package/dist/custom/github/index.d.ts +7 -0
- package/dist/custom/github/index.d.ts.map +1 -0
- package/dist/custom/github/index.js +7 -0
- package/dist/custom/github/index.js.map +1 -0
- package/dist/custom/utilities/docx-renderer.d.ts.map +1 -1
- package/dist/custom/utilities/docx-renderer.js +29 -6
- package/dist/custom/utilities/docx-renderer.js.map +1 -1
- package/dist/custom/visualization/create-svg-network.action.js +1 -1
- package/dist/custom/visualization/create-svg-network.action.js.map +1 -1
- package/dist/custom/visualization/create-svg-sketch-diagram.action.js +3 -3
- package/dist/custom/visualization/create-svg-sketch-diagram.action.js.map +1 -1
- package/dist/custom/visualization/shared/svg-utils.d.ts +23 -5
- package/dist/custom/visualization/shared/svg-utils.d.ts.map +1 -1
- package/dist/custom/visualization/shared/svg-utils.js +54 -19
- package/dist/custom/visualization/shared/svg-utils.js.map +1 -1
- package/dist/custom/web/rss-feed-parsing.d.ts.map +1 -1
- package/dist/custom/web/rss-feed-parsing.js +15 -1
- package/dist/custom/web/rss-feed-parsing.js.map +1 -1
- package/dist/custom/web/url-metadata-extractor.action.d.ts.map +1 -1
- package/dist/custom/web/url-metadata-extractor.action.js +21 -8
- package/dist/custom/web/url-metadata-extractor.action.js.map +1 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/package.json +46 -45
|
@@ -0,0 +1,898 @@
|
|
|
1
|
+
import { CompositeKey, Metadata, RunView, } from '@memberjunction/core';
|
|
2
|
+
import { AgentUserPolicyEngine, } from '@memberjunction/ai-core-plus';
|
|
3
|
+
import { ClientClauseScreen, RenderPipeline } from '@memberjunction/generic-database-provider';
|
|
4
|
+
import { EscapeSQLString, IndexByUUID, UUIDsEqual } from '@memberjunction/global';
|
|
5
|
+
function hasSyntheticRowWhereEvaluator(provider) {
|
|
6
|
+
return (Boolean(provider) &&
|
|
7
|
+
'EvaluateSyntheticRowWhereClause' in provider &&
|
|
8
|
+
typeof provider.EvaluateSyntheticRowWhereClause === 'function');
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Shared runtime guard that wires `AgentUserPolicyEngine.EvaluateEntityAccess` and
|
|
12
|
+
* `AgentUserPolicyEngine.MaskRecordFields` into record CRUD actions and query actions
|
|
13
|
+
* whenever an action executes on behalf of an agent (`params.Context.AgentID`).
|
|
14
|
+
*/
|
|
15
|
+
export class AgentDataPolicyGuard {
|
|
16
|
+
/**
|
|
17
|
+
* Extracts the calling agent ID from `params.Context` when running inside an agent turn.
|
|
18
|
+
*/
|
|
19
|
+
static GetCallingAgentID(params) {
|
|
20
|
+
const ctx = params.Context;
|
|
21
|
+
if (!ctx || typeof ctx.AgentID !== 'string') {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const trimmed = ctx.AgentID.trim();
|
|
25
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Evaluates entity-level, field-write, time-window, and optional record-condition rules
|
|
29
|
+
* for a calling agent before or after loading/mutating an entity record.
|
|
30
|
+
*/
|
|
31
|
+
static async EvaluateRecordOperation(input) {
|
|
32
|
+
const callingAgentId = AgentDataPolicyGuard.GetCallingAgentID(input.params);
|
|
33
|
+
const contextUser = input.params.ContextUser;
|
|
34
|
+
if (!callingAgentId || !contextUser?.ID) {
|
|
35
|
+
return { Allowed: { Active: false } };
|
|
36
|
+
}
|
|
37
|
+
if (input.operation !== 'Read' &&
|
|
38
|
+
input.entityInfo.Name.trim().toLowerCase() === 'mj: ai agent user policies') {
|
|
39
|
+
return {
|
|
40
|
+
Blocked: {
|
|
41
|
+
Success: false,
|
|
42
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
43
|
+
Message: 'Direct Create/Update/Delete on "MJ: AI Agent User Policies" via generic CRUD actions is not permitted for agents. Use the "Configure Agent User Policy" action instead, which enforces self-only non-widening rules.',
|
|
44
|
+
Params: input.params.Params,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const policyLookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(callingAgentId, contextUser.ID, contextUser, { provider: input.params.Provider });
|
|
49
|
+
if (policyLookup.status === 'error') {
|
|
50
|
+
return {
|
|
51
|
+
Blocked: {
|
|
52
|
+
Success: false,
|
|
53
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
54
|
+
Message: `Agent data-access policy lookup failed; refusing operation (fail-closed): ${policyLookup.errorMessage}`,
|
|
55
|
+
Params: input.params.Params,
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const policy = policyLookup.policy;
|
|
60
|
+
if (!policy) {
|
|
61
|
+
return { Allowed: { Active: false } };
|
|
62
|
+
}
|
|
63
|
+
const evalResult = AgentUserPolicyEngine.Instance.EvaluateEntityAccess({
|
|
64
|
+
policy,
|
|
65
|
+
contextUser,
|
|
66
|
+
entityName: input.entityInfo.Name,
|
|
67
|
+
operation: input.operation,
|
|
68
|
+
mutatedFields: input.mutatedFields,
|
|
69
|
+
record: input.record ? AgentDataPolicyGuard.toScalarRecord(input.record) : undefined,
|
|
70
|
+
provider: input.params.Provider,
|
|
71
|
+
});
|
|
72
|
+
const verdictError = AgentDataPolicyGuard.verdictToActionError(evalResult, input.params);
|
|
73
|
+
if (verdictError) {
|
|
74
|
+
return { Blocked: verdictError };
|
|
75
|
+
}
|
|
76
|
+
const rlsResolution = AgentDataPolicyGuard.resolveEffectiveWhereClause(evalResult, contextUser, input.params.Provider);
|
|
77
|
+
if ('Blocked' in rlsResolution) {
|
|
78
|
+
return rlsResolution;
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
Allowed: {
|
|
82
|
+
Active: true,
|
|
83
|
+
Policy: policy,
|
|
84
|
+
EvalResult: evalResult,
|
|
85
|
+
EffectiveWhereClause: rlsResolution.whereClause,
|
|
86
|
+
HasRecordConditionRules: AgentDataPolicyGuard.hasRecordConditionRulesForEntity(policy, input.entityInfo),
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Verifies that a specific primary-key record satisfies the agent policy's SQL row-level
|
|
92
|
+
* filter (`whereClause` / `rlsFilterIds`) via `RunView` before returning, updating, or deleting it.
|
|
93
|
+
*/
|
|
94
|
+
static async VerifyPrimaryKeyPassesWhereClause(input) {
|
|
95
|
+
const clause = input.effectiveWhereClause.trim();
|
|
96
|
+
if (!clause) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
const pairs = input.primaryKey instanceof CompositeKey
|
|
100
|
+
? input.primaryKey.KeyValuePairs
|
|
101
|
+
: Object.entries(input.primaryKey).map(([FieldName, Value]) => ({ FieldName, Value }));
|
|
102
|
+
const pkPredicates = [];
|
|
103
|
+
for (const kv of pairs) {
|
|
104
|
+
const fieldMeta = input.entityInfo.Fields.find((f) => f.Name.trim().toLowerCase() === kv.FieldName.trim().toLowerCase());
|
|
105
|
+
const colName = fieldMeta ? fieldMeta.Name : kv.FieldName;
|
|
106
|
+
if (kv.Value === null || kv.Value === undefined) {
|
|
107
|
+
pkPredicates.push(`[${colName}] IS NULL`);
|
|
108
|
+
}
|
|
109
|
+
else if (typeof kv.Value === 'number' && Number.isFinite(kv.Value)) {
|
|
110
|
+
pkPredicates.push(`[${colName}] = ${kv.Value}`);
|
|
111
|
+
}
|
|
112
|
+
else if (typeof kv.Value === 'boolean') {
|
|
113
|
+
pkPredicates.push(`[${colName}] = ${kv.Value ? 1 : 0}`);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
pkPredicates.push(`[${colName}] = '${EscapeSQLString(String(kv.Value))}'`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (pkPredicates.length === 0) {
|
|
120
|
+
return {
|
|
121
|
+
Success: false,
|
|
122
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
123
|
+
Message: `Agent policy row filter on "${input.entityInfo.Name}" could not verify primary key.`,
|
|
124
|
+
Params: input.params.Params,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
const combinedFilter = `(${pkPredicates.join(' AND ')}) AND (${clause})`;
|
|
128
|
+
const rv = input.params.Provider
|
|
129
|
+
? RunView.FromMetadataProvider(input.params.Provider)
|
|
130
|
+
: new RunView();
|
|
131
|
+
const checkResult = await rv.RunView({
|
|
132
|
+
EntityName: input.entityInfo.Name,
|
|
133
|
+
ExtraFilter: combinedFilter,
|
|
134
|
+
Fields: input.entityInfo.PrimaryKeys.map((pk) => pk.Name),
|
|
135
|
+
MaxRows: 1,
|
|
136
|
+
SkipTotalRowCount: true,
|
|
137
|
+
ResultType: 'simple',
|
|
138
|
+
}, input.params.ContextUser);
|
|
139
|
+
if (!checkResult.Success || !checkResult.Results || checkResult.Results.length === 0) {
|
|
140
|
+
return {
|
|
141
|
+
Success: false,
|
|
142
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
143
|
+
Message: `Record on entity "${input.entityInfo.Name}" is outside the calling agent's row-level policy scope.`,
|
|
144
|
+
Params: input.params.Params,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Verifies that an entity's pending in-memory field values satisfy the agent policy's SQL
|
|
151
|
+
* row-level filter (`effectiveWhereClause`) BEFORE `entity.Save()` commits (covering Create
|
|
152
|
+
* and post-mutation Update / WriteEntityFields without holding or deadlocking on DB locks).
|
|
153
|
+
*/
|
|
154
|
+
static async VerifyEntityStatePassesWhereClause(input) {
|
|
155
|
+
const clause = input.effectiveWhereClause.trim();
|
|
156
|
+
if (!clause) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
const contextUser = input.params.ContextUser;
|
|
160
|
+
if (!contextUser) {
|
|
161
|
+
return {
|
|
162
|
+
Success: false,
|
|
163
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
164
|
+
Message: `Agent policy row filter on "${input.entityInfo.Name}" requires an acting ContextUser.`,
|
|
165
|
+
Params: input.params.Params,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const candidateProvider = input.params.Provider ?? Metadata.Provider;
|
|
169
|
+
let passed = false;
|
|
170
|
+
try {
|
|
171
|
+
if (hasSyntheticRowWhereEvaluator(candidateProvider)) {
|
|
172
|
+
passed = await candidateProvider.EvaluateSyntheticRowWhereClause(input.entity, clause, contextUser, input.dirtyOnlyOptimization === true);
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
const dialect = ClientClauseScreen.DialectFor(candidateProvider);
|
|
176
|
+
// fls-guard: built as input.params.ContextUser and evaluated in-process against the agent row policy (never returned to caller)
|
|
177
|
+
const pendingState = input.entity.GetAll();
|
|
178
|
+
passed = ClientClauseScreen.EvaluateSimpleSqlWherePredicate(clause, pendingState, dialect);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
catch (err) {
|
|
182
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
183
|
+
return {
|
|
184
|
+
Success: false,
|
|
185
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
186
|
+
Message: `Record on entity "${input.entityInfo.Name}" could not be verified against the calling agent's row-level policy filter: ${msg}`,
|
|
187
|
+
Params: input.params.Params,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if (!passed) {
|
|
191
|
+
return {
|
|
192
|
+
Success: false,
|
|
193
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
194
|
+
Message: `Record state on entity "${input.entityInfo.Name}" violates the calling agent's row-level policy scope.`,
|
|
195
|
+
Params: input.params.Params,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Returns true when `fieldName` is read-denied for the caller (either by role FLS
|
|
202
|
+
* `entityInfo.GetDeniedReadFields(contextUser)` or by active agent policy `deniedFieldPatterns`).
|
|
203
|
+
*/
|
|
204
|
+
static IsFieldReadDeniedForCaller(input) {
|
|
205
|
+
const normalized = input.fieldName.trim();
|
|
206
|
+
if (!normalized)
|
|
207
|
+
return false;
|
|
208
|
+
if (input.entityInfo && input.contextUser && typeof input.entityInfo.GetDeniedReadFields === 'function') {
|
|
209
|
+
const roleDenied = input.entityInfo.GetDeniedReadFields(input.contextUser);
|
|
210
|
+
const targetLower = normalized.toLowerCase();
|
|
211
|
+
for (const f of roleDenied) {
|
|
212
|
+
if (f.trim().toLowerCase() === targetLower) {
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (input.deniedFieldPatterns && input.deniedFieldPatterns.length > 0) {
|
|
218
|
+
const probe = { [normalized]: 1 };
|
|
219
|
+
const masked = AgentUserPolicyEngine.Instance.MaskRecordFields(probe, input.deniedFieldPatterns);
|
|
220
|
+
if (!(normalized in masked)) {
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Screens `Filter`, `OrderBy`, and `AlternateBaseView` supplied to `Get Records` by an agent:
|
|
228
|
+
* 1. Refuses unbalanced parentheses (`1=1) OR (1=1`), statement separators, comments, and
|
|
229
|
+
* non-entity-view subqueries via {@link ClientClauseScreen.ScreenAgentClause}.
|
|
230
|
+
* 2. Enforces the agent's data-access policy on any subquery entity referenced in `Filter`/`OrderBy`.
|
|
231
|
+
* 3. Validates `AlternateBaseView` against usable `entityInfo.AlternateBaseViews`.
|
|
232
|
+
* 4. Refuses `Filter` or `OrderBy` tokens that reference fields denied by role FLS or agent
|
|
233
|
+
* policy `deniedFieldPatterns` (blocking predicate/sort inference oracles such as `SSN LIKE '1%'`).
|
|
234
|
+
*/
|
|
235
|
+
static ScreenGetRecordsClauses(input) {
|
|
236
|
+
const md = input.params.Provider ?? Metadata.Provider;
|
|
237
|
+
const entities = md?.Entities ?? [input.entityInfo];
|
|
238
|
+
const dialect = ClientClauseScreen.DialectFor(md);
|
|
239
|
+
const contextUser = input.params.ContextUser;
|
|
240
|
+
if (input.alternateBaseView?.trim()) {
|
|
241
|
+
const requestedView = ClientClauseScreen.StripIdentifierQuotes(input.alternateBaseView).trim().toLowerCase();
|
|
242
|
+
const canonicalView = ClientClauseScreen.StripIdentifierQuotes(input.entityInfo.BaseView).trim().toLowerCase();
|
|
243
|
+
const isRegistered = requestedView === canonicalView ||
|
|
244
|
+
(input.entityInfo.AlternateBaseViews ?? []).some((abv) => abv.IsUsable &&
|
|
245
|
+
ClientClauseScreen.StripIdentifierQuotes(abv.ViewName).trim().toLowerCase() === requestedView);
|
|
246
|
+
if (!isRegistered) {
|
|
247
|
+
return {
|
|
248
|
+
Success: false,
|
|
249
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
250
|
+
Message: `AlternateBaseView "${input.alternateBaseView}" is not a registered usable view on entity "${input.entityInfo.Name}".`,
|
|
251
|
+
Params: input.params.Params,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const subqueryEntities = new Map();
|
|
256
|
+
for (const [label, clause] of [
|
|
257
|
+
['Filter', input.filter],
|
|
258
|
+
['OrderBy', input.orderBy],
|
|
259
|
+
]) {
|
|
260
|
+
if (!clause?.trim())
|
|
261
|
+
continue;
|
|
262
|
+
try {
|
|
263
|
+
const refs = ClientClauseScreen.ScreenAgentClause(clause, label, entities, dialect, contextUser);
|
|
264
|
+
for (const ref of refs) {
|
|
265
|
+
subqueryEntities.set(ref.ID || ref.Name, ref);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
270
|
+
return {
|
|
271
|
+
Success: false,
|
|
272
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
273
|
+
Message: `Get Records ${label} rejected by agent data-policy guard: ${msg}`,
|
|
274
|
+
Params: input.params.Params,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const deniedPatterns = new Set(input.evalState.Active ? input.evalState.EvalResult.deniedFieldPatterns : []);
|
|
279
|
+
if (subqueryEntities.size > 0 && input.evalState.Active && contextUser) {
|
|
280
|
+
const subEval = AgentDataPolicyGuard.evaluateEntitiesForSqlRead(input.params, input.evalState.Policy, contextUser, Array.from(subqueryEntities.values()), 'Get Records subquery');
|
|
281
|
+
if ('Blocked' in subEval) {
|
|
282
|
+
return subEval.Blocked;
|
|
283
|
+
}
|
|
284
|
+
for (const pat of subEval.Allowed.DeniedFieldPatterns) {
|
|
285
|
+
deniedPatterns.add(pat);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const patternList = Array.from(deniedPatterns);
|
|
289
|
+
const hasRoleDeniedFields = [input.entityInfo, ...subqueryEntities.values()].some((ent) => Boolean(contextUser &&
|
|
290
|
+
typeof ent.GetDeniedReadFields === 'function' &&
|
|
291
|
+
ent.GetDeniedReadFields(contextUser).size > 0));
|
|
292
|
+
const hasAnyDeniedFields = patternList.length > 0 || hasRoleDeniedFields;
|
|
293
|
+
for (const [label, clause] of [
|
|
294
|
+
['Filter', input.filter],
|
|
295
|
+
['OrderBy', input.orderBy],
|
|
296
|
+
]) {
|
|
297
|
+
if (!clause?.trim())
|
|
298
|
+
continue;
|
|
299
|
+
if (hasAnyDeniedFields) {
|
|
300
|
+
try {
|
|
301
|
+
ClientClauseScreen.AssertNoWholeRowOrOrdinalInClause(clause, label, dialect);
|
|
302
|
+
}
|
|
303
|
+
catch (err) {
|
|
304
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
305
|
+
return {
|
|
306
|
+
Success: false,
|
|
307
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
308
|
+
Message: `Get Records ${label} rejected by agent field-masking guard: ${msg}`,
|
|
309
|
+
Params: input.params.Params,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const tokens = ClientClauseScreen.ExtractStatementIdentifierTokens(clause, dialect);
|
|
314
|
+
const offending = tokens.filter((tok) => AgentDataPolicyGuard.IsFieldReadDeniedForCaller({
|
|
315
|
+
fieldName: tok,
|
|
316
|
+
entityInfo: input.entityInfo,
|
|
317
|
+
contextUser,
|
|
318
|
+
deniedFieldPatterns: patternList,
|
|
319
|
+
}));
|
|
320
|
+
if (offending.length > 0) {
|
|
321
|
+
return {
|
|
322
|
+
Success: false,
|
|
323
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
324
|
+
Message: `Get Records ${label} references field(s) denied by field-level policy: ${offending.join(', ')}.`,
|
|
325
|
+
Params: input.params.Params,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Evaluates `rlsNarrowing.recordConditionExpression` on a loaded/post-mutation record when active rules exist,
|
|
333
|
+
* returning a deterministic denial/approval/deferral `ActionResultSimple` if blocked.
|
|
334
|
+
*/
|
|
335
|
+
static CheckRecordCondition(input) {
|
|
336
|
+
if (!input.params.ContextUser) {
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const evalResult = AgentUserPolicyEngine.Instance.EvaluateEntityAccess({
|
|
340
|
+
policy: input.policy,
|
|
341
|
+
contextUser: input.params.ContextUser,
|
|
342
|
+
entityName: input.entityInfo.Name,
|
|
343
|
+
operation: input.operation,
|
|
344
|
+
mutatedFields: input.mutatedFields,
|
|
345
|
+
record: AgentDataPolicyGuard.toScalarRecord(input.record),
|
|
346
|
+
provider: input.params.Provider,
|
|
347
|
+
});
|
|
348
|
+
return AgentDataPolicyGuard.verdictToActionError(evalResult, input.params);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Filters an array of `Get Records` rows through `EvaluateEntityAccess` when the policy carries
|
|
352
|
+
* `recordConditionExpression` rules, then masks denied fields on every surviving row.
|
|
353
|
+
*/
|
|
354
|
+
static FilterAndMaskRows(input) {
|
|
355
|
+
if (!input.evalState.Active) {
|
|
356
|
+
return input.rows;
|
|
357
|
+
}
|
|
358
|
+
const { Policy: policy, EvalResult: evalResult, HasRecordConditionRules: hasRecordConditionRules } = input.evalState;
|
|
359
|
+
let filtered = input.rows;
|
|
360
|
+
if (hasRecordConditionRules && input.entityInfo && input.contextUser) {
|
|
361
|
+
filtered = input.rows.filter((row) => {
|
|
362
|
+
const rowEval = AgentUserPolicyEngine.Instance.EvaluateEntityAccess({
|
|
363
|
+
policy,
|
|
364
|
+
contextUser: input.contextUser,
|
|
365
|
+
entityName: input.entityInfo.Name,
|
|
366
|
+
operation: 'Read',
|
|
367
|
+
record: AgentDataPolicyGuard.toScalarRecord(row),
|
|
368
|
+
provider: input.provider,
|
|
369
|
+
});
|
|
370
|
+
return rowEval.verdict === 'Allow';
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
return AgentDataPolicyGuard.MaskRows(filtered, evalResult.deniedFieldPatterns);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Masks denied fields on a single record using `AgentUserPolicyEngine.Instance.MaskRecordFields`
|
|
377
|
+
* while preserving non-scalar values (such as `Date` or nested objects) on allowed fields.
|
|
378
|
+
*/
|
|
379
|
+
static MaskRecord(record, deniedFieldPatterns) {
|
|
380
|
+
if (!deniedFieldPatterns || deniedFieldPatterns.length === 0) {
|
|
381
|
+
return record;
|
|
382
|
+
}
|
|
383
|
+
const probe = {};
|
|
384
|
+
for (const key of Object.keys(record)) {
|
|
385
|
+
probe[key] = 1;
|
|
386
|
+
}
|
|
387
|
+
const allowedKeys = AgentUserPolicyEngine.Instance.MaskRecordFields(probe, deniedFieldPatterns);
|
|
388
|
+
const masked = {};
|
|
389
|
+
for (const key of Object.keys(allowedKeys)) {
|
|
390
|
+
masked[key] = record[key];
|
|
391
|
+
}
|
|
392
|
+
return masked;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Masks denied fields across an array of result rows.
|
|
396
|
+
*/
|
|
397
|
+
static MaskRows(rows, deniedFieldPatterns) {
|
|
398
|
+
if (!deniedFieldPatterns || deniedFieldPatterns.length === 0 || rows.length === 0) {
|
|
399
|
+
return rows;
|
|
400
|
+
}
|
|
401
|
+
return rows.map((row) => AgentDataPolicyGuard.MaskRecord(row, deniedFieldPatterns));
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Enforces agent data-access narrowing for `Run Stored Query`.
|
|
405
|
+
*/
|
|
406
|
+
static async EvaluateStoredQuery(params, queryId, queryName, queryParameters) {
|
|
407
|
+
const callingAgentId = AgentDataPolicyGuard.GetCallingAgentID(params);
|
|
408
|
+
const contextUser = params.ContextUser;
|
|
409
|
+
if (!callingAgentId || !contextUser?.ID) {
|
|
410
|
+
return { Allowed: { Active: false, DeniedFieldPatterns: [] } };
|
|
411
|
+
}
|
|
412
|
+
const policyLookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(callingAgentId, contextUser.ID, contextUser, { provider: params.Provider });
|
|
413
|
+
if (policyLookup.status === 'error') {
|
|
414
|
+
return {
|
|
415
|
+
Blocked: {
|
|
416
|
+
Success: false,
|
|
417
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
418
|
+
Message: `Agent data-access policy lookup failed; refusing stored query (fail-closed): ${policyLookup.errorMessage}`,
|
|
419
|
+
Params: params.Params,
|
|
420
|
+
},
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
const policy = policyLookup.policy;
|
|
424
|
+
if (!policy) {
|
|
425
|
+
return { Allowed: { Active: false, DeniedFieldPatterns: [] } };
|
|
426
|
+
}
|
|
427
|
+
if (policy.Status === 'Disabled') {
|
|
428
|
+
return {
|
|
429
|
+
Blocked: {
|
|
430
|
+
Success: false,
|
|
431
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
432
|
+
Message: 'Agent user policy status is Disabled; stored query execution is denied.',
|
|
433
|
+
Params: params.Params,
|
|
434
|
+
},
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
const md = params.Provider ?? Metadata.Provider;
|
|
438
|
+
const queryInfo = AgentDataPolicyGuard.findStoredQueryInfo(md, queryId, queryName);
|
|
439
|
+
if (!queryInfo) {
|
|
440
|
+
if (AgentDataPolicyGuard.policyNarrowsEntityReads(policy)) {
|
|
441
|
+
return {
|
|
442
|
+
Blocked: {
|
|
443
|
+
Success: false,
|
|
444
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
445
|
+
Message: `Stored query "${queryName ?? queryId}" metadata could not be resolved to verify agent data-access policy.`,
|
|
446
|
+
Params: params.Params,
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
return { Allowed: { Active: true, DeniedFieldPatterns: [] } };
|
|
451
|
+
}
|
|
452
|
+
const dialect = ClientClauseScreen.DialectFor(md);
|
|
453
|
+
const renderedOutcome = AgentDataPolicyGuard.renderStoredQuerySql(md, queryInfo, contextUser, queryParameters);
|
|
454
|
+
if ('blockedMessage' in renderedOutcome) {
|
|
455
|
+
return {
|
|
456
|
+
Blocked: {
|
|
457
|
+
Success: false,
|
|
458
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
459
|
+
Message: renderedOutcome.blockedMessage,
|
|
460
|
+
Params: params.Params,
|
|
461
|
+
},
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const referencedEntities = AgentDataPolicyGuard.resolveStoredQueryEntities(md, queryInfo, renderedOutcome.renderedSql, AgentDataPolicyGuard.policyNarrowsEntityReads(policy));
|
|
465
|
+
if (referencedEntities === null) {
|
|
466
|
+
return {
|
|
467
|
+
Blocked: {
|
|
468
|
+
Success: false,
|
|
469
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
470
|
+
Message: `Stored query "${queryInfo.Name}" entity references could not be verified against the calling agent's data-access policy.`,
|
|
471
|
+
Params: params.Params,
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
if (referencedEntities.length === 0 && AgentDataPolicyGuard.policyNarrowsEntityReads(policy)) {
|
|
476
|
+
return {
|
|
477
|
+
Blocked: {
|
|
478
|
+
Success: false,
|
|
479
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
480
|
+
Message: `Stored query "${queryInfo.Name}" has no verifiable entity lineage and cannot be executed under a narrowed agent data-access policy.`,
|
|
481
|
+
Params: params.Params,
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
const entityCheck = AgentDataPolicyGuard.evaluateEntitiesForSqlRead(params, policy, contextUser, referencedEntities, `stored query "${queryInfo.Name}"`);
|
|
486
|
+
if ('Blocked' in entityCheck) {
|
|
487
|
+
return entityCheck;
|
|
488
|
+
}
|
|
489
|
+
const { DeniedFieldPatterns: deniedFieldPatterns } = entityCheck.Allowed;
|
|
490
|
+
if (deniedFieldPatterns.length > 0) {
|
|
491
|
+
if (!renderedOutcome.renderedSql) {
|
|
492
|
+
return {
|
|
493
|
+
Blocked: {
|
|
494
|
+
Success: false,
|
|
495
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
496
|
+
Message: `Stored query "${queryInfo.Name}" SQL is unavailable to verify field-level masking rules.`,
|
|
497
|
+
Params: params.Params,
|
|
498
|
+
},
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
try {
|
|
502
|
+
ClientClauseScreen.AssertNoPositionalColumnRenames(renderedOutcome.renderedSql, dialect, `stored query "${queryInfo.Name}"`);
|
|
503
|
+
}
|
|
504
|
+
catch (err) {
|
|
505
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
506
|
+
return {
|
|
507
|
+
Blocked: {
|
|
508
|
+
Success: false,
|
|
509
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
510
|
+
Message: `Stored query "${queryInfo.Name}" rejected by agent field-masking guard: ${msg}`,
|
|
511
|
+
Params: params.Params,
|
|
512
|
+
},
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
const unmaskable = ClientClauseScreen.FindUnmaskableStoredQueryDeniedFields(renderedOutcome.renderedSql, dialect, (identifier) => {
|
|
516
|
+
const probe = { [identifier]: 1 };
|
|
517
|
+
const masked = AgentUserPolicyEngine.Instance.MaskRecordFields(probe, deniedFieldPatterns);
|
|
518
|
+
return !(identifier in masked);
|
|
519
|
+
});
|
|
520
|
+
if (unmaskable.length > 0) {
|
|
521
|
+
return {
|
|
522
|
+
Blocked: {
|
|
523
|
+
Success: false,
|
|
524
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
525
|
+
Message: `Stored query "${queryInfo.Name}" aliases, aggregates, or filters on field(s) denied by the calling agent's policy (${unmaskable.join(', ')}), which output column masking cannot strip safely.`,
|
|
526
|
+
Params: params.Params,
|
|
527
|
+
},
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return entityCheck;
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Enforces agent data-access narrowing for `Run Ad-hoc Query`.
|
|
535
|
+
*/
|
|
536
|
+
static async EvaluateAdhocQuery(params, normalizedSql, readOnlyProvider) {
|
|
537
|
+
const callingAgentId = AgentDataPolicyGuard.GetCallingAgentID(params);
|
|
538
|
+
const contextUser = params.ContextUser;
|
|
539
|
+
if (!callingAgentId || !contextUser?.ID) {
|
|
540
|
+
return { Allowed: { Active: false, DeniedFieldPatterns: [] } };
|
|
541
|
+
}
|
|
542
|
+
const policyLookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(callingAgentId, contextUser.ID, contextUser, { provider: params.Provider });
|
|
543
|
+
if (policyLookup.status === 'error') {
|
|
544
|
+
return {
|
|
545
|
+
Blocked: {
|
|
546
|
+
Success: false,
|
|
547
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
548
|
+
Message: `Agent data-access policy lookup failed; refusing ad-hoc query (fail-closed): ${policyLookup.errorMessage}`,
|
|
549
|
+
Params: params.Params,
|
|
550
|
+
},
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
const policy = policyLookup.policy;
|
|
554
|
+
if (!policy) {
|
|
555
|
+
return { Allowed: { Active: false, DeniedFieldPatterns: [] } };
|
|
556
|
+
}
|
|
557
|
+
if (policy.Status === 'Disabled') {
|
|
558
|
+
return {
|
|
559
|
+
Blocked: {
|
|
560
|
+
Success: false,
|
|
561
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
562
|
+
Message: 'Agent user policy status is Disabled; ad-hoc query execution is denied.',
|
|
563
|
+
Params: params.Params,
|
|
564
|
+
},
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
const entities = readOnlyProvider.Entities?.length
|
|
568
|
+
? readOnlyProvider.Entities
|
|
569
|
+
: (params.Provider ?? Metadata.Provider)?.Entities ?? [];
|
|
570
|
+
const dialect = ClientClauseScreen.DialectFor(readOnlyProvider);
|
|
571
|
+
let renderedSql = normalizedSql;
|
|
572
|
+
try {
|
|
573
|
+
const rendered = RenderPipeline.Run(normalizedSql, {
|
|
574
|
+
Platform: readOnlyProvider.PlatformKey,
|
|
575
|
+
ContextUser: contextUser,
|
|
576
|
+
RequireReadStatement: true,
|
|
577
|
+
});
|
|
578
|
+
renderedSql = rendered.Trace.AfterTemplates;
|
|
579
|
+
}
|
|
580
|
+
catch (err) {
|
|
581
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
582
|
+
return {
|
|
583
|
+
Blocked: {
|
|
584
|
+
Success: false,
|
|
585
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
586
|
+
Message: `Ad-hoc SQL could not be rendered safely for agent data-policy verification: ${msg}`,
|
|
587
|
+
Params: params.Params,
|
|
588
|
+
},
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
let referencedEntities;
|
|
592
|
+
try {
|
|
593
|
+
referencedEntities = ClientClauseScreen.ResolveStatementEntities(renderedSql, entities, dialect, 'ad-hoc SQL');
|
|
594
|
+
}
|
|
595
|
+
catch (err) {
|
|
596
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
597
|
+
return {
|
|
598
|
+
Blocked: {
|
|
599
|
+
Success: false,
|
|
600
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
601
|
+
Message: `Ad-hoc SQL rejected by agent data-policy guard: ${msg}`,
|
|
602
|
+
Params: params.Params,
|
|
603
|
+
},
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
if (referencedEntities.length === 0 && policy.DefaultDataAccessMode === 'AllowListOnly') {
|
|
607
|
+
return {
|
|
608
|
+
Blocked: {
|
|
609
|
+
Success: false,
|
|
610
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
611
|
+
Message: 'Agent DefaultDataAccessMode is AllowListOnly; ad-hoc queries that do not reference an allow-listed entity are denied.',
|
|
612
|
+
Params: params.Params,
|
|
613
|
+
},
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
const entityCheck = AgentDataPolicyGuard.evaluateEntitiesForSqlRead(params, policy, contextUser, referencedEntities, 'ad-hoc SQL');
|
|
617
|
+
if ('Blocked' in entityCheck) {
|
|
618
|
+
return entityCheck;
|
|
619
|
+
}
|
|
620
|
+
const { DeniedFieldPatterns: deniedFieldPatterns } = entityCheck.Allowed;
|
|
621
|
+
if (deniedFieldPatterns.length > 0) {
|
|
622
|
+
try {
|
|
623
|
+
ClientClauseScreen.AssertNoPositionalColumnRenames(renderedSql, dialect, 'ad-hoc SQL');
|
|
624
|
+
}
|
|
625
|
+
catch (err) {
|
|
626
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
627
|
+
return {
|
|
628
|
+
Blocked: {
|
|
629
|
+
Success: false,
|
|
630
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
631
|
+
Message: `Ad-hoc SQL rejected by agent field-masking guard: ${msg}`,
|
|
632
|
+
Params: params.Params,
|
|
633
|
+
},
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
const sqlTokens = ClientClauseScreen.ExtractStatementIdentifierTokens(renderedSql, dialect);
|
|
637
|
+
const tokenProbe = {};
|
|
638
|
+
for (const token of sqlTokens) {
|
|
639
|
+
tokenProbe[token] = 1;
|
|
640
|
+
}
|
|
641
|
+
const survivingTokens = AgentUserPolicyEngine.Instance.MaskRecordFields(tokenProbe, deniedFieldPatterns);
|
|
642
|
+
const referencedDeniedTokens = sqlTokens.filter((token) => !(token in survivingTokens));
|
|
643
|
+
if (referencedDeniedTokens.length > 0) {
|
|
644
|
+
return {
|
|
645
|
+
Blocked: {
|
|
646
|
+
Success: false,
|
|
647
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
648
|
+
Message: `Ad-hoc SQL references field(s) denied by the calling agent's policy: ${referencedDeniedTokens.join(', ')}.`,
|
|
649
|
+
Params: params.Params,
|
|
650
|
+
},
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return entityCheck;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Combines an action's optional user `ExtraFilter` with the agent policy's effective SQL
|
|
658
|
+
* row-level filter (`whereClause` + resolved `rlsFilterIds`), asserting first that `existingFilter`
|
|
659
|
+
* has balanced parentheses and no statement separators or comments so `(${left}) AND (${right})`
|
|
660
|
+
* can never be broken out of via `1=1) OR (1=1`.
|
|
661
|
+
*/
|
|
662
|
+
static CombineExtraFilters(existingFilter, policyWhereClause, provider) {
|
|
663
|
+
const left = existingFilter?.trim() ?? '';
|
|
664
|
+
const right = policyWhereClause.trim();
|
|
665
|
+
if (left) {
|
|
666
|
+
const dialect = ClientClauseScreen.DialectFor(provider);
|
|
667
|
+
ClientClauseScreen.AssertBalancedSingleFragment(left, 'Filter', dialect);
|
|
668
|
+
}
|
|
669
|
+
if (left && right) {
|
|
670
|
+
return `(${left}) AND (${right})`;
|
|
671
|
+
}
|
|
672
|
+
if (right) {
|
|
673
|
+
return right;
|
|
674
|
+
}
|
|
675
|
+
return left || undefined;
|
|
676
|
+
}
|
|
677
|
+
static evaluateEntitiesForSqlRead(params, policy, contextUser, entities, queryLabel) {
|
|
678
|
+
const deniedPatterns = new Set();
|
|
679
|
+
for (const entity of entities) {
|
|
680
|
+
const evalResult = AgentUserPolicyEngine.Instance.EvaluateEntityAccess({
|
|
681
|
+
policy,
|
|
682
|
+
contextUser,
|
|
683
|
+
entityName: entity.Name,
|
|
684
|
+
operation: 'Read',
|
|
685
|
+
provider: params.Provider,
|
|
686
|
+
});
|
|
687
|
+
const verdictError = AgentDataPolicyGuard.verdictToActionError(evalResult, params);
|
|
688
|
+
if (verdictError) {
|
|
689
|
+
return { Blocked: verdictError };
|
|
690
|
+
}
|
|
691
|
+
const rlsResolution = AgentDataPolicyGuard.resolveEffectiveWhereClause(evalResult, contextUser, params.Provider);
|
|
692
|
+
if ('Blocked' in rlsResolution) {
|
|
693
|
+
return rlsResolution;
|
|
694
|
+
}
|
|
695
|
+
if (rlsResolution.whereClause.length > 0 ||
|
|
696
|
+
AgentDataPolicyGuard.hasRecordConditionRulesForEntity(policy, entity)) {
|
|
697
|
+
return {
|
|
698
|
+
Blocked: {
|
|
699
|
+
Success: false,
|
|
700
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
701
|
+
Message: `Cannot execute ${queryLabel}: calling agent policy narrows rows on entity "${entity.Name}", which raw/stored SQL cannot enforce. Read "${entity.Name}" with Get Records instead.`,
|
|
702
|
+
Params: params.Params,
|
|
703
|
+
},
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
for (const pattern of evalResult.deniedFieldPatterns) {
|
|
707
|
+
deniedPatterns.add(pattern);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return {
|
|
711
|
+
Allowed: {
|
|
712
|
+
Active: true,
|
|
713
|
+
DeniedFieldPatterns: Array.from(deniedPatterns),
|
|
714
|
+
},
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
static findStoredQueryInfo(md, queryId, queryName) {
|
|
718
|
+
const queries = md?.Queries ?? [];
|
|
719
|
+
if (queryId) {
|
|
720
|
+
const byId = queries.find((q) => UUIDsEqual(q.ID, queryId));
|
|
721
|
+
if (byId) {
|
|
722
|
+
return byId;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
if (queryName) {
|
|
726
|
+
const target = queryName.trim().toLowerCase();
|
|
727
|
+
return queries.find((q) => q.Name?.trim().toLowerCase() === target);
|
|
728
|
+
}
|
|
729
|
+
return undefined;
|
|
730
|
+
}
|
|
731
|
+
static renderStoredQuerySql(md, queryInfo, contextUser, queryParameters) {
|
|
732
|
+
const rawSql = queryInfo.SQL?.trim() ?? '';
|
|
733
|
+
if (!rawSql) {
|
|
734
|
+
return { renderedSql: null };
|
|
735
|
+
}
|
|
736
|
+
const platform = md && 'PlatformKey' in md && (md.PlatformKey === 'postgresql' || md.PlatformKey === 'sqlserver')
|
|
737
|
+
? md.PlatformKey
|
|
738
|
+
: 'sqlserver';
|
|
739
|
+
try {
|
|
740
|
+
const rendered = RenderPipeline.Run(rawSql, {
|
|
741
|
+
Platform: platform,
|
|
742
|
+
QueryID: queryInfo.ID,
|
|
743
|
+
QueryName: queryInfo.Name,
|
|
744
|
+
ContextUser: contextUser,
|
|
745
|
+
Parameters: queryParameters,
|
|
746
|
+
UsesTemplate: Boolean(queryInfo.UsesTemplate),
|
|
747
|
+
RequireReadStatement: true,
|
|
748
|
+
QueryInfo: {
|
|
749
|
+
SQL: rawSql,
|
|
750
|
+
UsesTemplate: Boolean(queryInfo.UsesTemplate),
|
|
751
|
+
Parameters: queryInfo.Parameters,
|
|
752
|
+
},
|
|
753
|
+
});
|
|
754
|
+
return { renderedSql: rendered.Trace.AfterTemplates };
|
|
755
|
+
}
|
|
756
|
+
catch (err) {
|
|
757
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
758
|
+
return {
|
|
759
|
+
blockedMessage: `Stored query "${queryInfo.Name}" SQL could not be rendered safely for agent data-policy verification: ${msg}`,
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
static resolveStoredQueryEntities(md, queryInfo, renderedSql, policyNarrowsReads) {
|
|
764
|
+
const entities = md?.Entities ?? [];
|
|
765
|
+
const entityById = IndexByUUID(entities);
|
|
766
|
+
const resolved = new Map();
|
|
767
|
+
for (const qe of queryInfo.Entities ?? []) {
|
|
768
|
+
const match = (qe.EntityID ? entityById.Get(qe.EntityID) : undefined) ??
|
|
769
|
+
(qe.Entity ? entities.find((e) => e.Name.trim().toLowerCase() === qe.Entity.trim().toLowerCase()) : undefined);
|
|
770
|
+
if (!match) {
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
resolved.set(match.ID || match.Name, match);
|
|
774
|
+
}
|
|
775
|
+
if (renderedSql && renderedSql.trim().length > 0) {
|
|
776
|
+
if (entities.length === 0 && policyNarrowsReads) {
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
if (entities.length > 0) {
|
|
780
|
+
try {
|
|
781
|
+
const dialect = ClientClauseScreen.DialectFor(md);
|
|
782
|
+
const parsedEntities = ClientClauseScreen.ResolveStatementEntities(renderedSql, entities, dialect, `stored query "${queryInfo.Name}"`);
|
|
783
|
+
for (const pe of parsedEntities) {
|
|
784
|
+
resolved.set(pe.ID || pe.Name, pe);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
catch {
|
|
788
|
+
return null;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
else if (policyNarrowsReads) {
|
|
793
|
+
// Do not trust QueryEntities metadata alone without verifiable SQL under a narrowed policy
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
return Array.from(resolved.values());
|
|
797
|
+
}
|
|
798
|
+
static policyNarrowsEntityReads(policy) {
|
|
799
|
+
if (policy.DefaultDataAccessMode === 'AllowListOnly') {
|
|
800
|
+
return true;
|
|
801
|
+
}
|
|
802
|
+
const rules = policy.EntityAccessRulesObject ?? [];
|
|
803
|
+
return rules.length > 0;
|
|
804
|
+
}
|
|
805
|
+
static resolveEffectiveWhereClause(evalResult, contextUser, provider) {
|
|
806
|
+
const clauses = [];
|
|
807
|
+
const inlineClause = evalResult.combinedRlsWhereClause?.trim() ?? '';
|
|
808
|
+
if (inlineClause.length > 0) {
|
|
809
|
+
clauses.push(inlineClause);
|
|
810
|
+
}
|
|
811
|
+
if (evalResult.rlsFilterIds.length > 0) {
|
|
812
|
+
const rlsCatalog = (provider ?? Metadata.Provider)?.RowLevelSecurityFilters ?? [];
|
|
813
|
+
const rlsById = IndexByUUID(rlsCatalog);
|
|
814
|
+
for (const filterId of evalResult.rlsFilterIds) {
|
|
815
|
+
const found = rlsById.Get(filterId);
|
|
816
|
+
if (!found || !found.FilterText?.trim()) {
|
|
817
|
+
return {
|
|
818
|
+
Blocked: {
|
|
819
|
+
Success: false,
|
|
820
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
821
|
+
Message: `Agent policy references Row Level Security Filter "${filterId}" which could not be resolved; failing closed.`,
|
|
822
|
+
},
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
const expanded = found.MarkupFilterText(contextUser).trim();
|
|
826
|
+
if (!expanded) {
|
|
827
|
+
return {
|
|
828
|
+
Blocked: {
|
|
829
|
+
Success: false,
|
|
830
|
+
ResultCode: 'PERMISSION_DENIED',
|
|
831
|
+
Message: `Agent policy Row Level Security Filter "${found.Name || filterId}" rendered an empty predicate; failing closed.`,
|
|
832
|
+
},
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
clauses.push(`(${expanded})`);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
return { whereClause: clauses.join(' AND ') };
|
|
839
|
+
}
|
|
840
|
+
static hasRecordConditionRulesForEntity(policy, entityInfo) {
|
|
841
|
+
const rules = policy.EntityAccessRulesObject ?? [];
|
|
842
|
+
const normalizedName = entityInfo.Name.trim().toLowerCase();
|
|
843
|
+
return rules.some((rule) => {
|
|
844
|
+
const cond = rule.rlsNarrowing?.recordConditionExpression;
|
|
845
|
+
if (!cond || cond.trim().length === 0) {
|
|
846
|
+
return false;
|
|
847
|
+
}
|
|
848
|
+
const pattern = rule.entityPattern?.trim().toLowerCase() ?? '';
|
|
849
|
+
return (pattern === '*' ||
|
|
850
|
+
pattern === normalizedName ||
|
|
851
|
+
(pattern.includes('*') &&
|
|
852
|
+
new RegExp('^' + pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$', 'i').test(entityInfo.Name)));
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
static verdictToActionError(evalResult, params) {
|
|
856
|
+
if (evalResult.verdict === 'Allow') {
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
const codeMap = {
|
|
860
|
+
Deny: 'PERMISSION_DENIED',
|
|
861
|
+
RequireApproval: 'APPROVAL_REQUIRED',
|
|
862
|
+
DeferUntilNextWindow: 'DEFERRED_OUTSIDE_WINDOW',
|
|
863
|
+
};
|
|
864
|
+
return {
|
|
865
|
+
Success: false,
|
|
866
|
+
ResultCode: codeMap[evalResult.verdict],
|
|
867
|
+
Message: evalResult.reason,
|
|
868
|
+
Params: params.Params,
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
static toScalarRecord(raw) {
|
|
872
|
+
const out = {};
|
|
873
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
874
|
+
if (v === null) {
|
|
875
|
+
out[k] = null;
|
|
876
|
+
}
|
|
877
|
+
else if (v === undefined) {
|
|
878
|
+
out[k] = undefined;
|
|
879
|
+
}
|
|
880
|
+
else if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
|
|
881
|
+
out[k] = v;
|
|
882
|
+
}
|
|
883
|
+
else if (v instanceof Date) {
|
|
884
|
+
out[k] = v.toISOString();
|
|
885
|
+
}
|
|
886
|
+
else {
|
|
887
|
+
try {
|
|
888
|
+
out[k] = JSON.stringify(v);
|
|
889
|
+
}
|
|
890
|
+
catch {
|
|
891
|
+
out[k] = String(v);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
return out;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
//# sourceMappingURL=agent-data-policy-guard.js.map
|