unbound-cli 1.20.5 → 1.21.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 CHANGED
@@ -219,6 +219,8 @@ Before creating any policy, run `unbound policy form-data` to see available user
219
219
 
220
220
  Keep policies in versioned YAML files and sync them to your org with `unbound pack`. One file is one **pack**: a named, versioned bundle of one or more policies of kind `tool`, `security`, `model` or `cost`. Every policy in a pack is marked on the server as managed by code, with the pack name and the policy `id` as its identity; its `name` is free text (it defaults to the id). The pack commands match, update and prune only by that identity, so policies made in the console are never read for diffing and never written, whatever they are called.
221
221
 
222
+ The bundled terminal command-family fields come from the backend's `aigateway/globals.py`. After a backend catalog change, run `npm run catalog:generate -- --backend ../ai-gateway-data`; `npm run catalog:check -- --backend ../ai-gateway-data` fails if the bundle has drifted.
223
+
222
224
  The console shows a **Managed by Code** badge on those policies and only lets people switch them on or off; every other change goes through the pack file. A policy switched off in the console shows up in `pack diff` as `enabled: false -> true (off on the server, on in the pack)`, and `pack apply` turns it back on (set `enabled: false` in the file to keep it off). `unbound pack adopt` brings a console policy into a pack without renaming it. Needs a backend that stores the code identity (ai-gateway-data 0448 or later).
223
225
 
224
226
  Docs: https://docs.getunbound.ai/policies/policy-as-code
@@ -316,6 +318,7 @@ Listing needs Admin, Manager or Analytics Viewer. `mark-fp` needs Admin.
316
318
  | `unbound flags data-security` | PII and secrets a guardrail found (values masked; `--reveal` shows them) |
317
319
  | `unbound flags data-security mark-fp <action-id>` | Mark a detection as a false positive |
318
320
  | `unbound trace <trace-id>` | The log, terminal runs and data security detections for one trace ID (prompts and values hidden; `--reveal` shows them) |
321
+ | `unbound false-positive list\|mark\|unmark <trace-id>` | Any user: show, mark or unmark a false positive on their own findings (alias `fp`; admins can act on any finding in their org) |
319
322
 
