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
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright 2025-2026 mrveiss
// SPDX-License-Identifier: Apache-2.0
// AutoBot - AI-Powered Automation Platform
// Author: mrveiss
/**
* useCodeIntelligence reads the cached security score through the canonical reader (#18907).
*
* The route requires `source_id`; the request must carry it, and the fields the old copy
* exposed (`from_cache`, `completed_at`) stay reachable.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('@/utils/fetchWithAuth', () => ({ fetchWithAuth: vi.fn() }))
vi.mock('@/config/AppConfig.js', () => ({
default: { getServiceUrl: vi.fn(async () => 'http://backend.test') },
}))

import { fetchWithAuth } from '@/utils/fetchWithAuth'
import { useCodeIntelligence } from '../useCodeIntelligence'

const mockedFetch = vi.mocked(fetchWithAuth)
const withSourceId = (url: string) => `${url}?source_id=atlas`

function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}

describe('useCodeIntelligence cached security score (#18907)', () => {
beforeEach(() => mockedFetch.mockReset())

it('sends source_id and keeps every payload field', async () => {
mockedFetch.mockResolvedValueOnce(
jsonResponse({
status: 'success',
security_score: 88,
from_cache: true,
completed_at: '2026-11-08T00:00:00Z',
}),
)
const ci = useCodeIntelligence({ withSourceId })
const result = await ci.getSecurityScoreCached()

expect(mockedFetch).toHaveBeenCalledTimes(1)
const [url] = mockedFetch.mock.calls[0] as [string]
expect(url).toBe(
'http://backend.test/api/code-intelligence/security/score/cached?source_id=atlas',
)
expect(result?.from_cache).toBe(true)
expect(result?.completed_at).toBe('2026-11-08T00:00:00Z')
expect(ci.securityScoreCached.value?.security_score).toBe(88)
})

it('without a source scoper no request is sent', async () => {
const ci = useCodeIntelligence()
expect(await ci.getSecurityScoreCached()).toBeNull()
expect(mockedFetch).not.toHaveBeenCalled()
})

it('a failed read lands in errors and returns null', async () => {
mockedFetch.mockResolvedValueOnce(new Response('{}', { status: 422 }))
const ci = useCodeIntelligence({ withSourceId })
expect(await ci.getSecurityScoreCached()).toBeNull()
expect(ci.errors.value.length).toBe(1)
})

it('a no_data payload is returned and stored, and loading returns to false', async () => {
mockedFetch.mockResolvedValueOnce(jsonResponse({ status: 'no_data' }))
const ci = useCodeIntelligence({ withSourceId })
const result = await ci.getSecurityScoreCached()

expect(result?.status).toBe('no_data')
expect(ci.securityScoreCached.value?.status).toBe('no_data')
expect(ci.isLoading.value).toBe(false)
expect(ci.errors.value).toEqual([])
})

it('an overlapping call aborts the first, which returns null instead of stale data', async () => {
mockedFetch.mockImplementationOnce(
(_url, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () =>
reject(new DOMException('aborted', 'AbortError')),
)
}),
)
mockedFetch.mockResolvedValueOnce(jsonResponse({ status: 'success', security_score: 70 }))
const ci = useCodeIntelligence({ withSourceId })
const first = ci.getSecurityScoreCached()
await vi.waitFor(() => expect(mockedFetch).toHaveBeenCalledTimes(1))
const second = ci.getSecurityScoreCached()

expect(await first).toBeNull()
expect((await second)?.security_score).toBe(70)
expect(ci.errors.value).toEqual([])
expect(ci.isLoading.value).toBe(false)
})

it('an aborted call does not duplicate the newer call error', async () => {
mockedFetch.mockImplementationOnce(
(_url, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () =>
reject(new DOMException('aborted', 'AbortError')),
)
}),
)
mockedFetch.mockResolvedValueOnce(new Response('{}', { status: 500 }))
const ci = useCodeIntelligence({ withSourceId })
const first = ci.getSecurityScoreCached()
await vi.waitFor(() => expect(mockedFetch).toHaveBeenCalledTimes(1))
const second = ci.getSecurityScoreCached()

expect(await first).toBeNull()
expect(await second).toBeNull()
expect(ci.errors.value.length).toBe(1)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright 2025-2026 mrveiss
// SPDX-License-Identifier: Apache-2.0
// AutoBot - AI-Powered Automation Platform
// Author: mrveiss
/**
* One home for the cached security score read (#18907, #20999).
*
* Only `useCachedSecurityScore.ts` may name the route or import `CACHED_SECURITY_SCORE_PATH`;
* a second reader in any other source file fails this sweep. Planted controls prove the
* detector can fail, and a comment-only control proves it does not fire on prose.
*
* Limit: this is a LITERAL text match on code lines. It matches `security/score` (so template
* literals and `'/security/score' + '/cached'` are caught), but a path assembled from pieces
* that never spell `security/score` on one line (e.g. `['security', 'score'].join('/')`) is
* invisible to it. The live, non-cached route `.../security/score` (path ends right after
* `score`, a different endpoint, and no next line starts with `+`) is the one exempt shape.
*/
import { describe, expect, it } from 'vitest'
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join, relative } from 'node:path'

