api/src/routes/private/security.ts

150 lines · 4434 bytes

  1// Repo security report: deps.dev scorecard + OSS-Fuzz + GitHub advisories
  2import { createRoute, z } from '@hono/zod-openapi'
  3import { fetchJson } from '@/lib/fetch'
  4import { githubHeaders } from '@/lib/github'
  5import { freshSeconds } from '@/lib/cache/freshness'
  6import { newApp } from '@/lib/openapi'
  7import { ErrorResponse, Ok, SecurityReportSchema } from '@/schemas'
  8
  9const app = newApp()
 10
 11const FRESH_TTL = freshSeconds('security')
 12
 13interface Check {
 14  name?: string
 15  score?: number
 16  reason?: string
 17  documentation?: { url?: string }
 18}
 19
 20interface Project {
 21  scorecard?: { date?: string; overallScore?: number; checks?: Check[] }
 22  ossFuzz?: unknown
 23}
 24
 25interface Vuln {
 26  vulnerable_version_range?: string | null
 27  // Repo advisories carry the fix here, the global advisory db uses first_patched_version
 28  patched_versions?: string | null
 29  first_patched_version?: { identifier?: string } | null
 30}
 31
 32interface Advisory {
 33  ghsa_id?: string
 34  cve_id?: string | null
 35  summary?: string
 36  severity?: string
 37  cvss?: { score?: number | null }
 38  published_at?: string
 39  withdrawn_at?: string | null
 40  state?: string
 41  html_url?: string
 42  vulnerabilities?: Vuln[] | null
 43}
 44
 45const mapCheck = (check: Check) => ({
 46  name: check.name ?? '',
 47  score: check.score ?? -1,
 48  reason: check.reason ?? '',
 49  url: check.documentation?.url ?? '',
 50})
 51
 52// A lone strict "< x" range names the fix version, otherwise unknown
 53const deriveFix = (ranges: string[]) => {
 54  const match = ranges.length === 1 ? ranges[0].match(/^<\s*([\w.+-]+)$/) : null
 55  return match ? match[1] : null
 56}
 57
 58const mapAdvisory = (a: Advisory) => {
 59  const vulns = a.vulnerabilities ?? []
 60  const ranges = [
 61    ...new Set(
 62      vulns
 63        .map((v) => v.vulnerable_version_range?.trim())
 64        .filter((r): r is string => !!r),
 65    ),
 66  ]
 67  const vulnerableRange = ranges.join('; ')
 68  const explicit = vulns
 69    .map((v) => v.patched_versions?.trim() || v.first_patched_version?.identifier)
 70    .find(Boolean)
 71  const firstPatchedVersion = explicit ?? deriveFix(ranges)
 72  return {
 73    ghsaId: a.ghsa_id ?? '',
 74    cveId: a.cve_id ?? null,
 75    summary: a.summary ?? '',
 76    severity: a.severity ?? '',
 77    cvssScore: a.cvss?.score ?? null,
 78    publishedAt: a.published_at ?? '',
 79    url: a.html_url ?? '',
 80    firstPatchedVersion,
 81    vulnerableRange,
 82    // an upper bound means later versions are safe, so a fix exists
 83    isPatched: Boolean(firstPatchedVersion) || vulnerableRange.includes('<'),
 84  }
 85}
 86
 87// OpenSSF Scorecard + fuzzing signal from deps.dev, degrades to empty
 88const getPosture = async (slug: string) => {
 89  try {
 90    const key = encodeURIComponent(`github.com/${slug}`)
 91    const project = await fetchJson<Project>(`https://api.deps.dev/v3/projects/${key}`)
 92    const card = project.scorecard
 93    return {
 94      scorecard: {
 95        available: Boolean(card),
 96        overallScore: card?.overallScore ?? null,
 97        generatedAt: card?.date ?? '',
 98        checks: (card?.checks ?? []).map(mapCheck),
 99      },
100      fuzzed: Boolean(project.ossFuzz),
101    }
102  } catch {
103    return {
104      scorecard: { available: false, overallScore: null, generatedAt: '', checks: [] },
105      fuzzed: false,
106    }
107  }
108}
109
110// Maintainer-published GitHub security advisories, degrades to empty
111const getAdvisories = async (slug: string, token?: string) => {
112  try {
113    const list = await fetchJson<Advisory[]>(
114      `https://api.github.com/repos/${slug}/security-advisories?per_page=100&state=published`,
115      { headers: githubHeaders(token) },
116    )
117    const items = list.filter((a) => !a.withdrawn_at).map(mapAdvisory)
118    return { count: items.length, items }
119  } catch {
120    return { count: 0, items: [] }
121  }
122}
123
124const route = createRoute({
125  method: 'get',
126  path: '/enrich/security/{owner}/{repo}',
127  tags: ['Enrichment'],
128  summary: 'Repo security',
129  request: { params: z.object({ owner: z.string(), repo: z.string() }) },
130  responses: {
131    200: Ok(SecurityReportSchema),
132    401: ErrorResponse,
133    500: ErrorResponse,
134  },
135})
136
137app.openapi(route, async (c) => {
138  const { owner, repo } = c.req.valid('param')
139  const slug = `${owner}/${repo}`
140  const data = await c.var.storage.fetch(`sec:${slug}`, FRESH_TTL, async () => {
141    const [posture, advisories] = await Promise.all([
142      getPosture(slug),
143      getAdvisories(slug, c.env.GITHUB_TOKEN),
144    ])
145    return { repo: slug, ...posture, advisories }
146  })
147  return c.json(data, 200)
148})
149
150export default app