@highflame/policy 1.1.3

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/src/builder.ts ADDED
@@ -0,0 +1,478 @@
1
+ /**
2
+ * PolicyBuilder - Type-safe Cedar policy construction for Highflame.
3
+ *
4
+ * This builder ensures that policies created from the UI are always valid
5
+ * by construction. It uses the generated types from the Cedar schema to
6
+ * provide compile-time safety and autocomplete support.
7
+ *
8
+ * Example usage:
9
+ * ```typescript
10
+ * const policy = PolicyBuilder.permit()
11
+ * .principal(EntityType.User, "user-123")
12
+ * .action(ActionType.ReadFile)
13
+ * .resource(EntityType.FilePath, "/data/reports")
14
+ * .when("context.environment == \"production\"")
15
+ * .build();
16
+ *
17
+ * // Get Cedar policy text
18
+ * const cedarText = policy.toCedar();
19
+ *
20
+ * // Get JSON representation (for storage/editing)
21
+ * const policyJson = policy.toJSON();
22
+ * ```
23
+ */
24
+
25
+ import { EntityType, EntityUID } from './entities.gen.js';
26
+ import { ActionType } from './actions.gen.js';
27
+ import { ContextKey } from './context.gen.js';
28
+
29
+ /**
30
+ * Policy effect - permit or forbid
31
+ */
32
+ export type PolicyEffect = 'permit' | 'forbid';
33
+
34
+ /**
35
+ * Condition operator types
36
+ */
37
+ export type ConditionOperator =
38
+ | 'eq' // ==
39
+ | 'neq' // !=
40
+ | 'lt' // <
41
+ | 'lte' // <=
42
+ | 'gt' // >
43
+ | 'gte' // >=
44
+ | 'contains' // .contains()
45
+ | 'in' // in
46
+ | 'like'; // like
47
+
48
+ /**
49
+ * A single condition in a policy
50
+ */
51
+ export interface PolicyCondition {
52
+ /** The context key or attribute path */
53
+ field: string;
54
+ /** The comparison operator */
55
+ operator: ConditionOperator;
56
+ /** The value to compare against */
57
+ value: string | number | boolean | string[];
58
+ }
59
+
60
+ /**
61
+ * JSON representation of a policy for storage and editing
62
+ */
63
+ export interface PolicyJSON {
64
+ /** Unique identifier for this policy */
65
+ id?: string;
66
+ /** Human-readable name/description */
67
+ name?: string;
68
+ /** Policy effect */
69
+ effect: PolicyEffect;
70
+ /** Principal constraint */
71
+ principal: {
72
+ type: string;
73
+ id?: string;
74
+ } | null;
75
+ /** Action constraint */
76
+ action: string | string[];
77
+ /** Resource constraint */
78
+ resource: {
79
+ type: string;
80
+ id?: string;
81
+ } | null;
82
+ /** Conditions (when clause) */
83
+ conditions: PolicyCondition[];
84
+ /** Raw condition string (for advanced users) */
85
+ rawCondition?: string;
86
+ }
87
+
88
+ /**
89
+ * A built policy that can be converted to Cedar text or JSON
90
+ */
91
+ export class Policy {
92
+ constructor(private readonly data: PolicyJSON) {}
93
+
94
+ /**
95
+ * Convert to Cedar policy text
96
+ */
97
+ toCedar(): string {
98
+ const lines: string[] = [];
99
+
100
+ // Policy annotation (comment with name)
101
+ if (this.data.name) {
102
+ lines.push(`// @name: ${this.data.name}`);
103
+ }
104
+ if (this.data.id) {
105
+ lines.push(`// @id: ${this.data.id}`);
106
+ }
107
+
108
+ // Effect and principal
109
+ let policyLine = `${this.data.effect} (`;
110
+
111
+ // Principal
112
+ if (this.data.principal) {
113
+ if (this.data.principal.id) {
114
+ policyLine += `\n principal == ${this.data.principal.type}::\"${this.data.principal.id}\"`;
115
+ } else {
116
+ policyLine += `\n principal is ${this.data.principal.type}`;
117
+ }
118
+ } else {
119
+ policyLine += `\n principal`;
120
+ }
121
+
122
+ // Action
123
+ if (Array.isArray(this.data.action)) {
124
+ if (this.data.action.length === 1) {
125
+ policyLine += `,\n action == Action::\"${this.data.action[0]}\"`;
126
+ } else {
127
+ const actions = this.data.action.map(a => `Action::\"${a}\"`).join(', ');
128
+ policyLine += `,\n action in [${actions}]`;
129
+ }
130
+ } else {
131
+ policyLine += `,\n action == Action::\"${this.data.action}\"`;
132
+ }
133
+
134
+ // Resource
135
+ if (this.data.resource) {
136
+ if (this.data.resource.id) {
137
+ policyLine += `,\n resource == ${this.data.resource.type}::\"${this.data.resource.id}\"`;
138
+ } else {
139
+ policyLine += `,\n resource is ${this.data.resource.type}`;
140
+ }
141
+ } else {
142
+ policyLine += `,\n resource`;
143
+ }
144
+
145
+ policyLine += '\n)';
146
+ lines.push(policyLine);
147
+
148
+ // When clause
149
+ if (this.data.rawCondition) {
150
+ lines.push(`when { ${this.data.rawCondition} };`);
151
+ } else if (this.data.conditions.length > 0) {
152
+ const conditionStr = this.data.conditions
153
+ .map(c => this.conditionToCedar(c))
154
+ .join(' && ');
155
+ lines.push(`when { ${conditionStr} };`);
156
+ } else {
157
+ lines.push(';');
158
+ }
159
+
160
+ return lines.join('\n');
161
+ }
162
+
163
+ /**
164
+ * Convert a condition to Cedar syntax
165
+ */
166
+ private conditionToCedar(condition: PolicyCondition): string {
167
+ const { field, operator, value } = condition;
168
+ const valueStr = this.valueToString(value);
169
+
170
+ switch (operator) {
171
+ case 'eq':
172
+ return `context.${field} == ${valueStr}`;
173
+ case 'neq':
174
+ return `context.${field} != ${valueStr}`;
175
+ case 'lt':
176
+ return `context.${field} < ${valueStr}`;
177
+ case 'lte':
178
+ return `context.${field} <= ${valueStr}`;
179
+ case 'gt':
180
+ return `context.${field} > ${valueStr}`;
181
+ case 'gte':
182
+ return `context.${field} >= ${valueStr}`;
183
+ case 'contains':
184
+ return `context.${field}.contains(${valueStr})`;
185
+ case 'in':
186
+ if (Array.isArray(value)) {
187
+ const items = value.map(v => `\"${v}\"`).join(', ');
188
+ return `context.${field} in [${items}]`;
189
+ }
190
+ return `context.${field} in ${valueStr}`;
191
+ case 'like':
192
+ return `context.${field} like ${valueStr}`;
193
+ default:
194
+ return `context.${field} == ${valueStr}`;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Convert a value to Cedar string representation
200
+ */
201
+ private valueToString(value: string | number | boolean | string[]): string {
202
+ if (typeof value === 'string') {
203
+ return `\"${value}\"`;
204
+ }
205
+ if (typeof value === 'number' || typeof value === 'boolean') {
206
+ return String(value);
207
+ }
208
+ if (Array.isArray(value)) {
209
+ return `[${value.map(v => `\"${v}\"`).join(', ')}]`;
210
+ }
211
+ return String(value);
212
+ }
213
+
214
+ /**
215
+ * Get JSON representation for storage
216
+ */
217
+ toJSON(): PolicyJSON {
218
+ return { ...this.data };
219
+ }
220
+
221
+ /**
222
+ * Get the policy ID
223
+ */
224
+ getId(): string | undefined {
225
+ return this.data.id;
226
+ }
227
+
228
+ /**
229
+ * Get the policy name
230
+ */
231
+ getName(): string | undefined {
232
+ return this.data.name;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Builder for constructing Cedar policies with type safety.
238
+ */
239
+ export class PolicyBuilder {
240
+ private data: PolicyJSON = {
241
+ effect: 'permit',
242
+ principal: null,
243
+ action: '',
244
+ resource: null,
245
+ conditions: [],
246
+ };
247
+
248
+ private constructor(effect: PolicyEffect) {
249
+ this.data.effect = effect;
250
+ }
251
+
252
+ /**
253
+ * Start building a permit policy
254
+ */
255
+ static permit(): PolicyBuilder {
256
+ return new PolicyBuilder('permit');
257
+ }
258
+
259
+ /**
260
+ * Start building a forbid policy
261
+ */
262
+ static forbid(): PolicyBuilder {
263
+ return new PolicyBuilder('forbid');
264
+ }
265
+
266
+ /**
267
+ * Create a builder from existing JSON (for editing)
268
+ */
269
+ static fromJSON(json: PolicyJSON): PolicyBuilder {
270
+ const builder = new PolicyBuilder(json.effect);
271
+ builder.data = { ...json };
272
+ return builder;
273
+ }
274
+
275
+ /**
276
+ * Set policy ID
277
+ */
278
+ id(id: string): PolicyBuilder {
279
+ this.data.id = id;
280
+ return this;
281
+ }
282
+
283
+ /**
284
+ * Set policy name/description
285
+ */
286
+ name(name: string): PolicyBuilder {
287
+ this.data.name = name;
288
+ return this;
289
+ }
290
+
291
+ /**
292
+ * Set principal constraint by type only (any entity of this type)
293
+ */
294
+ principalType(type: EntityType | string): PolicyBuilder {
295
+ this.data.principal = { type };
296
+ return this;
297
+ }
298
+
299
+ /**
300
+ * Set principal constraint by type and ID (specific entity)
301
+ */
302
+ principal(type: EntityType | string, id: string): PolicyBuilder {
303
+ this.data.principal = { type, id };
304
+ return this;
305
+ }
306
+
307
+ /**
308
+ * Set principal from EntityUID
309
+ */
310
+ principalEntity(entity: EntityUID): PolicyBuilder {
311
+ this.data.principal = { type: entity.type, id: entity.id };
312
+ return this;
313
+ }
314
+
315
+ /**
316
+ * Set single action constraint
317
+ */
318
+ action(action: ActionType | string): PolicyBuilder {
319
+ this.data.action = action;
320
+ return this;
321
+ }
322
+
323
+ /**
324
+ * Set multiple action constraints (action in [list])
325
+ */
326
+ actions(actions: (ActionType | string)[]): PolicyBuilder {
327
+ this.data.action = actions;
328
+ return this;
329
+ }
330
+
331
+ /**
332
+ * Set resource constraint by type only (any entity of this type)
333
+ */
334
+ resourceType(type: EntityType | string): PolicyBuilder {
335
+ this.data.resource = { type };
336
+ return this;
337
+ }
338
+
339
+ /**
340
+ * Set resource constraint by type and ID (specific entity)
341
+ */
342
+ resource(type: EntityType | string, id: string): PolicyBuilder {
343
+ this.data.resource = { type, id };
344
+ return this;
345
+ }
346
+
347
+ /**
348
+ * Set resource from EntityUID
349
+ */
350
+ resourceEntity(entity: EntityUID): PolicyBuilder {
351
+ this.data.resource = { type: entity.type, id: entity.id };
352
+ return this;
353
+ }
354
+
355
+ /**
356
+ * Add a structured condition
357
+ */
358
+ when(field: ContextKey | string, operator: ConditionOperator, value: string | number | boolean | string[]): PolicyBuilder {
359
+ this.data.conditions.push({ field, operator, value });
360
+ return this;
361
+ }
362
+
363
+ /**
364
+ * Add a raw condition string (for advanced users)
365
+ */
366
+ whenRaw(condition: string): PolicyBuilder {
367
+ this.data.rawCondition = condition;
368
+ return this;
369
+ }
370
+
371
+ /**
372
+ * Clear all conditions
373
+ */
374
+ clearConditions(): PolicyBuilder {
375
+ this.data.conditions = [];
376
+ this.data.rawCondition = undefined;
377
+ return this;
378
+ }
379
+
380
+ /**
381
+ * Build the policy
382
+ */
383
+ build(): Policy {
384
+ // Validate required fields
385
+ if (!this.data.action || (Array.isArray(this.data.action) && this.data.action.length === 0)) {
386
+ throw new Error('Policy must have at least one action');
387
+ }
388
+
389
+ return new Policy({ ...this.data });
390
+ }
391
+
392
+ /**
393
+ * Get current state as JSON (for preview/debugging)
394
+ */
395
+ toJSON(): PolicyJSON {
396
+ return { ...this.data };
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Parse Cedar policy text back to PolicyJSON (best effort)
402
+ * Note: This is a simplified parser for policies created by PolicyBuilder.
403
+ * Complex hand-written policies may not parse correctly.
404
+ */
405
+ export function parseCedarPolicy(cedarText: string): PolicyJSON | null {
406
+ try {
407
+ const result: PolicyJSON = {
408
+ effect: 'permit',
409
+ principal: null,
410
+ action: '',
411
+ resource: null,
412
+ conditions: [],
413
+ };
414
+
415
+ // Extract name from annotation
416
+ const nameMatch = cedarText.match(/\/\/ @name: (.+)/);
417
+ if (nameMatch) {
418
+ result.name = nameMatch[1].trim();
419
+ }
420
+
421
+ // Extract id from annotation
422
+ const idMatch = cedarText.match(/\/\/ @id: (.+)/);
423
+ if (idMatch) {
424
+ result.id = idMatch[1].trim();
425
+ }
426
+
427
+ // Extract effect
428
+ if (cedarText.includes('forbid')) {
429
+ result.effect = 'forbid';
430
+ }
431
+
432
+ // Extract principal
433
+ const principalMatch = cedarText.match(/principal\s*==\s*(\w+)::"([^"]+)"/);
434
+ if (principalMatch) {
435
+ result.principal = { type: principalMatch[1], id: principalMatch[2] };
436
+ } else {
437
+ const principalTypeMatch = cedarText.match(/principal\s+is\s+(\w+)/);
438
+ if (principalTypeMatch) {
439
+ result.principal = { type: principalTypeMatch[1] };
440
+ }
441
+ }
442
+
443
+ // Extract action(s)
444
+ const actionMatch = cedarText.match(/action\s*==\s*Action::"([^"]+)"/);
445
+ if (actionMatch) {
446
+ result.action = actionMatch[1];
447
+ } else {
448
+ const actionsMatch = cedarText.match(/action\s+in\s+\[([^\]]+)\]/);
449
+ if (actionsMatch) {
450
+ const actions = actionsMatch[1].match(/Action::"([^"]+)"/g);
451
+ if (actions) {
452
+ result.action = actions.map(a => a.replace(/Action::"([^"]+)"/, '$1'));
453
+ }
454
+ }
455
+ }
456
+
457
+ // Extract resource
458
+ const resourceMatch = cedarText.match(/resource\s*==\s*(\w+)::"([^"]+)"/);
459
+ if (resourceMatch) {
460
+ result.resource = { type: resourceMatch[1], id: resourceMatch[2] };
461
+ } else {
462
+ const resourceTypeMatch = cedarText.match(/resource\s+is\s+(\w+)/);
463
+ if (resourceTypeMatch) {
464
+ result.resource = { type: resourceTypeMatch[1] };
465
+ }
466
+ }
467
+
468
+ // Extract when clause (as raw condition)
469
+ const whenMatch = cedarText.match(/when\s*\{([^}]+)\}/);
470
+ if (whenMatch) {
471
+ result.rawCondition = whenMatch[1].trim();
472
+ }
473
+
474
+ return result;
475
+ } catch {
476
+ return null;
477
+ }
478
+ }
@@ -0,0 +1,107 @@
1
+ // Code generated by highflame-policy-codegen. DO NOT EDIT.
2
+ // Source: schema/context.yaml
3
+
4
+ /**
5
+ * Context attribute keys for Cedar policy evaluation.
6
+ */
7
+ export const ContextKey = {
8
+ // Guardrails/Core context attributes
9
+ /** Name of tool being called */
10
+ ToolName: 'tool_name',
11
+ /** Name of resource being accessed */
12
+ ResourceName: 'resource_name',
13
+ /** Name of prompt */
14
+ PromptName: 'prompt_name',
15
+ /** Raw prompt text */
16
+ PromptText: 'prompt_text',
17
+ /** Response size in megabytes */
18
+ ResponseSizeMb: 'response_size_mb',
19
+ /** Set of detected YARA threat names */
20
+ YaraThreats: 'yara_threats',
21
+ /** Number of threats detected */
22
+ ThreatCount: 'threat_count',
23
+ /** Highest severity (0-4) */
24
+ MaxThreatSeverity: 'max_threat_severity',
25
+ /** User type: external or internal */
26
+ UserType: 'user_type',
27
+ /** Whether monitoring is active */
28
+ MonitoringEnabled: 'monitoring_enabled',
29
+ /** File path */
30
+ Path: 'path',
31
+ /** HTTP hostname */
32
+ Hostname: 'hostname',
33
+ /** IP address */
34
+ IpAddress: 'ip_address',
35
+ /** Whether the IP is private/loopback (set by application layer) */
36
+ IsPrivateIp: 'is_private_ip',
37
+ /** HTTP scheme */
38
+ Scheme: 'scheme',
39
+ /** Port number */
40
+ Port: 'port',
41
+
42
+ // Palisade context attributes
43
+ /** Environment: production, development, research */
44
+ Environment: 'environment',
45
+ /** Format: pickle, safetensors, gguf, onnx */
46
+ ArtifactFormat: 'artifact_format',
47
+ /** Whether artifact has signature */
48
+ ArtifactSigned: 'artifact_signed',
49
+ /** Severity: CRITICAL, HIGH, MEDIUM, LOW, INFO */
50
+ Severity: 'severity',
51
+ /** Type of security finding */
52
+ FindingType: 'finding_type',
53
+ /** Who signed the artifact */
54
+ ProvenanceSigner: 'provenance_signer',
55
+ /** RCE path found in pickle */
56
+ PickleExecPathDetected: 'pickle_exec_path_detected',
57
+ /** Malicious pattern in metadata */
58
+ MetadataMaliciousPattern: 'metadata_malicious_pattern',
59
+ /** Number of added tokens */
60
+ TokenizerAddedTokensCount: 'tokenizer_added_tokens_count',
61
+ /** Safetensors integrity failed */
62
+ SafetensorsIntegrityViolation: 'safetensors_integrity_violation',
63
+ /** Suspicious GGUF metadata */
64
+ GgufSuspiciousMetadata: 'gguf_suspicious_metadata',
65
+ /** LoRA adapter digest mismatch */
66
+ AdapterBaseDigestMismatch: 'adapter_base_digest_mismatch',
67
+ /** CoSAI maturity level (0-5) */
68
+ MetadataCosaiLevelNumeric: 'metadata_cosai_level_numeric',
69
+
70
+ // Overwatch context attributes
71
+ /** IDE source: cursor, claudecode, vscode, geminicli */
72
+ Source: 'source',
73
+ /** Hook event type: beforeShellExecution, PreToolUse, etc. */
74
+ Event: 'event',
75
+ /** The prompt/request content being evaluated */
76
+ Content: 'content',
77
+ /** User's email address (or 'anonymous') */
78
+ UserEmail: 'user_email',
79
+ /** Custom principal ID for policy evaluation */
80
+ CedarPrincipal: 'cedar_principal',
81
+ /** MCP server name: filesystem, playwright, etc. */
82
+ ServerName: 'server_name',
83
+ /** Whether the path is within the workspace */
84
+ IsWithinWorkspace: 'is_within_workspace',
85
+ /** Response content from tool execution */
86
+ ResponseContent: 'response_content',
87
+ /** Highest severity level: critical, high, medium, low */
88
+ HighestSeverity: 'highest_severity',
89
+ /** Array of threat types detected */
90
+ ThreatTypes: 'threat_types',
91
+ /** Array of threat categories found */
92
+ ThreatCategories: 'threat_categories',
93
+ /** Whether secrets were detected in the content */
94
+ ContainsSecrets: 'contains_secrets',
95
+ /** Number of concurrent calls */
96
+ ConcurrentCalls: 'concurrent_calls',
97
+ /** Request rate per minute */
98
+ RequestsPerMinute: 'requests_per_minute',
99
+ /** User trust level: high, medium, low */
100
+ UserTrustLevel: 'user_trust_level',
101
+ /** Whether alerting is enabled for this request */
102
+ AlertEnabled: 'alert_enabled',
103
+ /** Type of security scan being performed */
104
+ ScanType: 'scan_type',
105
+ } as const;
106
+
107
+ export type ContextKey = (typeof ContextKey)[keyof typeof ContextKey];