const SRC = join(__dirname, '..', '..', '..')
const HOME = 'composables/analytics/useCachedSecurityScore.ts'
const ROUTE = /security\/score/
const PATH_CONST = /\bCACHED_SECURITY_SCORE_PATH\b/
const LIVE_ROUTE = /security\/score[`'"]\s*[,)]?\s*$/
const SKIP = /(^types\/generated\/|\.test\.ts$|__tests__\/|__mocks__\/)/

function sourceFiles(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const full = join(dir, name)
if (statSync(full).isDirectory()) return sourceFiles(full)
return /\.(ts|vue|js)$/.test(name) ? [full] : []
})
}

function isCode(line: string): boolean {
return !/^\s*(\*|\/\/|\/\*)/.test(line)
}

function namesRoute(line: string, next = ''): boolean {
const exempt = LIVE_ROUTE.test(line) && !/^\s*\+/.test(next) // a following `+` concatenates
return (ROUTE.test(line) && !exempt) || PATH_CONST.test(line)
}

/** Code lines only: doc comments may mention the route. */
function names(text: string): boolean {
const lines = text.split('\n')
return lines.some((l, i) => isCode(l) && namesRoute(l, lines[i + 1]))
}

function readers(files: Record<string, string>): string[] {
return Object.keys(files).filter(
(f) => f !== HOME && !SKIP.test(f) && names(files[f]),
)
}

describe('cached security score read has one home', () => {
it('no source file other than the canonical composable names the route or path constant', () => {
const files: Record<string, string> = {}
for (const f of sourceFiles(SRC)) {
files[relative(SRC, f)] = readFileSync(f, 'utf-8')
}
expect(names(files[HOME])).toBe(true)
expect(readers(files)).toEqual([])
})

it('planted control: a second direct reader is detected', () => {
const planted = {
[HOME]: "path: '/api/code-intelligence/security/score/cached'",
'composables/other.ts': "ApiClient.get('/code-intelligence/security/score/cached')",
}
expect(readers(planted)).toEqual(['composables/other.ts'])
})

it('planted control: dynamic and concatenated paths are detected', () => {
const planted = {
[HOME]: "path: '/api/code-intelligence/security/score/cached'",
'composables/tpl.ts': 'get(`${base}/code-intelligence/security/score/${kind}`)',
'composables/cat.ts': "get(base + '/security/score' + '/cached')",
}
expect(readers(planted).sort()).toEqual(['composables/cat.ts', 'composables/tpl.ts'])
})

it('planted control: multi-line concatenation after the live-route shape is detected', () => {
const planted = {
[HOME]: 'export const CACHED_SECURITY_SCORE_PATH = 1',
'composables/multi.ts': "get(base + '/security/score'\n + '/cached')",
}
expect(readers(planted)).toEqual(['composables/multi.ts'])
})

it('planted control: importing the path constant elsewhere is detected', () => {
const planted = {
[HOME]: 'export const CACHED_SECURITY_SCORE_PATH = 1',
'composables/importer.ts': "import { CACHED_SECURITY_SCORE_PATH } from './x'",
}
expect(readers(planted)).toEqual(['composables/importer.ts'])
})

it('negative control: comment-only mentions are not readers', () => {
const planted = {
[HOME]: 'export const CACHED_SECURITY_SCORE_PATH = 1',
'composables/doc.ts': '// GET /api/code-intelligence/security/score/cached\n/**\n * security/score\n */',
}
expect(readers(planted)).toEqual([])
})

it('negative control: the live non-cached route is not a cached reader', () => {
const planted = {
[HOME]: 'export const CACHED_SECURITY_SCORE_PATH = 1',
'composables/live.ts': '`${getApiBase()}/code-intelligence/security/score`,',
}
expect(readers(planted)).toEqual([])
})
})
17 changes: 17 additions & 0 deletions autobot-frontend/src/composables/analytics/codeIntelTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ export interface SecurityScoreResult {
owasp_breakdown: Record<string, number>
}

/** Raw payload of `security/score/cached`; `no_data` carries no score. */
export interface CachedSecurityScoreRaw {
status: 'success' | 'no_data'
from_cache?: boolean
completed_at?: string
security_score?: number
grade?: string
risk_level?: string
status_message?: string
total_findings?: number
critical_issues?: number
high_issues?: number
files_analyzed?: number
severity_breakdown?: Record<string, number>
owasp_breakdown?: Record<string, number>
}

export interface PerformanceScoreResult {
performance_score: number
grade: string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2025-2026 mrveiss
// SPDX-License-Identifier: Apache-2.0
// AutoBot - AI-Powered Automation Platform
// Author: mrveiss
/**
* The one reader of `GET /api/code-intelligence/security/score/cached` (#18907, #20999).
*
* The route requires `source_id`, so the read is always source-scoped. Both
* `useCodeIntelScores` (the page) and `useCodeIntelligence` delegate here; no other
* composable may name the path (guarded by `useCachedSecurityScore.oneHome.test.ts`).
*/
import { ref, type Ref } from 'vue'
import { useFetchEndpoint } from '@/composables/api/useFetchEndpoint'
import type {
CachedSecurityScoreRaw,
SecurityScoreResult,
} from '@/composables/analytics/codeIntelTypes'

export const CACHED_SECURITY_SCORE_PATH = '/api/code-intelligence/security/score/cached'

export interface UseCachedSecurityScoreOptions {
withSourceId?: (url: string) => string
/** Fired with the picked score and the full raw payload after a successful read. */
onSuccess?: (score: SecurityScoreResult, raw: CachedSecurityScoreRaw) => void
}

/** Maps the raw payload; `null` for `no_data` so a prior result stays visible. */
export function pickCachedSecurityScore(r: CachedSecurityScoreRaw): SecurityScoreResult | null {
if (r.status !== 'success' || r.security_score === undefined) return null
return {
security_score: r.security_score,
grade: r.grade ?? 'N/A',
risk_level: r.risk_level ?? 'unknown',
status_message: r.status_message ?? '',
total_findings: r.total_findings ?? 0,
critical_issues: r.critical_issues ?? 0,
high_issues: r.high_issues ?? 0,
files_analyzed: r.files_analyzed ?? 0,
severity_breakdown: r.severity_breakdown ?? {},
owasp_breakdown: r.owasp_breakdown ?? {},
}
}

export function useCachedSecurityScore(options: UseCachedSecurityScoreOptions = {}) {
/** The last answered payload, including `from_cache` and `completed_at`. */
const raw: Ref<CachedSecurityScoreRaw | null> = ref(null)
const endpoint = useFetchEndpoint<CachedSecurityScoreRaw, SecurityScoreResult>(
{
path: CACHED_SECURITY_SCORE_PATH,
scopeToSource: true,
label: 'Cached security score',
// Recorded before the pick so a `no_data` answer is kept too, as callers saw it before.
pickData: (payload) => {
raw.value = payload
return pickCachedSecurityScore(payload)
},
onSuccess: (picked, payload) => options.onSuccess?.(picked, payload),
},
{ withSourceId: options.withSourceId },
)
return { ...endpoint, raw }
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { computed, ref } from 'vue'
import i18n from '@/i18n'
import { useTaskLoader } from '@/composables/useTaskLoader'
import { useFetchEndpoint } from '@/composables/api/useFetchEndpoint'
import { useCachedSecurityScore } from '@/composables/analytics/useCachedSecurityScore'
import { createLogger } from '@/utils/debugUtils'
import type {
UseCodeIntelAnalysisDeps,
Expand Down Expand Up @@ -279,53 +280,14 @@ export function useCodeIntelScores(deps: UseCodeIntelAnalysisDeps) {
// --- Cached security score loader (#5235: best-effort read; on failure
// the useTaskLoader-backed `securityScore` ref is left untouched) ---

interface CachedSecurityScoreRaw {
status: string
security_score?: number
grade?: string
risk_level?: string
status_message?: string
total_findings?: number
critical_issues?: number
high_issues?: number
files_analyzed?: number
severity_breakdown?: Record<string, number>
owasp_breakdown?: Record<string, number>
}

const cachedSecurityScoreEndpoint = useFetchEndpoint<
CachedSecurityScoreRaw,
SecurityScoreResult
>(
{
path: '/api/code-intelligence/security/score/cached',
// #20491: the route requires source_id; without it the page-open read answered 422.
scopeToSource: true,
label: 'Cached security score',
pickData: (r) =>
r.status === 'success' && r.security_score !== undefined
? {
security_score: r.security_score ?? 0,
grade: r.grade ?? 'N/A',
risk_level: r.risk_level ?? 'unknown',
status_message: r.status_message ?? '',
total_findings: r.total_findings ?? 0,
critical_issues: r.critical_issues ?? 0,
high_issues: r.high_issues ?? 0,
files_analyzed: r.files_analyzed ?? 0,
severity_breakdown: r.severity_breakdown ?? {},
owasp_breakdown: r.owasp_breakdown ?? {},
}
: null,
// Mutate the useTaskLoader-backed `securityScore` ref only on a
// successful cached read. On no_data / error / !ok, leave it alone
// so a prior live-scan result remains visible.
onSuccess: (picked) => {
securityScore.value = picked
},
// The read itself lives in useCachedSecurityScore (#18907). On no_data / error the
// `securityScore` ref is left alone so a prior live-scan result remains visible.
const cachedSecurityScoreEndpoint = useCachedSecurityScore({
withSourceId,
onSuccess: (picked) => {
securityScore.value = picked
},
{ withSourceId },
)
})

// A failed stored read (422, network) shows in the panel's error slot; a legitimate
// `no_data` leaves the endpoint error empty, so it stays the empty state.
Expand Down
Loading