import { authenticateDavPat } from "@/worker/auth/basic"; import { DAV_AREAS } from "@/worker/dav/areas"; import { isDavWellKnownPath } from "@/worker/dav/discovery"; import { davError, unauthorizedDav } from "@/worker/dav/http"; import { dispatchDavArea, expensiveDavRequestArea, findDavArea, isExpensiveDavRequest } from "@/worker/dav/runtime"; import { createControlPlaneDb } from "@/worker/db/d1/client"; import { getSubjectByHostLabel } from "@/worker/db/d1/repository"; import { enforceRateLimit } from "@/worker/middleware/rate-limit"; import type { AppContext } from "@/worker/types"; import { clientIp } from "@/worker/util/request-context"; import { jsonError } from "@/worker/util/response"; function isControlPlaneOnlyPath(pathname: string): boolean { return ( pathname === "/healthz" || pathname.startsWith("/api/v1/") || pathname === "/api/v1" || pathname === "/api/v1/openapi.json" || pathname === "/api/v1/openapi.yaml" ); } function isLoopbackHost(host: string): boolean { return ( host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host.endsWith(".127.0.0.1") || host === "[::1]" ); } function requiresHttps(c: AppContext): boolean { const url = new URL(c.req.url); const hostInfo = c.get("hostInfo"); return url.protocol === "http:" && !isLoopbackHost(hostInfo.normalizedHost); } export async function handleSubjectDavRequest(c: AppContext): Promise { const hostInfo = c.get("hostInfo"); if (hostInfo.kind !== "subject") return c.notFound(); const pathname = new URL(c.req.url).pathname; if (isControlPlaneOnlyPath(pathname)) return c.notFound(); if (!hostInfo.hostLabel) return c.notFound(); const subject = await getSubjectByHostLabel(createControlPlaneDb(c.env.DAV_CONTROL_PLANE), hostInfo.hostLabel); if (!subject) return c.notFound(); if (requiresHttps(c)) return davError(403, "HTTPS is required for DAV requests"); if (isDavWellKnownPath(pathname)) return c.redirect("/", 302); const auth = await authenticateDavPat(c.env, c.req.raw, subject); if (!auth) { const limited = await enforceRateLimit(c, "RL_DAV_AUTH", [ "dav_auth_failure", subject.id, hostInfo.hostLabel, clientIp(c.req.raw), ]); if (limited) return limited; return unauthorizedDav(); } if (auth.subjectId !== subject.id) return jsonError("forbidden", "PAT does not match the subject host.", 403); const area = findDavArea(pathname, DAV_AREAS); if (c.req.method === "OPTIONS") return area ? await dispatchDavArea(area, { c, subject, auth, pathname }) : c.notFound(); if (isExpensiveDavRequest(c.req.raw)) { const limited = await enforceRateLimit(c, "RL_REPORT", [ "dav_expensive", auth.subjectId, auth.patId, c.req.method, expensiveDavRequestArea(pathname), ]); if (limited) return limited; } return area ? await dispatchDavArea(area, { c, subject, auth, pathname }) : c.notFound(); }