320
323
  ```bash
321
324
  unbound flags terminal --action block,warn --time-window SEVEN_DAYS
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unbound-cli",
3
- "version": "1.20.5",
3
+ "version": "1.21.0",
4
4
  "description": "CLI tool for Unbound - AI Gateway management",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -10,7 +10,9 @@
10
10
  "scripts": {
11
11
  "start": "node src/index.js",
12
12
  "lint": "eslint src/",
13
- "test": "node --test test/*.test.js"
13
+ "test": "node --test test/*.test.js",
14
+ "catalog:generate": "python3 scripts/generate-command-family-fields.py",
15
+ "catalog:check": "python3 scripts/generate-command-family-fields.py --check"
14
16
  },
15
17
  "keywords": [
16
18
  "unbound",
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env python3
2
+ """Generate the CLI command-family catalog from the backend's checked-in source."""
3
+
4
+ import argparse
5
+ import ast
6
+ import difflib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import sys
11
+
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ OUTPUT = ROOT / 'src/lib/command-family-fields.js'
15
+
16
+
17
+ def read_catalog(source):
18
+ tree = ast.parse(source.read_text(encoding='utf-8'), filename=str(source))
19
+ for statement in tree.body:
20
+ if isinstance(statement, ast.Assign) and any(
21
+ isinstance(target, ast.Name) and target.id == 'COMMAND_FAMILY_FIELDS'
22
+ for target in statement.targets
23
+ ):
24
+ catalog = ast.literal_eval(statement.value)
25
+ if not isinstance(catalog, dict) or not all(
26
+ isinstance(family, str) and isinstance(fields, list)
27
+ and all(isinstance(field, str) for field in fields)
28
+ for family, fields in catalog.items()
29
+ ):
30
+ raise ValueError('COMMAND_FAMILY_FIELDS must map family names to lists of field names')
31
+ return catalog
32
+ raise ValueError('COMMAND_FAMILY_FIELDS was not found in the backend source')
33
+
34
+
35
+ def render(catalog):
36
+ lines = [
37
+ '// Generated from ai-gateway-data/aigateway/globals.py.',
38
+ '// Run npm run catalog:generate -- --backend /path/to/ai-gateway-data to update.',
39
+ 'module.exports = {',
40
+ ]
41
+ families = sorted(catalog)
42
+ for index, family in enumerate(families):
43
+ lines.append(f' {json.dumps(family)}: [')
44
+ for field_index, field in enumerate(catalog[family]):
45
+ suffix = ',' if field_index < len(catalog[family]) - 1 else ''
46
+ lines.append(f' {json.dumps(field)}{suffix}')
47
+ suffix = ',' if index < len(families) - 1 else ''
48
+ lines.append(f' ]{suffix}')
49
+ lines.append('};')
50
+ return '\n'.join(lines) + '\n'
51
+
52
+
53
+ def main():
54
+ parser = argparse.ArgumentParser(description=__doc__)
55
+ parser.add_argument('--backend', type=Path, default=Path(os.environ.get(
56
+ 'AI_GATEWAY_DATA_DIR', ROOT.parent / 'ai-gateway-data')),
57
+ help='Backend repository root or aigateway/globals.py path')
58
+ parser.add_argument('--check', action='store_true', help='Fail if the generated catalog differs')
59
+ args = parser.parse_args()
60
+ source = args.backend if args.backend.is_file() else args.backend / 'aigateway/globals.py'
61
+ if not source.is_file():
62
+ parser.error(f'backend catalog not found at {source}; pass --backend or AI_GATEWAY_DATA_DIR')
63
+ try:
64
+ generated = render(read_catalog(source))
65
+ except (OSError, SyntaxError, ValueError) as exc:
66
+ parser.error(str(exc))
67
+
68
+ if args.check:
69
+ current = OUTPUT.read_text(encoding='utf-8') if OUTPUT.exists() else ''
70
+ if current != generated:
71
+ sys.stdout.writelines(difflib.unified_diff(
72
+ current.splitlines(keepends=True), generated.splitlines(keepends=True),
73
+ fromfile=str(OUTPUT), tofile=str(source),
74
+ ))
75
+ return 1
76
+ print('Command-family catalog matches the backend source.')
77
+ return 0
78
+
79
+ OUTPUT.write_text(generated, encoding='utf-8')
80
+ print(f'Generated {OUTPUT} from {source}')
81
+ return 0
82
+
83
+
84
+ if __name__ == '__main__':
85
+ raise SystemExit(main())
@@ -0,0 +1,130 @@
1
+ const api = require('../api');
2
+ const config = require('../config');
3
+ const output = require('../output');
4
+ const { confirm } = require('../utils');
5
+ const { resolveTraceId } = require('../lib/flags');
6
+
7
+ const PATH = '/api/v1/analytics/guardrails/my_false_positive/';
8
+ const HEADERS = ['ID', 'Type', 'Action', 'Status'];
9
+
10
+ function statusOf(finding) {
11
+ return finding.is_false_positive ? 'False positive' : 'Flagged';
12
+ }
13
+
14
+ // The one finding a mark or unmark acts on: the --finding id, or the only candidate on the trace.
15
+ function chooseFinding(findings, mark, findingId) {
16
+ if (findingId !== undefined) {
17
+ const id = Number(findingId);
18
+ const found = findings.find((f) => f.id === id);
19
+ if (!found) throw new Error(`Finding ${findingId} is not one of your findings on this trace.`);
20
+ return found;
21
+ }
22
+ const candidates = findings.filter((f) => (mark ? f.markable : f.unmarkable));
23
+ if (candidates.length === 0) {
24
+ throw new Error(mark ? 'Nothing on this trace is left to mark.' : 'No mark of yours on this trace can be unmarked.');
25
+ }
26
+ if (candidates.length > 1) {
27
+ throw new Error(`${candidates.length} findings match (IDs ${candidates.map((f) => f.id).join(', ')}). Pass --finding <id>.`);
28
+ }
29
+ return candidates[0];
30
+ }
31
+
32
+ async function fetchFindings(trace) {
33
+ const data = await api.get(`${PATH}?trace_id=${trace}`);
34
+ return data.findings || [];
35
+ }
36
+
37
+ async function run(fn) {
38
+ try {
39
+ if (!config.isLoggedIn()) throw new Error('Not logged in. Run `unbound login` first.');
40
+ await fn();
41
+ } catch (err) {
42
+ output.error(err.message);
43
+ process.exitCode = 1;
44
+ }
45
+ }
46
+
47
+ async function list(traceValue, opts) {
48
+ const trace = resolveTraceId(traceValue);
49
+ const findings = await fetchFindings(trace);
50
+ if (opts.json) {
51
+ output.json({ trace_id: trace, findings });
52
+ return;
53
+ }
54
+ if (findings.length === 0) {
55
+ output.info(`No findings of yours on trace ${trace}.`);
56
+ return;
57
+ }
58
+ output.logTable(HEADERS, findings.map((f) => [String(f.id), f.type, f.action, statusOf(f)]));
59
+ }
60
+
61
+ async function setMark(traceValue, opts, mark) {
62
+ const trace = resolveTraceId(traceValue);
63
+ const finding = chooseFinding(await fetchFindings(trace), mark, opts.finding);
64
+ const verb = mark ? 'Mark' : 'Unmark';
65
+ if (!opts.yes && !(await confirm(`${verb} ${finding.type} finding ${finding.id} on trace ${trace} as a false positive?`))) {
66
+ output.info('Cancelled.');
67
+ return;
68
+ }
69
+ const data = await api.post(PATH, {
70
+ body: { trace_id: trace, guardrail_action_id: finding.id, is_false_positive: mark },
71
+ });
72
+ if (opts.json) {
73
+ output.json(data);
74
+ return;
75
+ }
76
+ output.success(`${data.message}: ${finding.type} finding ${finding.id}.`);
77
+ }
78
+
79
+ function register(program) {
80
+ const fp = program
81
+ .command('false-positive')
82
+ .alias('fp')
83
+ .description('Mark or unmark a data security finding of yours as a false positive, by trace ID.');
84
+
85
+ fp
86
+ .command('list <trace-id>')
87
+ .description('Show your findings on a trace ID.')
88
+ .option('--json', 'Output JSON')
89
+ .addHelpText('after', `
90
+ The trace ID is the UUID shown under "Enforced by Unbound" on a blocked request.
91
+ Only findings on your own requests are listed. Detected values are never shown.
92
+
93
+ Examples:
94
+ $ unbound false-positive list 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c
95
+ `)
96
+ .action((trace, opts) => run(() => list(trace, opts)));
97
+
98
+ fp
99
+ .command('mark <trace-id>')
100
+ .description('Mark one of your findings on a trace ID as a false positive.')
101
+ .option('--finding <id>', 'Finding ID, when the trace has more than one (see "list")')
102
+ .option('-y, --yes', 'Skip the confirmation prompt')
103
+ .option('--json', 'Output the JSON response')
104
+ .addHelpText('after', `
105
+ You can only mark findings on your own requests. Admins can use this command on
106
+ any finding in their organization, or work by action ID with
107
+ \`unbound flags data-security mark-fp\`.
108
+
109
+ Examples:
110
+ $ unbound false-positive mark 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c
111
+ $ unbound false-positive mark 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c --finding 5521 --yes
112
+ `)
113
+ .action((trace, opts) => run(() => setMark(trace, opts, true)));
114
+
115
+ fp
116
+ .command('unmark <trace-id>')
117
+ .description('Unmark a false positive you marked.')
118
+ .option('--finding <id>', 'Finding ID, when the trace has more than one (see "list")')
119
+ .option('-y, --yes', 'Skip the confirmation prompt')
120
+ .option('--json', 'Output the JSON response')
121
+ .addHelpText('after', `
122
+ You can unmark only a mark you made. Admins can unmark any.
123
+
124
+ Examples:
125
+ $ unbound false-positive unmark 3f2a6c1e-8b7d-4e2f-9a1c-5d6e7f8a9b0c
126
+ `)
127
+ .action((trace, opts) => run(() => setMark(trace, opts, false)));
128
+ }
129
+
130
+ module.exports = { register, chooseFinding };
@@ -243,7 +243,8 @@ same value for everyone in your organization.
243
243
  Examples:
244
244
  $ unbound flags data-security mark-fp 5521
245
245
 
246
- Admin only.
246
+ Admin only. To mark a finding of your own without a role, use
247
+ \`unbound false-positive mark <trace-id>\`.
247
248
  `)
248
249
  .action((id, opts) => run(() => markDataSecurityFalsePositive(id, opts)));
249
250
 
