Harden dashboard security surfaces

This commit is contained in:
Codex
2026-04-25 03:00:13 +00:00
parent 28dfa3074c
commit 5fc2ea78de
11 changed files with 323 additions and 172 deletions
+11 -5
View File
@@ -19,6 +19,12 @@ function sanitizeSegment(value: string) {
return value.trim().replace(/[^\w.@:+-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "backup"
}
function normalizeBackupId(value: string) {
const safeId = sanitizeSegment(value)
if (safeId !== value) throw new Error("backup id contains unsupported characters")
return safeId
}
function archivePath(id: string) {
return path.join(BACKUP_DIR, `${id}.tar.gz`)
}
@@ -28,7 +34,7 @@ function metadataPath(id: string) {
}
async function ensureBackupDirectory() {
await mkdir(BACKUP_DIR, { recursive: true })
await mkdir(BACKUP_DIR, { recursive: true, mode: 0o700 })
}
export async function listBackupCatalog() {
@@ -67,8 +73,8 @@ export async function createCatalogBackup(sandboxId: string, sourcePath: string)
createdAt: archive.createdAt,
}
await writeFile(archivePath(id), archive.bytes)
await writeFile(metadataPath(id), `${JSON.stringify(entry, null, 2)}\n`)
await writeFile(archivePath(id), archive.bytes, { mode: 0o600 })
await writeFile(metadataPath(id), `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600 })
const entries = await listBackupCatalog()
await Promise.all(entries.slice(MAX_BACKUP_COUNT).map((stale) => deleteCatalogBackup(stale.id).catch(() => undefined)))
@@ -77,7 +83,7 @@ export async function createCatalogBackup(sandboxId: string, sourcePath: string)
}
export async function getCatalogBackup(id: string) {
const safeId = sanitizeSegment(id)
const safeId = normalizeBackupId(id)
const metadata = JSON.parse(await readFile(metadataPath(safeId), "utf8")) as BackupCatalogEntry
const bytes = await readFile(archivePath(safeId))
return { metadata, bytes }
@@ -89,7 +95,7 @@ export async function restoreCatalogBackup(id: string, targetSandboxId: string,
}
export async function deleteCatalogBackup(id: string) {
const safeId = sanitizeSegment(id)
const safeId = normalizeBackupId(id)
await Promise.all([
rm(archivePath(safeId), { force: true }),
rm(metadataPath(safeId), { force: true }),
+51
View File
@@ -0,0 +1,51 @@
type RateLimitBucket = {
count: number
resetAt: number
}
const buckets = new Map<string, RateLimitBucket>()
export type RateLimitResult = {
limited: boolean
retryAfterSeconds: number
}
function clientAddress(request: Request) {
const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
return forwarded
|| request.headers.get("x-real-ip")
|| request.headers.get("cf-connecting-ip")
|| "local"
}
export function rateLimitKey(request: Request, scope: string) {
return `${scope}:${clientAddress(request)}`
}
export function checkRateLimit(key: string, maxAttempts: number, windowMs: number): RateLimitResult {
const now = Date.now()
const current = buckets.get(key)
if (!current || current.resetAt <= now) {
return { limited: false, retryAfterSeconds: 0 }
}
return {
limited: current.count >= maxAttempts,
retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)),
}
}
export function recordRateLimitFailure(key: string, windowMs: number) {
const now = Date.now()
const current = buckets.get(key)
const next = !current || current.resetAt <= now
? { count: 1, resetAt: now + windowMs }
: { count: current.count + 1, resetAt: current.resetAt }
buckets.set(key, next)
return next
}
export function clearRateLimit(key: string) {
buckets.delete(key)
}
+16 -3
View File
@@ -14,7 +14,8 @@ const HOST_PATH = [
process.env.PATH || "",
].filter(Boolean).join(":")
const MAX_FILE_BYTES = Number.parseInt(process.env.SANDBOX_FILE_TRANSFER_MAX_BYTES || String(128 * 1024 * 1024), 10)
export const MAX_FILE_BYTES = Number.parseInt(process.env.SANDBOX_FILE_TRANSFER_MAX_BYTES || String(128 * 1024 * 1024), 10)
export const MAX_MULTIPART_REQUEST_BYTES = MAX_FILE_BYTES + Math.min(10 * 1024 * 1024, Math.max(1024 * 1024, Math.floor(MAX_FILE_BYTES / 10)))
const ALLOWED_ROOTS = ["/sandbox", "/tmp"]
const MAX_LIST_ENTRIES = Number.parseInt(process.env.SANDBOX_FILE_LIST_MAX_ENTRIES || "200", 10)
@@ -46,6 +47,15 @@ export function normalizeSandboxPath(input: string, fallbackFileName?: string) {
return normalized
}
export function assertRequestContentLength(request: Request, maxBytes = MAX_MULTIPART_REQUEST_BYTES) {
const raw = request.headers.get("content-length")
if (!raw) return
const size = Number.parseInt(raw, 10)
if (Number.isFinite(size) && size > maxBytes) {
throw new Error(`request is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
}
}
function runSandboxExec(sandboxName: string, script: string, input?: Buffer, timeoutMs = 60000) {
return new Promise<{ stdout: Buffer; stderr: string; code: number | null }>((resolve, reject) => {
const child = spawn(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
@@ -224,14 +234,17 @@ export async function restoreSandboxArchive(
`tmp_archive="$(mktemp /tmp/openshell-restore.XXXXXX.tar.gz)"`,
`cat > "$tmp_archive"`,
`tar -tzf "$tmp_archive" >/tmp/openshell-restore-list.$$`,
`while IFS= read -r entry; do case "$entry" in ""|/*|../*|*/../*|*"/..") rm -f "$tmp_archive" /tmp/openshell-restore-list.$$; exit 42;; esac; done < /tmp/openshell-restore-list.$$`,
`tar -tvzf "$tmp_archive" >/tmp/openshell-restore-verbose.$$`,
`while IFS= read -r entry; do case "$entry" in ""|/*|../*|*/../*|*"/..") rm -f "$tmp_archive" /tmp/openshell-restore-list.$$ /tmp/openshell-restore-verbose.$$; exit 42;; esac; done < /tmp/openshell-restore-list.$$`,
`while IFS= read -r entry; do case "$entry" in [-d]*) :;; *) rm -f "$tmp_archive" /tmp/openshell-restore-list.$$ /tmp/openshell-restore-verbose.$$; exit 43;; esac; done < /tmp/openshell-restore-verbose.$$`,
`mkdir -p ${shellQuote(targetPath)}`,
replace ? `find ${shellQuote(targetPath)} -mindepth 1 -maxdepth 1 -exec rm -rf -- {} +` : `:`,
`if grep -q '^payload/' /tmp/openshell-restore-list.$$; then tar -xzf "$tmp_archive" -C ${shellQuote(targetPath)} --strip-components=1 --wildcards 'payload/*'; else tar -xzf "$tmp_archive" -C ${shellQuote(targetPath)}; fi`,
`rm -f "$tmp_archive" /tmp/openshell-restore-list.$$`,
`rm -f "$tmp_archive" /tmp/openshell-restore-list.$$ /tmp/openshell-restore-verbose.$$`,
].join(" && ")
const result = await runSandboxExec(sandboxName, script, payload, 120000)
if (result.code === 42) throw new Error("archive contains unsafe paths")
if (result.code === 43) throw new Error("archive contains unsupported entry types")
if (result.code !== 0) throw new Error(result.stderr || "failed to restore sandbox archive")
return {