unbound-cli 1.21.1 → 1.21.2
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/package.json +1 -1
- package/src/commands/pack.js +89 -20
- package/src/lib/pack-export.js +2 -1
- package/src/lib/pack-remote.js +16 -4
- package/test/pack-cli-integration.test.js +135 -13
- package/test/pack-confirm.test.js +15 -1
- package/test/pack-export.test.js +2 -2
- package/test/pack-remote.test.js +14 -4
package/package.json
CHANGED
package/src/commands/pack.js
CHANGED
|
@@ -7,6 +7,7 @@ const { PackError, parsePackText, validatePack, slugify, SLUG_RE } = require('..
|
|
|
7
7
|
const { toDesired, buildPlan, summarize, stable } = require('../lib/pack-plan');
|
|
8
8
|
const { liveToPack, stringifyPack } = require('../lib/pack-export');
|
|
9
9
|
const remote = require('../lib/pack-remote');
|
|
10
|
+
const api = require('../api');
|
|
10
11
|
|
|
11
12
|
const DOCS_PACKS = 'https://docs.getunbound.ai/policies/policy-as-code';
|
|
12
13
|
const PACK_EXTENSIONS = ['.yaml', '.yml', '.json'];
|
|
@@ -124,7 +125,7 @@ const ACTION_LABEL = {
|
|
|
124
125
|
conflict: 'CONFLICT',
|
|
125
126
|
};
|
|
126
127
|
|
|
127
|
-
function printPlan({ file, pack, ops, live, versionState }) {
|
|
128
|
+
function printPlan({ file, pack, ops, live, versionState, commit, pr }) {
|
|
128
129
|
console.log('');
|
|
129
130
|
output.info(`Pack ${pack.name} v${pack.version} (${file})`);
|
|
130
131
|
output.table(ops, [
|
|
@@ -146,6 +147,15 @@ function printPlan({ file, pack, ops, live, versionState }) {
|
|
|
146
147
|
if (versionState.supported && versionState.version !== pack.version) {
|
|
147
148
|
output.info(`Stored version: ${versionState.version || 'none'} -> ${pack.version}`);
|
|
148
149
|
}
|
|
150
|
+
if (versionState.provenanceSupported && (versionState.owner || null) !== (pack.owner || null)) {
|
|
151
|
+
output.info(`Stored owner: ${versionState.owner || 'none'} -> ${pack.owner || 'none'}`);
|
|
152
|
+
}
|
|
153
|
+
if (versionState.supported && commit !== undefined && versionState.commit !== commit) {
|
|
154
|
+
output.info(`Stored commit: ${versionState.commit || 'none'} -> ${commit}`);
|
|
155
|
+
}
|
|
156
|
+
if (versionState.supported && pr !== undefined && versionState.pr !== pr) {
|
|
157
|
+
output.info(`Stored PR: ${versionState.pr || 'none'} -> ${pr}`);
|
|
158
|
+
}
|
|
149
159
|
const parts = [];
|
|
150
160
|
if (s.create) parts.push(`${s.create} to create`);
|
|
151
161
|
if (s.update) parts.push(`${s.update} to update`);
|
|
@@ -157,14 +167,16 @@ function printPlan({ file, pack, ops, live, versionState }) {
|
|
|
157
167
|
console.log(` ${parts.join(', ')}`);
|
|
158
168
|
}
|
|
159
169
|
|
|
160
|
-
function planJson({ file, pack, ops, versionState }) {
|
|
170
|
+
function planJson({ file, pack, ops, versionState, commit, pr }) {
|
|
161
171
|
const summary = summarize(ops);
|
|
162
|
-
const
|
|
172
|
+
const metadata = metadataChanges(pack, versionState, { commit, pr });
|
|
173
|
+
const metadataOnly = Object.keys(metadata).length > 0 && !summary.drift;
|
|
163
174
|
return {
|
|
164
175
|
pack: pack.name,
|
|
165
176
|
version: pack.version,
|
|
166
177
|
file,
|
|
167
|
-
summary: { ...summary, drift: summary.drift + (
|
|
178
|
+
summary: { ...summary, drift: summary.drift + (metadataOnly ? 1 : 0) },
|
|
179
|
+
metadata,
|
|
168
180
|
ops: ops.map((op) => ({
|
|
169
181
|
op: op.op,
|
|
170
182
|
kind: op.kind,
|
|
@@ -176,6 +188,22 @@ function planJson({ file, pack, ops, versionState }) {
|
|
|
176
188
|
};
|
|
177
189
|
}
|
|
178
190
|
|
|
191
|
+
function metadataChanges(pack, versionState, { commit, pr } = {}) {
|
|
192
|
+
const changes = {};
|
|
193
|
+
if (!versionState.supported) return changes;
|
|
194
|
+
if (versionState.version !== pack.version) changes.version = { before: versionState.version, after: pack.version };
|
|
195
|
+
if (versionState.provenanceSupported && (versionState.owner || null) !== (pack.owner || null)) {
|
|
196
|
+
changes.owner = { before: versionState.owner || null, after: pack.owner || null };
|
|
197
|
+
}
|
|
198
|
+
if (commit !== undefined && versionState.commit !== commit) changes.commit = { before: versionState.commit, after: commit };
|
|
199
|
+
if (pr !== undefined && versionState.pr !== pr) changes.pr = { before: versionState.pr, after: pr };
|
|
200
|
+
return changes;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function metadataChanged(pack, versionState, options = {}) {
|
|
204
|
+
return Object.keys(metadataChanges(pack, versionState, options)).length > 0;
|
|
205
|
+
}
|
|
206
|
+
|
|
179
207
|
async function planPack(pack, { prune, names }) {
|
|
180
208
|
const needsMcp = pack.policies.some((p) => p.kind === 'tool' && p.type === 'MCP_TOOL' && p.mcp && p.mcp.actionType);
|
|
181
209
|
const ref = await remote.loadReference({ mcp: needsMcp });
|
|
@@ -195,17 +223,18 @@ async function fetchStablePack(name) {
|
|
|
195
223
|
const before = await remote.fetchVersion(name);
|
|
196
224
|
const live = await remote.fetchManaged(name);
|
|
197
225
|
const after = await remote.fetchVersion(name);
|
|
198
|
-
if (before.supported !== after.supported || before.version !== after.version
|
|
226
|
+
if (before.supported !== after.supported || before.version !== after.version || before.owner !== after.owner ||
|
|
227
|
+
before.commit !== after.commit || before.pr !== after.pr || before.applicationId !== after.applicationId) {
|
|
199
228
|
throw new PackError(`pack "${name}" changed during export; retry`);
|
|
200
229
|
}
|
|
201
|
-
return { live, version: after.version };
|
|
230
|
+
return { live, version: after.version, owner: after.owner };
|
|
202
231
|
}
|
|
203
232
|
|
|
204
233
|
/**
|
|
205
234
|
* Shared body of apply / sync / diff.
|
|
206
235
|
* Returns { drift, failed } so callers can set the exit code.
|
|
207
236
|
*/
|
|
208
|
-
async function runApply(target, { dryRun = false, prune = false, yes = false, json = false, label = 'apply' }) {
|
|
237
|
+
async function runApply(target, { dryRun = false, prune = false, yes = false, json = false, label = 'apply', commit, pr, force = false }) {
|
|
209
238
|
requireLogin();
|
|
210
239
|
const packs = loadPackFiles(target);
|
|
211
240
|
// Names are unique per org, so two packs in one run cannot both claim one.
|
|
@@ -224,13 +253,16 @@ async function runApply(target, { dryRun = false, prune = false, yes = false, js
|
|
|
224
253
|
const planned = [];
|
|
225
254
|
for (const { file, pack } of packs) {
|
|
226
255
|
const { ops, live, versionState } = await planPack(pack, { prune, names });
|
|
227
|
-
planned.push({ file, pack, ops, live, versionState });
|
|
256
|
+
planned.push({ file, pack, ops, live, versionState, commit, pr });
|
|
257
|
+
}
|
|
258
|
+
if (planned.some((p) => !p.versionState.provenanceSupported && (commit !== undefined || pr !== undefined || force))) {
|
|
259
|
+
throw new PackError('pack provenance and forced downgrades require a newer backend');
|
|
228
260
|
}
|
|
229
261
|
|
|
230
262
|
const totals = planned.reduce((acc, p) => {
|
|
231
263
|
const s = summarize(p.ops);
|
|
232
264
|
for (const k of Object.keys(s)) acc[k] = (acc[k] || 0) + s[k];
|
|
233
|
-
if (p.
|
|
265
|
+
if (metadataChanged(p.pack, p.versionState, { commit, pr }) && !s.drift) acc.drift += 1;
|
|
234
266
|
return acc;
|
|
235
267
|
}, {});
|
|
236
268
|
|
|
@@ -260,11 +292,13 @@ async function runApply(target, { dryRun = false, prune = false, yes = false, js
|
|
|
260
292
|
const results = [];
|
|
261
293
|
for (const p of planned) {
|
|
262
294
|
const todo = p.ops.filter((op) => ['create', 'update', 'replace', 'delete'].includes(op.op));
|
|
263
|
-
if (!todo.length && (
|
|
295
|
+
if (!todo.length && !metadataChanged(p.pack, p.versionState, { commit, pr })) continue;
|
|
264
296
|
if (p.versionState.supported) {
|
|
265
297
|
try {
|
|
266
298
|
await remote.applyPlan(p.pack.name, p.pack.version, todo, {
|
|
267
299
|
expectedVersion: p.versionState.version,
|
|
300
|
+
expectedApplicationId: p.versionState.provenanceSupported ? p.versionState.applicationId : undefined,
|
|
301
|
+
owner: p.versionState.provenanceSupported ? (p.pack.owner || null) : undefined, commit, pr, force,
|
|
268
302
|
});
|
|
269
303
|
results.push(...(todo.length ? todo.map((op) => ({ pack: p.pack.name, policy: op.serverName, op: op.op, status: 'ok', error: null }))
|
|
270
304
|
: [{ pack: p.pack.name, policy: null, op: 'version', status: 'ok', error: null }]));
|
|
@@ -327,6 +361,7 @@ console are never read for diffing and never written.
|
|
|
327
361
|
diff Show what apply would change; exit 1 when there is drift (CI)
|
|
328
362
|
apply Create and update policies from a file or folder (--prune deletes)
|
|
329
363
|
sync Folder is the source of truth: apply every pack with --prune
|
|
364
|
+
status Show the latest saved apply record for a pack
|
|
330
365
|
export Write the live policies of a pack back to YAML
|
|
331
366
|
adopt Mark console-made policies as managed by a pack (names stay)
|
|
332
367
|
delete Remove every policy a pack manages
|
|
@@ -382,6 +417,9 @@ Learn more: ${DOCS_PACKS}
|
|
|
382
417
|
.option('--dry-run', 'Print the plan and change nothing')
|
|
383
418
|
.option('--prune', 'Delete managed policies that are not in the file')
|
|
384
419
|
.option('--yes', 'Skip the confirmation prompt for deletes')
|
|
420
|
+
.option('--commit <sha>', 'Git commit associated with this apply')
|
|
421
|
+
.option('--pr <url>', 'Pull request associated with this apply')
|
|
422
|
+
.option('--force', 'Allow a pack version older than the live version')
|
|
385
423
|
.option('--json', 'Output the plan and results as JSON')
|
|
386
424
|
.addHelpText('after', `
|
|
387
425
|
Examples:
|
|
@@ -394,7 +432,7 @@ Learn more: ${DOCS_PACKS}
|
|
|
394
432
|
`)
|
|
395
433
|
.action(async (opts) => {
|
|
396
434
|
try {
|
|
397
|
-
const { failed } = await runApply(opts.file, { dryRun: !!opts.dryRun, prune: !!opts.prune, yes: !!opts.yes, json: !!opts.json, label: 'apply' });
|
|
435
|
+
const { failed } = await runApply(opts.file, { dryRun: !!opts.dryRun, prune: !!opts.prune, yes: !!opts.yes, json: !!opts.json, label: 'apply', commit: opts.commit, pr: opts.pr, force: !!opts.force });
|
|
398
436
|
if (failed) process.exitCode = 1;
|
|
399
437
|
} catch (err) {
|
|
400
438
|
fail(err);
|
|
@@ -406,6 +444,9 @@ Learn more: ${DOCS_PACKS}
|
|
|
406
444
|
.description('Make the org match a folder (or file) of pack files: apply every pack with --prune.')
|
|
407
445
|
.option('--dry-run', 'Print the plan and change nothing')
|
|
408
446
|
.option('--yes', 'Skip the confirmation prompt for deletes')
|
|
447
|
+
.option('--commit <sha>', 'Git commit associated with this sync')
|
|
448
|
+
.option('--pr <url>', 'Pull request associated with this sync')
|
|
449
|
+
.option('--force', 'Allow pack versions older than the live versions')
|
|
409
450
|
.option('--json', 'Output the plan and results as JSON')
|
|
410
451
|
.addHelpText('after', `
|
|
411
452
|
Examples:
|
|
@@ -417,13 +458,38 @@ A pack whose file is removed from the folder keeps its policies. Use
|
|
|
417
458
|
`)
|
|
418
459
|
.action(async (target, opts) => {
|
|
419
460
|
try {
|
|
420
|
-
const { failed } = await runApply(target, { dryRun: !!opts.dryRun, prune: true, yes: !!opts.yes, json: !!opts.json, label: 'sync' });
|
|
461
|
+
const { failed } = await runApply(target, { dryRun: !!opts.dryRun, prune: true, yes: !!opts.yes, json: !!opts.json, label: 'sync', commit: opts.commit, pr: opts.pr, force: !!opts.force });
|
|
421
462
|
if (failed) process.exitCode = 1;
|
|
422
463
|
} catch (err) {
|
|
423
464
|
fail(err);
|
|
424
465
|
}
|
|
425
466
|
});
|
|
426
467
|
|
|
468
|
+
pack
|
|
469
|
+
.command('status <pack>')
|
|
470
|
+
.description('Show the latest saved apply record for a pack.')
|
|
471
|
+
.option('--json', 'Print the saved record as JSON')
|
|
472
|
+
.action(async (packName, opts) => {
|
|
473
|
+
try {
|
|
474
|
+
requireLogin();
|
|
475
|
+
if (!SLUG_RE.test(packName)) throw new PackError('pack name must match [a-z0-9][a-z0-9-]{0,63}');
|
|
476
|
+
const state = await api.get(`/api/v1/packs/${encodeURIComponent(packName)}/`);
|
|
477
|
+
if (!['owner', 'commit', 'pr', 'application_id', 'applied_by_id', 'applied_at']
|
|
478
|
+
.every((field) => Object.prototype.hasOwnProperty.call(state, field))) {
|
|
479
|
+
throw new PackError('backend does not support pack metadata');
|
|
480
|
+
}
|
|
481
|
+
const record = {
|
|
482
|
+
name: packName, version: state.version, owner: state.owner, commit: state.commit,
|
|
483
|
+
pr: state.pr, application_id: state.application_id, applied_by_id: state.applied_by_id,
|
|
484
|
+
applied_at: state.applied_at,
|
|
485
|
+
};
|
|
486
|
+
if (opts.json) output.json(record);
|
|
487
|
+
else output.keyValue(Object.entries(record));
|
|
488
|
+
} catch (err) {
|
|
489
|
+
fail(err);
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
|
|
427
493
|
pack
|
|
428
494
|
.command('export [pack]')
|
|
429
495
|
.description('Write the live policies of a pack as a pack file.')
|
|
@@ -454,13 +520,13 @@ Examples:
|
|
|
454
520
|
}
|
|
455
521
|
fs.mkdirSync(opts.out, { recursive: true });
|
|
456
522
|
for (const name of [...packs.keys()].sort((a, b) => a.localeCompare(b))) {
|
|
457
|
-
const { live, version } = await fetchStablePack(name);
|
|
523
|
+
const { live, version, owner } = await fetchStablePack(name);
|
|
458
524
|
for (const { row } of live.unsupported) output.warn(`${row.name}: unsupported policy type, not exported.`);
|
|
459
525
|
if (!live.tool.length && !live.generic.length) {
|
|
460
526
|
output.warn(`pack "${name}": only unsupported policies, no file written.`);
|
|
461
527
|
continue;
|
|
462
528
|
}
|
|
463
|
-
const doc = liveToPack(name, live, ref, { version: opts.packVersion || version || '1.0.0' });
|
|
529
|
+
const doc = liveToPack(name, live, ref, { version: opts.packVersion || version || '1.0.0', owner });
|
|
464
530
|
writeOrPrint(serialize(doc), path.join(opts.out, `${name}${ext}`));
|
|
465
531
|
}
|
|
466
532
|
if (unmanaged.length) {
|
|
@@ -469,14 +535,14 @@ Examples:
|
|
|
469
535
|
return;
|
|
470
536
|
}
|
|
471
537
|
|
|
472
|
-
const { live, version } = await fetchStablePack(packName);
|
|
538
|
+
const { live, version, owner } = await fetchStablePack(packName);
|
|
473
539
|
for (const { row } of live.unsupported) output.warn(`${row.name}: unsupported policy type, not exported.`);
|
|
474
540
|
if (!live.tool.length && !live.generic.length) {
|
|
475
541
|
throw new PackError(live.unsupported.length
|
|
476
542
|
? `pack "${packName}" only has policies of types this CLI version does not manage; nothing to export`
|
|
477
543
|
: `pack "${packName}" manages no policies in this org`);
|
|
478
544
|
}
|
|
479
|
-
const doc = liveToPack(packName, live, ref, { version: opts.packVersion || version || '1.0.0' });
|
|
545
|
+
const doc = liveToPack(packName, live, ref, { version: opts.packVersion || version || '1.0.0', owner });
|
|
480
546
|
writeOrPrint(serialize(doc), opts.out);
|
|
481
547
|
} catch (err) {
|
|
482
548
|
fail(err);
|
|
@@ -547,17 +613,19 @@ manage the pack with apply.
|
|
|
547
613
|
await remote.applyPlan(packName, packVersion, adoptions.map((r) => ({
|
|
548
614
|
op: 'adopt', table: r.table, row: r.row,
|
|
549
615
|
body: { origin: 'CODE', code_pack: packName, code_slug: r.id },
|
|
550
|
-
})), { expectedVersion: versionState.version
|
|
616
|
+
})), { expectedVersion: versionState.version,
|
|
617
|
+
expectedApplicationId: versionState.provenanceSupported ? versionState.applicationId : undefined,
|
|
618
|
+
owner: versionState.provenanceSupported ? versionState.owner : undefined });
|
|
551
619
|
} else {
|
|
552
620
|
output.warn('Older backend: adopting policies one at a time; this run is not atomic.');
|
|
553
621
|
for (const r of adoptions) await remote.updateRow(r.table, r.row.id, { code_pack: packName, code_slug: r.id });
|
|
554
622
|
}
|
|
555
623
|
for (const r of adoptions) output.info(`Adopted "${r.row.name}" as ${packName}/${r.id}`);
|
|
556
624
|
const ref = await remote.loadReference();
|
|
557
|
-
const { live, version } = versionState.supported
|
|
625
|
+
const { live, version, owner } = versionState.supported
|
|
558
626
|
? await fetchStablePack(packName)
|
|
559
627
|
: { live: await remote.fetchManaged(packName), version: packVersion };
|
|
560
|
-
writeOrPrint(stringifyPack(liveToPack(packName, live, ref, { version: version || packVersion })), opts.out);
|
|
628
|
+
writeOrPrint(stringifyPack(liveToPack(packName, live, ref, { version: version || packVersion, owner })), opts.out);
|
|
561
629
|
} catch (err) {
|
|
562
630
|
fail(err);
|
|
563
631
|
}
|
|
@@ -597,7 +665,8 @@ manage the pack with apply.
|
|
|
597
665
|
if (versionState.supported) {
|
|
598
666
|
await remote.applyPlan(packName, opts.packVersion || versionState.version || '1.0.0',
|
|
599
667
|
rows.map(({ table, row }) => ({ op: 'delete', table, row })),
|
|
600
|
-
{ deletePack: true, expectedVersion: versionState.version
|
|
668
|
+
{ deletePack: true, expectedVersion: versionState.version,
|
|
669
|
+
expectedApplicationId: versionState.provenanceSupported ? versionState.applicationId : undefined });
|
|
601
670
|
for (const { row } of rows) output.success(`Deleted ${row.name}`);
|
|
602
671
|
if (!rows.length) output.success(`Pack "${packName}" has no policies; stored version advanced.`);
|
|
603
672
|
} else {
|
package/src/lib/pack-export.js
CHANGED
|
@@ -113,13 +113,14 @@ function genericRowToPolicy(row, ref) {
|
|
|
113
113
|
* Build a PolicyPack document from the live rows of one pack.
|
|
114
114
|
* live: { tool: [rows], generic: [rows] }
|
|
115
115
|
*/
|
|
116
|
-
function liveToPack(packName, live, ref, { version = '1.0.0', description } = {}) {
|
|
116
|
+
function liveToPack(packName, live, ref, { version = '1.0.0', description, owner } = {}) {
|
|
117
117
|
const policies = [
|
|
118
118
|
...(live.tool || []).map((r) => toolRowToPolicy(r)),
|
|
119
119
|
...(live.generic || []).map((r) => genericRowToPolicy(r, ref)),
|
|
120
120
|
].sort((a, b) => a.id.localeCompare(b.id));
|
|
121
121
|
const metadata = { name: packName, version };
|
|
122
122
|
if (description) metadata.description = description;
|
|
123
|
+
if (owner) metadata.owner = owner;
|
|
123
124
|
return { apiVersion: API_VERSION, kind: KIND, metadata, policies };
|
|
124
125
|
}
|
|
125
126
|
|
package/src/lib/pack-remote.js
CHANGED
|
@@ -197,14 +197,19 @@ async function deleteRow(table, id) {
|
|
|
197
197
|
async function fetchVersion(name) {
|
|
198
198
|
try {
|
|
199
199
|
const result = await api.get(PACK_PATH(name));
|
|
200
|
-
|
|
200
|
+
const provenanceSupported = ['owner', 'commit', 'pr', 'application_id']
|
|
201
|
+
.every((field) => Object.prototype.hasOwnProperty.call(result, field));
|
|
202
|
+
return { supported: true, provenanceSupported, applicationId: result.application_id ?? null,
|
|
203
|
+
version: result.version || null, owner: result.owner || null, commit: result.commit || null, pr: result.pr || null };
|
|
201
204
|
} catch (err) {
|
|
202
|
-
if (err && err.statusCode === 404) return { supported: false,
|
|
205
|
+
if (err && err.statusCode === 404) return { supported: false, provenanceSupported: false,
|
|
206
|
+
applicationId: null, version: null, owner: null, commit: null, pr: null };
|
|
203
207
|
throw err;
|
|
204
208
|
}
|
|
205
209
|
}
|
|
206
210
|
|
|
207
|
-
async function applyPlan(name, version, ops, { deletePack = false, expectedVersion = null
|
|
211
|
+
async function applyPlan(name, version, ops, { deletePack = false, expectedVersion = null, expectedApplicationId,
|
|
212
|
+
owner, commit, pr, force = false } = {}) {
|
|
208
213
|
const operations = ops.map((op) => {
|
|
209
214
|
const operation = { op: op.op, table: op.table };
|
|
210
215
|
if (op.row) operation.id = op.row.id;
|
|
@@ -219,7 +224,14 @@ async function applyPlan(name, version, ops, { deletePack = false, expectedVersi
|
|
|
219
224
|
return operation;
|
|
220
225
|
});
|
|
221
226
|
return api.post(`${PACK_PATH(name)}apply/`, {
|
|
222
|
-
body: {
|
|
227
|
+
body: {
|
|
228
|
+
version, expected_version: expectedVersion, operations, delete_pack: deletePack,
|
|
229
|
+
...(expectedApplicationId !== undefined ? { expected_application_id: expectedApplicationId } : {}),
|
|
230
|
+
...(owner !== undefined ? { owner } : {}),
|
|
231
|
+
...(commit !== undefined ? { commit } : {}),
|
|
232
|
+
...(pr !== undefined ? { pr } : {}),
|
|
233
|
+
...(force ? { force: true } : {}),
|
|
234
|
+
},
|
|
223
235
|
});
|
|
224
236
|
}
|
|
225
237
|
|
|
@@ -25,6 +25,33 @@ function runCli(file, port, home, args = ['apply', '-f', file, '--yes']) {
|
|
|
25
25
|
});
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
test('pack status shows the saved apply record in text and JSON', async () => {
|
|
29
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pack-status-'));
|
|
30
|
+
const record = {
|
|
31
|
+
name: 'sample', version: '2.0.0', owner: 'Security', commit: 'abc123',
|
|
32
|
+
pr: 'https://example.com/pr/1', application_id: 42, applied_by_id: 7,
|
|
33
|
+
applied_at: '2026-11-19T10:00:00Z',
|
|
34
|
+
};
|
|
35
|
+
const server = http.createServer((req, res) => {
|
|
36
|
+
assert.equal(req.url, '/api/v1/packs/sample/');
|
|
37
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
38
|
+
res.end(JSON.stringify(record));
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
42
|
+
const json = await runCli(null, server.address().port, home, ['status', 'sample', '--json']);
|
|
43
|
+
assert.equal(json.code, 0, json.stderr);
|
|
44
|
+
assert.deepEqual(JSON.parse(json.stdout), record);
|
|
45
|
+
const text = await runCli(null, server.address().port, home, ['status', 'sample']);
|
|
46
|
+
assert.equal(text.code, 0, text.stderr);
|
|
47
|
+
assert.match(text.stdout, /application_id\s+42/);
|
|
48
|
+
assert.match(text.stdout, /applied_at\s+2026-11-19T10:00:00Z/);
|
|
49
|
+
} finally {
|
|
50
|
+
server.close();
|
|
51
|
+
fs.rmSync(home, { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
28
55
|
test('two CLI applies produce one success and one clear lock conflict', async () => {
|
|
29
56
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pack-cli-'));
|
|
30
57
|
const file = path.join(home, 'pack.yaml');
|
|
@@ -96,7 +123,7 @@ test('folder apply continues after one pack fails atomically', async () => {
|
|
|
96
123
|
for (const name of ['alpha', 'beta']) {
|
|
97
124
|
fs.writeFileSync(path.join(home, `${name}.yaml`), [
|
|
98
125
|
'apiVersion: unbound.security/v1', 'kind: PolicyPack', 'metadata:',
|
|
99
|
-
` name: ${name}`, ' version: 1.0.0', 'policies:',
|
|
126
|
+
` name: ${name}`, ' version: 1.0.0', ' owner: Security', 'policies:',
|
|
100
127
|
` - id: ${name}-budget`, ' kind: cost', ' config:', ' monthly_budget: 500', '',
|
|
101
128
|
].join('\n'));
|
|
102
129
|
}
|
|
@@ -115,10 +142,15 @@ test('folder apply continues after one pack fails atomically', async () => {
|
|
|
115
142
|
const match = req.url.match(/^\/api\/v1\/packs\/(alpha|beta)\/(apply\/)?$/);
|
|
116
143
|
if (match && req.method === 'GET') return send(200, { name: match[1], version: null });
|
|
117
144
|
if (match && req.method === 'POST') {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
145
|
+
const chunks = [];
|
|
146
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
147
|
+
req.on('end', () => {
|
|
148
|
+
posts.push({ name: match[1], body: JSON.parse(Buffer.concat(chunks).toString()) });
|
|
149
|
+
return match[1] === 'alpha'
|
|
150
|
+
? send(409, { error: 'another apply is running, retry' })
|
|
151
|
+
: send(200, { name: 'beta', version: '1.0.0', operations_applied: 1 });
|
|
152
|
+
});
|
|
153
|
+
return;
|
|
122
154
|
}
|
|
123
155
|
return send(404, { error: 'not found' });
|
|
124
156
|
});
|
|
@@ -126,20 +158,27 @@ test('folder apply continues after one pack fails atomically', async () => {
|
|
|
126
158
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
127
159
|
const result = await runCli(home, server.address().port, home);
|
|
128
160
|
assert.equal(result.code, 1);
|
|
129
|
-
assert.deepEqual(posts, ['alpha', 'beta']);
|
|
161
|
+
assert.deepEqual(posts.map(({ name }) => name), ['alpha', 'beta']);
|
|
162
|
+
for (const { body } of posts) {
|
|
163
|
+
for (const field of ['owner', 'commit', 'pr', 'force']) assert.equal(field in body, false);
|
|
164
|
+
}
|
|
130
165
|
assert.match(result.stderr, /another apply is running, retry/i);
|
|
166
|
+
const provenance = await runCli(home, server.address().port, home, ['apply', '-f', home, '--commit', 'abc123']);
|
|
167
|
+
assert.notEqual(provenance.code, 0);
|
|
168
|
+
assert.match(provenance.stderr, /pack provenance and forced downgrades require a newer backend/);
|
|
169
|
+
assert.equal(posts.length, 2);
|
|
131
170
|
} finally {
|
|
132
171
|
server.close();
|
|
133
172
|
fs.rmSync(home, { recursive: true, force: true });
|
|
134
173
|
}
|
|
135
174
|
});
|
|
136
175
|
|
|
137
|
-
test('in-sync
|
|
176
|
+
test('in-sync owner-bearing pack on an older backend has no drift or empty write', async () => {
|
|
138
177
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pack-noop-'));
|
|
139
178
|
const file = path.join(home, 'sample.yaml');
|
|
140
179
|
fs.writeFileSync(file, [
|
|
141
180
|
'apiVersion: unbound.security/v1', 'kind: PolicyPack', 'metadata:',
|
|
142
|
-
' name: sample', ' version: 1.0.0', 'policies:',
|
|
181
|
+
' name: sample', ' version: 1.0.0', ' owner: Security', 'policies:',
|
|
143
182
|
' - id: budget', ' kind: cost', ' config:', ' monthly_budget: 500', '',
|
|
144
183
|
].join('\n'));
|
|
145
184
|
let posts = 0;
|
|
@@ -165,8 +204,12 @@ test('in-sync apply avoids an empty write', async () => {
|
|
|
165
204
|
});
|
|
166
205
|
try {
|
|
167
206
|
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
207
|
+
const diff = await runCli(file, server.address().port, home, ['diff', '-f', file, '--json']);
|
|
208
|
+
assert.equal(diff.code, 0, diff.stderr);
|
|
209
|
+
assert.equal(JSON.parse(diff.stdout).packs[0].summary.drift, 0);
|
|
168
210
|
const result = await runCli(file, server.address().port, home);
|
|
169
211
|
assert.equal(result.code, 0, result.stderr);
|
|
212
|
+
assert.doesNotMatch(result.stdout, /Stored owner:/);
|
|
170
213
|
assert.equal(posts, 0);
|
|
171
214
|
} finally {
|
|
172
215
|
server.close();
|
|
@@ -207,7 +250,7 @@ test('version-only apply stores the new version with an empty plan', async () =>
|
|
|
207
250
|
const file = path.join(home, 'sample.yaml');
|
|
208
251
|
fs.writeFileSync(file, [
|
|
209
252
|
'apiVersion: unbound.security/v1', 'kind: PolicyPack', 'metadata:',
|
|
210
|
-
' name: sample', ' version: 2.0.0', 'policies:',
|
|
253
|
+
' name: sample', ' version: 2.0.0', ' owner: Security', 'policies:',
|
|
211
254
|
' - id: budget', ' kind: cost', ' config:', ' monthly_budget: 500', '',
|
|
212
255
|
].join('\n'));
|
|
213
256
|
const row = {
|
|
@@ -216,6 +259,10 @@ test('version-only apply stores the new version with an empty plan', async () =>
|
|
|
216
259
|
scope_user_groups: [], scope_tool_types: [], labels: [],
|
|
217
260
|
};
|
|
218
261
|
let version = '1.0.0';
|
|
262
|
+
let owner = null;
|
|
263
|
+
let commit = null;
|
|
264
|
+
let pr = null;
|
|
265
|
+
let applicationId = 7;
|
|
219
266
|
const writes = [];
|
|
220
267
|
const server = http.createServer((req, res) => {
|
|
221
268
|
const send = (status, body) => {
|
|
@@ -226,10 +273,18 @@ test('version-only apply stores the new version with an empty plan', async () =>
|
|
|
226
273
|
if (req.url.startsWith('/api/v1/labels/')) return send(200, { labels: [] });
|
|
227
274
|
if (req.url.startsWith('/api/v1/command-policies/')) return send(200, { policies: [], total_pages: 1 });
|
|
228
275
|
if (req.url.startsWith('/api/v1/policies/')) return send(200, { policies: [row] });
|
|
229
|
-
if (req.url === '/api/v1/packs/sample/' && req.method === 'GET') return send(200, { name: 'sample', version });
|
|
276
|
+
if (req.url === '/api/v1/packs/sample/' && req.method === 'GET') return send(200, { name: 'sample', version, owner, commit, pr, application_id: applicationId });
|
|
230
277
|
if (req.url === '/api/v1/packs/sample/apply/' && req.method === 'POST') {
|
|
231
278
|
req.on('data', (chunk) => writes.push(chunk));
|
|
232
|
-
req.on('end', () => {
|
|
279
|
+
req.on('end', () => {
|
|
280
|
+
const body = JSON.parse(Buffer.concat(writes).toString());
|
|
281
|
+
version = body.version;
|
|
282
|
+
owner = body.owner;
|
|
283
|
+
commit = body.commit;
|
|
284
|
+
pr = body.pr;
|
|
285
|
+
applicationId += 1;
|
|
286
|
+
send(200, { name: 'sample', version, operations_applied: 0 });
|
|
287
|
+
});
|
|
233
288
|
return;
|
|
234
289
|
}
|
|
235
290
|
return send(404, { error: 'not found' });
|
|
@@ -239,10 +294,31 @@ test('version-only apply stores the new version with an empty plan', async () =>
|
|
|
239
294
|
const diff = await runCli(file, server.address().port, home, ['diff', '-f', file, '--json']);
|
|
240
295
|
assert.equal(diff.code, 1, diff.stderr);
|
|
241
296
|
assert.equal(JSON.parse(diff.stdout).packs[0].summary.drift, 1);
|
|
242
|
-
|
|
297
|
+
assert.deepEqual(JSON.parse(diff.stdout).packs[0].metadata, {
|
|
298
|
+
version: { before: '1.0.0', after: '2.0.0' },
|
|
299
|
+
owner: { before: null, after: 'Security' },
|
|
300
|
+
});
|
|
301
|
+
const result = await runCli(file, server.address().port, home, ['apply', '-f', file, '--commit', 'abc123', '--pr', 'https://github.com/example/pull/1', '--force']);
|
|
243
302
|
assert.equal(result.code, 0, result.stderr);
|
|
244
303
|
assert.equal(version, '2.0.0');
|
|
245
|
-
assert.deepEqual(JSON.parse(Buffer.concat(writes).toString())
|
|
304
|
+
assert.deepEqual(JSON.parse(Buffer.concat(writes).toString()), {
|
|
305
|
+
version: '2.0.0', expected_version: '1.0.0', expected_application_id: 7,
|
|
306
|
+
operations: [], delete_pack: false,
|
|
307
|
+
owner: 'Security', commit: 'abc123', pr: 'https://github.com/example/pull/1', force: true,
|
|
308
|
+
});
|
|
309
|
+
const exported = await runCli(null, server.address().port, home, ['export', 'sample', '--json']);
|
|
310
|
+
assert.equal(exported.code, 0, exported.stderr);
|
|
311
|
+
assert.deepEqual(JSON.parse(exported.stdout).metadata, { name: 'sample', version: '2.0.0', owner: 'Security' });
|
|
312
|
+
writes.length = 0;
|
|
313
|
+
const provenance = ['apply', '-f', file, '--commit', 'def456', '--pr', pr];
|
|
314
|
+
const changed = await runCli(file, server.address().port, home, provenance);
|
|
315
|
+
assert.equal(changed.code, 0, changed.stderr);
|
|
316
|
+
assert.equal(JSON.parse(Buffer.concat(writes).toString()).commit, 'def456');
|
|
317
|
+
writes.length = 0;
|
|
318
|
+
const unchanged = await runCli(file, server.address().port, home, provenance);
|
|
319
|
+
assert.equal(unchanged.code, 0, unchanged.stderr);
|
|
320
|
+
assert.match(unchanged.stdout, /Already in sync/);
|
|
321
|
+
assert.equal(writes.length, 0);
|
|
246
322
|
} finally {
|
|
247
323
|
server.close();
|
|
248
324
|
fs.rmSync(home, { recursive: true, force: true });
|
|
@@ -310,3 +386,49 @@ test('adopt refuses to print a pack changed during the final read', async () =>
|
|
|
310
386
|
fs.rmSync(home, { recursive: true, force: true });
|
|
311
387
|
}
|
|
312
388
|
});
|
|
389
|
+
|
|
390
|
+
test('adopt keeps the stored owner in the apply and generated pack', async () => {
|
|
391
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pack-adopt-owner-'));
|
|
392
|
+
const row = { id: 5, name: 'Budget', type: 'COST', origin: 'MANUAL', enabled: true,
|
|
393
|
+
status: 'ACTIVE', config: { monthly_budget: 500 }, scope_user_groups: [],
|
|
394
|
+
scope_tool_types: [], labels: [] };
|
|
395
|
+
let owner = 'Security';
|
|
396
|
+
let body;
|
|
397
|
+
const server = http.createServer((req, res) => {
|
|
398
|
+
const send = (status, data) => {
|
|
399
|
+
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
400
|
+
res.end(JSON.stringify(data));
|
|
401
|
+
};
|
|
402
|
+
if (req.url.startsWith('/api/v1/policies/form_data/')) return send(200, { user_groups: [], guardrails: [], ai_models: [], tool_types: [] });
|
|
403
|
+
if (req.url.startsWith('/api/v1/labels/')) return send(200, { labels: [] });
|
|
404
|
+
if (req.url.startsWith('/api/v1/command-policies/')) return send(200, { policies: [], total_pages: 1 });
|
|
405
|
+
if (req.url.startsWith('/api/v1/policies/')) return send(200, { policies: [row] });
|
|
406
|
+
if (req.url === '/api/v1/packs/sample/' && req.method === 'GET') {
|
|
407
|
+
return send(200, { name: 'sample', version: '2.0.0', owner, commit: null, pr: null, application_id: 7 });
|
|
408
|
+
}
|
|
409
|
+
if (req.url === '/api/v1/packs/sample/apply/' && req.method === 'POST') {
|
|
410
|
+
const chunks = [];
|
|
411
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
412
|
+
req.on('end', () => {
|
|
413
|
+
body = JSON.parse(Buffer.concat(chunks).toString());
|
|
414
|
+
owner = body.owner;
|
|
415
|
+
Object.assign(row, { origin: 'CODE', code_pack: 'sample', code_slug: 'budget' });
|
|
416
|
+
send(200, { name: 'sample', version: '2.0.0', operations_applied: 1 });
|
|
417
|
+
});
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
return send(404, { error: 'not found' });
|
|
421
|
+
});
|
|
422
|
+
try {
|
|
423
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
424
|
+
const result = await runCli(null, server.address().port, home,
|
|
425
|
+
['adopt', 'sample', '--from', 'Budget', '--pack-version', '2.0.0', '--yes']);
|
|
426
|
+
assert.equal(result.code, 0, result.stderr);
|
|
427
|
+
assert.equal(body.owner, 'Security');
|
|
428
|
+
assert.equal(body.expected_application_id, 7);
|
|
429
|
+
assert.match(result.stdout, /owner: Security/);
|
|
430
|
+
} finally {
|
|
431
|
+
server.close();
|
|
432
|
+
fs.rmSync(home, { recursive: true, force: true });
|
|
433
|
+
}
|
|
434
|
+
});
|
|
@@ -48,7 +48,21 @@ test('export accepts rows bracketed by the same stored version', async () => {
|
|
|
48
48
|
remote.fetchVersion = async () => ({ supported: true, version: '2.0.0' });
|
|
49
49
|
remote.fetchManaged = async () => live;
|
|
50
50
|
try {
|
|
51
|
-
assert.deepEqual(await fetchStablePack('sample'), { live, version: '2.0.0' });
|
|
51
|
+
assert.deepEqual(await fetchStablePack('sample'), { live, version: '2.0.0', owner: undefined });
|
|
52
|
+
} finally {
|
|
53
|
+
remote.fetchVersion = fetchVersion;
|
|
54
|
+
remote.fetchManaged = fetchManaged;
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('export refuses rows read across a stored owner change', async () => {
|
|
59
|
+
const fetchVersion = remote.fetchVersion;
|
|
60
|
+
const fetchManaged = remote.fetchManaged;
|
|
61
|
+
let reads = 0;
|
|
62
|
+
remote.fetchVersion = async () => ({ supported: true, version: '2.0.0', owner: ++reads === 1 ? 'Security' : 'Platform' });
|
|
63
|
+
remote.fetchManaged = async () => ({ generic: [], tool: [], unsupported: [] });
|
|
64
|
+
try {
|
|
65
|
+
await assert.rejects(() => fetchStablePack('sample'), /changed during export; retry/);
|
|
52
66
|
} finally {
|
|
53
67
|
remote.fetchVersion = fetchVersion;
|
|
54
68
|
remote.fetchManaged = fetchManaged;
|
package/test/pack-export.test.js
CHANGED
|
@@ -27,9 +27,9 @@ const LIVE = {
|
|
|
27
27
|
};
|
|
28
28
|
|
|
29
29
|
test('liveToPack: ids become names and sugar is restored', () => {
|
|
30
|
-
const doc = exp.liveToPack('base', LIVE, REF, { version: '2.0.0' });
|
|
30
|
+
const doc = exp.liveToPack('base', LIVE, REF, { version: '2.0.0', owner: 'Security' });
|
|
31
31
|
assert.equal(doc.apiVersion, 'unbound.security/v1');
|
|
32
|
-
assert.deepEqual(doc.metadata, { name: 'base', version: '2.0.0' });
|
|
32
|
+
assert.deepEqual(doc.metadata, { name: 'base', version: '2.0.0', owner: 'Security' });
|
|
33
33
|
const byId = Object.fromEntries(doc.policies.map((p) => [p.id, p]));
|
|
34
34
|
assert.deepEqual(byId['no-rm'], { id: 'no-rm', kind: 'tool', type: 'TERMINAL_COMMAND', action: 'BLOCK', enabled: false, description: 'd', customMessage: 'no', commandFamily: 'custom', config: { command: 'rm -rf*' }, scope: { userGroups: ['Engineering'] } });
|
|
35
35
|
assert.deepEqual(byId['gh-writes'].mcp, { server: 'GitHub', tools: ['push_files'] });
|
package/test/pack-remote.test.js
CHANGED
|
@@ -27,10 +27,19 @@ function reset() {
|
|
|
27
27
|
|
|
28
28
|
test('fetchVersion preserves a stored version and only treats 404 as an old backend', async () => {
|
|
29
29
|
reset();
|
|
30
|
+
stub.onGet = async () => ({ name: 'base', version: '2.0.0', owner: 'Security', commit: 'abc123', pr: 'https://github.com/example/pull/1', application_id: 17 });
|
|
31
|
+
assert.deepEqual(await remote.fetchVersion('base'), {
|
|
32
|
+
supported: true, provenanceSupported: true, applicationId: 17,
|
|
33
|
+
version: '2.0.0', owner: 'Security', commit: 'abc123', pr: 'https://github.com/example/pull/1',
|
|
34
|
+
});
|
|
30
35
|
stub.onGet = async () => ({ name: 'base', version: '2.0.0' });
|
|
31
|
-
assert.deepEqual(await remote.fetchVersion('base'), {
|
|
36
|
+
assert.deepEqual(await remote.fetchVersion('base'), {
|
|
37
|
+
supported: true, provenanceSupported: false, applicationId: null,
|
|
38
|
+
version: '2.0.0', owner: null, commit: null, pr: null,
|
|
39
|
+
});
|
|
32
40
|
stub.onGet = async () => { throw Object.assign(new Error('missing'), { statusCode: 404 }); };
|
|
33
|
-
assert.deepEqual(await remote.fetchVersion('base'), { supported: false,
|
|
41
|
+
assert.deepEqual(await remote.fetchVersion('base'), { supported: false, provenanceSupported: false,
|
|
42
|
+
applicationId: null, version: null, owner: null, commit: null, pr: null });
|
|
34
43
|
stub.onGet = async () => { throw Object.assign(new Error('unavailable'), { statusCode: 503 }); };
|
|
35
44
|
await assert.rejects(() => remote.fetchVersion('base'), /unavailable/);
|
|
36
45
|
});
|
|
@@ -41,11 +50,12 @@ test('applyPlan submits all operations in one request with a stored-version chec
|
|
|
41
50
|
{ op: 'update', table: 'tool', row: { id: 7, code_slug: 'tool' },
|
|
42
51
|
desired: { id: 'tool' }, body: { action: 'AUDIT' } },
|
|
43
52
|
{ op: 'delete', table: 'generic', row: { id: 9 } },
|
|
44
|
-
], { expectedVersion: '2.0.0' });
|
|
53
|
+
], { expectedVersion: '2.0.0', expectedApplicationId: 17, owner: 'Security', commit: 'abc123', pr: 'https://github.com/example/pull/1', force: true });
|
|
45
54
|
assert.equal(calls.length, 1);
|
|
46
55
|
assert.equal(calls[0][1], '/api/v1/packs/base/apply/');
|
|
47
56
|
assert.deepEqual(calls[0][2].body, {
|
|
48
|
-
version: '3.0.0', expected_version: '2.0.0', delete_pack: false,
|
|
57
|
+
version: '3.0.0', expected_version: '2.0.0', expected_application_id: 17, delete_pack: false,
|
|
58
|
+
owner: 'Security', commit: 'abc123', pr: 'https://github.com/example/pull/1', force: true,
|
|
49
59
|
operations: [
|
|
50
60
|
{ op: 'update', table: 'tool', id: 7, body: {
|
|
51
61
|
action: 'AUDIT', origin: 'CODE', code_pack: 'base', code_slug: 'tool',
|