package/src/index.js CHANGED
@@ -183,6 +183,11 @@ FLAGS AND FALSE POSITIVES (Admin/Analytics Viewer/Manager; mark-fp is Admin only
183
183
  Mark a detection as a false positive
184
184
  $ unbound trace <trace-id> Log, terminal runs and data security for one trace ID
185
185
 
186
+ FALSE POSITIVES ON YOUR OWN REQUESTS (any user)
187
+ $ unbound false-positive list <trace-id> Your findings on a blocked request
188
+ $ unbound false-positive mark <trace-id> Mark one as a false positive
189
+ $ unbound false-positive unmark <trace-id> Undo a mark you made
190
+
186
191
  CHAT (Admin/Analytics Viewer/Manager)
187
192
  $ unbound chat Interactive REPL (multi-turn, in-memory history)
188
193
  $ unbound chat -m "show cost by provider for the last 30 days"
@@ -228,6 +233,7 @@ require('./commands/tools').register(program);
228
233
  require('./commands/analytics').register(program);
229
234
  require('./commands/flags').register(program);
230
235
  require('./commands/trace').register(program);
236
+ require('./commands/false-positive').register(program);
231
237
  require('./commands/download').register(program);
232
238
  require('./commands/setup').register(program);
233
239
  require('./commands/discover').register(program);
@@ -0,0 +1,158 @@
1
+ // Generated from ai-gateway-data/aigateway/globals.py.
2
+ // Run npm run catalog:generate -- --backend /path/to/ai-gateway-data to update.
3
+ module.exports = {
4
+ "access_password": [
5
+ "target",
6
+ "credential_type",
7
+ "location"
8
+ ],
9
+ "build_operation": [
10
+ "target",
11
+ "environment",
12
+ "tool",
13
+ "package"
14
+ ],
15
+ "cloud_config": [
16
+ "provider",
17
+ "service",
18
+ "config_key",
19
+ "operation",
20
+ "environment"
21
+ ],
22
+ "cloud_destroy": [
23
+ "provider",
24
+ "service",
25
+ "operation",
26
+ "resource",
27
+ "environment"
28
+ ],
29
+ "cloud_iam": [
30
+ "provider",
31
+ "service",
32
+ "operation",
33
+ "principal",
34
+ "environment"
35
+ ],
36
+ "cloud_provision": [
37
+ "provider",
38
+ "service",
39
+ "operation",
40
+ "resource",
41
+ "environment"
42
+ ],
43
+ "cloud_read": [
44
+ "provider",
45
+ "service",
46
+ "query_type",
47
+ "resource",
48
+ "environment"
49
+ ],
50
+ "cloud_secrets": [
51
+ "provider",
52
+ "service",
53
+ "secret_name",
54
+ "operation",
55
+ "environment"
56
+ ],
57
+ "container_operation": [
58
+ "container",
59
+ "image",
60
+ "operation",
61
+ "resource",
62
+ "namespace",
63
+ "runtime"
64
+ ],
65
+ "data_transfer": [
66
+ "destination",
67
+ "protocol",
68
+ "operation"
69
+ ],
70
+ "database_admin": [
71
+ "database",
72
+ "table",
73
+ "operation",
74
+ "environment"
75
+ ],
76
+ "database_read": [
77
+ "database",
78
+ "table",
79
+ "query_type",
80
+ "environment"
81
+ ],
82
+ "database_write": [
83
+ "database",
84
+ "table",
85
+ "operation",
86
+ "environment"
87
+ ],
88
+ "delete_file": [
89
+ "path",
90
+ "operation"
91
+ ],
92
+ "environment_exposure": [
93
+ "method",
94
+ "variable_pattern",
95
+ "source"
96
+ ],
97
+ "environment_setup": [
98
+ "variable",
99
+ "value_pattern",
100
+ "scope",
101
+ "method"
102
+ ],
103
+ "execute_script": [
104
+ "script_path",
105
+ "interpreter",
106
+ "arguments"
107
+ ],
108
+ "git_action": [
109
+ "branch",
110
+ "remote",
111
+ "repo",
112
+ "operation"
113
+ ],
114
+ "package_management": [
115
+ "package",
116
+ "manager",
117
+ "operation"
118
+ ],
119
+ "privilege_escalation": [
120
+ "method",
121
+ "target_user",
122
+ "original_command"
123
+ ],
124
+ "process_management": [
125
+ "process",
126
+ "signal",
127
+ "pid",
128
+ "service",
129
+ "tool"
130
+ ],
131
+ "read_file": [
132
+ "path"
133
+ ],
134
+ "remote_access": [
135
+ "host",
136
+ "port",
137
+ "user",
138
+ "protocol"
139
+ ],
140
+ "remote_execution": [
141
+ "target_host",
142
+ "script_name",
143
+ "operation"
144
+ ],
145
+ "update_cron": [
146
+ "schedule",
147
+ "command",
148
+ "operation"
149
+ ],
150
+ "update_system_file": [
151
+ "path",
152
+ "operation"
153
+ ],
154
+ "write_file": [
155
+ "path",
156
+ "operation"
157
+ ]
158
+ };
@@ -0,0 +1,282 @@
1
+ const MODEL_NAME_RE = /^[A-Za-z0-9._@:*-]+$/;
2
+ const COMMAND_FAMILY_FIELDS = require('./command-family-fields');
3
+
4
+ const POLICY_CONFIG_FIELDS = {
5
+ SECURITY: ['sub_type', 'guardrails', 'default_routing_rules', 'error_routing_rules', 'command_policy_ids'],
6
+ MODEL: ['support_all_models', 'allowed_model_ids', 'excluded_model_ids', 'allowed_model_patterns', 'excluded_model_patterns', 'default_model_id'],
7
+ COST: ['monthly_budget', 'window_hours', 'spend_limit', 'meter', 'reset_style', 'alert_pct', 'enforcement_message'],
8
+ };
9
+
10
+ const SECURITY_SUB_TYPES = new Set(['guardrails', 'default_routing', 'error_code_routing', 'command_policy', 'mcp_policy']);
11
+ const GUARDRAIL_FIELDS = ['guardrail_id', 'enabled', 'action', 'threshold', 'route_model_id', 'priority', 'entities', 'config', 'enforcement_message'];
12
+ const QUANTIFIER_RE = /^(any|all|every|everything|anything|each|whole|entire)\b/i;
13
+ const PATTERN_STRUCTURE_RE = /[/\\*?\[\]^$|+{}]/;
14
+ const UNSAFE_REGEX_RE = [
15
+ /\(\?<[=!]/,
16
+ /\(\?[=!]/,
17
+ /\(\?>/,
18
+ /\\[1-9]/,
19
+ /\\k</,
20
+ /\\[AZ]/,
21
+ /\(\?P[<=]/,
22
+ /\(\?[aiLmsux]+[):]/,
23
+ /\[\[:/,
24
+ /\([^()]*[*+][^()]*\)[*+{]/,
25
+ /\([^()]*\|[^()]*\)[*+]/,
26
+ ];
27
+ const PYTHON_REGEX_ESCAPES = new Set('abfnrtvABdDsSwWZuxUN0');
28
+
29
+ function isObject(value) {
30
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
31
+ }
32
+
33
+ function fail(path, reason) {
34
+ throw new Error(`${path}: ${reason}`);
35
+ }
36
+
37
+ function isPositiveInteger(value) {
38
+ return Number.isInteger(value) && value > 0;
39
+ }
40
+
41
+ function rejectUnknownKeys(value, allowed, kind, path, file) {
42
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key)).sort();
43
+ if (unknown.length) fail(`${path}.${unknown[0]}`, `unknown key for ${kind} policy`);
44
+ }
45
+
46
+ function hasInvalidPythonRegexEscape(pattern) {
47
+ for (let index = 0; index < pattern.length; index += 1) {
48
+ if (pattern[index] !== '\\') continue;
49
+ index += 1;
50
+ if (index >= pattern.length) return true;
51
+ const escaped = pattern[index];
52
+ if (/[A-Za-z]/.test(escaped) && !PYTHON_REGEX_ESCAPES.has(escaped)) return true;
53
+ const width = escaped === 'x' ? 2 : escaped === 'u' ? 4 : escaped === 'U' ? 8 : 0;
54
+ if (width) {
55
+ const hex = pattern.slice(index + 1, index + 1 + width);
56
+ if (hex.length !== width || !/^[0-9A-Fa-f]+$/.test(hex)) return true;
57
+ index += width;
58
+ } else if (escaped === 'N') {
59
+ const name = /^\{[^{}]+\}/.exec(pattern.slice(index + 1));
60
+ if (!name) return true;
61
+ index += name[0].length;
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+
67
+ function validateSecurityConfig(config, file) {
68
+ const kind = 'SECURITY';
69
+ rejectUnknownKeys(config, POLICY_CONFIG_FIELDS[kind], kind, 'config');
70
+
71
+ const subType = config.sub_type === undefined ? 'guardrails' : config.sub_type;
72
+ if (!SECURITY_SUB_TYPES.has(subType)) {
73
+ fail('config.sub_type', `must be one of: ${[...SECURITY_SUB_TYPES].sort().join(', ')}`);
74
+ }
75
+
76
+ if (config.guardrails != null) {
77
+ if (!Array.isArray(config.guardrails)) fail('config.guardrails', 'must be a list');
78
+ config.guardrails.forEach((item, index) => {
79
+ const path = `config.guardrails[${index}]`;
80
+ if (!isObject(item)) fail(path, 'must be an object');
81
+ rejectUnknownKeys(item, GUARDRAIL_FIELDS, kind, path);
82
+ if (item.guardrail_id != null && !isPositiveInteger(item.guardrail_id)) {
83
+ fail(`${path}.guardrail_id`, 'must be a positive integer ID');
84
+ }
85
+ if (item.enabled != null && typeof item.enabled !== 'boolean') {
86
+ fail(`${path}.enabled`, 'must be a boolean');
87
+ }
88
+ if (item.action != null && !['AUDIT', 'BLOCK', 'REDACT', 'ROUTE'].includes(item.action)) {
89
+ fail(`${path}.action`, 'must be one of: AUDIT, BLOCK, REDACT, ROUTE');
90
+ }
91
+ if (item.threshold != null && (!Number.isInteger(item.threshold) || item.threshold < 1 || item.threshold > 100)) {
92
+ fail(`${path}.threshold`, 'must be an integer from 1 to 100');
93
+ }
94
+ if (item.route_model_id !== undefined && item.route_model_id !== null && item.route_model_id !== '' && !isPositiveInteger(item.route_model_id)) {
95
+ fail(`${path}.route_model_id`, 'must be a positive integer ID');
96
+ }
97
+ if (item.action === 'ROUTE' && !item.route_model_id) {
98
+ fail(`${path}.route_model_id`, 'is required when action is ROUTE');
99
+ }
100
+ if (item.priority != null && !Number.isInteger(item.priority)) {
101
+ fail(`${path}.priority`, 'must be an integer');
102
+ }
103
+ if (item.entities != null) {
104
+ if (!Array.isArray(item.entities)) fail(`${path}.entities`, 'must be a list');
105
+ item.entities.forEach((entity, entityIndex) => {
106
+ const entityPath = `${path}.entities[${entityIndex}]`;
107
+ if (!isObject(entity)) fail(entityPath, 'must be an object');
108
+ rejectUnknownKeys(entity, ['entity_id', 'enabled'], kind, entityPath);
109
+ if (!isPositiveInteger(entity.entity_id)) fail(`${entityPath}.entity_id`, 'must be a positive integer ID');
110
+ if (typeof entity.enabled !== 'boolean') fail(`${entityPath}.enabled`, 'must be a boolean');
111
+ });
112
+ }
113
+ if (item.config != null && !isObject(item.config)) fail(`${path}.config`, 'must be an object');
114
+ if (item.enforcement_message != null && typeof item.enforcement_message !== 'string') {
115
+ fail(`${path}.enforcement_message`, 'must be a string');
116
+ }
117
+ });
118
+ }
119
+
120
+ if (config.default_routing_rules != null) {
121
+ if (!Array.isArray(config.default_routing_rules)) fail('config.default_routing_rules', 'must be a list');
122
+ config.default_routing_rules.forEach((rule, index) => {
123
+ const path = `config.default_routing_rules[${index}]`;
124
+ if (!isObject(rule)) fail(path, 'must be an object');
125
+ rejectUnknownKeys(rule, ['source_model_id', 'destination_model_id'], kind, path);
126
+ for (const field of ['source_model_id', 'destination_model_id']) {
127
+ if (!isPositiveInteger(rule[field])) fail(`${path}.${field}`, 'must be a positive integer ID');
128
+ }
129
+ });
130
+ }
131
+
132
+ if (config.error_routing_rules != null) {
133
+ if (!Array.isArray(config.error_routing_rules)) fail('config.error_routing_rules', 'must be a list');
134
+ config.error_routing_rules.forEach((rule, index) => {
135
+ const path = `config.error_routing_rules[${index}]`;
136
+ if (!isObject(rule)) fail(path, 'must be an object');
137
+ rejectUnknownKeys(rule, ['error_code', 'source_model_id', 'target_model_id'], kind, path);
138
+ if (typeof rule.error_code !== 'string' || !rule.error_code.trim()) {
139
+ fail(`${path}.error_code`, 'must be a non-empty string');
140
+ }
141
+ for (const field of ['source_model_id', 'target_model_id']) {
142
+ if (!isPositiveInteger(rule[field])) fail(`${path}.${field}`, 'must be a positive integer ID');
143
+ }
144
+ });
145
+ }
146
+
147
+ if (config.command_policy_ids != null && (
148
+ !Array.isArray(config.command_policy_ids) || !config.command_policy_ids.every(isPositiveInteger)
149
+ )) {
150
+ fail('config.command_policy_ids', 'must be a list of positive integer IDs');
151
+ }
152
+ }
153
+
154
+ function validateToolConfig(config, commandFamily) {
155
+ if (!isObject(config)) fail('config', 'must be a JSON object');
156
+ if (!commandFamily || (commandFamily !== 'custom' && !COMMAND_FAMILY_FIELDS[commandFamily])) {
157
+ fail('commandFamily', 'unknown command family');
158
+ }
159
+ if (!Object.keys(config).length) fail('config', 'must be a non-empty object');
160
+ if (commandFamily === 'custom') {
161
+ const keys = Object.keys(config).sort();
162
+ if (keys.some((key) => key !== 'command')) {
163
+ fail(`config.${keys.find((key) => key !== 'command')}`, "unknown field for command family 'custom'");
164
+ }
165
+ } else {
166
+ const allowed = new Set(COMMAND_FAMILY_FIELDS[commandFamily]);
167
+ const unknown = Object.keys(config).filter((key) => key !== 'ANY' && !allowed.has(key)).sort();
168
+ if (unknown.length) fail(`config.${unknown[0]}`, `unknown field for command family '${commandFamily}'`);
169
+ }
170
+ const nullField = Object.keys(config).sort().find((field) => config[field] === null);
171
+ if (nullField) fail(`config.${nullField}`, 'must have a non-null value');
172
+ if (Object.entries(config).some(([key, value]) => value !== null && (typeof value !== 'string' || !value.trim()))) {
173
+ const [key] = Object.entries(config).find(([, value]) => value !== null && (typeof value !== 'string' || !value.trim()));
174
+ fail(`config.${key}`, 'must be a string pattern');
175
+ }
176
+ if (config.ANY !== undefined && Object.keys(config).length > 1) {
177
+ throw new Error("The 'ANY' field cannot be combined with other match conditions");
178
+ }
179
+ if (commandFamily === 'custom') {
180
+ const value = config.command.trim();
181
+ const prefix = ['regex:', 'glob:', 'exact:'].find((candidate) => value.startsWith(candidate));
182
+ const body = prefix ? value.slice(prefix.length) : value;
183
+ const regex = prefix ? prefix === 'regex:'
184
+ : ((body.startsWith('.') && ['*', '+', '?'].includes(body[1]))
185
+ || /[\\^$]|\(\?|\[|\||\+|\{/.test(body));
186
+ if (regex) {
187
+ if (!body || UNSAFE_REGEX_RE.some((detector) => detector.test(body)) || hasInvalidPythonRegexEscape(body)) {
188
+ fail('config.command', 'invalid pattern');
189
+ }
190
+ try {
191
+ new RegExp(body, 'i');
192
+ } catch {
193
+ fail('config.command', 'invalid pattern');
194
+ }
195
+ }
196
+ return;
197
+ }
198
+
199
+ for (const [field, value] of Object.entries(config)) {
200
+ if (value === null) continue;
201
+ const trimmed = value.trim();
202
+ if (!/\s/.test(trimmed)) continue;
203
+ if (PATTERN_STRUCTURE_RE.test(trimmed)) continue;
204
+ if (QUANTIFIER_RE.test(trimmed)) {
205
+ config[field] = '*';
206
+ } else {
207
+ fail(`config.${field}`, 'must be a concrete pattern or quantifier');
208
+ }
209
+ }
210
+ }
211
+
212
+ function validateConfig(kind, config, { commandFamily } = {}) {
213
+ const policyKind = String(kind || '').toUpperCase();
214
+ if (!isObject(config)) fail('config', 'must be a JSON object');
215
+ if (policyKind === 'TOOL') return validateToolConfig(config, commandFamily);
216
+ const allowed = POLICY_CONFIG_FIELDS[policyKind];
217
+ if (!allowed) fail('config', `unsupported policy kind ${policyKind}`);
218
+ rejectUnknownKeys(config, allowed, policyKind, 'config');
219
+
220
+ if (policyKind === 'COST') {
221
+ for (const field of ['monthly_budget', 'window_hours', 'spend_limit']) {
222
+ const value = config[field];
223
+ if (field === 'monthly_budget' && value !== undefined && value !== null && (
224
+ typeof value !== 'number' || !Number.isFinite(value) || value < 0
225
+ )) fail('config.monthly_budget', 'must be a non-negative number');
226
+ }
227
+ const windowHours = config.window_hours;
228
+ const spendLimit = config.spend_limit;
229
+ const hasWindowHours = windowHours !== undefined && windowHours !== null;
230
+ const hasSpendLimit = spendLimit !== undefined && spendLimit !== null;
231
+ if (hasWindowHours !== hasSpendLimit) {
232
+ fail('config.window_hours', 'must be provided together with config.spend_limit');
233
+ }
234
+ if (hasWindowHours && (typeof windowHours !== 'number' || !Number.isFinite(windowHours) || windowHours <= 0)) {
235
+ fail('config.window_hours', 'must be a number greater than 0');
236
+ }
237
+ if (hasWindowHours && windowHours > 720) {
238
+ fail('config.window_hours', 'must be at most 720 (30 days)');
239
+ }
240
+ if (hasWindowHours && (typeof spendLimit !== 'number' || !Number.isFinite(spendLimit) || spendLimit <= 0)) {
241
+ fail('config.spend_limit', 'must be a number greater than 0');
242
+ }
243
+ if (config.meter !== undefined && config.meter !== null && config.meter !== 'cost') {
244
+ fail('config.meter', "must be 'cost' ('requests' and 'tokens' are reserved for future use)");
245
+ }
246
+ if (config.reset_style !== undefined && config.reset_style !== null && config.reset_style !== 'per_user_rolling') {
247
+ fail('config.reset_style', "must be 'per_user_rolling'");
248
+ }
249
+ if (config.alert_pct !== undefined && config.alert_pct !== null && (
250
+ typeof config.alert_pct !== 'number' || !Number.isFinite(config.alert_pct)
251
+ || config.alert_pct <= 0 || config.alert_pct > 1
252
+ )) fail('config.alert_pct', 'must be greater than 0 and at most 1 (default 0.8)');
253
+ if (config.enforcement_message !== undefined && config.enforcement_message !== null && (
254
+ typeof config.enforcement_message !== 'string' || config.enforcement_message.length > 500
255
+ )) {
256
+ fail('config.enforcement_message', 'must be a string of at most 500 characters');
257
+ }
258
+ } else if (policyKind === 'MODEL') {
259
+ if (config.default_model_id !== undefined && config.default_model_id !== null && !isPositiveInteger(config.default_model_id)) {
260
+ fail('config.default_model_id', 'must be a positive integer ID');
261
+ }
262
+ if (Object.hasOwn(config, 'support_all_models') && typeof config.support_all_models !== 'boolean') {
263
+ fail('config.support_all_models', 'must be a boolean');
264
+ }
265
+ for (const field of ['allowed_model_ids', 'excluded_model_ids']) {
266
+ const values = config[field];
267
+ if (Object.hasOwn(config, field) && (!Array.isArray(values) || !values.every(isPositiveInteger))) {
268
+ fail(`config.${field}`, 'must be a list of positive integer IDs');
269
+ }
270
+ }
271
+ for (const field of ['allowed_model_patterns', 'excluded_model_patterns']) {
272
+ const patterns = config[field] === undefined ? [] : config[field];
273
+ if (!Array.isArray(patterns) || !patterns.every((value) => typeof value === 'string' && MODEL_NAME_RE.test(value))) {
274
+ fail(`config.${field}`, 'must be a list of model names using letters, numbers, . _ @ : - and *');
275
+ }
276
+ }
277
+ } else if (policyKind === 'SECURITY') {
278
+ validateSecurityConfig(config);
279
+ }
280
+ }
281
+
282
+ module.exports = { POLICY_CONFIG_FIELDS, validateConfig };
@@ -8,11 +8,11 @@
8
8
  // everything in this module is pure: no network, no ids, just names.
9
9
  //
10
10
  // Validation is strict on purpose. A typo must never silently become an
11
- // unmanaged field, so unknown keys fail at every level. `config` is the one
12
- // exception: it is passed to the server verbatim and never inspected here.
11
+ // unmanaged field, so unknown keys fail at every level.
13
12
 
14
13
  const path = require('path');
15
14
  const YAML = require('yaml');
15
+ const { validateConfig } = require('./pack-config-schema');
16
16
 
17
17
  const API_VERSION = 'unbound.security/v1';
18
18
  const KIND = 'PolicyPack';
@@ -173,10 +173,16 @@ function validateToolPolicy(p, where, file) {
173
173
  if ((p.action === 'BLOCK' || p.action === 'WARN') && typeof p.customMessage !== 'string') {
174
174
  throw new PackError(`${where}.customMessage is required when action is BLOCK or WARN (an empty string is allowed)`, { file });
175
175
  }
176
- if (p.config !== undefined && !isPlainObject(p.config)) throw new PackError(`${where}.config must be an object`, { file });
176
+ if (p.config !== undefined && !isPlainObject(p.config)) {
177
+ throw new PackError(`${where}.config must be an object`, { file });
178
+ }
177
179
  if (p.type === 'TERMINAL_COMMAND') {
178
- if (typeof p.commandFamily !== 'string' || p.commandFamily.trim() === '') throw new PackError(`${where}.commandFamily is required for TERMINAL_COMMAND policies`, { file });
179
- if (!p.config || Object.keys(p.config).length === 0) throw new PackError(`${where}.config is required for TERMINAL_COMMAND policies (field -> pattern)`, { file });
180
+ if (typeof p.commandFamily !== 'string' || p.commandFamily.trim() === '') throw new PackError(`${where}.commandFamily is required`, { file });
181
+ try {
182
+ validateConfig('tool', p.config === undefined ? {} : p.config, { commandFamily: p.commandFamily });
183
+ } catch (err) {
184
+ throw new PackError(`${where}: ${err.message}`, { file });
185
+ }
180
186
  if (p.mcp !== undefined) throw new PackError(`${where}.mcp applies to MCP_TOOL policies only`, { file });
181
187
  } else {
182
188
  if (p.commandFamily !== undefined) throw new PackError(`${where}.commandFamily applies to TERMINAL_COMMAND policies only`, { file });
@@ -244,6 +250,12 @@ function validateGenericPolicy(p, where, file) {
244
250
  } else if (p.kind === 'cost') {
245
251
  if (!p.config || Object.keys(p.config).length === 0) throw new PackError(`${where}: a cost policy needs a config (for example monthly_budget)`, { file });
246
252
  }
253
+
254
+ try {
255
+ validateConfig(p.kind, p.config === undefined ? {} : p.config);
256
+ } catch (err) {
257
+ throw new PackError(`${where}: ${err.message}`, { file });
258
+ }
247
259
  }
248
260
 
249
261
  /**
@@ -0,0 +1,116 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const http = require('http');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { spawn } = require('child_process');
8
+
9
+ const { chooseFinding } = require('../src/commands/false-positive');
10
+
11
+ const TRACE = '225c6413-26e4-4cd2-85a6-8c5ccfc3c5ef';
12
+ const PATH = '/api/v1/analytics/guardrails/my_false_positive/';
13
+ const flagged = { id: 11, type: 'API Key', action: 'BLOCK', is_false_positive: false, markable: true, unmarkable: false };
14
+ const marked = { id: 12, type: 'PII', action: 'AUDIT', is_false_positive: true, markable: false, unmarkable: true };
15
+
16
+ test('mark picks the only unmarked finding and unmark the only marked one', () => {
17
+ assert.equal(chooseFinding([flagged, marked], true).id, 11);
18
+ assert.equal(chooseFinding([flagged, marked], false).id, 12);
19
+ });
20
+
21
+ test('--finding picks that finding and refuses one that is not on the list', () => {
22
+ assert.equal(chooseFinding([flagged, marked], true, '12').id, 12);
23
+ assert.throws(() => chooseFinding([flagged], true, '99'), /not one of your findings/);
24
+ });
25
+
26
+ test('several candidates need --finding, and none is an error', () => {
27
+ const other = { ...flagged, id: 13 };
28
+ assert.throws(() => chooseFinding([flagged, other], true), /Pass --finding/);
29
+ assert.throws(() => chooseFinding([marked], true), /left to mark/);
30
+ assert.throws(() => chooseFinding([flagged], false), /can be unmarked/);
31
+ });
32
+
33
+ function startServer(routes) {
34
+ const seen = [];
35
+ const server = http.createServer((req, res) => {
36
+ let body = '';
37
+ req.on('data', (c) => { body += c; });
38
+ req.on('end', () => {
39
+ const url = new URL(req.url, 'http://x');
40
+ seen.push({ method: req.method, path: url.pathname, query: url.searchParams, body: body ? JSON.parse(body) : null });
41
+ const [status, payload] = routes(req.method) || [404, { error: 'no route' }];
42
+ res.writeHead(status, { 'Content-Type': 'application/json' });
43
+ res.end(JSON.stringify(payload));
44
+ });
45
+ });
46
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve({ server, seen, port: server.address().port })));
47
+ }
48
+
49
+ function runCli(port, args) {
50
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'fp-test-'));
51
+ fs.mkdirSync(path.join(home, '.unbound'));
52
+ fs.writeFileSync(path.join(home, '.unbound', 'config.json'),
53
+ JSON.stringify({ api_key: 'test-key', base_url: `http://127.0.0.1:${port}` }));
54
+ return new Promise((resolve) => {
55
+ const child = spawn('node', [path.join(__dirname, '..', 'src', 'index.js'), ...args], {
56
+ env: { ...process.env, HOME: home, UNBOUND_TOKEN: 'test-key', UNBOUND_API_URL: '', UNBOUND_TELEMETRY: '0', UNBOUND_NO_UPDATE_CHECK: '1' },
57
+ });
58
+ let stdout = '';
59
+ let stderr = '';
60
+ child.stdout.on('data', (d) => { stdout += d; });
61
+ child.stderr.on('data', (d) => { stderr += d; });
62
+ child.on('close', (code) => {
63
+ fs.rmSync(home, { recursive: true, force: true });
64
+ resolve({ code, stdout, stderr });
65
+ });
66
+ });
67
+ }
68
+
69
+ test('mark looks the trace up, then posts the chosen finding', async () => {
70
+ const { server, seen, port } = await startServer((method) =>
71
+ (method === 'GET' ? [200, { findings: [flagged] }] : [200, { message: 'False positive marked' }]));
72
+ try {
73
+ const r = await runCli(port, ['false-positive', 'mark', TRACE.toUpperCase(), '--yes']);
74
+ assert.equal(r.code, 0, r.stderr);
75
+ assert.equal(seen[0].path, PATH);
76
+ assert.equal(seen[0].query.get('trace_id'), TRACE);
77
+ assert.deepEqual(seen[1].body, { trace_id: TRACE, guardrail_action_id: 11, is_false_positive: true });
78
+ assert.match(r.stdout + r.stderr, /False positive marked/);
79
+ } finally {
80
+ server.close();
81
+ }
82
+ });
83
+
84
+ test('unmark posts is_false_positive false', async () => {
85
+ const { server, seen, port } = await startServer((method) =>
86
+ (method === 'GET' ? [200, { findings: [marked] }] : [200, { message: 'False positive unmarked' }]));
87
+ try {
88
+ const r = await runCli(port, ['fp', 'unmark', TRACE, '-y']);
89
+ assert.equal(r.code, 0, r.stderr);
90
+ assert.deepEqual(seen[1].body, { trace_id: TRACE, guardrail_action_id: 12, is_false_positive: false });
91
+ } finally {
92
+ server.close();
93
+ }
94
+ });
95
+
96
+ test('a trace with none of your findings posts nothing and exits 1', async () => {
97
+ const { server, seen, port } = await startServer(() => [200, { findings: [] }]);
98
+ try {
99
+ const r = await runCli(port, ['false-positive', 'mark', TRACE, '--yes']);
100
+ assert.equal(r.code, 1);
101
+ assert.equal(seen.filter((s) => s.method === 'POST').length, 0);
102
+ } finally {
103
+ server.close();
104
+ }
105
+ });
106
+
107
+ test('an invalid trace ID never reaches the backend', async () => {
108
+ const { server, seen, port } = await startServer(() => [200, { findings: [] }]);
109
+ try {
110
+ const r = await runCli(port, ['false-positive', 'list', 'not-a-uuid']);
111
+ assert.equal(r.code, 1);
112
+ assert.equal(seen.length, 0);
113
+ } finally {
114
+ server.close();
115
+ }
116
+ });
@@ -0,0 +1,38 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { spawnSync } = require('child_process');
7
+
8
+ const CLI = path.resolve(__dirname, '../src/index.js');
9
+
10
+ function validate(policy) {
11
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'unbound-pack-validation-'));
12
+ const file = path.join(dir, 'pack.yaml');
13
+ fs.writeFileSync(file, `apiVersion: unbound.security/v1\nkind: PolicyPack\nmetadata:\n name: sample\n version: '1'\npolicies:\n${policy}\n`);
14
+ const result = spawnSync(process.execPath, [CLI, 'pack', 'validate', '-f', file], {
15
+ encoding: 'utf8',
16
+ env: process.env,
17
+ });
18
+ fs.rmSync(dir, { recursive: true, force: true });
19
+ return result;
20
+ }
21
+
22
+ test('pack validate rejects malformed COST config with field path and exit 2', () => {
23
+ const result = validate(' - id: cap\n kind: cost\n config:\n montly_budget: 20\n monthly_budget: -5\n bogus_key: true');
24
+ assert.equal(result.status, 2);
25
+ assert.match(result.stderr, /config\.bogus_key: unknown key for COST policy/);
26
+ });
27
+
28
+ test('pack validate reports a negative budget at its field path', () => {
29
+ const result = validate(' - id: cap\n kind: cost\n config:\n monthly_budget: -5');
30
+ assert.equal(result.status, 2);
31
+ assert.match(result.stderr, /config\.monthly_budget: must be a non-negative number/);
32
+ });
33
+
34
+ test('pack validate rejects unknown terminal command fields with field path and exit 2', () => {
35
+ const result = validate(' - id: tool\n kind: tool\n type: TERMINAL_COMMAND\n action: AUDIT\n commandFamily: git_action\n config:\n not_a_real_key: nope');
36
+ assert.equal(result.status, 2);
37
+ assert.match(result.stderr, /config\.not_a_real_key: unknown field for command family/);
38
+ });
@@ -90,3 +90,12 @@ test('export keeps a loadable file for an empty BLOCK message and an allow-nothi
90
90
  const ops = plan.buildPlan(plan.toDesired(packDoc, REF), live, { prune: true });
91
91
  assert.deepEqual(ops.map((o) => o.op), ['unchanged', 'unchanged']);
92
92
  });
93
+
94
+ test('round trip validates a checked-in terminal command family', () => {
95
+ const live = { tool: [
96
+ { id: '41', name: 'git-push', code_slug: 'git-push', policy_type: 'TERMINAL_COMMAND', action: 'AUDIT', custom_message: '', enabled: true, status: 'ACTIVE', command_family: 'git_action', config: { operation: 'push' }, scope_user_groups: [] },
97
+ ], generic: [] };
98
+ const doc = exp.liveToPack('base', live, REF);
99
+ const validated = schema.validatePack(schema.parsePackText(exp.stringifyPack(doc), 'base.yaml'), 'base.yaml');
100
+ assert.deepEqual(validated.policies[0].config, { operation: 'push' });
101
+ });
@@ -115,13 +115,14 @@ test('fetchManaged asks for the pack by identity and splits unsupported types',
115
115
  return { policies: [
116
116
  { id: 10, name: 'Cap', type: 'COST', origin: 'CODE', code_pack: 'base', code_slug: 'cost' },
117
117
  { id: 11, name: 'Repo', type: 'REPO', origin: 'CODE', code_pack: 'base', code_slug: 'repo' },
118
- { id: 12, name: 'Other', type: 'COST', origin: 'CODE', code_pack: 'other', code_slug: 'x' },
118
+ { id: 12, name: 'Accounts', type: 'ACCOUNT', origin: 'CODE', code_pack: 'base', code_slug: 'account' },
119
+ { id: 13, name: 'Other', type: 'COST', origin: 'CODE', code_pack: 'other', code_slug: 'x' },
119
120
  ] };
120
121
  };
121
122
  const live = await remote.fetchManaged('base');
122
123
  assert.deepEqual(live.tool.map((r) => r.name), ['Audit pushes'], 'a MANUAL row named like a pack policy is not managed');
123
- assert.deepEqual(live.generic.map((r) => r.name), ['Cap'], 'a row of another pack is not managed');
124
- assert.deepEqual(live.unsupported.map((u) => u.row.name), ['Skill', 'Repo']);
124
+ assert.deepEqual(live.generic.map((r) => r.name), ['Cap'], 'only existing pack kinds are managed');
125
+ assert.deepEqual(live.unsupported.map((u) => u.row.name), ['Skill', 'Repo', 'Accounts']);
125
126
  assert.deepEqual(calls[0][2].query, { code_pack: 'base', origin: 'CODE', page: 1, page_size: 200 });
126
127
  assert.deepEqual(calls[1][2].query, { code_pack: 'base', origin: 'CODE' });
127
128
  });
@@ -102,7 +102,7 @@ test('validatePack: kind-specific keys are enforced', () => {
102
102
  test('validatePack: tool policy rules', () => {
103
103
  assert.throws(() => load(BASE.replace('action: BLOCK\n commandFamily', 'action: DENY\n commandFamily')), /action must be one of/);
104
104
  assert.throws(() => load(BASE.replace(' customMessage: Reading cluster secrets is blocked.\n', '')), /customMessage is required when action is BLOCK or WARN/);
105
- assert.throws(() => load(BASE.replace(' commandFamily: custom\n', '')), /commandFamily is required/);
105
+ assert.throws(() => load(BASE.replace(' commandFamily: custom\n', '')), /\.commandFamily is required/);
106
106
  assert.throws(() => load(BASE.replace(' tools: [create_pull_request, push_files]', ' tool: a\n actionType: write')), /exactly one of tool, tools or actionType/);
107
107
  assert.throws(() => load(BASE.replace(' tools: [create_pull_request, push_files]', ' actionType: nuke')), /actionType must be one of/);
108
108
  });
@@ -142,3 +142,103 @@ test('validatePack: description is a tool-policy key only', () => {
142
142
  assert.throws(() => load(BASE.replace(' kind: cost', ' kind: cost\n description: dropped')), /unknown key "description"/);
143
143
  assert.doesNotThrow(() => load(BASE.replace(' kind: tool\n type: TERMINAL_COMMAND', ' kind: tool\n description: kept\n type: TERMINAL_COMMAND')));
144
144
  });
145
+
146
+ test('validatePack: generic config keys and values are validated by kind', () => {
147
+ const base = { apiVersion: 'unbound.security/v1', kind: 'PolicyPack', metadata: { name: 'p', version: '1' } };
148
+ const invalid = (policy) => assert.throws(
149
+ () => schema.validatePack({ ...base, policies: [{ id: 'a', ...policy }] }, 'p.yaml'),
150
+ (err) => err instanceof schema.PackError && err.exitCode === 2
151
+ );
152
+ invalid({ kind: 'cost', config: { montly_budget: 20, monthly_budget: -5, bogus_key: true } });
153
+ assert.throws(() => schema.validatePack({ ...base, policies: [{ id: 'a', kind: 'cost', config: { monthly_budget: -5 } }] }, 'p.yaml'),
154
+ (err) => err.message === 'p.yaml: policies[0] (a): config.monthly_budget: must be a non-negative number' && err.exitCode === 2);
155
+ assert.throws(() => schema.validatePack({ ...base, policies: [
156
+ { id: 'good', kind: 'cost', config: { monthly_budget: 10 } },
157
+ { id: 'bad-cap', kind: 'cost', config: { monthly_budget: -5 } },
158
+ ] }, 'p.yaml'),
159
+ (err) => err.message === 'p.yaml: policies[1] (bad-cap): config.monthly_budget: must be a non-negative number' && err.exitCode === 2);
160
+ invalid({ kind: 'model', config: { support_all_models: 'yes' } });
161
+ invalid({ kind: 'security', config: { guardrails: [{ threshold: 101 }] } });
162
+ invalid({ kind: 'repo', config: { github_org: 'unbound' } });
163
+ invalid({ kind: 'account', config: { tools: { codex: { enabled: true } } } });
164
+ assert.doesNotThrow(() => schema.validatePack({ ...base, policies: [
165
+ { id: 'cost', kind: 'cost', config: { monthly_budget: 0, enforcement_message: 'Limit reached' } },
166
+ ] }, 'p.yaml'));
167
+ });
168
+
169
+ test('validatePack: COST nulls mean unset and MODEL accepts default_model_id', () => {
170
+ const base = { apiVersion: 'unbound.security/v1', kind: 'PolicyPack', metadata: { name: 'p', version: '1' } };
171
+ assert.doesNotThrow(() => schema.validatePack({ ...base, policies: [
172
+ { id: 'cost', kind: 'cost', config: {
173
+ monthly_budget: null, window_hours: null, spend_limit: null, meter: null,
174
+ reset_style: null, alert_pct: null, enforcement_message: null,
175
+ } },
176
+ { id: 'model', kind: 'model', config: { support_all_models: true, default_model_id: 42 } },
177
+ ] }, 'p.yaml'));
178
+ assert.throws(() => schema.validatePack({ ...base, policies: [
179
+ { id: 'half-window', kind: 'cost', config: { window_hours: null, spend_limit: 5 } },
180
+ ] }, 'p.yaml'), /policies\[0\].*config\.window_hours: must be provided together/);
181
+ assert.throws(() => schema.validatePack({ ...base, policies: [
182
+ { id: 'bad-model', kind: 'model', config: { support_all_models: true, default_model_id: 'bad' } },
183
+ ] }, 'p.yaml'), /policies\[0\].*config\.default_model_id: must be a positive integer ID/);
184
+ });
185
+
186
+ test('validatePack: checked-in tool family fields are enforced with backend messages', () => {
187
+ const base = { apiVersion: 'unbound.security/v1', kind: 'PolicyPack', metadata: { name: 'p', version: '1' } };
188
+ const make = (commandFamily, config) => schema.validatePack({ ...base, policies: [
189
+ { id: 'tool', kind: 'tool', type: 'TERMINAL_COMMAND', action: 'AUDIT', commandFamily, config },
190
+ ] }, 'p.yaml');
191
+ assert.doesNotThrow(() => make('git_action', { operation: 'push' }));
192
+ assert.throws(() => make('git_action', { not_a_real_key: 'x' }),
193
+ (err) => err.message === "p.yaml: policies[0] (tool): config.not_a_real_key: unknown field for command family 'git_action'" && err.exitCode === 2);
194
+ assert.throws(() => make('not_a_family', { ANY: '*' }),
195
+ (err) => err.message === 'p.yaml: policies[0] (tool): commandFamily: unknown command family' && err.exitCode === 2);
196
+ assert.throws(() => make('git_action', { operation: null }),
197
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.operation: must have a non-null value' && err.exitCode === 2);
198
+ assert.throws(() => make('git_action', { operation: 'push', branch: null }),
199
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.branch: must have a non-null value' && err.exitCode === 2);
200
+ assert.throws(() => make('git_action', { operation: 2 }),
201
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.operation: must be a string pattern' && err.exitCode === 2);
202
+ assert.throws(() => make('git_action', { ANY: '*', operation: 'push' }),
203
+ (err) => err.message === "p.yaml: policies[0] (tool): The 'ANY' field cannot be combined with other match conditions" && err.exitCode === 2);
204
+ });
205
+
206
+ test('validatePack: tool values are grounded and custom regexes are checked for safety', () => {
207
+ const base = { apiVersion: 'unbound.security/v1', kind: 'PolicyPack', metadata: { name: 'p', version: '1' } };
208
+ const make = (commandFamily, config) => schema.validatePack({ ...base, policies: [
209
+ { id: 'tool', kind: 'tool', type: 'TERMINAL_COMMAND', action: 'AUDIT', commandFamily, config },
210
+ ] }, 'p.yaml');
211
+ const normalized = make('git_action', { operation: 'any operation' });
212
+ assert.equal(normalized.policies[0].config.operation, '*');
213
+ for (const pattern of ['node.js --all', 'release_all files', 'remove report.csv later']) {
214
+ assert.throws(() => make('delete_file', { path: pattern }),
215
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.path: must be a concrete pattern or quantifier' && err.exitCode === 2);
216
+ }
217
+ assert.throws(() => make('git_action', { operation: 'run all operations' }),
218
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.operation: must be a concrete pattern or quantifier' && err.exitCode === 2);
219
+ assert.throws(() => make('git_action', { operation: 'deploy staging' }),
220
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.operation: must be a concrete pattern or quantifier' && err.exitCode === 2);
221
+ assert.throws(() => make('custom', { command: '(a+)+$' }),
222
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.command: invalid pattern' && err.exitCode === 2);
223
+ assert.throws(() => make('custom', { command: 'regex:(unterminated' }),
224
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.command: invalid pattern' && err.exitCode === 2);
225
+ assert.throws(() => make('custom', { command: 'regex:\\p{L}' }),
226
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.command: invalid pattern' && err.exitCode === 2);
227
+ assert.throws(() => make('custom', { command: 'regex:\\xZZ' }),
228
+ (err) => err.message === 'p.yaml: policies[0] (tool): config.command: invalid pattern' && err.exitCode === 2);
229
+ assert.doesNotThrow(() => make('custom', { command: 'aws *' }));
230
+ const concrete = make('delete_file', { path: '/srv/all reports/*.csv' });
231
+ assert.equal(concrete.policies[0].config.path, '/srv/all reports/*.csv');
232
+ });
233
+
234
+ test('validatePack: MCP tool config must be an object and errors include policy location', () => {
235
+ const base = { apiVersion: 'unbound.security/v1', kind: 'PolicyPack', metadata: { name: 'p', version: '1' } };
236
+ const mcp = { id: 'tool', kind: 'tool', type: 'MCP_TOOL', action: 'AUDIT', mcp: { server: 'github', tool: 'search' } };
237
+ for (const config of ['x', [1], 1]) {
238
+ assert.throws(() => schema.validatePack({ ...base, policies: [{ ...mcp, config }] }, 'p.yaml'),
239
+ (err) => err.message === 'p.yaml: policies[0] (tool).config must be an object' && err.exitCode === 2);
240
+ }
241
+ assert.throws(() => schema.validatePack({ ...base, policies: [
242
+ { id: 'bad', kind: 'tool', type: 'TERMINAL_COMMAND', action: 'AUDIT', commandFamily: 'git_action', config: { nope: 'x' } },
243
+ ] }, 'p.yaml'), (err) => err.message === "p.yaml: policies[0] (bad): config.nope: unknown field for command family 'git_action'" && err.exitCode === 2);
244
+ });