unbound-cli 1.20.4 → 1.20.6
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/LOCAL_DEV.md +3 -3
- package/README.md +3 -1
- package/package.json +4 -2
- package/scripts/generate-command-family-fields.py +85 -0
- package/src/commands/policy.js +12 -6
- package/src/index.js +2 -2
- package/src/lib/command-family-fields.js +158 -0
- package/src/lib/pack-config-schema.js +282 -0
- package/src/lib/pack-schema.js +17 -5
- package/src/lib/policy-ai-assist.js +1 -1
- package/test/pack-cli-validation.test.js +38 -0
- package/test/pack-export.test.js +9 -0
- package/test/pack-remote.test.js +4 -3
- package/test/pack-schema.test.js +101 -1
- package/test/policy-ai-assist-mcp.test.js +1 -1
- package/test/policy-cost-update-edge-cases.test.js +161 -0
- package/test/policy-cost-update.test.js +93 -0
package/LOCAL_DEV.md
CHANGED
|
@@ -155,10 +155,10 @@ node src/index.js policy security create --name "Route 429s" --sub-type error-co
|
|
|
155
155
|
node src/index.js policy tool list
|
|
156
156
|
node src/index.js policy tool families
|
|
157
157
|
node src/index.js policy tool mcp-servers
|
|
158
|
-
node src/index.js policy tool create-terminal --name "Block rm -rf" \
|
|
159
|
-
--command-family
|
|
158
|
+
node src/index.js policy tool create-terminal --no-ai --name "Block rm -rf" \
|
|
159
|
+
--command-family custom --field command='rm -rf*' --action BLOCK \
|
|
160
160
|
--custom-message "Destructive command blocked."
|
|
161
|
-
node src/index.js policy tool create-mcp --name "Audit Linear writes" \
|
|
161
|
+
node src/index.js policy tool create-mcp --no-ai --name "Audit Linear writes" \
|
|
162
162
|
--mcp-server Linear --mcp-action-type write --action AUDIT
|
|
163
163
|
|
|
164
164
|
# Users
|
package/README.md
CHANGED
|
@@ -200,7 +200,7 @@ unbound policy tool families
|
|
|
200
200
|
unbound policy tool mcp-servers
|
|
201
201
|
|
|
202
202
|
# Flag-based fallback: block destructive shell commands explicitly
|
|
203
|
-
unbound policy tool create-terminal --no-ai --name "Block rm -rf" --command-family
|
|
203
|
+
unbound policy tool create-terminal --no-ai --name "Block rm -rf" --command-family custom \
|
|
204
204
|
--field command='rm -rf*' --action BLOCK --custom-message "Destructive command blocked."
|
|
205
205
|
|
|
206
206
|
# Flag-based MCP fallback: audit Linear write operations
|
|
@@ -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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "unbound-cli",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.6",
|
|
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())
|
package/src/commands/policy.js
CHANGED
|
@@ -854,7 +854,13 @@ Learn more: ${DOCS_COST}
|
|
|
854
854
|
body.config = parseJsonOrThrow(opts.config);
|
|
855
855
|
} else if (opts.monthlyBudget != null) {
|
|
856
856
|
if (Number.isNaN(opts.monthlyBudget)) throw new Error('Invalid --monthly-budget value.');
|
|
857
|
-
|
|
857
|
+
// The backend replaces config wholesale, so keep the keys this flag doesn't own.
|
|
858
|
+
const stored = (await api.get(`/api/v1/policies/${id}/`))?.policy;
|
|
859
|
+
const storedConfig = stored?.config;
|
|
860
|
+
if (stored?.type !== 'COST' || !storedConfig || typeof storedConfig !== 'object' || Array.isArray(storedConfig)) {
|
|
861
|
+
throw new Error(`Policy ${id} is not a cost policy with a readable config; nothing was changed.`);
|
|
862
|
+
}
|
|
863
|
+
body.config = { ...storedConfig, monthly_budget: opts.monthlyBudget };
|
|
858
864
|
}
|
|
859
865
|
|
|
860
866
|
if (opts.group !== undefined) {
|
|
@@ -1463,7 +1469,7 @@ Subcommands:
|
|
|
1463
1469
|
.option('--prompt <text>', 'Natural-language description; routes through Unbound AI assist. Mutually exclusive with --command-family/--field/--config. Compatible with --name/--description/--action overrides.')
|
|
1464
1470
|
.option('--no-ai', 'Opt out of the AI-assist guard and use raw classification flags. Mutually exclusive with --prompt.')
|
|
1465
1471
|
.option('--name <name>', 'Policy name (required unless --prompt is used)')
|
|
1466
|
-
.option('--command-family <family>', 'Command family (e.g.
|
|
1472
|
+
.option('--command-family <family>', 'Command family (e.g. git_action, delete_file, data_transfer), or `custom` to match one pattern against the whole command. See `policy tool families`.')
|
|
1467
1473
|
.option('--field <key=pattern>', 'Match field: <key>=<pattern>. Repeatable — multiple --field are ANDed (all must match), one per field, for a more specific policy. At least one required unless --config is used. For the `custom` family the key is `command`.', (val, prev = []) => [...prev, val])
|
|
1468
1474
|
.option('--action <action>', `Action to take: ${TOOL_ACTIONS.join(' | ')}`)
|
|
1469
1475
|
.option('--description <text>', 'Human-readable description')
|
|
@@ -1484,11 +1490,11 @@ Examples:
|
|
|
1484
1490
|
--name "Block recursive deletes" --action WARN
|
|
1485
1491
|
|
|
1486
1492
|
$ unbound policy tool create-terminal --no-ai --name "Block rm -rf" \\
|
|
1487
|
-
--command-family
|
|
1493
|
+
--command-family custom --field command='rm -rf*' --action BLOCK \\
|
|
1488
1494
|
--custom-message "Destructive commands are blocked."
|
|
1489
1495
|
|
|
1490
1496
|
$ unbound policy tool create-terminal --no-ai --name "Audit git push" \\
|
|
1491
|
-
--command-family
|
|
1497
|
+
--command-family git_action --field operation=push --action AUDIT
|
|
1492
1498
|
|
|
1493
1499
|
# Multiple --field are ANDed — this fires only on a push to main on origin:
|
|
1494
1500
|
$ unbound policy tool create-terminal --no-ai --name "Block push to main on origin" \\
|
|
@@ -2099,9 +2105,9 @@ Examples:
|
|
|
2099
2105
|
$ unbound policy form-data # see available names
|
|
2100
2106
|
$ unbound policy cost create --name "Eng Budget" --monthly-budget 1000 --group engg
|
|
2101
2107
|
$ unbound policy security create --name "Block PII" --sub-type guardrails --guardrail PII:BLOCK
|
|
2102
|
-
$ unbound policy tool create-terminal --name "Block rm -rf" --command-family
|
|
2108
|
+
$ unbound policy tool create-terminal --no-ai --name "Block rm -rf" --command-family custom \\
|
|
2103
2109
|
--field command='rm -rf*' --action BLOCK --custom-message "Blocked by policy"
|
|
2104
|
-
$ unbound policy tool create-mcp --name "Audit Linear writes" \\
|
|
2110
|
+
$ unbound policy tool create-mcp --no-ai --name "Audit Linear writes" \\
|
|
2105
2111
|
--mcp-server Linear --mcp-action-type write --action AUDIT
|
|
2106
2112
|
|
|
2107
2113
|
Learn more: ${DOCS_POLICIES}
|
package/src/index.js
CHANGED
|
@@ -132,9 +132,9 @@ POLICY MANAGEMENT
|
|
|
132
132
|
|
|
133
133
|
Tool policies — shell command and MCP tool controls (separate backend):
|
|
134
134
|
$ unbound policy tool list
|
|
135
|
-
$ unbound policy tool create-terminal --name "Block rm -rf" --command-family
|
|
135
|
+
$ unbound policy tool create-terminal --no-ai --name "Block rm -rf" --command-family custom \\
|
|
136
136
|
--field command='rm -rf*' --action BLOCK --custom-message "Destructive command blocked."
|
|
137
|
-
$ unbound policy tool create-mcp --name "Audit Linear writes" --mcp-server Linear \\
|
|
137
|
+
$ unbound policy tool create-mcp --no-ai --name "Audit Linear writes" --mcp-server Linear \\
|
|
138
138
|
--mcp-action-type write --action AUDIT
|
|
139
139
|
$ unbound policy tool families Discover terminal command families
|
|
140
140
|
$ unbound policy tool mcp-servers Discover MCP servers and their tools
|
|
@@ -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 };
|
package/src/lib/pack-schema.js
CHANGED
|
@@ -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.
|
|
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))
|
|
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
|
|
179
|
-
|
|
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
|
/**
|
|
@@ -592,7 +592,7 @@ async function runMcpPromptCreate(opts) {
|
|
|
592
592
|
if (!response.canonical_group_id
|
|
593
593
|
|| !Array.isArray(response.mcp_tools)
|
|
594
594
|
|| response.mcp_tools.length === 0) {
|
|
595
|
-
const e = new Error('AI assist could not match any tools for your description. Try naming the service and tools more directly, or use `unbound policy tool create-mcp --name "..." --mcp-server <server> (--mcp-tool <tool> | --mcp-action-type <read|write|destructive>) --action <action>`.');
|
|
595
|
+
const e = new Error('AI assist could not match any tools for your description. Try naming the service and tools more directly, or use `unbound policy tool create-mcp --no-ai --name "..." --mcp-server <server> (--mcp-tool <tool> | --mcp-action-type <read|write|destructive>) --action <action>`.');
|
|
596
596
|
e.exitCode = 2;
|
|
597
597
|
throw e;
|
|
598
598
|
}
|
|
@@ -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
|
+
});
|
package/test/pack-export.test.js
CHANGED
|
@@ -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
|
+
});
|
package/test/pack-remote.test.js
CHANGED
|
@@ -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: '
|
|
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'], '
|
|
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
|
});
|
package/test/pack-schema.test.js
CHANGED
|
@@ -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', '')),
|
|
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
|
+
});
|
|
@@ -264,7 +264,7 @@ test('soft fail: mcp_tools:[] → exit 2 with helpful message; no create POST',
|
|
|
264
264
|
assert.equal(process.exitCode, 2);
|
|
265
265
|
const msg = h.captured.error.join('\n');
|
|
266
266
|
assert.ok(msg.includes('could not match any tools'), `expected soft-fail message, got: ${msg}`);
|
|
267
|
-
assert.ok(msg.includes('unbound policy tool create-mcp --name'), `expected manual escape hatch hint, got: ${msg}`);
|
|
267
|
+
assert.ok(msg.includes('unbound policy tool create-mcp --no-ai --name'), `expected manual escape hatch hint, got: ${msg}`);
|
|
268
268
|
assert.equal(
|
|
269
269
|
h.calls.posts.filter((c) => c.path === '/api/v1/command-policies/').length,
|
|
270
270
|
0,
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
const config = require('../src/config');
|
|
5
|
+
const api = require('../src/api');
|
|
6
|
+
const output = require('../src/output');
|
|
7
|
+
const { register } = require('../src/commands/policy');
|
|
8
|
+
|
|
9
|
+
// Edge cases around `policy cost update --monthly-budget`: the read-before-write
|
|
10
|
+
// must never turn a failed or odd GET into a PUT.
|
|
11
|
+
|
|
12
|
+
const STORED = {
|
|
13
|
+
monthly_budget: 1000,
|
|
14
|
+
window_hours: 24,
|
|
15
|
+
spend_limit: 50,
|
|
16
|
+
alert_pct: 0.5,
|
|
17
|
+
enforcement_message: 'Window spend limit reached.',
|
|
18
|
+
meter: 'cost',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function stub({ get, getBody } = {}) {
|
|
22
|
+
const orig = {
|
|
23
|
+
isLoggedIn: config.isLoggedIn, get: api.get, put: api.put,
|
|
24
|
+
success: output.success, error: output.error, json: output.json,
|
|
25
|
+
exitCode: process.exitCode,
|
|
26
|
+
};
|
|
27
|
+
const seen = { gets: [], puts: [], errors: [] };
|
|
28
|
+
config.isLoggedIn = () => true;
|
|
29
|
+
api.get = async (path) => {
|
|
30
|
+
seen.gets.push(path);
|
|
31
|
+
if (get) return get(path);
|
|
32
|
+
return getBody ?? { policy: { id: 5, type: 'COST', config: { ...STORED } } };
|
|
33
|
+
};
|
|
34
|
+
api.put = async (path, { body }) => { seen.puts.push({ path, body }); return { policy: { id: 5, ...body } }; };
|
|
35
|
+
output.success = () => {};
|
|
36
|
+
output.error = (m) => { seen.errors.push(m); };
|
|
37
|
+
output.json = () => {};
|
|
38
|
+
process.exitCode = undefined;
|
|
39
|
+
return {
|
|
40
|
+
seen,
|
|
41
|
+
restore() {
|
|
42
|
+
config.isLoggedIn = orig.isLoggedIn; api.get = orig.get; api.put = orig.put;
|
|
43
|
+
output.success = orig.success; output.error = orig.error; output.json = orig.json;
|
|
44
|
+
process.exitCode = orig.exitCode;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function run(id, args) {
|
|
50
|
+
const program = new Command();
|
|
51
|
+
program.exitOverride();
|
|
52
|
+
register(program);
|
|
53
|
+
await program.parseAsync(['node', 'x', 'policy', 'cost', 'update', id, ...args, '--json']);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function withStub(opts, fn) {
|
|
57
|
+
const s = stub(opts);
|
|
58
|
+
try { await fn(s.seen); } finally { s.restore(); }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
test('GET 404 (unknown id): clear error, exit 1, no PUT', () => withStub(
|
|
62
|
+
{ get: async () => { throw new api.ApiError(404, {}); } },
|
|
63
|
+
async (seen) => {
|
|
64
|
+
await run('999999', ['--monthly-budget', '10']);
|
|
65
|
+
assert.deepEqual(seen.gets, ['/api/v1/policies/999999/']);
|
|
66
|
+
assert.equal(seen.puts.length, 0);
|
|
67
|
+
assert.equal(process.exitCode, 1);
|
|
68
|
+
assert.match(seen.errors[0], /Not found/);
|
|
69
|
+
},
|
|
70
|
+
));
|
|
71
|
+
|
|
72
|
+
test('GET network failure: exit 1, no PUT', () => withStub(
|
|
73
|
+
{ get: async () => { throw new Error('connect ECONNREFUSED 127.0.0.1:1'); } },
|
|
74
|
+
async (seen) => {
|
|
75
|
+
await run('5', ['--monthly-budget', '10']);
|
|
76
|
+
assert.equal(seen.puts.length, 0);
|
|
77
|
+
assert.equal(process.exitCode, 1);
|
|
78
|
+
assert.match(seen.errors[0], /ECONNREFUSED/);
|
|
79
|
+
},
|
|
80
|
+
));
|
|
81
|
+
|
|
82
|
+
test('GET 403 (no read access): exit 1, no PUT', () => withStub(
|
|
83
|
+
{ get: async () => { throw new api.ApiError(403, {}); } },
|
|
84
|
+
async (seen) => {
|
|
85
|
+
await run('5', ['--monthly-budget', '10']);
|
|
86
|
+
assert.equal(seen.puts.length, 0);
|
|
87
|
+
assert.equal(process.exitCode, 1);
|
|
88
|
+
},
|
|
89
|
+
));
|
|
90
|
+
|
|
91
|
+
test('empty-object config: budget update goes through with only the budget', () => withStub(
|
|
92
|
+
{ getBody: { policy: { id: 5, type: 'COST', config: {} } } },
|
|
93
|
+
async (seen) => {
|
|
94
|
+
await run('5', ['--monthly-budget', '250']);
|
|
95
|
+
assert.deepEqual(seen.errors, []);
|
|
96
|
+
assert.deepEqual(seen.puts[0].body.config, { monthly_budget: 250 });
|
|
97
|
+
},
|
|
98
|
+
));
|
|
99
|
+
|
|
100
|
+
for (const [label, cfg] of [['null', null], ['an array', [1, 2]], ['a string', 'x'], ['a number', 7]]) {
|
|
101
|
+
test(`config that is ${label}: refuses, no PUT`, () => withStub(
|
|
102
|
+
{ getBody: { policy: { id: 5, type: 'COST', config: cfg } } },
|
|
103
|
+
async (seen) => {
|
|
104
|
+
await run('5', ['--monthly-budget', '250']);
|
|
105
|
+
assert.equal(seen.puts.length, 0);
|
|
106
|
+
assert.equal(process.exitCode, 1);
|
|
107
|
+
assert.match(seen.errors[0], /nothing was changed/);
|
|
108
|
+
},
|
|
109
|
+
));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
test('every stored key survives, including enforcement_message and alert_pct, and the stored object is not mutated', () => {
|
|
113
|
+
const storedConfig = { ...STORED };
|
|
114
|
+
return withStub(
|
|
115
|
+
{ getBody: { policy: { id: 5, type: 'COST', config: storedConfig } } },
|
|
116
|
+
async (seen) => {
|
|
117
|
+
await run('5', ['--monthly-budget', '1500.5']);
|
|
118
|
+
assert.deepEqual(seen.puts[0].body.config, { ...STORED, monthly_budget: 1500.5 });
|
|
119
|
+
assert.deepEqual(storedConfig, STORED);
|
|
120
|
+
},
|
|
121
|
+
);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('budget 0 is sent as 0, not dropped', () => withStub({}, async (seen) => {
|
|
125
|
+
await run('5', ['--monthly-budget', '0']);
|
|
126
|
+
assert.equal(seen.puts[0].body.config.monthly_budget, 0);
|
|
127
|
+
assert.equal(seen.puts[0].body.config.spend_limit, 50);
|
|
128
|
+
}));
|
|
129
|
+
|
|
130
|
+
test('non-numeric budget: rejected before any GET or PUT', () => withStub({}, async (seen) => {
|
|
131
|
+
await run('5', ['--monthly-budget', 'abc']);
|
|
132
|
+
assert.equal(seen.gets.length, 0);
|
|
133
|
+
assert.equal(seen.puts.length, 0);
|
|
134
|
+
assert.equal(process.exitCode, 1);
|
|
135
|
+
}));
|
|
136
|
+
|
|
137
|
+
test('--monthly-budget with --config: rejected before any GET or PUT', () => withStub({}, async (seen) => {
|
|
138
|
+
await run('5', ['--monthly-budget', '10', '--config', '{"monthly_budget":20}']);
|
|
139
|
+
assert.equal(seen.gets.length, 0);
|
|
140
|
+
assert.equal(seen.puts.length, 0);
|
|
141
|
+
assert.equal(process.exitCode, 1);
|
|
142
|
+
assert.match(seen.errors[0], /Cannot combine --config with --monthly-budget/);
|
|
143
|
+
}));
|
|
144
|
+
|
|
145
|
+
test('budget plus --name/--priority/--disabled: one PUT carries all of them and the merged config', () => withStub({}, async (seen) => {
|
|
146
|
+
await run('5', ['--monthly-budget', '700', '--name', 'Renamed', '--priority', '3', '--disabled']);
|
|
147
|
+
assert.equal(seen.gets.length, 1);
|
|
148
|
+
assert.equal(seen.puts.length, 1);
|
|
149
|
+
const { body, path } = seen.puts[0];
|
|
150
|
+
assert.equal(path, '/api/v1/policies/5/');
|
|
151
|
+
assert.equal(body.name, 'Renamed');
|
|
152
|
+
assert.equal(body.priority, 3);
|
|
153
|
+
assert.equal(body.enabled, false);
|
|
154
|
+
assert.deepEqual(body.config, { ...STORED, monthly_budget: 700 });
|
|
155
|
+
}));
|
|
156
|
+
|
|
157
|
+
test('GET reads the same policy id the PUT writes', () => withStub({}, async (seen) => {
|
|
158
|
+
await run('42', ['--monthly-budget', '9']);
|
|
159
|
+
assert.deepEqual(seen.gets, ['/api/v1/policies/42/']);
|
|
160
|
+
assert.equal(seen.puts[0].path, '/api/v1/policies/42/');
|
|
161
|
+
}));
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
const config = require('../src/config');
|
|
5
|
+
const api = require('../src/api');
|
|
6
|
+
const output = require('../src/output');
|
|
7
|
+
const { register } = require('../src/commands/policy');
|
|
8
|
+
|
|
9
|
+
// `policy cost update` sends a PUT whose config the backend stores wholesale, so a
|
|
10
|
+
// budget-only change must carry the policy's other config keys with it.
|
|
11
|
+
|
|
12
|
+
const STORED = { monthly_budget: 1000, window_hours: 24, spend_limit: 50, meter: 'cost' };
|
|
13
|
+
|
|
14
|
+
function stub(getBody = { policy: { id: 5, type: 'COST', config: { ...STORED } } }) {
|
|
15
|
+
const orig = {
|
|
16
|
+
isLoggedIn: config.isLoggedIn, get: api.get, put: api.put,
|
|
17
|
+
success: output.success, error: output.error, json: output.json,
|
|
18
|
+
exitCode: process.exitCode,
|
|
19
|
+
};
|
|
20
|
+
const seen = { gets: 0, putBody: null, errors: [] };
|
|
21
|
+
config.isLoggedIn = () => true;
|
|
22
|
+
api.get = async () => { seen.gets += 1; return getBody; };
|
|
23
|
+
api.put = async (_p, { body }) => { seen.putBody = body; return { policy: { id: 5, ...body } }; };
|
|
24
|
+
output.success = () => {};
|
|
25
|
+
output.error = (m) => { seen.errors.push(m); };
|
|
26
|
+
output.json = () => {};
|
|
27
|
+
return {
|
|
28
|
+
seen,
|
|
29
|
+
restore() {
|
|
30
|
+
config.isLoggedIn = orig.isLoggedIn; api.get = orig.get; api.put = orig.put;
|
|
31
|
+
output.success = orig.success; output.error = orig.error; output.json = orig.json;
|
|
32
|
+
process.exitCode = orig.exitCode;
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function run(args) {
|
|
38
|
+
const program = new Command();
|
|
39
|
+
register(program);
|
|
40
|
+
await program.parseAsync(['node', 'x', 'policy', 'cost', 'update', '5', ...args, '--json']);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test('--monthly-budget changes the budget and keeps the spend limit', async () => {
|
|
44
|
+
const { seen, restore } = stub();
|
|
45
|
+
try {
|
|
46
|
+
await run(['--monthly-budget', '1500']);
|
|
47
|
+
assert.deepEqual(seen.errors, []);
|
|
48
|
+
assert.deepEqual(seen.putBody.config, { ...STORED, monthly_budget: 1500 });
|
|
49
|
+
} finally {
|
|
50
|
+
restore();
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('--config still replaces the whole config', async () => {
|
|
55
|
+
const { seen, restore } = stub();
|
|
56
|
+
try {
|
|
57
|
+
await run(['--config', '{"monthly_budget":200}']);
|
|
58
|
+
assert.deepEqual(seen.putBody.config, { monthly_budget: 200 });
|
|
59
|
+
assert.equal(seen.gets, 0);
|
|
60
|
+
} finally {
|
|
61
|
+
restore();
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('an update without budget or config sends no config', async () => {
|
|
66
|
+
const { seen, restore } = stub();
|
|
67
|
+
try {
|
|
68
|
+
await run(['--disabled']);
|
|
69
|
+
assert.equal(seen.putBody.config, undefined);
|
|
70
|
+
assert.equal(seen.putBody.enabled, false);
|
|
71
|
+
assert.equal(seen.gets, 0);
|
|
72
|
+
} finally {
|
|
73
|
+
restore();
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
for (const [label, getBody] of [
|
|
78
|
+
['no config', { policy: { id: 5, type: 'COST' } }],
|
|
79
|
+
['no policy envelope', { id: 5, config: { ...STORED } }],
|
|
80
|
+
['a non-cost policy', { policy: { id: 5, type: 'SECURITY', config: { guardrails: [] } } }],
|
|
81
|
+
]) {
|
|
82
|
+
test(`--monthly-budget refuses to write when the GET returns ${label}`, async () => {
|
|
83
|
+
const { seen, restore } = stub(getBody);
|
|
84
|
+
try {
|
|
85
|
+
await run(['--monthly-budget', '1500']);
|
|
86
|
+
assert.equal(seen.putBody, null, 'nothing may be written');
|
|
87
|
+
assert.equal(seen.errors.length, 1);
|
|
88
|
+
assert.equal(process.exitCode, 1);
|
|
89
|
+
} finally {
|
|
90
|
+
restore();
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|