From b1f7e5c8d8c5925606b4b964c985909d90b435c3 Mon Sep 17 00:00:00 2001 From: Glastor Date: Sat, 21 Nov 2026 17:33:47 -0300 Subject: [PATCH] feat(security,perf): harden endpoints fail-closed, parallelize GitHub API with ETag, and hydrate KV 90-day history --- .github/workflows/ci.yml | 11 +- .github/workflows/codeql.yml | 14 +- example.env | 6 +- routes/_middleware.ts | 9 +- routes/api/ping/[owner]/[repo].ts | 43 +++- routes/api/status/[owner]/[repo].ts | 6 +- routes/api/webhook/github.ts | 32 ++- services/github.ts | 346 ++++++++++++++++++---------- services/kv.ts | 77 +++++++ services/security.ts | 57 +++++ tests/github_test.ts | 53 +++++ tests/kv_test.ts | 23 ++ tests/security_test.ts | 18 ++ 13 files changed, 551 insertions(+), 144 deletions(-) create mode 100644 tests/github_test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebf0d3b..6f4d395 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,17 +10,24 @@ on: permissions: contents: read +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: verify: name: Lint, TypeCheck & Tests runs-on: ubuntu-latest + timeout-minutes: 15 steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false - name: Setup Deno 2.x - uses: denoland/setup-deno@v2 + uses: denoland/setup-deno@22d081ff2d3a40755e97629de92e3bcbfa7cf2ed # v2 with: deno-version: v2.x diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index a85b871..7fa78bc 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -12,23 +12,29 @@ permissions: contents: read security-events: write +concurrency: + group: codeql-${{ github.ref }} + cancel-in-progress: true + jobs: analyze: name: CodeQL AppSec Vulnerability Scan runs-on: ubuntu-latest - timeout-minutes: 360 + timeout-minutes: 60 steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@aaf92c3279600a7c7217a1cd605774c6c791c6c3 # v3 with: languages: javascript-typescript queries: security-extended,security-and-quality - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@aaf92c3279600a7c7217a1cd605774c6c791c6c3 # v3 with: category: "/language:javascript-typescript" diff --git a/example.env b/example.env index db403d6..6c32ca8 100644 --- a/example.env +++ b/example.env @@ -19,6 +19,10 @@ # Si se define, solo las peticiones con 'Authorization: Bearer ' o 'x-statuszero-token' serán admitidas. # PING_SECRET=your_ping_secret_here -# GITHUB_WEBHOOK_SECRET (Opcional - AppSec) +# GITHUB_WEBHOOK_SECRET (Requerido en producción - fail-closed) # Clave secreta para verificar firmas HMAC-SHA256 (x-hub-signature-256) en /api/webhook/github. # GITHUB_WEBHOOK_SECRET=your_webhook_secret_here + +# Solo desarrollo local (NO activar en producción): +# ALLOW_UNAUTHENTICATED_PINGS=false +# ALLOW_UNAUTHENTICATED_WEBHOOKS=false diff --git a/routes/_middleware.ts b/routes/_middleware.ts index 9c1f2a8..c36525c 100644 --- a/routes/_middleware.ts +++ b/routes/_middleware.ts @@ -13,6 +13,10 @@ export async function handler( // Baseline Security Headers resp.headers.set("X-Content-Type-Options", "nosniff"); resp.headers.set("Referrer-Policy", "strict-origin-when-cross-origin"); + resp.headers.set( + "Strict-Transport-Security", + "max-age=31536000; includeSubDomains", + ); resp.headers.set( "Permissions-Policy", "camera=(), microphone=(), geolocation=()", @@ -21,7 +25,10 @@ export async function handler( // Badges need to be embeddable across any domain (GitHub README, docs, etc.) if (url.pathname.startsWith("/badge/")) { resp.headers.set("Access-Control-Allow-Origin", "*"); - resp.headers.set("X-Frame-Options", "ALLOWALL"); + resp.headers.set( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors *", + ); } else { resp.headers.set("X-Frame-Options", "SAMEORIGIN"); resp.headers.set( diff --git a/routes/api/ping/[owner]/[repo].ts b/routes/api/ping/[owner]/[repo].ts index 4d90dc6..5f555c2 100644 --- a/routes/api/ping/[owner]/[repo].ts +++ b/routes/api/ping/[owner]/[repo].ts @@ -1,7 +1,7 @@ // routes/api/ping/[owner]/[repo].ts import { FreshContext } from "$fresh/server.ts"; import { - getKv, + consumeRateLimit, getRepoPingSecret, invalidateRepoCache, PingRecord, @@ -9,12 +9,14 @@ import { } from "../../../../services/kv.ts"; import { isValidGitHubIdentifier, + readBoundedBody, sanitizeText, timingSafeEqualString, verifyHmacSha256, } from "../../../../services/security.ts"; const RATE_LIMIT_MAX_PER_MINUTE = 30; +const MAX_PING_BODY_BYTES = 32 * 1024; // 32 KiB export const handler = async ( req: Request, @@ -47,8 +49,7 @@ export const handler = async ( ); } - // AppSec: Rate Limiting via Deno KV sliding minute - const kv = await getKv(); + // AppSec: Atomic Rate Limiting via Deno KV sliding minute const currentMinute = Math.floor(Date.now() / 60000); const rateLimitKey = [ "ratelimit_ping", @@ -56,10 +57,13 @@ export const handler = async ( repo.toLowerCase(), currentMinute, ]; - const rateLimitEntry = await kv.get(rateLimitKey); - const currentCount = rateLimitEntry.value || 0; + const rateLimit = await consumeRateLimit( + rateLimitKey, + RATE_LIMIT_MAX_PER_MINUTE, + 120 * 1000, + ); - if (currentCount >= RATE_LIMIT_MAX_PER_MINUTE) { + if (!rateLimit.allowed) { return new Response( JSON.stringify({ error: @@ -75,9 +79,14 @@ export const handler = async ( ); } - await kv.set(rateLimitKey, currentCount + 1, { expireIn: 120 * 1000 }); - - const rawBody = await req.text(); + const bodyResult = await readBoundedBody(req, MAX_PING_BODY_BYTES); + if (!bodyResult.ok) { + return new Response(JSON.stringify({ error: bodyResult.error }), { + status: 413, + headers: { "Content-Type": "application/json" }, + }); + } + const rawBody = bodyResult.text; let body: Record = {}; if (rawBody.trim()) { try { @@ -93,8 +102,22 @@ export const handler = async ( } } - // AppSec: Authentication check (HMAC-SHA256 or Bearer secret token) + // AppSec: Fail-closed authentication check (HMAC-SHA256 or Bearer secret token) const configuredSecret = await getRepoPingSecret(owner, repo); + const allowUnauthenticated = + Deno.env.get("ALLOW_UNAUTHENTICATED_PINGS") === "true"; + if (!configuredSecret && !allowUnauthenticated) { + return new Response( + JSON.stringify({ + error: + "Endpoint de pings protegido (fail-closed): configura PING_SECRET o un secreto por repositorio.", + }), + { + status: 503, + headers: { "Content-Type": "application/json" }, + }, + ); + } if (configuredSecret) { const authHeader = req.headers.get("Authorization") || ""; const tokenHeader = req.headers.get("x-statuszero-token") || ""; diff --git a/routes/api/status/[owner]/[repo].ts b/routes/api/status/[owner]/[repo].ts index 78386f4..76b968c 100644 --- a/routes/api/status/[owner]/[repo].ts +++ b/routes/api/status/[owner]/[repo].ts @@ -1,6 +1,7 @@ // routes/api/status/[owner]/[repo].ts import { FreshContext } from "$fresh/server.ts"; import { fetchRepoStatus } from "../../../../services/github.ts"; +import { canForceRefresh } from "../../../../services/kv.ts"; import { isValidGitHubIdentifier } from "../../../../services/security.ts"; export const handler = async ( @@ -10,7 +11,7 @@ export const handler = async ( const owner = ctx.params.owner; const repo = ctx.params.repo; const url = new URL(req.url); - const forceRefresh = url.searchParams.get("refresh") === "true"; + const requestedRefresh = url.searchParams.get("refresh") === "true"; // AppSec: Strict input validation if (!isValidGitHubIdentifier(owner) || !isValidGitHubIdentifier(repo)) { @@ -36,6 +37,9 @@ export const handler = async ( } try { + const forceRefresh = requestedRefresh + ? await canForceRefresh(owner, repo) + : false; const data = await fetchRepoStatus(owner, repo, forceRefresh); return new Response(JSON.stringify(data, null, 2), { status: 200, diff --git a/routes/api/webhook/github.ts b/routes/api/webhook/github.ts index bd5efff..89c5784 100644 --- a/routes/api/webhook/github.ts +++ b/routes/api/webhook/github.ts @@ -4,9 +4,12 @@ import { fetchRepoStatus } from "../../../services/github.ts"; import { invalidateRepoCache } from "../../../services/kv.ts"; import { isValidGitHubIdentifier, + readBoundedBody, verifyHmacSha256, } from "../../../services/security.ts"; +const MAX_WEBHOOK_BODY_BYTES = 256 * 1024; // 256 KiB + export const handler = async ( req: Request, _ctx: FreshContext, @@ -21,12 +24,35 @@ export const handler = async ( ); } + // AppSec: Fail-closed if GITHUB_WEBHOOK_SECRET is not configured + const webhookSecret = Deno.env.get("GITHUB_WEBHOOK_SECRET")?.trim(); + const allowUnauthenticated = + Deno.env.get("ALLOW_UNAUTHENTICATED_WEBHOOKS") === "true"; + if (!webhookSecret && !allowUnauthenticated) { + return new Response( + JSON.stringify({ + error: + "Webhook deshabilitado: configura GITHUB_WEBHOOK_SECRET en el entorno (fail-closed).", + }), + { + status: 503, + headers: { "Content-Type": "application/json" }, + }, + ); + } + const event = req.headers.get("x-github-event") || "unknown"; const signature = req.headers.get("x-hub-signature-256") || ""; - const rawBody = await req.text(); + const bodyResult = await readBoundedBody(req, MAX_WEBHOOK_BODY_BYTES); + if (!bodyResult.ok) { + return new Response(JSON.stringify({ error: bodyResult.error }), { + status: 413, + headers: { "Content-Type": "application/json" }, + }); + } + const rawBody = bodyResult.text; - // AppSec: Verify HMAC-SHA256 signature if GITHUB_WEBHOOK_SECRET is configured - const webhookSecret = Deno.env.get("GITHUB_WEBHOOK_SECRET"); + // AppSec: Verify HMAC-SHA256 signature if (webhookSecret) { if (!signature) { return new Response( diff --git a/services/github.ts b/services/github.ts index d9d8d11..055765d 100644 --- a/services/github.ts +++ b/services/github.ts @@ -1,18 +1,26 @@ // services/github.ts -// GitHub API integration using Octokit, calculating status, uptime, workflow metrics and incidents. +// GitHub API integration using Octokit with ETag conditional requests, singleflight deduplication, +// parallel edge fetching, persistent Deno KV 90-day history, and synthetic ping status integration. import { Octokit } from "@octokit/rest"; import { + DailyHistorySnapshot, getCachedRepoStatus, + getCacheTtlMs, getPings, + getRepoHistoryMap, HistoryDay, IncidentItem, + PingRecord, ReleaseInfo, RepoStatusData, saveRepoStatus, WorkflowRunItem, } from "./kv.ts"; +const inFlightRequests = new Map>(); +const RECENT_PING_WINDOW_MS = 24 * 60 * 60 * 1000; + function getOctokit(): Octokit { const token = Deno.env.get("GITHUB_TOKEN")?.trim(); return new Octokit({ @@ -21,9 +29,27 @@ function getOctokit(): Octokit { }); } -function generateHistoryDays( +function computePingLatencyMetrics(pings: PingRecord[]): { + averageLatencyMs?: number; + lastPingLatencyMs?: number; +} { + const pingsWithLatency = pings.filter( + (p) => typeof p.latencyMs === "number" && p.latencyMs > 0, + ); + const averageLatencyMs = pingsWithLatency.length > 0 + ? Math.round( + pingsWithLatency.reduce((acc, p) => acc + (p.latencyMs || 0), 0) / + pingsWithLatency.length, + ) + : undefined; + const lastPingLatencyMs = pingsWithLatency[0]?.latencyMs; + return { averageLatencyMs, lastPingLatencyMs }; +} + +export function generateHistoryDays( workflowRuns: WorkflowRunItem[], incidents: IncidentItem[], + kvHistory?: Map, ): HistoryDay[] { const days: HistoryDay[] = []; const now = new Date(); @@ -59,12 +85,17 @@ function generateHistoryDays( uptimePercent = 95.0; } else { status = "degraded"; - uptimePercent = 98.2; + uptimePercent = + Math.round(((totalRuns - failedRuns) / totalRuns) * 10000) / + 100; } - } else if (totalRuns === 0 && i > 30) { - // Older days with no specific CI runs default to operational if no incidents - status = "operational"; - uptimePercent = 100; + } else if (totalRuns === 0 && kvHistory?.has(dateStr)) { + // Hydrate real persisted daily history from Deno KV for older days beyond the last 20 runs + const snap = kvHistory.get(dateStr)!; + status = snap.status === "unknown" ? "operational" : snap.status; + uptimePercent = typeof snap.uptimePercent === "number" + ? snap.uptimePercent + : 100; } days.push({ @@ -80,6 +111,68 @@ function generateHistoryDays( return days; } +export function computeOverallStatus( + workflowRuns: WorkflowRunItem[], + incidents: IncidentItem[], + recentPings: PingRecord[], + nowMs = Date.now(), +): { status: RepoStatusData["status"]; statusMessage: string } { + const openIncidents = incidents.filter((i) => i.state === "open"); + const recentRuns = workflowRuns.slice(0, 10); + const failedRecent = recentRuns.filter((r) => r.conclusion === "failure"); + + if (openIncidents.length > 0) { + return { + status: "outage", + statusMessage: `Incidente activo: ${openIncidents[0].title}`, + }; + } + + // Factor in recent synthetic healthcheck pings (last 24h) + const latestPing = recentPings[0]; + if (latestPing) { + const pingAgeMs = nowMs - new Date(latestPing.timestamp).getTime(); + const isFreshPing = Number.isFinite(pingAgeMs) && + pingAgeMs <= RECENT_PING_WINDOW_MS; + const isPingFailure = latestPing.status === "failure" || + (typeof latestPing.httpStatus === "number" && + latestPing.httpStatus >= 500); + if (isFreshPing && isPingFailure) { + return { + status: "outage", + statusMessage: `Fallo en heartbeat sintético: ${ + latestPing.message || latestPing.workflow || "Healthcheck fallido" + }`, + }; + } + } + + if (failedRecent.length > 0) { + if (failedRecent.length > recentRuns.length / 2) { + return { + status: "outage", + statusMessage: "Fallos críticos en pipelines de CI/CD detectados", + }; + } + return { + status: "degraded", + statusMessage: "Degradación parcial en flujos de trabajo", + }; + } + + if (recentRuns.length === 0) { + return { + status: "operational", + statusMessage: "Operacional • Sin incidencias en CI/CD", + }; + } + + return { + status: "operational", + statusMessage: "Todos los sistemas y flujos operacionales", + }; +} + export async function fetchRepoStatus( owner: string, repo: string, @@ -87,38 +180,90 @@ export async function fetchRepoStatus( ): Promise { const normalizedOwner = owner.trim(); const normalizedRepo = repo.trim(); + const flightKey = + `${normalizedOwner.toLowerCase()}/${normalizedRepo.toLowerCase()}`; - // 1. Check Deno KV cache + // 1. Check Deno KV cache honoring dynamic TTL (1m with token, 5m without) if (!forceRefresh) { const cached = await getCachedRepoStatus(normalizedOwner, normalizedRepo); if (cached) { const age = Date.now() - (cached.cachedAt || 0); - if (age < 60 * 1000) { + if (age < getCacheTtlMs()) { return cached; } } } + // 2. Singleflight deduplication: coalesce concurrent requests for the same repo + const existingFlight = inFlightRequests.get(flightKey); + if (existingFlight) { + return await existingFlight; + } + + const task = fetchRepoStatusFromGitHub( + normalizedOwner, + normalizedRepo, + forceRefresh, + ).finally(() => { + inFlightRequests.delete(flightKey); + }); + + inFlightRequests.set(flightKey, task); + return await task; +} + +async function fetchRepoStatusFromGitHub( + normalizedOwner: string, + normalizedRepo: string, + forceRefresh: boolean, +): Promise { const octokit = getOctokit(); + const staleCached = await getCachedRepoStatus( + normalizedOwner, + normalizedRepo, + true, + ); try { - // 2. Fetch repository info - const { data: repoData } = await octokit.rest.repos.get({ + // 1. Fetch repository metadata with conditional ETag when available (304 costs 0 rate-limit) + const repoResp = await octokit.rest.repos.get({ owner: normalizedOwner, repo: normalizedRepo, + headers: !forceRefresh && staleCached?.etag + ? { "If-None-Match": staleCached.etag } + : undefined, }); + const repoData = repoResp.data; + const newEtag = typeof repoResp.headers?.etag === "string" + ? repoResp.headers.etag + : undefined; - // 3. Fetch workflow runs (actions) - let workflowRuns: WorkflowRunItem[] = []; - try { - const { data: runsData } = await octokit.rest.actions - .listWorkflowRunsForRepo({ + // 2. Fetch workflow runs, issues, latest release, pings, and persisted KV history in parallel + const [runsRes, issuesRes, releaseRes, pingsRes, historyRes] = await Promise + .allSettled([ + octokit.rest.actions.listWorkflowRunsForRepo({ owner: normalizedOwner, repo: normalizedRepo, per_page: 20, - }); + }), + octokit.rest.issues.listForRepo({ + owner: normalizedOwner, + repo: normalizedRepo, + state: "all", + per_page: 20, + sort: "updated", + }), + octokit.rest.repos.getLatestRelease({ + owner: normalizedOwner, + repo: normalizedRepo, + }), + getPings(normalizedOwner, normalizedRepo), + getRepoHistoryMap(normalizedOwner, normalizedRepo), + ]); - workflowRuns = (runsData.workflow_runs || []).map((run) => { + let workflowRuns: WorkflowRunItem[] = []; + if (runsRes.status === "fulfilled") { + workflowRuns = (runsRes.value.data.workflow_runs || []).map((run) => { const createdMs = new Date(run.created_at).getTime(); const updatedMs = new Date(run.updated_at).getTime(); const durationSeconds = Math.max( @@ -150,25 +295,12 @@ export async function fetchRepoStatus( durationSeconds, }; }); - } catch (_err) { - // Actions may be disabled or empty in some repos - workflowRuns = []; } - // 4. Fetch issues for incident tracking let incidents: IncidentItem[] = []; - try { - const { data: issuesData } = await octokit.rest.issues.listForRepo({ - owner: normalizedOwner, - repo: normalizedRepo, - state: "all", - per_page: 20, - sort: "updated", - }); - - // Filter issues labeled or titled as incident/outage/downtime/bug - incidents = issuesData - .filter((issue) => !issue.pull_request) // exclude PRs + if (issuesRes.status === "fulfilled") { + incidents = issuesRes.value.data + .filter((issue) => !issue.pull_request) .map((issue) => { const labelList = (issue.labels || []).map((l) => typeof l === "string" @@ -199,18 +331,11 @@ export async function fetchRepoStatus( }; }) .filter((i) => i.isIncident); - } catch (_err) { - incidents = []; } - // 5. Fetch latest release let latestRelease: ReleaseInfo | null = null; - try { - const { data: releaseData } = await octokit.rest.repos.getLatestRelease({ - owner: normalizedOwner, - repo: normalizedRepo, - }); - + if (releaseRes.status === "fulfilled") { + const releaseData = releaseRes.value.data; latestRelease = { tag: releaseData.tag_name, name: releaseData.name || releaseData.tag_name, @@ -218,39 +343,21 @@ export async function fetchRepoStatus( publishedAt: releaseData.published_at || releaseData.created_at, author: releaseData.author?.login || "Maintainer", }; - } catch (_err) { - latestRelease = null; } - // 6. Fetch any custom pings recorded in Deno KV - const recentPings = await getPings(normalizedOwner, normalizedRepo); - - // 7. Calculate Status & Uptime - const openIncidents = incidents.filter((i) => i.state === "open"); - const recentRuns = workflowRuns.slice(0, 10); - const failedRecent = recentRuns.filter((r) => r.conclusion === "failure"); - - let status: RepoStatusData["status"] = "operational"; - let statusMessage = "Todos los sistemas y flujos operacionales"; + const recentPings = pingsRes.status === "fulfilled" ? pingsRes.value : []; + const kvHistory = historyRes.status === "fulfilled" + ? historyRes.value + : undefined; - if (openIncidents.length > 0) { - status = "outage"; - statusMessage = `Incidente activo: ${openIncidents[0].title}`; - } else if (failedRecent.length > 0) { - if (failedRecent.length > recentRuns.length / 2) { - status = "outage"; - statusMessage = "Fallos críticos en pipelines de CI/CD detectados"; - } else { - status = "degraded"; - statusMessage = "Degradación parcial en flujos de trabajo"; - } - } else if (recentRuns.length === 0) { - status = "operational"; - statusMessage = "Operacional • Sin incidencias en CI/CD"; - } + // 3. Calculate overall status (including synthetic pings) & 90-day uptime history + const { status, statusMessage } = computeOverallStatus( + workflowRuns, + incidents, + recentPings, + ); - // Compute uptime percentage across the history days - const historyBars = generateHistoryDays(workflowRuns, incidents); + const historyBars = generateHistoryDays(workflowRuns, incidents, kvHistory); const totalUptimeSum = historyBars.reduce( (acc, curr) => acc + curr.uptimePercent, 0, @@ -258,17 +365,9 @@ export async function fetchRepoStatus( const uptimePercentage = Math.round((totalUptimeSum / historyBars.length) * 100) / 100; - // Compute latency metrics if pings contain latency reports - const pingsWithLatency = recentPings.filter( - (p) => typeof p.latencyMs === "number" && p.latencyMs > 0, + const { averageLatencyMs, lastPingLatencyMs } = computePingLatencyMetrics( + recentPings, ); - const averageLatencyMs = pingsWithLatency.length > 0 - ? Math.round( - pingsWithLatency.reduce((acc, p) => acc + (p.latencyMs || 0), 0) / - pingsWithLatency.length, - ) - : undefined; - const lastPingLatencyMs = pingsWithLatency[0]?.latencyMs; const result: RepoStatusData = { owner: repoData.owner.login, @@ -292,51 +391,62 @@ export async function fetchRepoStatus( recentPings, averageLatencyMs, lastPingLatencyMs, + etag: newEtag, }; - // Save to Deno KV await saveRepoStatus(result); - return result; } catch (error: unknown) { - // 1. Si hay datos cacheados en Deno KV (incluso antiguos), los usamos como fallback - const staleCached = await getCachedRepoStatus( - normalizedOwner, - normalizedRepo, - true, - ); - if (staleCached) { - staleCached.isRateLimited = true; - staleCached.recentPings = await getPings( - normalizedOwner, - normalizedRepo, - ); - const pingsWithLatency = staleCached.recentPings.filter( - (p) => typeof p.latencyMs === "number" && p.latencyMs > 0, - ); - staleCached.averageLatencyMs = pingsWithLatency.length > 0 - ? Math.round( - pingsWithLatency.reduce((acc, p) => acc + (p.latencyMs || 0), 0) / - pingsWithLatency.length, - ) - : undefined; - staleCached.lastPingLatencyMs = pingsWithLatency[0]?.latencyMs; - return staleCached; - } - const err = error as { status?: number; message?: string; response?: { headers?: Record }; }; + // Conditional ETag hit (304 Not Modified): refresh timestamp & pings at 0 rate-limit cost + if (err.status === 304 && staleCached) { + const recentPings = await getPings(normalizedOwner, normalizedRepo); + const { averageLatencyMs, lastPingLatencyMs } = computePingLatencyMetrics( + recentPings, + ); + const { status, statusMessage } = computeOverallStatus( + staleCached.workflowRuns, + staleCached.incidents, + recentPings, + ); + const refreshed: RepoStatusData = { + ...staleCached, + status, + statusMessage, + recentPings, + averageLatencyMs, + lastPingLatencyMs, + lastUpdated: new Date().toISOString(), + cachedAt: Date.now(), + isRateLimited: false, + }; + await saveRepoStatus(refreshed); + return refreshed; + } + + // Fallback to stale cache during rate limits or transient GitHub outages + if (staleCached && err.status !== 404) { + staleCached.isRateLimited = err.status === 403 || err.status === 429; + staleCached.recentPings = await getPings(normalizedOwner, normalizedRepo); + const { averageLatencyMs, lastPingLatencyMs } = computePingLatencyMetrics( + staleCached.recentPings, + ); + staleCached.averageLatencyMs = averageLatencyMs; + staleCached.lastPingLatencyMs = lastPingLatencyMs; + return staleCached; + } + if (err.status === 404) { throw new Error( - `El repositorio "${owner}/${repo}" no fue encontrado en GitHub.`, + `El repositorio "${normalizedOwner}/${normalizedRepo}" no fue encontrado en GitHub.`, ); } - // 2. Si es rate limit (403/429) y no hay caché, modo degradado de resiliencia if (err.status === 403 || err.status === 429) { const resetHeader = err.response?.headers?.["x-ratelimit-reset"]; const resetTimestamp = resetHeader @@ -348,16 +458,9 @@ export async function fetchRepoStatus( ); const recentPings = await getPings(normalizedOwner, normalizedRepo); - const pingsWithLatency = recentPings.filter( - (p) => typeof p.latencyMs === "number" && p.latencyMs > 0, + const { averageLatencyMs, lastPingLatencyMs } = computePingLatencyMetrics( + recentPings, ); - const averageLatencyMs = pingsWithLatency.length > 0 - ? Math.round( - pingsWithLatency.reduce((acc, p) => acc + (p.latencyMs || 0), 0) / - pingsWithLatency.length, - ) - : undefined; - const lastPingLatencyMs = pingsWithLatency[0]?.latencyMs; const fallbackData: RepoStatusData = { owner: normalizedOwner, @@ -387,13 +490,12 @@ export async function fetchRepoStatus( rateLimitResetMinutes: minutesUntilReset, }; - // Guardar en KV para evitar golpear la API de GitHub mientras dure el bloqueo await saveRepoStatus(fallbackData); return fallbackData; } throw new Error( - `Error al consultar el estado de "${owner}/${repo}": ${ + `Error al consultar el estado de "${normalizedOwner}/${normalizedRepo}": ${ err.message || "Error desconocido" }`, ); diff --git a/services/kv.ts b/services/kv.ts index 70e0edc..b00848a 100644 --- a/services/kv.ts +++ b/services/kv.ts @@ -87,6 +87,14 @@ export interface RepoStatusData { lastPingLatencyMs?: number; isRateLimited?: boolean; rateLimitResetMinutes?: number; + etag?: string; +} + +export interface DailyHistorySnapshot { + date: string; + status: "operational" | "degraded" | "outage" | "unknown"; + uptimePercent: number; + updatedAt: string; } let kvInstance: Deno.Kv | null = null; @@ -221,3 +229,72 @@ export async function invalidateRepoCache( const key = ["repo_status", owner.toLowerCase(), repo.toLowerCase()]; await kv.delete(key); } + +/** + * Retrieves persisted daily history snapshots for a repository (up to 90 days). + */ +export async function getRepoHistoryMap( + owner: string, + repo: string, +): Promise> { + const kv = await getKv(); + const prefix = ["repo_history", owner.toLowerCase(), repo.toLowerCase()]; + const map = new Map(); + const iter = kv.list({ prefix }); + for await (const entry of iter) { + if (entry.value?.date) { + map.set(entry.value.date, entry.value); + } + } + return map; +} + +/** + * Atomic CAS rate-limiter backed by Deno KV (prevents concurrent TOCTOU bypasses). + */ +export async function consumeRateLimit( + key: Deno.KvKey, + maxPerWindow: number, + expireInMs: number, +): Promise<{ allowed: boolean; count: number }> { + const kv = await getKv(); + for (let attempt = 0; attempt < 5; attempt++) { + const entry = await kv.get(key); + const current = entry.value ?? 0; + if (current >= maxPerWindow) { + return { allowed: false, count: current }; + } + const next = current + 1; + const res = await kv + .atomic() + .check(entry) + .set(key, next, { expireIn: expireInMs }) + .commit(); + if (res.ok) { + return { allowed: true, count: next }; + } + } + return { allowed: false, count: maxPerWindow }; +} + +/** + * Guards `?refresh=true` against cache-busting DoS with an atomic per-repo cooldown. + */ +export async function canForceRefresh( + owner: string, + repo: string, + cooldownMs = 30 * 1000, +): Promise { + const kv = await getKv(); + const key = ["refresh_cooldown", owner.toLowerCase(), repo.toLowerCase()]; + const entry = await kv.get(key); + if (entry.value && Date.now() - entry.value < cooldownMs) { + return false; + } + const res = await kv + .atomic() + .check(entry) + .set(key, Date.now(), { expireIn: cooldownMs }) + .commit(); + return res.ok; +} diff --git a/services/security.ts b/services/security.ts index 6b9aa13..2297610 100644 --- a/services/security.ts +++ b/services/security.ts @@ -120,3 +120,60 @@ export async function verifyHmacSha256( return false; } } + +/** + * Reads a Request body up to `maxBytes`, aborting early if Content-Length or streamed bytes + * exceed the limit (mitigates memory exhaustion / payload flooding). + */ +export async function readBoundedBody( + req: Request, + maxBytes: number, +): Promise<{ ok: true; text: string } | { ok: false; error: string }> { + const contentLength = req.headers.get("content-length"); + if (contentLength) { + const declared = Number(contentLength); + if (Number.isFinite(declared) && declared > maxBytes) { + return { + ok: false, + error: + `Cuerpo de la petición demasiado grande (máximo ${maxBytes} bytes).`, + }; + } + } + + if (!req.body) { + return { ok: true, text: "" }; + } + + const reader = req.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel(); + return { + ok: false, + error: + `Cuerpo de la petición demasiado grande (máximo ${maxBytes} bytes).`, + }; + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + + const merged = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + merged.set(chunk, offset); + offset += chunk.byteLength; + } + return { ok: true, text: new TextDecoder().decode(merged) }; +} diff --git a/tests/github_test.ts b/tests/github_test.ts new file mode 100644 index 0000000..44e01bf --- /dev/null +++ b/tests/github_test.ts @@ -0,0 +1,53 @@ +// tests/github_test.ts +import { assertEquals } from "$std/assert/mod.ts"; +import { + computeOverallStatus, + generateHistoryDays, +} from "../services/github.ts"; +import { DailyHistorySnapshot, PingRecord } from "../services/kv.ts"; + +Deno.test("GitHub status - integrates recent failed synthetic pings into overall outage status", () => { + const now = Date.now(); + const failedPing: PingRecord = { + timestamp: new Date(now - 60_000).toISOString(), + workflow: "Synthetic Healthcheck", + status: "failure", + message: "HTTP 503 Service Unavailable", + httpStatus: 503, + }; + + const result = computeOverallStatus([], [], [failedPing], now); + assertEquals(result.status, "outage"); + assertEquals(result.statusMessage.includes("HTTP 503"), true); + + // Stale ping (>24h old) should not trigger an active outage + const stalePing: PingRecord = { + ...failedPing, + timestamp: new Date(now - 48 * 60 * 60 * 1000).toISOString(), + }; + const staleResult = computeOverallStatus([], [], [stalePing], now); + assertEquals(staleResult.status, "operational"); +}); + +Deno.test("GitHub history - hydrates older days from persisted Deno KV snapshots", () => { + const fortyDaysAgo = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000) + .toISOString() + .slice(0, 10); + + const kvHistory = new Map([ + [ + fortyDaysAgo, + { + date: fortyDaysAgo, + status: "degraded", + uptimePercent: 97.5, + updatedAt: new Date().toISOString(), + }, + ], + ]); + + const bars = generateHistoryDays([], [], kvHistory); + const target = bars.find((b) => b.date === fortyDaysAgo); + assertEquals(target?.status, "degraded"); + assertEquals(target?.uptimePercent, 97.5); +}); diff --git a/tests/kv_test.ts b/tests/kv_test.ts index a96d423..c0dbe05 100644 --- a/tests/kv_test.ts +++ b/tests/kv_test.ts @@ -74,3 +74,26 @@ Deno.test("Deno KV - secret management and cache invalidation", async () => { ); assertEquals(cachedAfterInvalidation, null); }); + +Deno.test("Deno KV - history map, atomic rate limit, and refresh cooldown", async () => { + const { + canForceRefresh, + consumeRateLimit, + getRepoHistoryMap, + } = await import("../services/kv.ts"); + + const history = await getRepoHistoryMap("test-owner", "test-repo"); + assertEquals(history.size >= 1, true); + + const rlKey = ["test_rl", crypto.randomUUID()]; + const r1 = await consumeRateLimit(rlKey, 2, 60_000); + const r2 = await consumeRateLimit(rlKey, 2, 60_000); + const r3 = await consumeRateLimit(rlKey, 2, 60_000); + assertEquals(r1.allowed, true); + assertEquals(r2.allowed, true); + assertEquals(r3.allowed, false); + + const repoName = `cooldown-${crypto.randomUUID().slice(0, 8)}`; + assertEquals(await canForceRefresh("test-owner", repoName, 60_000), true); + assertEquals(await canForceRefresh("test-owner", repoName, 60_000), false); +}); diff --git a/tests/security_test.ts b/tests/security_test.ts index 04d1483..a98cea5 100644 --- a/tests/security_test.ts +++ b/tests/security_test.ts @@ -85,3 +85,21 @@ Deno.test("Security - verifyHmacSha256 calculates and verifies HMAC signatures", const wrongSecret = await verifyHmacSha256("wrong-key", payload, signature); assertEquals(wrongSecret, false); }); + +Deno.test("Security - readBoundedBody enforces maximum byte limits", async () => { + const { readBoundedBody } = await import("../services/security.ts"); + + const smallReq = new Request("https://example.com/api", { + method: "POST", + body: JSON.stringify({ ok: true }), + }); + const okRes = await readBoundedBody(smallReq, 1024); + assertEquals(okRes.ok, true); + + const hugeReq = new Request("https://example.com/api", { + method: "POST", + body: "A".repeat(2048), + }); + const deniedRes = await readBoundedBody(hugeReq, 512); + assertEquals(deniedRes.ok, false); +});