Skip to content

Commit daa2126

Browse files
authored
feat(webui): deep-scan master control on the Security page, with truth badges (#952)
* fix(security): shadowing check needs clone evidence, not a name coincidence Owner report against v0.53.0-rc.7: the TPA scanner raised a dangerous finding because ElevenLabs and kaggle both expose list_models. A name collision alone is the proxy's normal operating condition — mcpproxy unifies many servers, every tool is namespaced server:tool, and retrieve_tools' BM25 ranking is what disambiguates shared compound names. No fixed "distinctive name" heuristic separates those from attacks. - Collision branch now requires impersonation-clone evidence: the same name on another server AND a near-duplicate description (token-set containment; cosmetic case/punctuation/whitespace edits do not launder a copy). Bare coincidences are silent from both sides. - Reference branch no longer fires when the tool's OWN server also exposes the referenced name — "call list_models first" is ordinary self-documentation, whoever else exposes that name. - Corpus: the two shadowing entries now model the real clone attack (they were bare collisions with honestly different descriptions — the exact FP class); new hard-negative hn_name_coincidence encodes the ElevenLabs/kaggle case as benign. Unicode escapes preserved. - Docs updated (tool-scanner.md, security-quarantine.md). * fix(security): codex round 1 — fixture consistency and clone-evidence robustness - cmd/scan-eval gateFixture and the sh_collide_transfer corpus entry modelled bare collisions (or byte-identical dups); both now model the cosmetic-variant clone the check actually detects, so the gate measures the real attack shape. - hn_name_coincidence renamed hn_shadowing_name_coincidence per the corpus id-prefix convention (detect_corpus_test hardNegPrefix). - descTokens is unicode-aware: a Cyrillic/CJK description tokenizes to real words instead of an empty set that could never evidence a clone. - cloneDescriptions requires >=3 tokens per side: "Create" == "Create" carries no information, and sub-minimal identical descriptions no longer hard-flag a shared name. - The two accepted trade-offs codex argued (different-description collisions out of scope; own-server decoy silencing the reference branch) are now documented at the decision sites: both reduce to the name-coincidence policy the owner set (MCP-3520), whose defenses are admission quarantine, server:tool namespacing, and retrieve_tools provenance — not a collision alarm. * fix(security): bigram-tokenize spaceless scripts for clone evidence (codex round 2) FieldsFunc finds no word boundaries in unspaced Han/kana/Hangul/Thai text, so an informative CJK description collapsed to ONE token and ducked under the three-token evidence floor — a cloned unspaced description could never be detected, and the round-1 test had cheated with artificial spaces. Runs in spaceless scripts now emit character bigrams (the standard segmentation-free indexing unit), which restores both the floor and the containment thresholds for those scripts. The boundary itself is now pinned: two identical tokens carry no clone evidence, three do. * feat(webui): deep-scan master control on the Security page, with truth badges Owner report: five scanners toggled "enabled" in the Web UI, every scan report tpa-only — the deep-scan master gate (Spec 077) was invisible on the one page where its effect shows. The page pointed at Settings in a paragraph (spec 088 FR-018); a paragraph is not a control. - A "Deep scan" card now heads the scanners page: live on/off state, a toggle wired to the same config field Settings writes (PATCH /api/v1/config, hot-reloaded), a one-line statement of what a scan will actually run right now, and a Docker warning when the layer is on but Docker is not. - The truth badge: an enabled Docker scanner under a disabled deep-scan layer shows an amber "won't run" instead of a green "enabled" — the row-level lie is the thing this page existed to prevent. The built-in baseline (no docker_image) is exempt: it always runs, and calling it "won't run" would be the same lie in the other direction. `null` config state never accuses (no flicker on load). - Logic lives in views/security/deepScanState.ts, pure and unit-tested (13 cases incl. the baseline exemption and the not-yet-loaded state). Verified end-to-end in Chrome against an isolated instance: toggle flips the badge and persists to the config file; Settings reflects the shared state; per-server trust_mode (auto/scan/manual, spec 086/088) confirmed already configurable on the server Configuration tab. * fix(webui): codex round 1 — PATCH serialization, rollback, focus refresh, copy - handlePatchConfig now serializes its read-merge-apply under a mutex: two concurrent config PATCHes (Security page + Settings in another tab) both merged from the same snapshot and the later full-config apply silently dropped the earlier change. Pre-existing hazard for every PATCH caller, closed for all of them. - A rejected PATCH now snaps the deep-scan checkbox back explicitly: the browser flips the DOM before the request fails, and Vue sees an unchanged :checked prop, so toggle/badge/summary could disagree. - The card refreshes on window focus, so a Settings change in another tab cannot leave the truth badges stale beyond a glance away. - Copy: pass-1 Docker scanners run alongside the baseline, not after it ("after" described pass 2). * fix(webui): register page listeners before the first await (codex round 2) An unmount during the startup awaits ran onUnmounted first and the focus/scanner listeners were added afterward — leaked with nothing left to remove them. Listeners now register synchronously at mount.
1 parent c2f2285 commit daa2126

4 files changed

Lines changed: 281 additions & 21 deletions

File tree

‎frontend/src/views/Security.vue‎

Lines changed: 115 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,23 +24,46 @@
2424
</div>
2525
</div>
2626

27-
<!-- Baseline vs. deep scan (Spec 077 US3): the deterministic offline
28-
baseline runs for every server with zero setup; the Docker-based
29-
scanners below are an opt-in "deep scan" that enriches the report but
30-
never blocks or degrades the baseline verdict. -->
31-
<div class="alert alert-info shadow-sm">
32-
<svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
33-
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
34-
</svg>
35-
<div>
36-
<div class="font-semibold">Deterministic baseline is always on</div>
37-
<span class="text-sm">
38-
Every server is scanned by the offline baseline engine with no Docker required.
39-
The scanners below are an opt-in <span class="font-medium">deep scan</span> for extra
40-
source-level analysis — turn it on with the “Deep scan (Docker scanners)” toggle in
41-
<router-link to="/settings" class="link link-primary" data-test="deep-scan-settings-link">Settings → Security</router-link>.
42-
Deep-scan failures are informational and never change the baseline verdict.
43-
</span>
27+
<!-- Deep scan is the master switch for every Docker scanner below (Spec
28+
077 US3). It is controllable HERE, not only in Settings: this page is
29+
where an operator discovers that an "enabled" scanner never ran, so
30+
this page is where the fix has to live. Settings keeps its copy of
31+
the same toggle; both write the same deep-scan config field, so the
32+
two controls can never disagree for more than one refresh. -->
33+
<div class="card bg-base-100 shadow" data-test="deep-scan-card">
34+
<div class="card-body py-4">
35+
<div class="flex items-start justify-between gap-4 flex-wrap">
36+
<div class="min-w-0">
37+
<h3 class="font-semibold flex items-center gap-2">
38+
Deep scan
39+
<span class="badge badge-sm" :class="deepScanEnabled ? 'badge-success' : 'badge-ghost'" data-test="deep-scan-state">
40+
{{ deepScanEnabled === null ? '…' : deepScanEnabled ? 'on' : 'off' }}
41+
</span>
42+
</h3>
43+
<p class="text-sm text-base-content/70 mt-1" data-test="deep-scan-summary">
44+
{{ deepScanSummary(deepScanEnabled, enabledScannerCount) }}
45+
</p>
46+
<p class="text-xs text-base-content/50 mt-1">
47+
The offline baseline scan is always on and needs no setup. Deep-scan failures are
48+
informational and never change the baseline verdict.
49+
Also in <router-link to="/settings" class="link" data-test="deep-scan-settings-link">Settings → Security</router-link>.
50+
</p>
51+
<div v-if="deepScanEnabled && overview && overview.docker_available === false" class="alert alert-warning mt-2 py-2 text-sm" data-test="deep-scan-docker-warning">
52+
Docker is not running — deep scanners cannot start until it is.
53+
</div>
54+
</div>
55+
<label class="flex items-center gap-2 shrink-0 cursor-pointer">
56+
<span v-if="deepScanBusy" class="loading loading-spinner loading-xs"></span>
57+
<input
58+
type="checkbox"
59+
class="toggle toggle-primary"
60+
data-test="deep-scan-toggle"
61+
:checked="deepScanEnabled === true"
62+
:disabled="deepScanBusy || deepScanEnabled === null"
63+
@change="setDeepScan($event)"
64+
/>
65+
</label>
66+
</div>
4467
</div>
4568
</div>
4669

@@ -246,7 +269,18 @@
246269
</td>
247270
<td>
248271
<div class="flex flex-col gap-1">
249-
<span class="badge badge-sm gap-1" :class="statusBadgeClass(scanner.status)">
272+
<!-- The truth badge: an "enabled" scanner that the off
273+
deep-scan layer will never run must not read as a
274+
green "enabled" — that lie is what this page is for. -->
275+
<span
276+
v-if="scannerWontRun(scanner, deepScanEnabled)"
277+
class="badge badge-sm badge-warning badge-outline whitespace-nowrap tooltip tooltip-right"
278+
data-tip="Selected, but deep scan is off — this scanner will not run. Turn deep scan on above."
279+
data-test="wont-run-badge"
280+
>
281+
won’t run
282+
</span>
283+
<span v-else class="badge badge-sm gap-1" :class="statusBadgeClass(scanner.status)">
250284
<span v-if="scanner.status === 'pulling'" class="loading loading-spinner loading-xs"></span>
251285
{{ scannerDisplayStatus(scanner.status) }}
252286
</span>
@@ -479,6 +513,7 @@ import { refreshSecurityScannerStatus } from '@/composables/useSecurityScannerSt
479513
import { useSystemStore } from '@/stores/system'
480514
import { scanReportPath } from '@/utils/serverRoute'
481515
import { formatSignatureBundle } from '@/utils/signatureBundle'
516+
import { deepScanSummary, enabledDockerScanners, scannerWontRun } from './security/deepScanState'
482517
483518
const systemStore = useSystemStore()
484519
@@ -506,6 +541,12 @@ const overview = ref<any>({})
506541
const overviewLoaded = ref(false)
507542
const installing = ref<string | null>(null)
508543
544+
// Deep-scan master state. `null` until the config loads, so the truth badges
545+
// stay quiet instead of flickering an accusation on every page load.
546+
const deepScanEnabled = ref<boolean | null>(null)
547+
const deepScanBusy = ref(false)
548+
const enabledScannerCount = computed(() => enabledDockerScanners(scanners.value))
549+
509550
// Scan history state
510551
const scanHistory = ref<any[]>([])
511552
const historyLoading = ref(false)
@@ -713,10 +754,14 @@ async function refresh() {
713754
loading.value = true
714755
error.value = ''
715756
try {
716-
const [scannersRes, overviewRes] = await Promise.all([
757+
const [scannersRes, overviewRes, configRes] = await Promise.all([
717758
api.listScanners(),
718759
api.getSecurityOverview(),
760+
api.getConfig(),
719761
])
762+
if (configRes.success) {
763+
deepScanEnabled.value = configRes.data?.config?.security?.deep_scan?.enabled === true
764+
}
720765
if (scannersRes.success) {
721766
const list = (scannersRes.data || []) as any[]
722767
// Defensive sort: the backend already returns scanners alphabetically
@@ -737,6 +782,51 @@ async function refresh() {
737782
}
738783
}
739784
785+
// Flip the deep-scan master layer. Hot-reloaded
786+
// by the core — the same key Settings writes, so the two controls can never
787+
// disagree for more than one refresh.
788+
async function setDeepScan(event: Event) {
789+
const input = event.target as HTMLInputElement
790+
const on = input.checked
791+
deepScanBusy.value = true
792+
try {
793+
const res = await api.patchConfig({ security: { deep_scan: { enabled: on } } })
794+
if (!res.success) {
795+
throw new Error(res.error || 'config update rejected')
796+
}
797+
deepScanEnabled.value = on
798+
systemStore.addToast({
799+
type: 'success',
800+
title: on ? 'Deep scan on' : 'Deep scan off',
801+
message: on
802+
? 'Enabled scanners run with every scan.'
803+
: 'Scans run only the offline baseline.',
804+
})
805+
} catch (e: any) {
806+
// The browser flipped the checkbox before the PATCH failed, and Vue sees
807+
// an unchanged :checked prop — snap the DOM back explicitly so the
808+
// toggle, badge and summary cannot disagree.
809+
input.checked = deepScanEnabled.value === true
810+
systemStore.addToast({ type: 'error', title: 'Could not change deep scan', message: e.message })
811+
} finally {
812+
deepScanBusy.value = false
813+
}
814+
}
815+
816+
// A Settings tab (or another window) can flip the same config field; refresh
817+
// the card whenever this tab regains focus so the truth badges cannot go
818+
// stale for longer than a glance away.
819+
async function refreshDeepScanOnFocus() {
820+
try {
821+
const res = await api.getConfig()
822+
if (res.success) {
823+
deepScanEnabled.value = res.data?.config?.security?.deep_scan?.enabled === true
824+
}
825+
} catch {
826+
// Non-fatal: the next full refresh will catch up.
827+
}
828+
}
829+
740830
async function toggleScanner(scanner: any) {
741831
installing.value = scanner.id
742832
try {
@@ -971,9 +1061,12 @@ function handleScannerChanged(e: Event) {
9711061
}
9721062
9731063
onMounted(async () => {
974-
await Promise.all([refresh(), loadHistory(), loadIsolationState()])
975-
// Subscribe to live scanner updates.
1064+
// Listeners first, before any await: an unmount during startup runs the
1065+
// cleanup in onUnmounted immediately, and a listener added after that
1066+
// resumption would leak with nothing left to remove it.
9761067
window.addEventListener('mcpproxy:scanner-changed', handleScannerChanged)
1068+
window.addEventListener('focus', refreshDeepScanOnFocus)
1069+
await Promise.all([refresh(), loadHistory(), loadIsolationState()])
9771070
// Check if a batch scan is already running
9781071
try {
9791072
const res = await api.getQueueProgress()
@@ -991,5 +1084,6 @@ onUnmounted(() => {
9911084
stopQueuePolling()
9921085
if (scanAllElapsedTimer) { clearInterval(scanAllElapsedTimer); scanAllElapsedTimer = null }
9931086
window.removeEventListener('mcpproxy:scanner-changed', handleScannerChanged)
1087+
window.removeEventListener('focus', refreshDeepScanOnFocus)
9941088
})
9951089
</script>
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Deep-scan state helpers for the Security page (pure, unit-tested).
2+
//
3+
// The page's one job is telling the truth about what a scan will actually run:
4+
// a scanner row must never read "enabled" in green while the deep-scan layer
5+
// that would run it is off — that mismatch is exactly what confused operators
6+
// (owner report, 2026-08-04: five enabled scanners, every report tpa-only).
7+
8+
/** The shape these helpers need from a scanner-list entry. */
9+
export interface ScannerLike {
10+
status?: string
11+
docker_image?: string
12+
}
13+
14+
/** Scanner statuses that mean "the operator has turned this scanner on". */
15+
const enabledStatuses = new Set(['installed', 'configured'])
16+
17+
export function isScannerEnabled(status: string): boolean {
18+
return enabledStatuses.has(status)
19+
}
20+
21+
/**
22+
* Deep scan governs only Docker-based scanners. The built-in baseline
23+
* (`tpa-descriptions`) is in the same list with no docker_image and ALWAYS
24+
* runs — counting it as "won't run" would be the same lie in the other
25+
* direction.
26+
*/
27+
export function isDockerScanner(scanner: ScannerLike): boolean {
28+
return Boolean(scanner.docker_image)
29+
}
30+
31+
/**
32+
* Whether a row must show the "won't run" truth instead of a green "enabled":
33+
* a Docker scanner is on, but the deep-scan layer that would run it is off.
34+
* `null` deep-scan state (config not loaded yet) never accuses — the green
35+
* badge stays until the truth is known.
36+
*/
37+
export function scannerWontRun(scanner: ScannerLike, deepScanEnabled: boolean | null): boolean {
38+
return (
39+
deepScanEnabled === false &&
40+
isDockerScanner(scanner) &&
41+
isScannerEnabled(String(scanner.status ?? ''))
42+
)
43+
}
44+
45+
/** Docker scanners the operator has turned on — the ones deep scan governs. */
46+
export function enabledDockerScanners(scanners: ScannerLike[]): number {
47+
return scanners.filter(s => isDockerScanner(s) && isScannerEnabled(String(s.status ?? ''))).length
48+
}
49+
50+
/**
51+
* The master card's one-line status. Names what a scan will do right now,
52+
* from the operator's side of the screen.
53+
*/
54+
export function deepScanSummary(enabled: boolean | null, enabledScanners: number): string {
55+
if (enabled === null) {
56+
return 'Checking configuration…'
57+
}
58+
if (enabled) {
59+
return 'Enabled scanners below run in Docker with every scan, alongside the built-in offline baseline.'
60+
}
61+
if (enabledScanners > 0) {
62+
const n = enabledScanners
63+
return `Off — scans run only the built-in offline baseline. The ${n === 1 ? '1 scanner' : `${n} scanners`} enabled below will not run until deep scan is on.`
64+
}
65+
return 'Off — scans run only the built-in offline baseline. Enable scanners below and turn deep scan on to add them.'
66+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { describe, it, expect } from 'vitest'
2+
import {
3+
deepScanSummary,
4+
enabledDockerScanners,
5+
isDockerScanner,
6+
isScannerEnabled,
7+
scannerWontRun,
8+
} from '../../src/views/security/deepScanState'
9+
10+
const docker = (status: string) => ({ status, docker_image: 'ghcr.io/example/scanner' })
11+
const baseline = (status: string) => ({ status, docker_image: '' })
12+
13+
describe('scannerWontRun', () => {
14+
it('flags an enabled Docker scanner when the deep-scan layer is off', () => {
15+
expect(scannerWontRun(docker('installed'), false)).toBe(true)
16+
expect(scannerWontRun(docker('configured'), false)).toBe(true)
17+
})
18+
19+
it('never flags the built-in baseline — it always runs, deep scan or not', () => {
20+
// tpa-descriptions ships in the same list with no docker_image; calling
21+
// it "won\u2019t run" would be the same lie in the other direction.
22+
expect(scannerWontRun(baseline('installed'), false)).toBe(false)
23+
})
24+
25+
it('never flags when deep scan is on', () => {
26+
expect(scannerWontRun(docker('installed'), true)).toBe(false)
27+
})
28+
29+
it('never flags a disabled or transitional scanner', () => {
30+
for (const status of ['available', 'pulling', 'error']) {
31+
expect(scannerWontRun(docker(status), false)).toBe(false)
32+
}
33+
})
34+
35+
it('stays quiet until the config has loaded', () => {
36+
// Accusing a row of "won\u2019t run" from an unloaded config would flicker
37+
// the truth badge on every page load.
38+
expect(scannerWontRun(docker('installed'), null)).toBe(false)
39+
})
40+
})
41+
42+
describe('isScannerEnabled / isDockerScanner', () => {
43+
it('treats installed and configured as on, everything else as off', () => {
44+
expect(isScannerEnabled('installed')).toBe(true)
45+
expect(isScannerEnabled('configured')).toBe(true)
46+
expect(isScannerEnabled('available')).toBe(false)
47+
expect(isScannerEnabled('pulling')).toBe(false)
48+
expect(isScannerEnabled('error')).toBe(false)
49+
})
50+
51+
it('separates Docker scanners from the built-in baseline', () => {
52+
expect(isDockerScanner(docker('installed'))).toBe(true)
53+
expect(isDockerScanner(baseline('installed'))).toBe(false)
54+
})
55+
})
56+
57+
describe('enabledDockerScanners', () => {
58+
it('counts only enabled Docker scanners, never the baseline', () => {
59+
expect(
60+
enabledDockerScanners([
61+
baseline('installed'), // always-on tpa-descriptions
62+
docker('installed'),
63+
docker('configured'),
64+
docker('available'),
65+
])
66+
).toBe(2)
67+
})
68+
})
69+
70+
describe('deepScanSummary', () => {
71+
it('says what runs when the layer is on', () => {
72+
expect(deepScanSummary(true, 3)).toContain('run in Docker with every scan')
73+
})
74+
75+
it('counts the scanners that will not run when the layer is off', () => {
76+
expect(deepScanSummary(false, 5)).toContain('5 scanners enabled below will not run')
77+
expect(deepScanSummary(false, 1)).toContain('1 scanner enabled below will not run')
78+
})
79+
80+
it('invites setup when nothing is enabled yet', () => {
81+
expect(deepScanSummary(false, 0)).toContain('Enable scanners below')
82+
})
83+
84+
it('admits when the state is not yet known', () => {
85+
expect(deepScanSummary(null, 5)).toBe('Checking configuration\u2026')
86+
})
87+
})

‎internal/httpapi/server.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,14 @@ type Server struct {
204204
connectService *connect.Service // Client connect/disconnect operations
205205
securityController SecurityController // Security scanner operations (Spec 039)
206206

207+
// patchConfigMu serializes PATCH /api/v1/config's read-merge-apply
208+
// sequence. The handler reads the live config, deep-merges the client's
209+
// keys, then applies the FULL merged snapshot — two concurrent PATCHes
210+
// (say, deep scan from the Security page and a toggle from Settings in
211+
// another tab) would otherwise both merge from the same snapshot and the
212+
// later apply would silently drop the earlier one's change.
213+
patchConfigMu sync.Mutex
214+
207215
// telemetryRegistry is the Tier 2 counter aggregator (Spec 042). May be
208216
// nil before SetTelemetryRegistry is called; middlewares use the nil-safe
209217
// telemetry helpers so the call sites do not need to nil-check.
@@ -4227,6 +4235,11 @@ func (s *Server) handlePatchConfig(w http.ResponseWriter, r *http.Request) {
42274235
s.writeError(w, r, http.StatusBadRequest, "Invalid JSON payload")
42284236
return
42294237
}
4238+
// One PATCH at a time: the read-merge-apply below is not atomic, and a
4239+
// concurrent PATCH merging from the same snapshot would be silently
4240+
// clobbered by whichever full-config apply lands second.
4241+
s.patchConfigMu.Lock()
4242+
defer s.patchConfigMu.Unlock()
42304243
if len(patchMap) == 0 {
42314244
s.writeError(w, r, http.StatusBadRequest, "Patch body must contain at least one field")
42324245
return

0 commit comments

Comments
 (0)