Files
yhy-mager/docs/operations-security.md
xiewenjun 54c318c615
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: implement license platform business flows and delivery tooling
Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation.

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-09 15:33:22 +08:00

51 lines
9.1 KiB
Markdown

# Operations and security slice
Status: isolated integration evidence only, not production acceptance or full Compose runtime acceptance.
## 2026-10-01 release-gate update (supersedes earlier local-only notes)
- Production server main now defaults to Redis entry limiting. Missing Redis configuration fails startup unless ENTRY_LIMIT_MODE=local-dev is explicitly selected. Lua INCR+PEXPIRE shares a 60-second fixed window across API instances. Redis runtime errors return 503 rate_limit_unavailable before handlers; no automatic fallback. Numeric private/loopback transport only in this profile; ENTRY_REDIS_PASSWORD_FILE is absolute with a size bound. Redis ACL/TLS, namespace policy, eviction/restart durability, key-cardinality attack capacity and production HA remain gates. Redis memory eviction/reset can reset counters; this is not equivalent to a durable security quota.
- Real isolated Redis integration passed: two independent HTTP servers/clients shared a 10-request login quota (11th=429); closing one Redis client produced 503 and no handler execution. Only login was exercised across clients in the real Redis test; existing unit tests cover all four route classifications. Infrastructure outage/restart/load/HA acceptance remains pending. CI now provides isolated Redis and requests race tests; no remote CI execution claim.
- Server main no longer registers readiness on the public router. METRICS_ADDR loopback operations listener serves readiness and metrics. Public ready and metrics returned 404 in two real API subprocess runs; internal ready/metrics returned 200. API Compose healthcheck uses loopback 19090; Web checks public liveness. If METRICS_ADDR is absent no readiness endpoint is available. This is source and isolated HTTP evidence, not full Compose validation.
- TestSigningFileAPIRestart built and launched the new API twice against isolated clean008 database. A test-only persistent P256 file was stored outside repository in an inheritance-disabled user-only Windows ACL directory, never logged or retained. Both public keys matched and previously signed canonical license-v1 and lease-v1 payloads verified after both launches. Test directory/key were removed by test cleanup. This tests key loading/restart continuity, NOT issuance/activation/heartbeat persistence through a complete business workflow. key_id, multi-key verification windows and rotation are NOT implemented and block production rollout.
- New API subprocesses loaded operations/security and checked internal HTTP boundaries plus real HTTP unauthorized write=401, foreign Origin=403, oversized login body=413, each with server X-Request-ID. Existing 18081 was NOT restarted. Browser at 15173 showed unauthenticated email/password/login form; no credentials entered; it still points to old API and is not new-backend authenticated acceptance.
- Local Linux race attempt found GCC in WSL but no Go; official toolchain download failed/timed out. Windows race previously blocked by CGO disabled. CI race configured, NOT executed here. Do not mark race passed.
- Release blockers: unsigned T01/T02 contracts; persistent production secret injection/rotation/key_id; Redis TLS/ACL/HA and outage-load acceptance; managed TLS/proxy spoof and complete CSRF acceptance; Docker API build/full Compose; logged-in browser/end-to-end issuance lifecycle; U07 chunk/resume/quota/crash reconciliation; compatibility/forced/gray releases; T19 notification/dedup/retries; OSS deferred; production backups/binlogs/restore/reconciliation/rollback; alerts/P95/capacity/vulnerability remediation; race evidence; UAT and signatures. No commit/push/release/task closure.
The following sections preserve earlier slice evidence; their local-only limiter and publicly accessible readiness descriptions are superseded by the update above.
## Logging and errors
The HTTP middleware emits JSON through slog with an allowlist: server-generated request_id/trace_id, route template, operation, HTTP status, error code and elapsed seconds. Client IDs are ignored. trace_id currently equals request_id; no W3C tracing or cross-service propagation is implemented. No request bodies, raw URL paths, query strings, cookies, authorization headers, IP addresses, SQL errors or panic values are logged. Panic handling emits a generic internal_error; startup logs a generic startup_error instead of dumping potentially secret connection errors. Error responses retain code/message and add request_id. Server errors have a generic message. Existing domain codes remain unchanged; a complete contract-signed error registry is still pending.
Audit details were inspected in activation, heartbeat, download, order and license handlers: they use explicit field lists (resource IDs, state, timestamps, package digest/size), not full request objects. Instance credentials, session tokens, passwords and signing PEM must never be added. This inspection is not a complete automated data-loss-prevention audit. Authentication success/failure metrics are not a durable audit trail.
## Metrics and exposure
Set METRICS_ADDR to a numeric loopback address such as 127.0.0.1:19090 to opt into a separate metrics listener. Non-loopback addresses are rejected. /metrics is not registered on the public API router or Nginx. In containers, collection must occur inside that network namespace; no host port publication or container-external collector is configured. Metrics are Prometheus text counters for requests and summed duration, with bounded operation/outcome labels (login, activation, heartbeat, download, authorization, other; success/failure). Authorization means license-route HTTP outcomes, not every internal authorization decision. Download success measures the authorization handoff, not completion of Nginx file transmission. Metrics reset on restart; histogram/P95, alerts, durable aggregation and dashboard setup are pending.
Liveness/readiness remain existing API endpoints for Compose checks, including the local Web proxy. They return generic statuses but are NOT restricted to an internal listener in the current scaffold. Production ingress must restrict /api/v1/health/ before external exposure; strict internal-only health enforcement is still pending.
## Entry rate limits
A bounded local fixed-window limiter runs before login, activation, heartbeat and download handlers: login 10 per minute per effective client IP; other three 60 per minute per IP per operation. Buckets are capped at 10,000; capacity exhaustion denies new keys (fail-closed) with 429/Retry-After. Trusted proxies default to none; production must configure exact proxy CIDRs and prevent direct upstream access. Forwarded IP spoof tests passed with default no-trust configuration.
IMPORTANT: this implementation is single-process only. Separate processes have independent counters; restart clears them, NAT shares quota and fixed-window boundaries permit bursts. Redis distributed limits, Redis authentication/TLS configuration, atomic distributed counters and outage fail-closed policy are NOT implemented or tested. Redis remains optional and unused. Do not deploy multiple replicas assuming a global limit. Thresholds need capacity acceptance and product approval.
## Browser and body controls
Session cookies are HttpOnly, SameSite=Strict, and Secure for direct TLS or explicit SESSION_COOKIE_SECURE=true. Write requests with an Origin must match request Host and effective secure scheme; cross-site Fetch Metadata is rejected. CORS does not allow external origins. Requests without Origin/Fetch Metadata are still allowed for non-browser clients; there is no synchronizer CSRF token, signed origin allowlist or complete browser CSRF acceptance yet. This policy requires same-origin browser deployment.
General request bodies have a 64 KiB MaxBytesReader; known-length overflows return 413. Unknown-length/chunked overflows reach existing JSON validation and return 400. Uploads retain their streaming 64 MiB bound; activation/heartbeat/download retain more restrictive existing guards where applicable. Path and SQL security still rely on existing digest/path validation and parameterized SQL; no new claim of exhaustive SQL injection testing is made.
## Executed checks
- go test ./... and go vet ./... passed after this slice.
- Logging tests verify secret body/query/path/cookie/panic text and forged request IDs are absent.
- All four entry routes tested for pre-handler 429 and forwarded-IP spoof resistance.
- Tests cover origin rejection, no external CORS allow header, known/chunked body limits, malformed sessions, cookie attributes, bucket capacity/reset and independent limiter scope.
- Frontend 10 tests, typecheck and production build passed; existing >500 kB bundle warning remains.
- scripts/check-delivery.sh checks contiguous migration versions, nonempty up/down pairs and shell syntax. Compose placeholder configuration passed. This is not SQL execution or container runtime validation.
- Local race execution was blocked because CGO is disabled. Linux CI now requests focused race tests; that remote workflow has not been run here.
- Existing API 18081 was not restarted and remains live. Docker API build remains blocked by outbound proxy.golang.org TCP/443 refusal; full Compose, production security, load and failure acceptance remain pending.