Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1393,8 +1393,10 @@ buttons appear only once all three pass.
refused and the read permissions the check needs, and a missing agent space shows
`enable security` to run again.

Steps 1 and 2 read local files only, and their card checks again every 10 seconds while it is open,
so it moves on by itself once you have run the command. A repo override is shown as information on
Steps 1 and 2 read local files only, and their card checks again every 10 seconds while it is open
and the tab is visible, so it moves on by itself once you have run the command. That re-check reads
only what the two steps need, for the picked repo (the AWS and `aws connect` files, `AWS_PROFILE`
and the setup records): no git and no scan of your other repos, which happens once the step passes. A repo override is shown as information on
the ready page, and a repo's code review is created by its first code review run, so neither is a
step.

Expand Down
4 changes: 2 additions & 2 deletions cli/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@prism-d1/cli",
"version": "1.19.0",
"version": "1.19.1",
"description": "PRISM D1 Velocity CLI — AI development lifecycle assessment tool",
"author": "andklee",
"engines": {
Expand Down
28 changes: 25 additions & 3 deletions cli/src/dashboard/security-agent.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
/**
* The Security Agent page's server side (#security, #security/<repo-id>).
*
* GET /api/security-agent/gate?repo=<id> is the light re-check the gate card
* runs every 10 s while step 1 or 2 is on screen: one repo, already known from
* the last full answer, from the AWS files, the aws connect files, the env and
* the setup records only. No git, no result files, no repo scan.
*
* GET /api/security-agent makes no AWS call: per discovered repo it returns the
* account and region prism-cli would use there (aws-identity.ts, from env and
* local files; the region of the Security Agent setup record wins, as in the
Expand Down Expand Up @@ -319,7 +324,10 @@ export const identityIn = (d: Pick<SecurityAgentDeps, 'identity'>, repoPath: str
* setup only). A repo override git tracks is ignored here too, as in the CLI, so
* a committed file never picks the region the Run actions get.
*/
export const setupIn = (d: Pick<SecurityAgentDeps, 'identity'>, repoPath: string | null): ResolvedSetup | null => loadSetup(d.identity.home, repoPath, (a) => run('git', a));
export const setupIn = (d: Pick<SecurityAgentDeps, 'identity'>, repoPath: string | null, light = false): ResolvedSetup | null =>
// light (the gate re-check): no git, so a repo override counts even when git tracks it; the full answer, which
// the page loads as soon as the step passes, applies the tracked-file rule and has the last word.
loadSetup(d.identity.home, repoPath, light ? undefined : (a) => run('git', a));

/** --profile/--region for the security commands in `repoPath`: the identity there, with the setup record's region, as the CLI resolves it. */
export function securityTargetIn(d: Pick<SecurityAgentDeps, 'identity'>, repoPath: string | null): AwsTargetArgs {
Expand Down Expand Up @@ -353,14 +361,14 @@ const shellWord = (p: string) => (/^[~A-Za-z0-9_./@%+,:=-]+$/.test(p) ? p : `'${
* space use the region the commands use there; the two for another account
* (--repo, --replace) use the connected profile's own region.
*/
export function gateIn(d: Pick<SecurityAgentDeps, 'identity' | 'cache'>, repoPath: string, repoName: string): Gate {
export function gateIn(d: Pick<SecurityAgentDeps, 'identity' | 'cache'>, repoPath: string, repoName: string, light = false): Gate {
const home = d.identity.home;
const idn = identityIn(d, repoPath);
const t = securityTargetIn(d, repoPath);
const connected = awsTargetFor(idn);
const saved = idn.saved?.inUse ? loadConnection(home, repoPath) : null;
return computeGate({
identity: idn, savedAccount: saved?.account ?? null, setup: setupIn(d, repoPath),
identity: idn, savedAccount: saved?.account ?? null, setup: setupIn(d, repoPath, light),
lookup: d.cache.peek(t), lookupAccount: d.cache.account(t), repoName, region: t.region,
commands: {
setup: displayCommand([...ENABLE_SECURITY_ARGS, ...targetArgs(t)]),
Expand Down Expand Up @@ -391,9 +399,23 @@ export async function writeGateIn(d: Pick<SecurityAgentDeps, 'identity' | 'cache
return writeNotice(kind, repo.name, d.cache.fresh(t)).reason ?? await d.cache.verify(t);
}

/** The repos the last full answer listed, per deps: the only ids the light gate re-check accepts. */
const KNOWN = new WeakMap<object, Map<string, ScanRepo>>();

/**
* GET /api/security-agent/gate?repo=<id>: the gate for one repo the last full
* answer named, with no git, no result-file read and no repo scan. null when
* the id is not one of them (the page then loads the full answer).
*/
export function securityAgentGate(d: Pick<SecurityAgentDeps, 'identity' | 'cache'>, id: string | null): { repo: string; gate: Gate } | null {
const r = id && /^[a-f0-9]{16}$/.test(id) ? KNOWN.get(d)?.get(id) : undefined;
return r ? { repo: r.id, gate: gateIn(d, r.path, r.name, true) } : null;
}

/** GET /api/security-agent: no AWS call. */
export async function securityAgentView(d: SecurityAgentDeps) {
const repos = await d.repos();
KNOWN.set(d, new Map(repos.map((r) => [r.id, { id: r.id, name: r.name, path: r.path }])));
return {
repos: repos.map((r) => {
const idn = identityIn(d, r.path);
Expand Down
32 changes: 27 additions & 5 deletions cli/src/dashboard/security-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
* First the setup gate (security-gate.ts): three steps, checked in order,
* and only the first one not met is shown, as one card with "step n of 3".
* Steps 1 and 2 read local files only, and their card checks again every
* 10 s (GET /api/security-agent) while it is open. Step 3 is the read-only
* 10 s while it is open and the tab is visible, through the light
* GET /api/security-agent/gate (one repo, no git, no repo scan); only when
* the step passes does the page load the full answer again. Step 3 is the read-only
* agent-space lookup: once steps 1 and 2 pass, the page starts it by itself,
* once per repo and profile and region (never on the minute refresh), and
* the server keeps the answer for the dashboard session; Check again and
Expand Down Expand Up @@ -348,16 +350,36 @@ function saAuto(repo) {
saLookup(repo, false);
}

/** Steps 1 and 2 check again every SA_POLL_MS while their card is on screen: GET /api/security-agent, local files only. */
/** Steps 1 and 2 check again every SA_POLL_MS while their card is on screen and the tab is visible (a hidden tab fetches nothing). */
function saSchedule(g) {
const poll = !SNAPSHOT && !!g && SA_POLL_STATES.includes(g.state) && currentView() === 'security';
// A redraw while one is pending keeps it: other loads (the heatmap's 3 s polls) must not push it back forever.
if (poll && SA_TIMER) return;
if (SA_TIMER) { clearTimeout(SA_TIMER); SA_TIMER = null; }
if (SNAPSHOT || !g || !SA_POLL_STATES.includes(g.state) || currentView() !== 'security') return;
SA_TIMER = setTimeout(() => { SA_TIMER = null; if (document.visibilityState === 'visible') renderSecurity(); else saSchedule(g); }, SA_POLL_MS);
if (!poll) return;
SA_TIMER = setTimeout(() => { SA_TIMER = null; if (document.visibilityState === 'visible') saRecheck(); else saSchedule(g); }, SA_POLL_MS);
}

/**
* The light re-check: GET /api/security-agent/gate for the picked repo (local
* files only, no git, no repo scan). Still on step 1 or 2: redraw the card
* only when the answer changed. Past it, or not answered: the full answer.
*/
async function saRecheck(force) {
const repo = saRepo();
if (!repo) return renderSecurity();
let r;
try { r = await api('/api/security-agent/gate?repo=' + repo.id); } catch (e) { r = { ok: false }; }
const g = r.ok && r.json && r.json.gate;
if (!g || !SA_POLL_STATES.includes(g.state)) return renderSecurity();
const same = JSON.stringify(g) === JSON.stringify(repo.gate);
repo.gate = g;
if (same && !force) saSchedule(g); else drawSecurity();
}

const saCheckAgain = (label) => {
const b = el('button', { type: 'button', class: 'run' }, label);
b.addEventListener('click', () => { b.disabled = true; renderSecurity(); });
b.addEventListener('click', () => { b.disabled = true; saRecheck(true); });
return b;
};
const saRetry = (repo, label) => {
Expand Down
8 changes: 7 additions & 1 deletion cli/src/dashboard/setup-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* POST /api/accountguard/baseline {run}: mark a run as the baseline (a local file only)
* POST /api/update-check asks the npm registry for the latest prism-cli now (one GET)
* GET /api/security-agent the Security Agent page's data (no AWS call; security-agent.ts)
* GET /api/security-agent/gate?repo=<id> the gate card's re-check for one repo (local files only, no git)
* POST /api/security-agent/spaces {repo, refresh?}: the read-only agent-space lookup
* GET /api/security-run?repo=<id>&run=<id> one security run's findings (local result files; security-runs.ts)
* Account ids and ARNs appear only here and in the page, never in `dashboard --json`.
Expand All @@ -18,7 +19,7 @@ import { profileChoices, resolveAwsIdentity, type IdentityDeps } from './aws-ide
import { accountGuardView, setBaseline, type AccountGuardDeps } from './accountguard.js';
import { tildeHome } from './payload.js';
import type { VersionInfo } from './update-check.js';
import { securityAgentLookup, securityAgentView, type SecurityAgentDeps } from './security-agent.js';
import { securityAgentGate, securityAgentLookup, securityAgentView, type SecurityAgentDeps } from './security-agent.js';
import { securityRunDetail } from './security-runs.js';
import { ApiAnswer } from './server.js';

Expand Down Expand Up @@ -79,6 +80,11 @@ export function setupApi(d: SetupApiDeps) {
'/api/action/status': async () => d.runner.status(),
'/api/recheck': async () => d.refresh(),
'/api/security-agent': async () => (d.securityAgent ? securityAgentView(d.securityAgent) : { repos: [], ttlSec: 0 }),
// The gate card's 10 s re-check: one known repo, local files only (no git, no repo scan). 404: load the full answer.
'/api/security-agent/gate': async (url: URL) => {
const g = d.securityAgent ? securityAgentGate(d.securityAgent, url.searchParams.get('repo')) : null;
return g ?? new ApiAnswer(404, { error: 'not a repo from the last Security Agent answer' });
},
'/api/accountguard': async () => (d.accountGuard ? accountGuardView(d.accountGuard) : null),
// Ids only: the repo id is matched against the scan list and the run id against that repo's result files.
// No such run answers 404 (the page shows Run not found and stops asking); any other failure is retried.
Expand Down
63 changes: 57 additions & 6 deletions cli/test/dashboard-security-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { buildPayload, type DashboardPayload } from '../src/dashboard/payload.js';
import { ACTIONS, ActionRunner, repoId, type ActionId, type ScanRepo } from '../src/dashboard/actions.js';
import {
awsTargetFor, commandLine, execAwsCall, identityIn, LOOKUP_TIMEOUT_MS, LookupCache, lookupSpaces, SECURITY_ACTIONS,
securityAgentLookup, securityAgentView, targetArgs, WRITE_KIND, writeNotice, type AwsCall, type Lookup, type SecurityAgentDeps,
securityAgentGate, securityAgentLookup, securityAgentView, targetArgs, WRITE_KIND, writeNotice, type AwsCall, type Lookup, type SecurityAgentDeps,
} from '../src/dashboard/security-agent.js';
import { setupApi } from '../src/dashboard/setup-api.js';
import type { Gate, GateState } from '../src/dashboard/security-gate.js';
Expand Down Expand Up @@ -438,21 +438,39 @@ test('gate step 1 and 2: Settings › AWS link, enable security copy-only with n
assert.equal(posts(conn).length, 0, 'no lookup before steps 1 and 2 pass');

const cmd = 'prism-cli enable security --profile demo --region us-west-2';
const page = await runPage([p], '#security', SETUP, { '/api/security-agent': saAnswer(p, null, 0, false, gate('setup', { copy: { setup: cmd } })) });
let light: Gate = gate('setup', { copy: { setup: cmd } });
const gateUrl = '/api/security-agent/gate?repo=' + p.repos[0].id;
const page = await runPage([p], '#security', SETUP, { '/api/security-agent': () => saAnswer(p, null, 0, false, light), [gateUrl]: () => ({ repo: p.repos[0].id, gate: light }) });
const sec = page.dom.byId.security;
assert.match(sec.textContent, new RegExp(cmd.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&') + 'Copy'));
assert.doesNotMatch(sec.textContent, /cd \S+ && prism-cli enable security/, 'once per machine: no cd');
assert.equal(btn(sec, 'Run'), undefined, 'enable security never runs from the page');
const gets = () => page.requests.filter((r) => r.url === '/api/security-agent').length;
const lights = () => page.requests.filter((r) => r.url === gateUrl).length;
assert.equal(page.pendingTimers().length, 1, 'one 10 s re-check held');
assert.equal(page.pendingTimers()[0].ms, 10000);
await page.reload();
assert.equal(page.pendingTimers().length, 1, 'a redraw keeps the pending re-check instead of pushing it back');
const before = gets();
await page.fireTimers();
assert.equal(gets(), before + 1, 'the re-check reads GET /api/security-agent (no AWS call)');
assert.deepEqual([lights(), gets()], [1, before], 'the re-check is the light gate endpoint for the picked repo, not the full answer');
assert.equal(page.pendingTimers().length, 1, 'and it waits again');
(page.dom.document as { visibilityState: string }).visibilityState = 'hidden';
await page.fireTimers();
assert.equal(lights(), 1, 'a hidden tab fetches nothing');
assert.equal(page.pendingTimers().length, 1, 'it only waits');
(page.dom.document as { visibilityState: string }).visibilityState = 'visible';
btn(page.dom.byId.security, 'I ran it, check again')!.listeners.click();
await page.settle();
assert.deepEqual([lights(), gets()], [2, before]);
assert.equal(posts(page).length, 0);
btn(sec, 'I ran it, check again')!.listeners.click();
// The step passes: then, and only then, the full answer.
light = gate('checking');
await page.fireTimers();
await page.settle();
assert.equal(gets(), before + 2);
assert.equal(lights(), 3);
assert.equal(posts(page).length, 1, 'past step 2: the full answer, then step 3 starts its lookup');
assert.equal(gets(), before + 2, 'one full answer for the step, one after the lookup');

const m = await runPage([p], '#security', SETUP, { '/api/security-agent': saAnswer(p, null, 0, true, gate('mismatch', { copy: { repo: 'cd ~/demo-shop && prism-cli enable security --repo --profile demo --region us-west-2', replace: 'prism-cli enable security --replace --profile demo --region us-west-2' } })) });
const mt = m.dom.byId.security.textContent;
Expand Down Expand Up @@ -657,3 +675,36 @@ test('Settings > AWS points to the Security Agent page; the Dashboard\'s securit
const link = dash.dom.byId.main.querySelectorAll('a').find((a) => a.textContent === 'View findings →');
assert.equal(link?.getAttribute('href'), '#security/run/' + q.repos[1].id + '/abc123456789-20261115T120000000Z-manual-security-review');
});

test('GET /api/security-agent/gate: one known repo, local files only: no git process, no repo scan', { skip: process.platform === 'win32' && 'a /bin/sh recorder git' }, async () => {
const { chmodSync } = await import('node:fs');
const home = tmp('home'), path = join(home, 'src', 'demo');
mkdirSync(join(path, '.prism'), { recursive: true });
const d = saDeps(home, [{ id: repoId(path), name: 'demo', path, current: true }]);
let scans = 0;
const repos = d.repos;
d.repos = async () => { scans++; return repos(); };
// Every git the dashboard spawns resolves through PATH: a recorder git first on it.
const bin = tmp('bin'), mark = join(bin, 'git-calls');
writeFileSync(join(bin, 'git'), `#!/bin/sh\necho "$*" >> '${mark}'\nexit 1\n`);
chmodSync(join(bin, 'git'), 0o755);
const saved = process.env.PATH;
process.env.PATH = bin + (saved ? ':' + saved : '');
try {
assert.equal(securityAgentGate(d, repoId(path)), null, 'before a full answer the id is not known');
await securityAgentView(d);
assert.ok(existsSync(mark), 'the full answer runs git (rev-parse, ls-files): the recorder works');
rmSync(mark);
const n = scans;
const g = securityAgentGate(d, repoId(path));
assert.equal(g?.gate.state, 'profile');
assert.equal(existsSync(mark), false, 'the re-check spawned no git process');
assert.equal(scans, n, 'and listed no repos');
assert.equal(d.aws.calls.length, 0, 'and made no AWS call');
assert.equal(securityAgentGate(d, 'ffffffffffffffff'), null);
assert.equal(securityAgentGate(d, '../x'), null);
} finally { process.env.PATH = saved; }
const api = setupApi({ runner: runnerWith([]), cwd: home, repoPaths: async () => [], identity: { env: {}, home, repoRoot: null }, refresh: async () => ({}), securityAgent: d } as never);
assert.equal(((await api.getApi['/api/security-agent/gate'](new URL('http://x/api/security-agent/gate?repo=' + repoId(path)))) as { gate: { state: string } }).gate.state, 'profile');
assert.equal(((await api.getApi['/api/security-agent/gate'](new URL('http://x/api/security-agent/gate?repo=nope'))) as { status: number }).status, 404);
});
Loading
Loading