[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECWQ4G86H0WEEJSSQYC8TZ":3,"skill-same:01M7ECWQ4G86H0WEEJSSQYC8TZ":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECWQ4G86H0WEEJSSQYC8TZ","python-fastapi-hardening",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fpython-fastapi-hardening\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# python-fastapi-hardening\n\n# FastAPI\u002FStarlette Security Hardening\n\nRun a hardening pass **section by section**, live-verify each guard with curl\nagainst the running service, and confirm what changed after each section. Never\nbreak existing endpoint contracts. Audit before implementing.\n\n## Starlette middleware gotchas (all hit live)\n\n- **`JSONResponse(415, content=...)` positionally crashes** — the first\n  positional arg binds to `content`, so passing an int + a `content=` kwarg\n  raises `TypeError: JSONResponse.__init__() got multiple values for 'content'`\n  → every guarded request 500s. Always write `JSONResponse(status_code=415,\n  content={...})`. One regex fix across the file:\n  `\u002FJSONResponse\\((\\d{3}), content=\u002FJSONResponse(status_code=\\1, content=\u002F`.\n- **`MutableHeaders` has no `.pop()`** — popping a header from a Starlette\n  response raises `AttributeError: 'MutableHeaders' object has no attribute\n  'pop'`. Use `try: del resp.headers[k] except (KeyError, AttributeError)`.\n- **`server: uvicorn` is added at send-time by uvicorn — middleware can't\n  remove it.** Strip identity with the uvicorn CLI flag `--no-server-header`\n  in the systemd\u002Fexec line, not in the middleware.\n- **Middleware ordering: last `add_middleware()` call runs FIRST (outermost).**\n  To short-circuit malformed bodies before the payment gateway\u002Fratelimiter sees\n  them, register the input-validation middleware LAST. Verify with a curl that\n  should 415\u002F400 BEFORE the 402 gate.\n- **Body is safe to re-read, never `_receive`.** Starlette buffers the request\n  body, so an outer middleware can `await request.body()` and the inner x402\n  routing re-reads it fine. Re-injecting `request._receive` in a\n  `BaseHTTPMiddleware` kills SSE (empty 200). Use `request.state` for\n  cross-middleware data, not contextvars.\n- **`raise HTTPException(...)` inside `@app.middleware(\"http\")` does NOT become\n  the intended status code — it becomes a 500.** FastAPI's exception handlers\n  wrap route handlers, not the middleware chain, so an exception raised in\n  middleware falls through to the generic 500 path uncaught. An auth-check\n  middleware that `raise`s 401 on a bad token will curl-test as `500` for both\n  the missing-token and wrong-token cases — looks like the auth logic is\n  broken when it's actually the wrong return mechanism. Fix: `return\n  JSONResponse(status_code=401, content={...})` directly from the middleware,\n  never `raise HTTPException` there. Verify with curl on all three cases (no\n  token, wrong token, right token) before trusting the status codes.\n\n## Input validation middleware (one pass, at the boundary)\n\nA single `InputValidationMiddleware` (outermost) covering all body\u002Fquery guards:\n\n- POST\u002FPUT\u002FPATCH\u002FDELETE → **415** unless `Content-Type: application\u002Fjson`.\n- **Gate by method first.** GET\u002FHEAD\u002FOPTIONS carry no body — guard them with\n  `if request.method not in (\"POST\",\"PUT\",\"PATCH\",\"DELETE\"): return await call_next(request)`\n  before the content-type check. A blanket 415 on \"not JSON\" fires on HEAD\u002FOPTIONS\n  (health probes, crawler probing, x402scan) and breaks them — verified regression:\n  `curl -sI \u002Fhealth` returned 415 until the method gate was added.\n- Body > 1MB → **413**.\n- Invalid JSON \u002F nesting depth > 10 → **400** (JSON bomb).\n- Chat: `messages` > 500 → 400; single message > 100KB → 400;\n  unknown `model` → 400; token estimate > model `context_length` → 400;\n  `tools` on a model w\u002Fo `tool_calling` capability → 400; `max_tokens` >\n  `context_length` → 400.\n- GET `\u002Fdata`: allowlist query chars, reject shell\u002FSQL\u002FURL-encoded payloads\n  → 400. Address params (`address`\u002F`addr`\u002F`pair`\u002F`token`) must be valid\n  checksummed ERC-55 (`web3.is_checksum_address`).\n- **Exempt form\u002Fmultipart**: OAuth2 login and multipart uploads are NOT JSON.\n  `if ct in (\"application\u002Fx-www-form-urlencoded\",) or ct.startswith(\"multipart\u002F\")`\n  → pass through, or you 415-break auth logins.\n\n### Path-matching bug\n`startswith(\"\u002Fdata\u002F\")` misses `\u002Fx402\u002Fv1\u002Fdata\u002F*`. Match the suffix: `\u002Fdata\u002F`.\n\n### DB model metadata\nMatch client-facing `model` against the DB registry `name` (not the UUID `id`).\nField is `context_length`, NOT `context_window`. Cache 60s; fail-empty (return\nempty set so the allowlist is skipped rather than blocking the gateway).\n\n### Live verification\nA `401`\u002F`402` means the payment gate ran FIRST (your guard didn't); a guard\nclaim needs 400\u002F413\u002F415. A `;` in a shell URL splits the command — use\nURL-encoded params or a python httpx probe, never inline semicolons.\n\n## Auth brute-force throttle\n\nLogin endpoints (OAuth2 form) usually have NO rate limit — add per-IP throttle\nreusing the existing Redis `RateLimiter.is_rate_limited(key, limit, window)`:\n`ratelimit:login:ip:{client_ip}`, e.g. 10\u002F60s → **429**. Fail-open on Redis\nerrors (don't lock everyone out because Redis hiccuped). Verify with 13 rapid\nattempts: expect 401×9 then 429×4.\n\n## TLS \u002F transport audit (live)\n\n- **Min-TLS is enforced at the TLS terminator, not in the app** — probe the edge:\n  `for v in tls1 tls1_1 tls1_2 tls1_3; do out=$(printf '' | timeout 12 openssl s_client -connect HOST:443 -$v 2>&1); echo \"$out\" | grep -q \"BEGIN CERTIFICATE\" && echo \"$v OK\" || echo \"$v REJECTED\"; done`\n  A naive `curl --tlsv1 \u002F --tlsv1.1` loop against the domain is unreliable (modern curl routes `--tlsv1` oddly; it \"errors\" ambiguously). Prefer `openssl s_client` matching the cert marker.\n- **Plain HTTP (port 80) returning 200 = no auto-redirect** — Cloudflare's\n  \"Always Use HTTPS\" is OFF. Flag it as a dashboard toggle (infra action, not\n  code); `curl -sI https:\u002F\u002Fhost` should NOT show port-80 200-without-redirect.\n  **How to verify after the user flips the toggle:**\n  `curl -sI http:\u002F\u002FHOST\u002Fhealth` must return `301` with `redirect_url=https:\u002F\u002FHOST\u002Fhealth`\n  (before: `200`). HTTPS itself must still be `200`. That pairing is your proof\n  the toggle took effect.\n- **Outbound provider cert verification**: grep the whole tree for `verify=False`, `check_hostname=False`, `ssl_unverified`, `create_default_context` — any hit is a disabled-verification leak. Ensure providers build pooled `httpx.AsyncClient`\u002FSDK clients with default verify ON (do not pass `verify=False`).\n\n## Dependency audit — pip-audit (Section 8)\n\n- Deps are already exactly pinned (`==`) via `requirements.txt` — that satisfies \"pin exactly\"; don't add a lockfile unless required.\n- `pip install pip-audit` in the venv (one-off; audit tool), then `pip-audit -r requirements.txt`. Crucial: for this class of API **`cryptography` is a live dependency (ECDSA response signing)** — if the audit flags it, the fix matters and the upgrade has blast radius.\n- **After upgrading a crypto\u002Fsigning library, re-verify the signing surface lives**: restart, then `curl -w %{http_code} \u002Fx402\u002Fv1\u002Fpubkey` must be 200 (proves the ECDSA path still loads), plus a `pip-audit` re-run must report clean. The test earlier showed PUBKEY=200 is the right liveness check — not just `\u002Fhealth`.\n- Add a tiny reusable gate `scripts\u002Fdep_audit.sh` that runs `pip-audit -r requirements.txt` and exits nonzero on any vulnerability — that's the \"CI fails on new vulns\" item; make it re-runnable rather than a one-off.\n- Don't prune \"unused\" deps that show 0 imports in `app\u002F` — they're usually transitive (uvloop\u002Fwatchfiles=uvicorn extras, regex=tiktoken, pluggy=pytest). Skipping pruning is the lazy correct call unless a full pip-breakage analysis says otherwise.\n\n## Rotating a live DB\u002Fsecret (Postgres) without breaking prod\n\nThe app reaches Postgres via Docker (`cortexcloud-db` container inside the LXC). To rotate and PROVE the new password works:\n1. Generate `openssl rand -hex 24`; ship the value to a file on the host\u002Fcontainer (`scp` → `pct push`) and `sed` it into `.env` — **never inline the password through ssh quoting** (nested `$NEW` through `ssh + pct exec + docker exec` layers mangles: set placeholder → `ALTER ROLE ''` cleared the password, an outage window). File-based transfer, then source\u002Fcat it at the destination.\n2. Set it in the role: `psql -c \"ALTER ROLE postgres PASSWORD '\u003Cthe value>';\"` — do not let `$NEW` come from a shell var that failed to expand.\n3. Restart the app and verify with a **DB-touching request, not just `\u002Fhealth`**: a login that returns `401` (not a 500) proves Postgres accepted the new credentials over TCP and ran the auth query. `401` = auth-result OK; `500` = auth failure.\n4. Credential hygiene: save the new secret to a chmod-600 file on the agent host, scrub all `\u002Ftmp` copies on host + container, and never ECHO\u002Freprint the value in chat or logs. Tell the user to move it to their password manager.\n5. After rotating a weak default, re-add it to the fail-fast dev-default list (it was excluded only pending rotation) so it can't regress.\n\n## HTTP security headers\n\nHSTS `max-age=31536000; includeSubDomains`, `X-Content-Type-Options: nosniff`,\n`X-Frame-Options: DENY`, `Content-Security-Policy: default-src 'none'`,\n`Referrer-Policy: no-referrer`, `Cache-Control: no-store`, `X-Request-Id`.\nStrip `Server`\u002F`X-Powered-By`\u002F`X-AspNet-Version`.\n\n### HSTS `preload` (browser list) — separate from the header\n\nThe header alone (`max-age=31536000; includeSubDomains`) is NOT enough for the\nbrowser preload list: hstspreload.org requires the literal `preload` directive\nand a max-age ≥ 31536000. Add it in-repo (one string):\n`Strict-Transport-Security: max-age=31536000; includeSubDomains; preload`.\nCloudflare passes the origin's HSTS header through, so the public edge then\nserves the `preload` value — verify with `curl -sI https:\u002F\u002Fhost\u002Fhealth |\ngrep -i strict-transport`. Then the user submits the domain at hstspreload.org\n(their step, not code). Order matters: enable Always-Use-HTTPS first, verify\nthe 301, wait a day, only then promote to preload — preload is near-irreversible\n(browsers ship it; removal takes months), so never enable it on a domain that\nstill serves plain HTTP.\n\n## Secrets fail-fast (Section 7)\n\nPydantic-settings `BaseSettings` reads `.env` via `env_file` but does **NOT\nexport values into `os.environ`**. A startup fail-fast that checks\n`os.environ.get(\"SECRET\")` will wrongly report secrets \"missing\" that exist\nonly in `.env` (killed a boot). Fix: declare the secret as a real Settings\nfield (`VAR: Optional[str] = Field(None, env=\"VAR\")`) and read it with\n`getattr(self, var, None)` — pydantic loads it from `.env`.\n\nAdd a `model_validator(mode=\"after\")` guarded by `if self.ENV == \"production\":\nreturn self`:\n- Reject known dev-placeholder defaults (`dev-jwt-...`, `dev-api-key-salt-...`,\n  `postgres`) → raise `ValueError(\"[S7] ...\")` so the process refuses to boot.\n- Require non-empty for critical secrets (wallet, signing key, facilitator key\n  ID+secret).\n- Rotate BEFORE enabling POSTGRES_PASSWORD fail-fast, or the service won't boot\n  until rotated. Temporarily exclude a secret pending rotation rather than\n  keeping prod offline; re-add it once real.\n\n### Verifying fail-fast\n`env -u SECRET python -c \"from app.core.config import settings\"` does NOT clear\nthe file value — pydantic still reads `.env`. True test: copy `.env` aside,\n`echo ENV=production > .env`, import (expect pydantic ValidationError), restore.\nHealth-200 proves all required secrets are present; a 500\u002F`ValueError` at boot\nis the guard working.\n\n## Security audit log + alert counters (Section 9)\n\nEvents already get logged to stdout→journald, but §9 wants a **separate,\nappend-only security log** plus alerting. Two tiny helpers in one\n`app\u002Fmiddleware\u002Faudit.py` module, both **fail-open** (an fs\u002FRedis error never\nbreaks the request path):\n\n```python\ndef audit(event, **fields):  # append one JSONL line to \u002Fvar\u002Flog\u002Fcortexcloud\u002Fsecurity.log\n    # os.open(path, O_WRONLY|O_CREAT|O_APPEND, 0o600); write json; 32MB cap via\n    # lseek+truncate. NEVER log secrets\u002Fbodies — coerce field values to str.\n\nasync def alert(client, bucket, window, threshold, event, **fields) -> bool:\n    # Redis: INCR secalert:{bucket}; expire on first incr; when n>=threshold\n    # logger.error(json.dumps(...)) then DEL so fresh windows re-alert.\n```\n\nWire `audit(...)` at every guard\u002Freject you already have (proof_rejected with\npayer+reason+ip, rate_limited, nonce_replay, login_bruteforce, and each\nvalidation reject kind with ip+path). Wire `alert(get_redis(), bucket, ...)`\nat the money\u002FDoS surfaces (e.g. 10 proof fails\u002F60s = attack signal; 200\nrate-limit\u002F5min = DoS). Reuse the app's existing redis singleton\n(`get_redis()`) rather than a new client — don't add a fresh dependency.\n\nLazy skips: the **outbound notification channel** (PagerDuty\u002Femail\u002Fwebhook) is\nNOT part of the lib — you emit to journald\u002Fstdout `ERROR` (`logger.error`) +\nRedis counters; shipping an actual notifier is the user's infra call. Direct page\nsubscribers at the channel, not in the code. Also skip an audit DB table unless\nanalytics demands it — append JSONL first.\n\nFile perms matter: the systemd unit may run as root (no `User=`), so the log\ndir\u002Ffile land owned by root; `mkdir -p \u002Fvar\u002Flog\u002Fcortexcloud` at bootstrap and\nlet the process own it.\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Fmlops\u002Fpython-fastapi-hardening","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill python-fastapi-hardening",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill python-fastapi-hardening",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill python-fastapi-hardening","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fpython-fastapi-hardening\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",315,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fpython-fastapi-hardening\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]