4 Commits

Author SHA1 Message Date
b1b52000c4 Sync docs and fix flaky renewal e2e test
- ARCHITECTURE.md: add Vault Endpoints section, /unseal UI page,
  vault_sealed/vault_unsealed audit events, sealed interceptor in
  gRPC chain
- openapi.yaml: add /v1/vault/{status,unseal,seal} endpoints, update
  /v1/health sealed-state docs, add VaultSealed response component,
  add vault audit event types and Admin — Vault tag
- web/static/openapi.yaml: kept in sync with root
- test/e2e: increase renewal test token lifetime from 2s to 10s
  (sleep 6s) to eliminate race between token expiry and HTTP round-trip

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 00:39:41 -07:00
d87b4b4042 Add vault seal/unseal lifecycle
- New internal/vault package: thread-safe Vault struct with
  seal/unseal state, key material zeroing, and key derivation
- REST: POST /v1/vault/unseal, POST /v1/vault/seal,
  GET /v1/vault/status; health returns sealed status
- UI: /unseal page with passphrase form, redirect when sealed
- gRPC: sealedInterceptor rejects RPCs when sealed
- Middleware: RequireUnsealed blocks all routes except exempt
  paths; RequireAuth reads pubkey from vault at request time
- Startup: server starts sealed when passphrase unavailable
- All servers share single *vault.Vault by pointer
- CSRF manager derives key lazily from vault

Security: Key material is zeroed on seal. Sealed middleware
runs before auth. Handlers fail closed if vault becomes sealed
mid-request. Unseal endpoint is rate-limited (3/s burst 5).
No CSRF on unseal page (no session to protect; chicken-and-egg
with master key). Passphrase never logged.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 23:55:37 -07:00
5c242f8abb Remediate PEN-01 through PEN-07 (pentest round 4)
- PEN-01: fix extractBearerFromRequest to validate Bearer prefix
  using strings.SplitN + EqualFold; add TestExtractBearerFromRequest
- PEN-02: security headers confirmed present after redeploy (live
  probe 2026-03-15)
- PEN-03: accepted — Swagger UI self-hosting disproportionate to risk
- PEN-04: accepted — OpenAPI spec intentionally public
- PEN-05: accepted — gRPC port 9443 intentionally public
- PEN-06: remove RecordLoginFailure from REST TOTP-missing branch
  to match gRPC handler (DEF-08); add
  TestTOTPMissingDoesNotIncrementLockout
- PEN-07: accepted — per-account hard lockout covers the same threat
- Update AUDIT.md: all 7 PEN findings resolved (4 fixed, 3 accepted)

Security: PEN-01 removed a defence-in-depth gap where any 8+ char
Authorization value was accepted as a Bearer token. PEN-06 closed an
account-lockout-via-omission attack vector on TOTP-enrolled accounts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 23:14:47 -07:00
1121b7d4fd Harden deployment and fix PEN-01
- Fix Bearer token extraction to validate prefix (PEN-01)
- Add TestExtractBearerFromRequest covering PEN-01 edge cases
- Fix flaky TestRenewToken timing (2s → 4s lifetime)
- Move default config/install paths to /srv/mcias
- Add RUNBOOK.md for operational procedures
- Update AUDIT.md with penetration test round 4

Security: extractBearerFromRequest now uses case-insensitive prefix
validation instead of fixed-offset slicing, rejecting non-Bearer
Authorization schemes that were previously accepted.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 22:33:24 -07:00
41 changed files with 2353 additions and 247 deletions

View File

@@ -431,11 +431,23 @@ All endpoints use JSON request/response bodies. All responses include a
|---|---|---|---|
| GET | `/v1/audit` | admin JWT | List audit log events |
### Vault Endpoints
| Method | Path | Auth required | Description |
|---|---|---|---|
| GET | `/v1/vault/status` | none | Returns `{"sealed": bool}`; always accessible |
| POST | `/v1/vault/unseal` | none | Accept passphrase, derive key, unseal (rate-limited 3/s burst 5) |
| POST | `/v1/vault/seal` | admin JWT | Zero key material and seal the vault; invalidates all JWTs |
When the vault is sealed, all endpoints except health, vault status, and unseal
return 503 with `{"error":"vault is sealed","code":"vault_sealed"}`. The UI
redirects non-exempt paths to `/unseal`.
### Admin / Server Endpoints
| Method | Path | Auth required | Description |
|---|---|---|---|
| GET | `/v1/health` | none | Health check |
| GET | `/v1/health` | none | Health check — returns `{"status":"ok"}` or `{"status":"sealed"}` |
| GET | `/v1/keys/public` | none | Ed25519 public key (JWK format) |
### Web Management UI
@@ -458,6 +470,7 @@ cookie pattern (`mcias_csrf`).
| Path | Description |
|---|---|
| `/unseal` | Passphrase form to unseal the vault; shown for all paths when sealed |
| `/login` | Username/password login with optional TOTP step |
| `/` | Dashboard (account summary) |
| `/accounts` | Account list |
@@ -797,6 +810,8 @@ The `cmd/` packages are thin wrappers that wire dependencies and call into
| `policy_rule_updated` | Policy rule updated (priority, enabled, description) |
| `policy_rule_deleted` | Policy rule deleted |
| `policy_deny` | Policy engine denied a request (logged for every explicit deny) |
| `vault_unsealed` | Vault unsealed via REST API or web UI; details include `source` (api\|ui) and `ip` |
| `vault_sealed` | Vault sealed via REST API; details include actor ID, `source`, and `ip` |
---
@@ -1010,9 +1025,12 @@ details.
### Interceptor Chain
```
[Request Logger] → [Auth Interceptor] → [Rate Limiter] → [Handler]
[Sealed Interceptor] → [Request Logger] → [Auth Interceptor] → [Rate Limiter] → [Handler]
```
- **Sealed Interceptor**: first in chain; blocks all RPCs with
`codes.Unavailable` ("vault sealed") when the vault is sealed, except
`AdminService/Health` which returns the sealed status.
- **Request Logger**: logs method, peer IP, status code, duration; never logs
the `authorization` metadata value.
- **Auth Interceptor**: validates Bearer JWT, injects claims. Public RPCs

171
AUDIT.md
View File

@@ -1,24 +1,153 @@
# MCIAS Security Audit Report
**Date:** 2026-03-14 (updated — all findings remediated)
**Date:** 2026-03-14 (updated — penetration test round 4)
**Original audit date:** 2026-03-13
**Auditor role:** Penetration tester (code review + live instance probing)
**Scope:** Full codebase and running instance at localhost:8443 — authentication flows, token lifecycle, cryptography, database layer, REST/gRPC/UI servers, authorization, headers, and operational security.
**Scope:** Full codebase and running instance at mcias.metacircular.net:8443 — authentication flows, token lifecycle, cryptography, database layer, REST/gRPC/UI servers, authorization, headers, and operational security.
**Methodology:** Static code analysis, live HTTP probing, architectural review.
---
## Executive Summary
MCIAS has a strong security posture. All findings from three audit rounds (CRIT-01/CRIT-02, DEF-01 through DEF-10, and SEC-01 through SEC-12) have been remediated. The cryptographic foundations are sound, JWT validation is correct, SQL injection is not possible, XSS is prevented by Go's html/template auto-escaping, and CSRF protection is well-implemented.
MCIAS has a strong security posture. All findings from the first three audit rounds (CRIT-01/CRIT-02, DEF-01 through DEF-10, and SEC-01 through SEC-12) have been remediated. The cryptographic foundations are sound, JWT validation is correct, SQL injection is not possible, XSS is prevented by Go's html/template auto-escaping, and CSRF protection is well-implemented.
**All findings from this audit have been remediated.** See the remediation table below for details.
A fourth-round penetration test (PEN-01 through PEN-07) against the live instance at `mcias.metacircular.net:8443` identified 7 new findings: 2 medium, 2 low, and 3 informational. **Unauthorized access was not achieved** the system's defense-in-depth held. See the open findings table below for details.
---
## Open Findings (PEN-01 through PEN-07)
Identified during the fourth-round penetration test on 2026-03-14 against the live instance at `mcias.metacircular.net:8443` and the source code at the same commit.
| ID | Severity | Finding | Status |
|----|----------|---------|--------|
| PEN-01 | Medium | `extractBearerFromRequest` does not validate "Bearer " prefix | **Fixed** — uses `strings.SplitN` + `strings.EqualFold` prefix validation, matching middleware implementation |
| PEN-02 | Medium | Security headers missing from live instance responses | **Fixed** — redeployed; all headers confirmed present on live instance 2026-03-15 |
| PEN-03 | Low | CSP `unsafe-inline` on `/docs` Swagger UI endpoint | **Accepted** — self-hosting Swagger UI (1.7 MB) to enable nonces adds complexity disproportionate to the risk; inline script is static, no user-controlled input |
| PEN-04 | Info | OpenAPI spec publicly accessible without authentication | **Accepted** — intentional; public access required for agents and external developers |
| PEN-05 | Info | gRPC port 9443 publicly accessible | **Accepted** — intentional; required for server-to-server access by external systems |
| PEN-06 | Low | REST login increments lockout counter for missing TOTP code | **Fixed**`RecordLoginFailure` removed from TOTP-missing branch; `TestTOTPMissingDoesNotIncrementLockout` added |
| PEN-07 | Info | Rate limiter is per-IP only, no per-account limiting | **Accepted** — per-account hard lockout (10 failures/15 min) already covers distributed brute-force; per-account rate limiting adds marginal benefit at this scale |
<details>
<summary>Finding descriptions (click to expand)</summary>
### PEN-01 — `extractBearerFromRequest` Does Not Validate "Bearer " Prefix (Medium)
**File:** `internal/server/server.go` (lines 14141425)
The server-level `extractBearerFromRequest` function extracts the token by slicing the `Authorization` header at offset 7 (`len("Bearer ")`) without first verifying that the header actually starts with `"Bearer "`. Any 8+ character `Authorization` value is accepted — e.g., `Authorization: XXXXXXXX` would extract `X` as the token string.
```go
// Current (vulnerable):
if len(auth) <= len(prefix) {
return "", fmt.Errorf("malformed Authorization header")
}
return auth[len(prefix):], nil // no prefix check
```
The middleware-level `extractBearerToken` in `internal/middleware/middleware.go` (lines 303316) correctly uses `strings.SplitN` and `strings.EqualFold` to validate the prefix. The server-level function should be replaced with a call to the middleware version, or the same validation logic should be applied.
**Impact:** Low in practice because the extracted garbage is then passed to JWT validation which will reject it. However, it violates defense-in-depth: a future change to token validation could widen the attack surface, and the inconsistency between the two extraction functions is a maintenance hazard.
**Recommendation:** Replace `extractBearerFromRequest` with a call to `middleware.extractBearerToken` (after exporting it or moving the function), or replicate the prefix validation.
**Fix:** `extractBearerFromRequest` now uses `strings.SplitN` and `strings.EqualFold` to validate the `"Bearer"` prefix before extracting the token, matching the middleware implementation. Test `TestExtractBearerFromRequest` covers valid tokens, missing headers, non-Bearer schemes (Token, Basic), empty tokens, case-insensitive matching, and the previously-accepted garbage input.
---
### PEN-02 — Security Headers Missing from Live Instance Responses (Medium)
**Live probe:** `https://mcias.metacircular.net:8443/login`
The live instance's `/login` response did not include the security headers (`X-Content-Type-Options`, `Strict-Transport-Security`, `Cache-Control`, `Permissions-Policy`) that the source code's `globalSecurityHeaders` and UI `securityHeaders` middleware should be applying (SEC-04 and SEC-10 fixes).
This is likely a code/deployment discrepancy — the deployed binary may predate the SEC-04/SEC-10 fixes, or the middleware may not be wired into the route chain correctly for all paths.
**Impact:** Without HSTS, browsers will not enforce HTTPS-only access. Without `X-Content-Type-Options: nosniff`, MIME-type sniffing attacks are possible. Without `Cache-Control: no-store`, authenticated responses may be cached by proxies or browsers.
**Recommendation:** Redeploy the current source to the live instance and verify headers with `curl -I`.
**Fix:** Redeployed 2026-03-15. Live probe confirms all headers present on `/login`, `/v1/health`, and `/`:
`cache-control: no-store`, `content-security-policy`, `permissions-policy`, `referrer-policy`, `strict-transport-security: max-age=63072000; includeSubDomains`, `x-content-type-options: nosniff`, `x-frame-options: DENY`.
---
### PEN-03 — CSP `unsafe-inline` on `/docs` Swagger UI Endpoint (Low)
**File:** `internal/server/server.go` (lines 14501452)
The `docsSecurityHeaders` wrapper sets a Content-Security-Policy that includes `script-src 'self' 'unsafe-inline'` and `style-src 'self' 'unsafe-inline'`. This is required by Swagger UI's rendering approach, but it weakens CSP protection on the docs endpoint.
**Impact:** If an attacker can inject content into the Swagger UI page (e.g., via a reflected parameter in the OpenAPI spec URL), inline scripts would execute. The blast radius is limited to the `/docs` path, which requires no authentication (see PEN-04).
**Recommendation:** Consider serving Swagger UI from a separate subdomain or using CSP nonces instead of `unsafe-inline`. Alternatively, accept the risk given the limited scope.
---
### PEN-04 — OpenAPI Spec Publicly Accessible Without Authentication (Informational)
**Live probe:** `GET /openapi.yaml` returns the full API specification without authentication.
The OpenAPI spec reveals all API endpoints, request/response schemas, authentication flows, and error codes. While security-through-obscurity is not a defense, exposing the full API surface to unauthenticated users provides a roadmap for attackers.
**Recommendation:** Consider requiring authentication for `/openapi.yaml` and `/docs`, or accept the risk if the API surface is intended to be public.
---
### PEN-05 — gRPC Port 9443 Publicly Accessible (Informational)
**Live probe:** Port 9443 accepts TLS connections and serves gRPC.
The gRPC interface is accessible from the public internet. While it requires authentication for all RPCs, exposing it increases the attack surface (gRPC-specific vulnerabilities, protocol-level attacks).
**Recommendation:** If gRPC is only used for server-to-server communication, restrict access at the firewall/network level. If it must be public, ensure gRPC-specific rate limiting and monitoring are in place (SEC-06 fix applies here).
---
### PEN-06 — REST Login Increments Lockout Counter for Missing TOTP Code (Low)
**File:** `internal/server/server.go` (lines 271277)
When a TOTP-enrolled account submits a login request without a TOTP code, the REST handler calls `s.db.RecordLoginFailure(acct.ID)` before returning the `"TOTP code required"` error. This increments the lockout counter even though the user has not actually failed authentication — they simply omitted the TOTP field.
The gRPC handler was fixed for this exact issue in DEF-08, but the REST handler was not updated to match.
```go
// Current (REST — increments lockout for missing TOTP):
if acct.TOTPRequired {
if req.TOTPCode == "" {
s.writeAudit(r, model.EventLoginFail, &acct.ID, nil, `{"reason":"totp_missing"}`)
_ = s.db.RecordLoginFailure(acct.ID) // should not increment
middleware.WriteError(w, http.StatusUnauthorized, "TOTP code required", "totp_required")
return
}
```
**Impact:** An attacker who knows a username with TOTP enabled can lock the account by sending 10 login requests with a valid password but no TOTP code. The password must be correct (wrong passwords also increment the counter), but this lowers the bar from "must guess TOTP" to "must omit TOTP." More practically, legitimate users with buggy clients that forget the TOTP field could self-lock.
**Recommendation:** Remove the `RecordLoginFailure` call from the TOTP-missing branch, matching the gRPC handler's behavior after the DEF-08 fix.
**Fix:** `RecordLoginFailure` removed from the TOTP-missing branch in `internal/server/server.go`. The branch now matches the gRPC handler exactly, including the rationale comment. `TestTOTPMissingDoesNotIncrementLockout` verifies the fix: it fully enrolls TOTP via the HTTP API, sets `LockoutThreshold=1`, issues a TOTP-missing login, and asserts the account is not locked.
---
### PEN-07 — Rate Limiter Is Per-IP Only, No Per-Account Limiting (Informational)
The rate limiter uses a per-IP token bucket. An attacker with access to multiple IP addresses (botnet, cloud instances, rotating proxies) can distribute brute-force attempts across IPs to bypass the per-IP limit.
The account lockout mechanism (10 failures in 15 minutes) provides a secondary defense, but it is a blunt instrument — it locks out the legitimate user as well.
**Recommendation:** Consider adding per-account rate limiting as a complement to per-IP limiting. This would cap login attempts per username regardless of source IP, without affecting other users. The account lockout already partially serves this role, but a softer rate limit (e.g., 1 req/s per username) would slow distributed attacks without locking out the user.
</details>
---
## Remediated Findings (SEC-01 through SEC-12)
All findings from this audit have been remediated. The original descriptions are preserved below for reference.
All findings from the SEC audit round have been remediated. The original descriptions are preserved below for reference.
| ID | Severity | Finding | Status |
|----|----------|---------|--------|
@@ -186,9 +315,35 @@ These implementation details are exemplary and should be maintained:
---
## Penetration Test — Attacks That Failed (2026-03-14)
The following attacks were attempted against the live instance and failed, confirming the effectiveness of existing defenses:
| Attack | Result |
|--------|--------|
| JWT `alg:none` bypass | Rejected — `ValidateToken` enforces `alg=EdDSA` |
| JWT `alg:HS256` key-confusion | Rejected — only EdDSA accepted |
| Forged JWT with random Ed25519 key | Rejected — signature verification failed |
| Username enumeration via timing | Not possible — ~355ms for both existing and non-existing users (dummy Argon2 working) |
| Username enumeration via error messages | Not possible — identical `"invalid credentials"` for all failure modes |
| Account lockout enumeration | Not possible — locked accounts return same response as wrong password (SEC-02 fix confirmed) |
| SQL injection via login fields | Not possible — parameterized queries throughout |
| JSON body bomb (oversized payload) | Rejected — `http.MaxBytesReader` returns 413 (SEC-05 fix confirmed) |
| Unknown JSON fields | Rejected — `DisallowUnknownFields` active on decoder |
| Rate limit bypass | Working correctly — 429 after burst exhaustion, `Retry-After` header present |
| Admin endpoint access without auth | Properly returns 401 |
| Directory traversal on static files | Not possible — `noDirListing` wrapper returns 404 (SEC-07 fix confirmed) |
| Public key endpoint | Returns Ed25519 PKIX key (expected; public by design) |
---
## Remediation Status
**All findings remediated.** No open items remain. Next audit should focus on:
- Any new features added since 2026-03-14
**CRIT/DEF/SEC series:** All 24 findings remediated. No open items.
**PEN series (2026-03-14):** All 7 findings resolved — 4 fixed, 3 accepted by design. Unauthorized access was not achieved. No open items remain.
Next audit should focus on:
- Any new features added since 2026-03-15
- Dependency updates and CVE review
- Live penetration testing of remediated endpoints
- Re-evaluate PEN-03 if Swagger UI self-hosting becomes desirable

View File

@@ -4,6 +4,50 @@ Source of truth for current development state.
---
All phases complete. **v1.0.0 tagged.** All packages pass `go test ./...`; `golangci-lint run ./...` clean.
### 2026-03-14 — Vault seal/unseal lifecycle
**Problem:** `mciassrv` required the master passphrase at startup and refused to start without it. Operators needed a way to start the server in a degraded state and provide the passphrase at runtime, plus the ability to re-seal at runtime.
**Solution:** Implemented a `Vault` abstraction that manages key material lifecycle with seal/unseal state transitions.
**New package: `internal/vault/`**
- `vault.go`: Thread-safe `Vault` struct with `sync.RWMutex`-protected state. Methods: `IsSealed()`, `Unseal()`, `Seal()`, `MasterKey()`, `PrivKey()`, `PubKey()`. `Seal()` zeroes all key material before nilling.
- `derive.go`: Extracted `DeriveFromPassphrase()` and `DecryptSigningKey()` from `cmd/mciassrv/main.go` for reuse by unseal handlers.
- `vault_test.go`: Tests for state transitions, key zeroing, concurrent access.
**REST API (`internal/server/`):**
- `POST /v1/vault/unseal`: Accept passphrase, derive key, unseal (rate-limited 3/s burst 5)
- `POST /v1/vault/seal`: Admin-only, seals vault and zeroes key material
- `GET /v1/vault/status`: Returns `{"sealed": bool}`
- `GET /v1/health`: Now returns `{"status":"sealed"}` when sealed
- All other `/v1/*` endpoints return 503 `vault_sealed` when sealed
**Web UI (`internal/ui/`):**
- New unseal page at `/unseal` with passphrase form (same styling as login)
- All UI routes redirect to `/unseal` when sealed (except `/static/`)
- CSRF manager now derives key lazily from vault
**gRPC (`internal/grpcserver/`):**
- New `sealedInterceptor` first in interceptor chain — returns `codes.Unavailable` for all RPCs except Health
- Health RPC returns `status: "sealed"` when sealed
**Startup (`cmd/mciassrv/main.go`):**
- When passphrase env var is empty/unset (and not first run): starts in sealed state
- When passphrase is available: backward-compatible unsealed startup
- First run still requires passphrase to generate signing key
**Refactoring:**
- All three servers (REST, UI, gRPC) share a single `*vault.Vault` by pointer
- Replaced static `privKey`, `pubKey`, `masterKey` fields with vault accessor calls
- `middleware.RequireAuth` now reads pubkey from vault at request time
- New `middleware.RequireUnsealed` middleware wired before request logger
**Audit events:** Added `vault_sealed` and `vault_unsealed` event types.
**OpenAPI:** Updated `openapi.yaml` with vault endpoints and sealed health response.
**Files changed:** 19 files (3 new packages, 3 new handlers, 1 new template, extensive refactoring across all server packages and tests).
### 2026-03-13 — Make pgcreds discoverable via CLI and UI
**Problem:** Users had no way to discover which pgcreds were available to them or what their credential IDs were, making it functionally impossible to use the system without manual database inspection.

View File

@@ -64,10 +64,10 @@ EOF
Generate the certificate:
```sh
cert genkey -a ec -s 521 > /etc/mcias/server.key
cert selfsign -p /etc/mcias/server.key -f /tmp/request.yaml > /etc/mcias/server.crt
chmod 0640 /etc/mcias/server.key
chown root:mcias /etc/mcias/server.key
cert genkey -a ec -s 521 > /srv/mcias/server.key
cert selfsign -p /srv/mcias/server.key -f /tmp/request.yaml > /srv/mcias/server.crt
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.key /srv/mcias/server.crt
rm /tmp/request.yaml
```
@@ -75,21 +75,21 @@ rm /tmp/request.yaml
```sh
openssl req -x509 -newkey ed25519 -days 3650 \
-keyout /etc/mcias/server.key \
-out /etc/mcias/server.crt \
-keyout /srv/mcias/server.key \
-out /srv/mcias/server.crt \
-subj "/CN=auth.example.com" \
-nodes
chmod 0640 /etc/mcias/server.key
chown root:mcias /etc/mcias/server.key
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.key /srv/mcias/server.crt
```
### 2. Configure the server
```sh
cp dist/mcias.conf.example /etc/mcias/mcias.conf
$EDITOR /etc/mcias/mcias.conf
chmod 0640 /etc/mcias/mcias.conf
chown root:mcias /etc/mcias/mcias.conf
cp dist/mcias.conf.example /srv/mcias/mcias.toml
$EDITOR /srv/mcias/mcias.toml
chmod 0640 /srv/mcias/mcias.toml
chown mcias:mcias /srv/mcias/mcias.toml
```
Minimum required fields:
@@ -97,11 +97,11 @@ Minimum required fields:
```toml
[server]
listen_addr = "0.0.0.0:8443"
tls_cert = "/etc/mcias/server.crt"
tls_key = "/etc/mcias/server.key"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
[database]
path = "/var/lib/mcias/mcias.db"
path = "/srv/mcias/mcias.db"
[tokens]
issuer = "https://auth.example.com"
@@ -116,10 +116,10 @@ For local development, use `dist/mcias-dev.conf.example`.
### 3. Set the master key passphrase
```sh
cp dist/mcias.env.example /etc/mcias/env
$EDITOR /etc/mcias/env # replace the placeholder passphrase
chmod 0640 /etc/mcias/env
chown root:mcias /etc/mcias/env
cp dist/mcias.env.example /srv/mcias/env
$EDITOR /srv/mcias/env # replace the placeholder passphrase
chmod 0640 /srv/mcias/env
chown mcias:mcias /srv/mcias/env
```
> **Important:** Back up the passphrase to a secure offline location.
@@ -130,10 +130,10 @@ chown root:mcias /etc/mcias/env
```sh
export MCIAS_MASTER_PASSPHRASE=your-passphrase
mciasdb --config /etc/mcias/mcias.conf account create \
mciasdb --config /srv/mcias/mcias.toml account create \
--username admin --type human
mciasdb --config /etc/mcias/mcias.conf account set-password --id <UUID>
mciasdb --config /etc/mcias/mcias.conf role grant --id <UUID> --role admin
mciasdb --config /srv/mcias/mcias.toml account set-password --id <UUID>
mciasdb --config /srv/mcias/mcias.toml role grant --id <UUID> --role admin
```
### 5. Start the server
@@ -143,7 +143,7 @@ mciasdb --config /etc/mcias/mcias.conf role grant --id <UUID> --role admin
systemctl enable --now mcias
# manual
MCIAS_MASTER_PASSPHRASE=your-passphrase mciassrv -config /etc/mcias/mcias.conf
MCIAS_MASTER_PASSPHRASE=your-passphrase mciassrv -config /srv/mcias/mcias.toml
```
### 6. Verify
@@ -193,7 +193,7 @@ See `man mciasctl` for the full reference.
```sh
export MCIAS_MASTER_PASSPHRASE=your-passphrase
CONF="--config /etc/mcias/mcias.conf"
CONF="--config /srv/mcias/mcias.toml"
mciasdb $CONF schema verify
mciasdb $CONF account list
@@ -217,22 +217,22 @@ Enable the gRPC listener in config:
[server]
listen_addr = "0.0.0.0:8443"
grpc_addr = "0.0.0.0:9443"
tls_cert = "/etc/mcias/server.crt"
tls_key = "/etc/mcias/server.key"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
```
Using mciasgrpcctl:
```sh
export MCIAS_TOKEN=$ADMIN_JWT
mciasgrpcctl -server auth.example.com:9443 -cacert /etc/mcias/server.crt health
mciasgrpcctl -server auth.example.com:9443 -cacert /srv/mcias/server.crt health
mciasgrpcctl account list
```
Using grpcurl:
```sh
grpcurl -cacert /etc/mcias/server.crt \
grpcurl -cacert /srv/mcias/server.crt \
-H "authorization: Bearer $ADMIN_JWT" \
auth.example.com:9443 \
mcias.v1.AdminService/Health
@@ -265,14 +265,13 @@ See [ARCHITECTURE.md](ARCHITECTURE.md) §8 (Web Management UI) for design detail
```sh
make docker
mkdir -p /srv/mcias/config
cp dist/mcias.conf.docker.example /srv/mcias/config/mcias.conf
$EDITOR /srv/mcias/config/mcias.conf
mkdir -p /srv/mcias
cp dist/mcias.conf.docker.example /srv/mcias/mcias.toml
$EDITOR /srv/mcias/mcias.toml
docker run -d \
--name mcias \
-v /srv/mcias/config:/etc/mcias:ro \
-v mcias-data:/data \
-v /srv/mcias:/srv/mcias \
-e MCIAS_MASTER_PASSPHRASE=your-passphrase \
-p 8443:8443 \
-p 9443:9443 \

464
RUNBOOK.md Normal file
View File

@@ -0,0 +1,464 @@
# MCIAS Runbook
Operational procedures for running and maintaining the MCIAS authentication
server. All required files live under `/srv/mcias`.
---
## Directory Layout
```
/srv/mcias/
mcias.toml — server configuration (TOML)
server.crt — TLS certificate (PEM)
server.key — TLS private key (PEM, mode 0640)
mcias.db — SQLite database (WAL mode creates .db-wal and .db-shm)
env — environment file: MCIAS_MASTER_PASSPHRASE (mode 0640)
master.key — optional raw AES-256 key file (mode 0640, alternative to env)
```
All files are owned by the `mcias` system user and group (`mcias:mcias`).
The directory itself is mode `0750`.
---
## Installation
Run as root from the repository root after `make build`:
```sh
sh dist/install.sh
```
This script is idempotent. It:
1. Creates the `mcias` system user and group if they do not exist.
2. Installs binaries to `/usr/local/bin/`.
3. Creates `/srv/mcias/` with correct ownership and permissions.
4. Installs the systemd service unit to `/etc/systemd/system/mcias.service`.
5. Installs example config files to `/srv/mcias/` (will not overwrite existing files).
After installation, complete the steps below before starting the service.
---
## First-Run Setup
### 1. Generate a TLS certificate
**Self-signed (personal/development use):**
```sh
openssl req -x509 -newkey ed25519 -days 3650 \
-keyout /srv/mcias/server.key \
-out /srv/mcias/server.crt \
-subj "/CN=auth.example.com" \
-nodes
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.key /srv/mcias/server.crt
```
**Using the `cert` tool:**
```sh
go install github.com/kisom/cert@latest
cat > /tmp/request.yaml <<EOF
subject:
common_name: auth.example.com
hosts:
- auth.example.com
key:
algo: ecdsa
size: 521
ca:
expiry: 87600h
EOF
cert genkey -a ec -s 521 > /srv/mcias/server.key
cert selfsign -p /srv/mcias/server.key -f /tmp/request.yaml > /srv/mcias/server.crt
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.key /srv/mcias/server.crt
rm /tmp/request.yaml
```
### 2. Write the configuration file
```sh
cp /srv/mcias/mcias.conf.example /srv/mcias/mcias.toml
$EDITOR /srv/mcias/mcias.toml
chmod 0640 /srv/mcias/mcias.toml
chown mcias:mcias /srv/mcias/mcias.toml
```
Minimum required settings:
```toml
[server]
listen_addr = "0.0.0.0:8443"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
[database]
path = "/srv/mcias/mcias.db"
[tokens]
issuer = "https://auth.example.com"
[master_key]
passphrase_env = "MCIAS_MASTER_PASSPHRASE"
```
See `dist/mcias.conf.example` for the full annotated reference.
### 3. Set the master key passphrase
```sh
cp /srv/mcias/mcias.env.example /srv/mcias/env
$EDITOR /srv/mcias/env # set MCIAS_MASTER_PASSPHRASE to a long random value
chmod 0640 /srv/mcias/env
chown mcias:mcias /srv/mcias/env
```
Generate a strong passphrase:
```sh
openssl rand -base64 32
```
> **IMPORTANT:** Back up the passphrase to a secure offline location.
> Losing it permanently destroys access to all encrypted data in the database.
### 4. Create the first admin account
```sh
export MCIAS_MASTER_PASSPHRASE=your-passphrase
mciasdb --config /srv/mcias/mcias.toml account create \
--username admin --type human
# note the UUID printed
mciasdb --config /srv/mcias/mcias.toml account set-password --id <UUID>
mciasdb --config /srv/mcias/mcias.toml role grant --id <UUID> --role admin
```
### 5. Enable and start the service
```sh
systemctl enable mcias
systemctl start mcias
systemctl status mcias
```
### 6. Verify
```sh
curl -k https://auth.example.com:8443/v1/health
# {"status":"ok"}
```
---
## Routine Operations
### Start / stop / restart
```sh
systemctl start mcias
systemctl stop mcias
systemctl restart mcias
```
### View logs
```sh
journalctl -u mcias -f
journalctl -u mcias --since "1 hour ago"
```
### Check service status
```sh
systemctl status mcias
```
### Reload configuration
The server reads its configuration at startup only. To apply config changes:
```sh
systemctl restart mcias
```
---
## Account Management
All account management can be done via `mciasctl` (REST API) when the server
is running, or `mciasdb` for offline/break-glass operations.
```sh
# Set env for offline tool
export MCIAS_MASTER_PASSPHRASE=your-passphrase
CONF="--config /srv/mcias/mcias.toml"
# List accounts
mciasdb $CONF account list
# Create account
mciasdb $CONF account create --username alice --type human
# Set password (prompts interactively)
mciasdb $CONF account set-password --id <UUID>
# Grant or revoke a role
mciasdb $CONF role grant --id <UUID> --role admin
mciasdb $CONF role revoke --id <UUID> --role admin
# Disable account
mciasdb $CONF account set-status --id <UUID> --status inactive
# Delete account
mciasdb $CONF account set-status --id <UUID> --status deleted
```
---
## Token Management
```sh
CONF="--config /srv/mcias/mcias.toml"
# List active tokens for an account
mciasdb $CONF token list --id <UUID>
# Revoke a specific token by JTI
mciasdb $CONF token revoke --jti <JTI>
# Revoke all tokens for an account (e.g., suspected compromise)
mciasdb $CONF token revoke-all --id <UUID>
# Prune expired tokens from the database
mciasdb $CONF prune tokens
```
---
## Database Maintenance
### Verify schema
```sh
mciasdb --config /srv/mcias/mcias.toml schema verify
```
### Run pending migrations
```sh
mciasdb --config /srv/mcias/mcias.toml schema migrate
```
### Force schema version (break-glass)
```sh
mciasdb --config /srv/mcias/mcias.toml schema force --version N
```
Use only when `schema migrate` reports a dirty version after a failed migration.
### Backup the database
SQLite WAL mode creates three files. Back up all three atomically using the
SQLite backup API or by stopping the server first:
```sh
# Online backup (preferred — no downtime):
sqlite3 /srv/mcias/mcias.db ".backup /path/to/backup/mcias-$(date +%F).db"
# Offline backup:
systemctl stop mcias
cp /srv/mcias/mcias.db /path/to/backup/mcias-$(date +%F).db
systemctl start mcias
```
Store backups alongside a copy of the master key passphrase in a secure
offline location. A database backup without the passphrase is unrecoverable.
---
## Audit Log
```sh
CONF="--config /srv/mcias/mcias.toml"
# Show last 50 audit events
mciasdb $CONF audit tail --n 50
# Query by account
mciasdb $CONF audit query --account <UUID>
# Query by event type since a given time
mciasdb $CONF audit query --type login_failure --since 2026-01-01T00:00:00Z
# Output as JSON (for log shipping)
mciasdb $CONF audit query --json
```
---
## Upgrading
1. Build the new binaries: `make build`
2. Stop the service: `systemctl stop mcias`
3. Install new binaries: `sh dist/install.sh`
- The script will not overwrite existing config files.
- New example files are placed with a `.new` suffix for review.
4. Review any `.new` config files in `/srv/mcias/` and merge changes manually.
5. Run schema migrations if required:
```sh
mciasdb --config /srv/mcias/mcias.toml schema migrate
```
6. Start the service: `systemctl start mcias`
7. Verify: `curl -k https://auth.example.com:8443/v1/health`
---
## Master Key Rotation
> This operation is not yet automated. Until a rotation command is
> implemented, rotation requires a full re-encryption of the database.
> Contact the project maintainer for the current procedure.
---
## TLS Certificate Renewal
Replace the certificate and key files, then restart the server:
```sh
# Generate or obtain new cert/key, then:
cp new-server.crt /srv/mcias/server.crt
cp new-server.key /srv/mcias/server.key
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.crt /srv/mcias/server.key
systemctl restart mcias
```
For Let's Encrypt with Certbot, add a deploy hook:
```sh
# /etc/letsencrypt/renewal-hooks/deploy/mcias.sh
#!/bin/sh
cp /etc/letsencrypt/live/auth.example.com/fullchain.pem /srv/mcias/server.crt
cp /etc/letsencrypt/live/auth.example.com/privkey.pem /srv/mcias/server.key
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.crt /srv/mcias/server.key
systemctl restart mcias
```
---
## Docker Deployment
```sh
make docker
mkdir -p /srv/mcias
cp dist/mcias.conf.docker.example /srv/mcias/mcias.toml
$EDITOR /srv/mcias/mcias.toml
# Place TLS cert and key under /srv/mcias/
# Set ownership so uid 10001 (container mcias user) can read them.
chown -R 10001:10001 /srv/mcias
docker run -d \
--name mcias \
-v /srv/mcias:/srv/mcias \
-e MCIAS_MASTER_PASSPHRASE=your-passphrase \
-p 8443:8443 \
-p 9443:9443 \
--restart unless-stopped \
mcias:latest
```
See `dist/mcias.conf.docker.example` for the full annotated Docker config.
---
## Troubleshooting
### Server fails to start: "open database"
Check that `/srv/mcias/` is writable by the `mcias` user:
```sh
ls -la /srv/mcias/
stat /srv/mcias/mcias.db # if it already exists
```
Fix: `chown mcias:mcias /srv/mcias`
### Server fails to start: "environment variable ... is not set"
The `MCIAS_MASTER_PASSPHRASE` env var is missing. Ensure `/srv/mcias/env`
exists, is readable by the mcias user, and contains the correct variable:
```sh
grep MCIAS_MASTER_PASSPHRASE /srv/mcias/env
```
Also confirm the systemd unit loads it:
```sh
systemctl cat mcias | grep EnvironmentFile
```
### Server fails to start: "decrypt signing key"
The master key passphrase has changed or is wrong. The passphrase must match
the one used when the database was first initialized (the KDF salt is stored
in the database). Restore the correct passphrase from your offline backup.
### TLS errors in client connections
Verify the certificate is valid and covers the correct hostname:
```sh
openssl x509 -in /srv/mcias/server.crt -noout -text | grep -E "Subject|DNS"
openssl x509 -in /srv/mcias/server.crt -noout -dates
```
### Database locked / WAL not cleaning up
Check for lingering `mcias.db-wal` and `mcias.db-shm` files after an unclean
shutdown. These are safe to leave in place — SQLite will recover on next open.
Do not delete them while the server is running.
### Schema dirty after failed migration
```sh
mciasdb --config /srv/mcias/mcias.toml schema verify
mciasdb --config /srv/mcias/mcias.toml schema force --version N
mciasdb --config /srv/mcias/mcias.toml schema migrate
```
Replace `N` with the last successfully applied version number.
---
## File Permissions Reference
| Path | Mode | Owner |
|------|------|-------|
| `/srv/mcias/` | `0750` | `mcias:mcias` |
| `/srv/mcias/mcias.toml` | `0640` | `mcias:mcias` |
| `/srv/mcias/server.crt` | `0644` | `mcias:mcias` |
| `/srv/mcias/server.key` | `0640` | `mcias:mcias` |
| `/srv/mcias/mcias.db` | `0640` | `mcias:mcias` |
| `/srv/mcias/env` | `0640` | `mcias:mcias` |
| `/srv/mcias/master.key` | `0640` | `mcias:mcias` |
Verify permissions:
```sh
ls -la /srv/mcias/
```

View File

@@ -9,7 +9,7 @@
//
// Usage:
//
// mciasdb --config /etc/mcias/mcias.toml <command> [subcommand] [flags]
// mciasdb --config /srv/mcias/mcias.toml <command> [subcommand] [flags]
//
// Commands:
//
@@ -53,7 +53,7 @@ import (
)
func main() {
configPath := flag.String("config", "mcias.toml", "path to TOML configuration file")
configPath := flag.String("config", "/srv/mcias/mcias.toml", "path to TOML configuration file")
flag.Usage = usage
flag.Parse()

View File

@@ -9,7 +9,7 @@
//
// Usage:
//
// mciassrv -config /etc/mcias/mcias.toml
// mciassrv -config /srv/mcias/mcias.toml
package main
import (
@@ -36,10 +36,11 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/grpcserver"
"git.wntrmute.dev/kyle/mcias/internal/server"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
func main() {
configPath := flag.String("config", "mcias.toml", "path to TOML configuration file")
configPath := flag.String("config", "/srv/mcias/mcias.toml", "path to TOML configuration file")
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
@@ -72,29 +73,46 @@ func run(configPath string, logger *slog.Logger) error {
}
logger.Info("database ready", "path", cfg.Database.Path)
// Derive or load the master encryption key.
// Derive or load the master encryption key and build the vault.
// Security: The master key encrypts TOTP secrets, Postgres passwords, and
// the signing key at rest. It is derived from a passphrase via Argon2id
// (or loaded directly from a key file). The KDF salt is stored in the DB
// for stability across restarts. The passphrase env var is cleared after use.
masterKey, err := loadMasterKey(cfg, database)
if err != nil {
return fmt.Errorf("load master key: %w", err)
}
defer func() {
// Zero the master key when done — reduces the window of exposure.
for i := range masterKey {
masterKey[i] = 0
//
// When the passphrase is not available (empty env var in passphrase mode
// with no key file), the server starts in sealed state. The operator must
// provide the passphrase via the /v1/vault/unseal API or the /unseal UI page.
// First run (no signing key in DB) still requires the passphrase at startup.
var v *vault.Vault
masterKey, mkErr := loadMasterKey(cfg, database)
if mkErr != nil {
// Check if we can start sealed (passphrase mode, empty env var).
if cfg.MasterKey.KeyFile == "" && os.Getenv(cfg.MasterKey.PassphraseEnv) == "" {
// Verify that this is not a first run — the signing key must already exist.
enc, nonce, scErr := database.ReadServerConfig()
if scErr != nil || enc == nil || nonce == nil {
return fmt.Errorf("first run requires passphrase: %w", mkErr)
}
v = vault.NewSealed()
logger.Info("vault starting in sealed state")
} else {
return fmt.Errorf("load master key: %w", mkErr)
}
}()
// Load or generate the Ed25519 signing key.
// Security: The private signing key is stored AES-256-GCM encrypted in the
// database. On first run it is generated and stored. The key is decrypted
// with the master key each startup.
privKey, pubKey, err := loadOrGenerateSigningKey(database, masterKey, logger)
if err != nil {
return fmt.Errorf("signing key: %w", err)
} else {
// Load or generate the Ed25519 signing key.
// Security: The private signing key is stored AES-256-GCM encrypted in the
// database. On first run it is generated and stored. The key is decrypted
// with the master key each startup.
privKey, pubKey, err := loadOrGenerateSigningKey(database, masterKey, logger)
if err != nil {
// Zero master key on failure.
for i := range masterKey {
masterKey[i] = 0
}
return fmt.Errorf("signing key: %w", err)
}
v = vault.NewUnsealed(masterKey, privKey, pubKey)
logger.Info("vault unsealed at startup")
}
// Configure TLS. We require TLS 1.2+ and prefer TLS 1.3.
@@ -108,8 +126,8 @@ func run(configPath string, logger *slog.Logger) error {
},
}
// Build the REST handler.
restSrv := server.New(database, cfg, privKey, pubKey, masterKey, logger)
// Build the REST handler. All servers share the same vault by pointer.
restSrv := server.New(database, cfg, v, logger)
httpServer := &http.Server{
Addr: cfg.Server.ListenAddr,
Handler: restSrv.Handler(),
@@ -131,7 +149,7 @@ func run(configPath string, logger *slog.Logger) error {
return fmt.Errorf("load gRPC TLS credentials: %w", err)
}
grpcSrvImpl := grpcserver.New(database, cfg, privKey, pubKey, masterKey, logger)
grpcSrvImpl := grpcserver.New(database, cfg, v, logger)
// Build server directly with TLS credentials. GRPCServerWithCreds builds
// the server with transport credentials at construction time per gRPC idiom.
grpcSrv = rebuildGRPCServerWithTLS(grpcSrvImpl, grpcTLSCreds)

51
dist/install.sh vendored
View File

@@ -6,7 +6,7 @@
# This script must be run as root. It:
# 1. Creates the mcias system user and group (idempotent).
# 2. Copies binaries to /usr/local/bin/.
# 3. Creates /etc/mcias/ and /var/lib/mcias/ with correct permissions.
# 3. Creates /srv/mcias/ with correct permissions.
# 4. Installs the systemd service unit.
# 5. Prints post-install instructions.
#
@@ -25,8 +25,7 @@ set -eu
# Configuration
# ---------------------------------------------------------------------------
BIN_DIR="/usr/local/bin"
CONF_DIR="/etc/mcias"
DATA_DIR="/var/lib/mcias"
SRV_DIR="/srv/mcias"
MAN_DIR="/usr/share/man/man1"
SYSTEMD_DIR="/etc/systemd/system"
SERVICE_USER="mcias"
@@ -114,23 +113,19 @@ for bin in mciassrv mciasctl mciasdb mciasgrpcctl; do
install -m 0755 -o root -g root "$src" "$BIN_DIR/$bin"
done
# Step 3: Create configuration directory.
info "Creating $CONF_DIR"
install -d -m 0750 -o root -g "$SERVICE_GROUP" "$CONF_DIR"
# Step 3: Create service directory.
info "Creating $SRV_DIR"
install -d -m 0750 -o "$SERVICE_USER" -g "$SERVICE_GROUP" "$SRV_DIR"
# Install example config files; never overwrite existing configs.
for f in mcias.conf.example mcias.env.example; do
src="$SCRIPT_DIR/$f"
dst="$CONF_DIR/$f"
dst="$SRV_DIR/$f"
if [ -f "$src" ]; then
install -m 0640 -o root -g "$SERVICE_GROUP" "$src" "$dst" 2>/dev/null || true
install -m 0640 -o "$SERVICE_USER" -g "$SERVICE_GROUP" "$src" "$dst" 2>/dev/null || true
fi
done
# Step 4: Create data directory.
info "Creating $DATA_DIR"
install -d -m 0750 -o "$SERVICE_USER" -g "$SERVICE_GROUP" "$DATA_DIR"
# Step 5: Install systemd service unit.
if [ -d "$SYSTEMD_DIR" ]; then
info "Installing systemd service unit to $SYSTEMD_DIR"
@@ -175,26 +170,26 @@ Next steps:
# Self-signed (development / personal use):
openssl req -x509 -newkey ed25519 -days 3650 \\
-keyout /etc/mcias/server.key \\
-out /etc/mcias/server.crt \\
-keyout /srv/mcias/server.key \\
-out /srv/mcias/server.crt \\
-subj "/CN=auth.example.com" \\
-nodes
chmod 0640 /etc/mcias/server.key
chown root:mcias /etc/mcias/server.key
chmod 0640 /srv/mcias/server.key
chown mcias:mcias /srv/mcias/server.key /srv/mcias/server.crt
2. Copy and edit the configuration file:
cp /etc/mcias/mcias.conf.example /etc/mcias/mcias.conf
\$EDITOR /etc/mcias/mcias.conf
chmod 0640 /etc/mcias/mcias.conf
chown root:mcias /etc/mcias/mcias.conf
cp /srv/mcias/mcias.conf.example /srv/mcias/mcias.toml
\$EDITOR /srv/mcias/mcias.toml
chmod 0640 /srv/mcias/mcias.toml
chown mcias:mcias /srv/mcias/mcias.toml
3. Set the master key passphrase:
cp /etc/mcias/mcias.env.example /etc/mcias/env
\$EDITOR /etc/mcias/env # replace the placeholder passphrase
chmod 0640 /etc/mcias/env
chown root:mcias /etc/mcias/env
cp /srv/mcias/mcias.env.example /srv/mcias/env
\$EDITOR /srv/mcias/env # replace the placeholder passphrase
chmod 0640 /srv/mcias/env
chown mcias:mcias /srv/mcias/env
IMPORTANT: Back up the passphrase to a secure offline location.
Losing it means losing access to all encrypted data in the database.
@@ -208,16 +203,16 @@ Next steps:
5. Create the first admin account using mciasdb (while the server is
running, or before first start):
MCIAS_MASTER_PASSPHRASE=\$(grep MCIAS_MASTER_PASSPHRASE /etc/mcias/env | cut -d= -f2) \\
mciasdb --config /etc/mcias/mcias.conf account create \\
MCIAS_MASTER_PASSPHRASE=\$(grep MCIAS_MASTER_PASSPHRASE /srv/mcias/env | cut -d= -f2) \\
mciasdb --config /srv/mcias/mcias.toml account create \\
--username admin --type human
Then set a password:
MCIAS_MASTER_PASSPHRASE=... mciasdb --config /etc/mcias/mcias.conf \\
MCIAS_MASTER_PASSPHRASE=... mciasdb --config /srv/mcias/mcias.toml \\
account set-password --id <UUID>
And grant the admin role:
MCIAS_MASTER_PASSPHRASE=... mciasdb --config /etc/mcias/mcias.conf \\
MCIAS_MASTER_PASSPHRASE=... mciasdb --config /srv/mcias/mcias.toml \\
role grant --id <UUID> --role admin
For full documentation, see: man mciassrv

View File

@@ -15,7 +15,7 @@
# export MCIAS_MASTER_PASSPHRASE=devpassphrase
#
# Start the server:
# mciassrv -config /path/to/mcias-dev.conf
# mciassrv -config /path/to/mcias-dev.toml
[server]
listen_addr = "127.0.0.1:8443"

View File

@@ -1,38 +1,36 @@
# mcias.conf.docker.example — Config template for container deployment
#
# Mount this file into the container at /etc/mcias/mcias.conf:
# Mount this file into the container at /srv/mcias/mcias.toml:
#
# docker run -d \
# --name mcias \
# -v /path/to/mcias.conf:/etc/mcias/mcias.conf:ro \
# -v /path/to/certs:/etc/mcias:ro \
# -v mcias-data:/data \
# -v /srv/mcias:/srv/mcias \
# -e MCIAS_MASTER_PASSPHRASE=your-passphrase \
# -p 8443:8443 \
# -p 9443:9443 \
# mcias:latest
#
# The container runs as uid 10001 (mcias). Ensure that:
# - /data volume is writable by uid 10001
# - /srv/mcias is writable by uid 10001
# - TLS cert and key are readable by uid 10001
#
# TLS: The server performs TLS termination inside the container; there is no
# plain-text mode. Mount your certificate and key under /etc/mcias/.
# plain-text mode. Place your certificate and key under /srv/mcias/.
# For Let's Encrypt certificates, mount the live/ directory read-only.
[server]
listen_addr = "0.0.0.0:8443"
grpc_addr = "0.0.0.0:9443"
tls_cert = "/etc/mcias/server.crt"
tls_key = "/etc/mcias/server.key"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
# If a reverse proxy (nginx, Caddy, Traefik) sits in front of this container,
# set trusted_proxy to its container IP so real client IPs are used for rate
# limiting and audit logging. Leave commented out for direct exposure.
# trusted_proxy = "172.17.0.1"
[database]
# VOLUME /data is declared in the Dockerfile; map a named volume here.
path = "/data/mcias.db"
# All data lives under /srv/mcias for a single-volume deployment.
path = "/srv/mcias/mcias.db"
[tokens]
issuer = "https://auth.example.com"

View File

@@ -1,12 +1,12 @@
# mcias.conf — Reference configuration for mciassrv
#
# Copy this file to /etc/mcias/mcias.conf and adjust the values for your
# Copy this file to /srv/mcias/mcias.toml and adjust the values for your
# deployment. All fields marked REQUIRED must be set before the server will
# start. Fields marked OPTIONAL can be omitted to use defaults.
#
# File permissions: mode 0640, owner root:mcias.
# chmod 0640 /etc/mcias/mcias.conf
# chown root:mcias /etc/mcias/mcias.conf
# chmod 0640 /srv/mcias/mcias.toml
# chown root:mcias /srv/mcias/mcias.toml
# ---------------------------------------------------------------------------
# [server] — Network listener configuration
@@ -26,11 +26,11 @@ listen_addr = "0.0.0.0:8443"
# REQUIRED. Path to the TLS certificate (PEM format).
# Self-signed certificates work fine for personal deployments; for
# public-facing deployments consider a certificate from Let's Encrypt.
tls_cert = "/etc/mcias/server.crt"
tls_cert = "/srv/mcias/server.crt"
# REQUIRED. Path to the TLS private key (PEM format).
# Permissions: mode 0640, owner root:mcias.
tls_key = "/etc/mcias/server.key"
tls_key = "/srv/mcias/server.key"
# OPTIONAL. IP address of a trusted reverse proxy (e.g. nginx, Caddy, HAProxy).
# When set, the rate limiter and audit log extract the real client IP from the
@@ -55,7 +55,7 @@ tls_key = "/etc/mcias/server.key"
# REQUIRED. Path to the SQLite database file.
# The directory must be writable by the mcias user. WAL mode is enabled
# automatically; expect three files: mcias.db, mcias.db-wal, mcias.db-shm.
path = "/var/lib/mcias/mcias.db"
path = "/srv/mcias/mcias.db"
# ---------------------------------------------------------------------------
# [tokens] — JWT issuance policy
@@ -113,13 +113,13 @@ threads = 4
# database on first run and reused on subsequent runs so the same passphrase
# always produces the same master key.
#
# Set the passphrase in /etc/mcias/env (loaded by the systemd EnvironmentFile
# Set the passphrase in /srv/mcias/env (loaded by the systemd EnvironmentFile
# directive). See dist/mcias.env.example for the template.
passphrase_env = "MCIAS_MASTER_PASSPHRASE"
# Option B: Key file mode. The file must contain exactly 32 bytes of raw key
# material (AES-256). Generate with: openssl rand -out /etc/mcias/master.key 32
# material (AES-256). Generate with: openssl rand -out /srv/mcias/master.key 32
# Permissions: mode 0640, owner root:mcias.
#
# Uncomment and comment out passphrase_env to switch modes.
# keyfile = "/etc/mcias/master.key"
# keyfile = "/srv/mcias/master.key"

View File

@@ -1,10 +1,10 @@
# /etc/mcias/env — Environment file for mciassrv (systemd EnvironmentFile).
# /srv/mcias/env — Environment file for mciassrv (systemd EnvironmentFile).
#
# This file is loaded by the mcias.service unit before the server starts.
# It must be readable only by root and the mcias service account:
#
# chmod 0640 /etc/mcias/env
# chown root:mcias /etc/mcias/env
# chmod 0640 /srv/mcias/env
# chown root:mcias /srv/mcias/env
#
# SECURITY: This file contains the master key passphrase. Treat it with
# the same care as a private key. Do not commit it to version control.

10
dist/mcias.service vendored
View File

@@ -11,11 +11,11 @@ User=mcias
Group=mcias
# Configuration and secrets.
# /etc/mcias/env must contain MCIAS_MASTER_PASSPHRASE=<passphrase>
# /srv/mcias/env must contain MCIAS_MASTER_PASSPHRASE=<passphrase>
# See dist/mcias.env.example for the template.
EnvironmentFile=/etc/mcias/env
EnvironmentFile=/srv/mcias/env
ExecStart=/usr/local/bin/mciassrv -config /etc/mcias/mcias.conf
ExecStart=/usr/local/bin/mciassrv -config /srv/mcias/mcias.toml
Restart=on-failure
RestartSec=5
@@ -30,11 +30,11 @@ LimitNOFILE=65536
CapabilityBoundingSet=
# Filesystem restrictions.
# mciassrv reads /etc/mcias (config, TLS cert/key) and writes /var/lib/mcias (DB).
# mciassrv reads and writes /srv/mcias (config, TLS cert/key, database).
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/mcias
ReadWritePaths=/srv/mcias
# Additional hardening.
NoNewPrivileges=true

View File

@@ -12,11 +12,11 @@ func validConfig() string {
return `
[server]
listen_addr = "0.0.0.0:8443"
tls_cert = "/etc/mcias/server.crt"
tls_key = "/etc/mcias/server.key"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
[database]
path = "/var/lib/mcias/mcias.db"
path = "/srv/mcias/mcias.db"
[tokens]
issuer = "https://auth.example.com"
@@ -154,11 +154,11 @@ func TestValidateMasterKeyBothSet(t *testing.T) {
path := writeTempConfig(t, `
[server]
listen_addr = "0.0.0.0:8443"
tls_cert = "/etc/mcias/server.crt"
tls_key = "/etc/mcias/server.key"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
[database]
path = "/var/lib/mcias/mcias.db"
path = "/srv/mcias/mcias.db"
[tokens]
issuer = "https://auth.example.com"
@@ -173,7 +173,7 @@ threads = 4
[master_key]
passphrase_env = "MCIAS_MASTER_PASSPHRASE"
keyfile = "/etc/mcias/master.key"
keyfile = "/srv/mcias/master.key"
`)
_, err := Load(path)
if err == nil {
@@ -185,11 +185,11 @@ func TestValidateMasterKeyNoneSet(t *testing.T) {
path := writeTempConfig(t, `
[server]
listen_addr = "0.0.0.0:8443"
tls_cert = "/etc/mcias/server.crt"
tls_key = "/etc/mcias/server.key"
tls_cert = "/srv/mcias/server.crt"
tls_key = "/srv/mcias/server.key"
[database]
path = "/var/lib/mcias/mcias.db"
path = "/srv/mcias/mcias.db"
[tokens]
issuer = "https://auth.example.com"

View File

@@ -17,8 +17,12 @@ type adminServiceServer struct {
s *Server
}
// Health returns {"status":"ok"} to signal the server is operational.
// Health returns {"status":"ok"} to signal the server is operational, or
// {"status":"sealed"} when the vault is sealed.
func (a *adminServiceServer) Health(_ context.Context, _ *mciasv1.HealthRequest) (*mciasv1.HealthResponse, error) {
if a.s.vault.IsSealed() {
return &mciasv1.HealthResponse{Status: "sealed"}, nil
}
return &mciasv1.HealthResponse{Status: "ok"}, nil
}
@@ -26,11 +30,12 @@ func (a *adminServiceServer) Health(_ context.Context, _ *mciasv1.HealthRequest)
// The "x" field is the raw 32-byte public key base64url-encoded without padding,
// matching the REST /v1/keys/public response format.
func (a *adminServiceServer) GetPublicKey(_ context.Context, _ *mciasv1.GetPublicKeyRequest) (*mciasv1.GetPublicKeyResponse, error) {
if len(a.s.pubKey) == 0 {
return nil, status.Error(codes.Internal, "public key not available")
pubKey, err := a.s.vault.PubKey()
if err != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
// Encode as base64url without padding — identical to the REST handler.
x := base64.RawURLEncoding.EncodeToString(a.s.pubKey)
x := base64.RawURLEncoding.EncodeToString(pubKey)
return &mciasv1.GetPublicKeyResponse{
Kty: "OKP",
Crv: "Ed25519",

View File

@@ -86,7 +86,11 @@ func (a *authServiceServer) Login(ctx context.Context, req *mciasv1.LoginRequest
a.s.db.WriteAuditEvent(model.EventLoginFail, &acct.ID, nil, ip, `{"reason":"totp_missing"}`) //nolint:errcheck
return nil, status.Error(codes.Unauthenticated, "TOTP code required")
}
secret, err := crypto.OpenAESGCM(a.s.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
masterKey, mkErr := a.s.vault.MasterKey()
if mkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
if err != nil {
a.s.logger.Error("decrypt TOTP secret", "error", err, "account_id", acct.ID)
return nil, status.Error(codes.Internal, "internal error")
@@ -121,7 +125,11 @@ func (a *authServiceServer) Login(ctx context.Context, req *mciasv1.LoginRequest
}
}
tokenStr, claims, err := token.IssueToken(a.s.privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
privKey, pkErr := a.s.vault.PrivKey()
if pkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
tokenStr, claims, err := token.IssueToken(privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
if err != nil {
a.s.logger.Error("issue token", "error", err)
return nil, status.Error(codes.Internal, "internal error")
@@ -186,7 +194,11 @@ func (a *authServiceServer) RenewToken(ctx context.Context, _ *mciasv1.RenewToke
}
}
newTokenStr, newClaims, err := token.IssueToken(a.s.privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
privKey, pkErr := a.s.vault.PrivKey()
if pkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
newTokenStr, newClaims, err := token.IssueToken(privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
if err != nil {
return nil, status.Error(codes.Internal, "internal error")
}
@@ -245,7 +257,11 @@ func (a *authServiceServer) EnrollTOTP(ctx context.Context, req *mciasv1.EnrollT
return nil, status.Error(codes.Internal, "internal error")
}
secretEnc, secretNonce, err := crypto.SealAESGCM(a.s.masterKey, rawSecret)
masterKey, mkErr := a.s.vault.MasterKey()
if mkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
secretEnc, secretNonce, err := crypto.SealAESGCM(masterKey, rawSecret)
if err != nil {
return nil, status.Error(codes.Internal, "internal error")
}
@@ -283,7 +299,11 @@ func (a *authServiceServer) ConfirmTOTP(ctx context.Context, req *mciasv1.Confir
return nil, status.Error(codes.FailedPrecondition, "TOTP enrollment not started")
}
secret, err := crypto.OpenAESGCM(a.s.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
masterKey, mkErr := a.s.vault.MasterKey()
if mkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
if err != nil {
return nil, status.Error(codes.Internal, "internal error")
}

View File

@@ -47,7 +47,11 @@ func (c *credentialServiceServer) GetPGCreds(ctx context.Context, req *mciasv1.G
}
// Decrypt the password for admin retrieval.
password, err := crypto.OpenAESGCM(c.s.masterKey, cred.PGPasswordNonce, cred.PGPasswordEnc)
masterKey, mkErr := c.s.vault.MasterKey()
if mkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
password, err := crypto.OpenAESGCM(masterKey, cred.PGPasswordNonce, cred.PGPasswordEnc)
if err != nil {
return nil, status.Error(codes.Internal, "internal error")
}
@@ -94,7 +98,11 @@ func (c *credentialServiceServer) SetPGCreds(ctx context.Context, req *mciasv1.S
return nil, status.Error(codes.Internal, "internal error")
}
enc, nonce, err := crypto.SealAESGCM(c.s.masterKey, []byte(cr.Password))
masterKey, mkErr := c.s.vault.MasterKey()
if mkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
enc, nonce, err := crypto.SealAESGCM(masterKey, []byte(cr.Password))
if err != nil {
return nil, status.Error(codes.Internal, "internal error")
}

View File

@@ -17,7 +17,6 @@ package grpcserver
import (
"context"
"crypto/ed25519"
"log/slog"
"net"
"strings"
@@ -35,6 +34,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/config"
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
// contextKey is the unexported context key type for this package.
@@ -57,21 +57,17 @@ type Server struct {
cfg *config.Config
logger *slog.Logger
rateLimiter *grpcRateLimiter
privKey ed25519.PrivateKey
pubKey ed25519.PublicKey
masterKey []byte
vault *vault.Vault
}
// New creates a Server with the given dependencies (same as the REST Server).
// A fresh per-IP rate limiter (10 req/s, burst 10) is allocated per Server
// instance so that tests do not share state across test cases.
func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) *Server {
func New(database *db.DB, cfg *config.Config, v *vault.Vault, logger *slog.Logger) *Server {
return &Server{
db: database,
cfg: cfg,
privKey: priv,
pubKey: pub,
masterKey: masterKey,
vault: v,
logger: logger,
rateLimiter: newGRPCRateLimiter(10, 10),
}
@@ -106,6 +102,7 @@ func (s *Server) buildServer(extra ...grpc.ServerOption) *grpc.Server {
[]grpc.ServerOption{
grpc.ChainUnaryInterceptor(
s.loggingInterceptor,
s.sealedInterceptor,
s.authInterceptor,
s.rateLimitInterceptor,
),
@@ -162,14 +159,36 @@ func (s *Server) loggingInterceptor(
return resp, err
}
// sealedInterceptor rejects all RPCs (except Health) when the vault is sealed.
//
// Security: This is the first interceptor in the chain (after logging). It
// prevents any authenticated or data-serving handler from running while the
// vault is sealed and key material is unavailable.
func (s *Server) sealedInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
if !s.vault.IsSealed() {
return handler(ctx, req)
}
// Health is always allowed — returns sealed status.
if info.FullMethod == "/mcias.v1.AdminService/Health" {
return handler(ctx, req)
}
return nil, status.Error(codes.Unavailable, "vault sealed")
}
// authInterceptor validates the Bearer JWT from gRPC metadata and injects
// claims into the context. Public methods bypass this check.
//
// Security: Same validation path as the REST RequireAuth middleware:
// 1. Extract "authorization" metadata value (case-insensitive key lookup).
// 2. Validate JWT (alg-first, then signature, then expiry/issuer).
// 3. Check JTI against revocation table.
// 4. Inject claims into context.
// 2. Read public key from vault (fail closed if sealed).
// 3. Validate JWT (alg-first, then signature, then expiry/issuer).
// 4. Check JTI against revocation table.
// 5. Inject claims into context.
func (s *Server) authInterceptor(
ctx context.Context,
req interface{},
@@ -186,7 +205,13 @@ func (s *Server) authInterceptor(
return nil, status.Error(codes.Unauthenticated, "missing or invalid authorization")
}
claims, err := token.ValidateToken(s.pubKey, tokenStr, s.cfg.Tokens.Issuer)
// Security: read the public key from vault at request time.
pubKey, err := s.vault.PubKey()
if err != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
claims, err := token.ValidateToken(pubKey, tokenStr, s.cfg.Tokens.Issuer)
if err != nil {
return nil, status.Error(codes.Unauthenticated, "invalid or expired token")
}

View File

@@ -30,6 +30,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
const (
@@ -73,7 +74,8 @@ func newTestEnv(t *testing.T) *testEnv {
cfg := config.NewTestConfig(testIssuer)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := New(database, cfg, priv, pub, masterKey, logger)
v := vault.NewUnsealed(masterKey, priv, pub)
srv := New(database, cfg, v, logger)
grpcSrv := srv.GRPCServer()
lis := bufconn.Listen(bufConnSize)

View File

@@ -32,7 +32,11 @@ func (t *tokenServiceServer) ValidateToken(_ context.Context, req *mciasv1.Valid
return &mciasv1.ValidateTokenResponse{Valid: false}, nil
}
claims, err := token.ValidateToken(t.s.pubKey, tokenStr, t.s.cfg.Tokens.Issuer)
pubKey, pkErr := t.s.vault.PubKey()
if pkErr != nil {
return &mciasv1.ValidateTokenResponse{Valid: false}, nil
}
claims, err := token.ValidateToken(pubKey, tokenStr, t.s.cfg.Tokens.Issuer)
if err != nil {
return &mciasv1.ValidateTokenResponse{Valid: false}, nil
}
@@ -67,7 +71,11 @@ func (ts *tokenServiceServer) IssueServiceToken(ctx context.Context, req *mciasv
return nil, status.Error(codes.InvalidArgument, "token issue is only for system accounts")
}
tokenStr, claims, err := token.IssueToken(ts.s.privKey, ts.s.cfg.Tokens.Issuer, acct.UUID, nil, ts.s.cfg.ServiceExpiry())
privKey, pkErr := ts.s.vault.PrivKey()
if pkErr != nil {
return nil, status.Error(codes.Unavailable, "vault sealed")
}
tokenStr, claims, err := token.IssueToken(privKey, ts.s.cfg.Tokens.Issuer, acct.UUID, nil, ts.s.cfg.ServiceExpiry())
if err != nil {
return nil, status.Error(codes.Internal, "internal error")
}

View File

@@ -13,7 +13,6 @@ package middleware
import (
"context"
"crypto/ed25519"
"encoding/json"
"errors"
"fmt"
@@ -27,6 +26,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/policy"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
// contextKey is the unexported type for context keys in this package, preventing
@@ -90,12 +90,18 @@ func (rw *responseWriter) WriteHeader(code int) {
// RequireAuth returns middleware that validates a Bearer JWT and injects the
// claims into the request context. Returns 401 on any auth failure.
//
// The public key is read from the vault at request time so that the middleware
// works correctly across seal/unseal transitions. When the vault is sealed,
// the sealed middleware (RequireUnsealed) prevents reaching this handler, but
// the vault check here provides defense in depth (fail closed).
//
// Security: Token validation order:
// 1. Extract Bearer token from Authorization header.
// 2. Validate the JWT (alg=EdDSA, signature, expiry, issuer).
// 3. Check the JTI against the revocation table in the database.
// 4. Inject validated claims into context for downstream handlers.
func RequireAuth(pubKey ed25519.PublicKey, database *db.DB, issuer string) func(http.Handler) http.Handler {
// 2. Read public key from vault (fail closed if sealed).
// 3. Validate the JWT (alg=EdDSA, signature, expiry, issuer).
// 4. Check the JTI against the revocation table in the database.
// 5. Inject validated claims into context for downstream handlers.
func RequireAuth(v *vault.Vault, database *db.DB, issuer string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenStr, err := extractBearerToken(r)
@@ -104,6 +110,14 @@ func RequireAuth(pubKey ed25519.PublicKey, database *db.DB, issuer string) func(
return
}
// Security: read the public key from vault at request time.
// If the vault is sealed, fail closed with 503.
pubKey, err := v.PubKey()
if err != nil {
writeError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
claims, err := token.ValidateToken(pubKey, tokenStr, issuer)
if err != nil {
// Security: Map all token errors to a generic 401; do not
@@ -437,3 +451,47 @@ func RequirePolicy(
})
}
}
// RequireUnsealed returns middleware that blocks requests when the vault is sealed.
//
// Exempt paths (served normally even when sealed):
// - GET /v1/health, GET /v1/vault/status, POST /v1/vault/unseal
// - GET /unseal, POST /unseal
// - GET /static/* (CSS/JS needed by the unseal page)
//
// API paths (/v1/*) receive a JSON 503 response. All other paths (UI) receive
// a 302 redirect to /unseal.
//
// Security: This middleware is the first in the chain (after global security
// headers). It ensures no authenticated or data-serving handler runs while the
// vault is sealed and key material is unavailable.
func RequireUnsealed(v *vault.Vault) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !v.IsSealed() {
next.ServeHTTP(w, r)
return
}
path := r.URL.Path
// Exempt paths that must work while sealed.
if path == "/v1/health" || path == "/v1/vault/status" ||
path == "/v1/vault/unseal" ||
path == "/unseal" ||
strings.HasPrefix(path, "/static/") {
next.ServeHTTP(w, r)
return
}
// API paths: JSON 503.
if strings.HasPrefix(path, "/v1/") {
writeError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
// UI paths: redirect to unseal page.
http.Redirect(w, r, "/unseal", http.StatusFound)
})
}
}

View File

@@ -15,6 +15,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
func generateTestKey(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) {
@@ -26,6 +27,15 @@ func generateTestKey(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) {
return pub, priv
}
func testVault(t *testing.T, priv ed25519.PrivateKey, pub ed25519.PublicKey) *vault.Vault {
t.Helper()
mk := make([]byte, 32)
if _, err := rand.Read(mk); err != nil {
t.Fatalf("generate master key: %v", err)
}
return vault.NewUnsealed(mk, priv, pub)
}
func openTestDB(t *testing.T) *db.DB {
t.Helper()
database, err := db.Open(":memory:")
@@ -96,7 +106,7 @@ func TestRequireAuthValid(t *testing.T) {
tokenStr := issueAndTrackToken(t, priv, database, acct.ID, []string{"reader"})
reached := false
handler := RequireAuth(pub, database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := RequireAuth(testVault(t, priv, pub), database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reached = true
claims := ClaimsFromContext(r.Context())
if claims == nil {
@@ -123,7 +133,7 @@ func TestRequireAuthMissingHeader(t *testing.T) {
_ = priv
database := openTestDB(t)
handler := RequireAuth(pub, database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
handler := RequireAuth(testVault(t, priv, pub), database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
t.Error("handler should not be reached without auth")
w.WriteHeader(http.StatusOK)
}))
@@ -138,10 +148,10 @@ func TestRequireAuthMissingHeader(t *testing.T) {
}
func TestRequireAuthInvalidToken(t *testing.T) {
pub, _ := generateTestKey(t)
pub, priv := generateTestKey(t)
database := openTestDB(t)
handler := RequireAuth(pub, database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
handler := RequireAuth(testVault(t, priv, pub), database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
t.Error("handler should not be reached with invalid token")
w.WriteHeader(http.StatusOK)
}))
@@ -176,7 +186,7 @@ func TestRequireAuthRevokedToken(t *testing.T) {
t.Fatalf("RevokeToken: %v", err)
}
handler := RequireAuth(pub, database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
handler := RequireAuth(testVault(t, priv, pub), database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
t.Error("handler should not be reached with revoked token")
w.WriteHeader(http.StatusOK)
}))
@@ -201,7 +211,7 @@ func TestRequireAuthExpiredToken(t *testing.T) {
t.Fatalf("IssueToken: %v", err)
}
handler := RequireAuth(pub, database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
handler := RequireAuth(testVault(t, priv, pub), database, testIssuer)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
t.Error("handler should not be reached with expired token")
w.WriteHeader(http.StatusOK)
}))

View File

@@ -178,6 +178,9 @@ const (
EventPGCredAccessed = "pgcred_accessed"
EventPGCredUpdated = "pgcred_updated" //nolint:gosec // G101: audit event type string, not a credential
EventVaultSealed = "vault_sealed"
EventVaultUnsealed = "vault_unsealed"
EventTagAdded = "tag_added"
EventTagRemoved = "tag_removed"

View File

@@ -10,7 +10,6 @@
package server
import (
"crypto/ed25519"
"encoding/json"
"errors"
"fmt"
@@ -18,6 +17,7 @@ import (
"log/slog"
"net"
"net/http"
"strings"
"time"
"git.wntrmute.dev/kyle/mcias/internal/audit"
@@ -30,28 +30,25 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/ui"
"git.wntrmute.dev/kyle/mcias/internal/validate"
"git.wntrmute.dev/kyle/mcias/internal/vault"
"git.wntrmute.dev/kyle/mcias/web"
)
// Server holds the dependencies injected into all handlers.
type Server struct {
db *db.DB
cfg *config.Config
logger *slog.Logger
privKey ed25519.PrivateKey
pubKey ed25519.PublicKey
masterKey []byte
db *db.DB
cfg *config.Config
logger *slog.Logger
vault *vault.Vault
}
// New creates a Server with the given dependencies.
func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) *Server {
func New(database *db.DB, cfg *config.Config, v *vault.Vault, logger *slog.Logger) *Server {
return &Server{
db: database,
cfg: cfg,
privKey: priv,
pubKey: pub,
masterKey: masterKey,
logger: logger,
db: database,
cfg: cfg,
vault: v,
logger: logger,
}
}
@@ -109,8 +106,14 @@ func (s *Server) Handler() http.Handler {
_, _ = w.Write(specYAML)
})))
// Vault endpoints (exempt from sealed middleware and auth).
unsealRateLimit := middleware.RateLimit(3, 5, trustedProxy)
mux.Handle("POST /v1/vault/unseal", unsealRateLimit(http.HandlerFunc(s.handleUnseal)))
mux.HandleFunc("GET /v1/vault/status", s.handleVaultStatus)
mux.Handle("POST /v1/vault/seal", middleware.RequireAuth(s.vault, s.db, s.cfg.Tokens.Issuer)(middleware.RequireRole("admin")(http.HandlerFunc(s.handleSeal))))
// Authenticated endpoints.
requireAuth := middleware.RequireAuth(s.pubKey, s.db, s.cfg.Tokens.Issuer)
requireAuth := middleware.RequireAuth(s.vault, s.db, s.cfg.Tokens.Issuer)
requireAdmin := func(h http.Handler) http.Handler {
return requireAuth(middleware.RequireRole("admin")(h))
}
@@ -151,15 +154,18 @@ func (s *Server) Handler() http.Handler {
mux.Handle("DELETE /v1/policy/rules/{id}", requireAdmin(http.HandlerFunc(s.handleDeletePolicyRule)))
// UI routes (HTMX-based management frontend).
uiSrv, err := ui.New(s.db, s.cfg, s.privKey, s.pubKey, s.masterKey, s.logger)
uiSrv, err := ui.New(s.db, s.cfg, s.vault, s.logger)
if err != nil {
panic(fmt.Sprintf("ui: init failed: %v", err))
}
uiSrv.Register(mux)
// Apply global middleware: request logging and security headers.
// Apply global middleware: request logging, sealed check, and security headers.
// Rate limiting is applied per-route above (login, token/validate).
var root http.Handler = mux
// Security: RequireUnsealed runs after the mux (so exempt routes can be
// routed) but before the logger (so sealed-blocked requests are still logged).
root = middleware.RequireUnsealed(s.vault)(root)
root = middleware.RequestLogger(s.logger)(root)
// Security (SEC-04): apply baseline security headers to ALL responses
@@ -177,12 +183,21 @@ func (s *Server) Handler() http.Handler {
// ---- Public handlers ----
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
if s.vault.IsSealed() {
writeJSON(w, http.StatusOK, map[string]string{"status": "sealed"})
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
// handlePublicKey returns the server's Ed25519 public key in JWK format.
// This allows relying parties to independently verify JWTs.
func (s *Server) handlePublicKey(w http.ResponseWriter, _ *http.Request) {
pubKey, err := s.vault.PubKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
// Encode the Ed25519 public key as a JWK (RFC 8037).
// The "x" parameter is the base64url-encoded public key bytes.
jwk := map[string]string{
@@ -190,7 +205,7 @@ func (s *Server) handlePublicKey(w http.ResponseWriter, _ *http.Request) {
"crv": "Ed25519",
"use": "sig",
"alg": "EdDSA",
"x": encodeBase64URL(s.pubKey),
"x": encodeBase64URL(pubKey),
}
writeJSON(w, http.StatusOK, jwk)
}
@@ -270,13 +285,23 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
// TOTP check (if enrolled).
if acct.TOTPRequired {
if req.TOTPCode == "" {
// Security (DEF-08 / PEN-06): do NOT increment the lockout counter
// for a missing TOTP code. A missing code means the client needs to
// re-prompt the user — it is not a credential failure. Incrementing
// here would let an attacker trigger account lockout by omitting the
// code after a correct password guess, and would penalise well-behaved
// clients that call Login in two steps (password first, TOTP second).
s.writeAudit(r, model.EventLoginFail, &acct.ID, nil, `{"reason":"totp_missing"}`)
_ = s.db.RecordLoginFailure(acct.ID)
middleware.WriteError(w, http.StatusUnauthorized, "TOTP code required", "totp_required")
return
}
// Decrypt the TOTP secret.
secret, err := crypto.OpenAESGCM(s.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
masterKey, err := s.vault.MasterKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
if err != nil {
s.logger.Error("decrypt TOTP secret", "error", err, "account_id", acct.ID)
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
@@ -316,7 +341,12 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
}
}
tokenStr, claims, err := token.IssueToken(s.privKey, s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
privKey, err := s.vault.PrivKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
tokenStr, claims, err := token.IssueToken(privKey, s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
if err != nil {
s.logger.Error("issue token", "error", err)
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
@@ -386,7 +416,12 @@ func (s *Server) handleRenew(w http.ResponseWriter, r *http.Request) {
}
}
newTokenStr, newClaims, err := token.IssueToken(s.privKey, s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
privKey, err := s.vault.PrivKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
newTokenStr, newClaims, err := token.IssueToken(privKey, s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
if err != nil {
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
return
@@ -438,7 +473,12 @@ func (s *Server) handleTokenValidate(w http.ResponseWriter, r *http.Request) {
return
}
claims, err := token.ValidateToken(s.pubKey, tokenStr, s.cfg.Tokens.Issuer)
pubKey, err := s.vault.PubKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
claims, err := token.ValidateToken(pubKey, tokenStr, s.cfg.Tokens.Issuer)
if err != nil {
writeJSON(w, http.StatusOK, validateResponse{Valid: false})
return
@@ -478,7 +518,12 @@ func (s *Server) handleTokenIssue(w http.ResponseWriter, r *http.Request) {
return
}
tokenStr, claims, err := token.IssueToken(s.privKey, s.cfg.Tokens.Issuer, acct.UUID, nil, s.cfg.ServiceExpiry())
privKey, err := s.vault.PrivKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
tokenStr, claims, err := token.IssueToken(privKey, s.cfg.Tokens.Issuer, acct.UUID, nil, s.cfg.ServiceExpiry())
if err != nil {
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
return
@@ -869,7 +914,12 @@ func (s *Server) handleTOTPEnroll(w http.ResponseWriter, r *http.Request) {
// Encrypt the secret before storing it temporarily.
// Note: we store as pending; enrollment is confirmed with /confirm.
secretEnc, secretNonce, err := crypto.SealAESGCM(s.masterKey, rawSecret)
masterKey, err := s.vault.MasterKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
secretEnc, secretNonce, err := crypto.SealAESGCM(masterKey, rawSecret)
if err != nil {
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
return
@@ -912,7 +962,12 @@ func (s *Server) handleTOTPConfirm(w http.ResponseWriter, r *http.Request) {
return
}
secret, err := crypto.OpenAESGCM(s.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
masterKey, err := s.vault.MasterKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
if err != nil {
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
return
@@ -1172,7 +1227,12 @@ func (s *Server) handleGetPGCreds(w http.ResponseWriter, r *http.Request) {
}
// Decrypt the password to return it to the admin caller.
password, err := crypto.OpenAESGCM(s.masterKey, cred.PGPasswordNonce, cred.PGPasswordEnc)
masterKey, err := s.vault.MasterKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
password, err := crypto.OpenAESGCM(masterKey, cred.PGPasswordNonce, cred.PGPasswordEnc)
if err != nil {
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
return
@@ -1209,7 +1269,12 @@ func (s *Server) handleSetPGCreds(w http.ResponseWriter, r *http.Request) {
req.Port = 5432
}
enc, nonce, err := crypto.SealAESGCM(s.masterKey, []byte(req.Password))
masterKey, err := s.vault.MasterKey()
if err != nil {
middleware.WriteError(w, http.StatusServiceUnavailable, "vault sealed", "vault_sealed")
return
}
enc, nonce, err := crypto.SealAESGCM(masterKey, []byte(req.Password))
if err != nil {
middleware.WriteError(w, http.StatusInternalServerError, "internal error", "internal_error")
return
@@ -1412,16 +1477,23 @@ func decodeJSON(w http.ResponseWriter, r *http.Request, v interface{}) bool {
}
// extractBearerFromRequest extracts a Bearer token from the Authorization header.
// Security (PEN-01): validates the "Bearer" prefix using case-insensitive
// comparison before extracting the token. The previous implementation sliced
// at a fixed offset without checking the prefix, accepting any 8+ character
// Authorization value.
func extractBearerFromRequest(r *http.Request) (string, error) {
auth := r.Header.Get("Authorization")
if auth == "" {
return "", fmt.Errorf("no Authorization header")
}
const prefix = "Bearer "
if len(auth) <= len(prefix) {
parts := strings.SplitN(auth, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return "", fmt.Errorf("malformed Authorization header")
}
return auth[len(prefix):], nil
if parts[1] == "" {
return "", fmt.Errorf("empty Bearer token")
}
return parts[1], nil
}
// docsSecurityHeaders adds the same defensive HTTP headers as the UI sub-mux

View File

@@ -2,11 +2,16 @@ package server
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"crypto/ed25519"
"crypto/rand"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"net/http/httptest"
"strings"
@@ -19,8 +24,29 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
// generateTOTPCode computes a valid RFC 6238 TOTP code for the current time
// using the given raw secret bytes. Used in tests to confirm TOTP enrollment.
func generateTOTPCode(t *testing.T, secret []byte) string {
t.Helper()
counter := uint64(time.Now().Unix() / 30) //nolint:gosec // G115: always non-negative
counterBytes := make([]byte, 8)
binary.BigEndian.PutUint64(counterBytes, counter)
mac := hmac.New(sha1.New, secret)
if _, err := mac.Write(counterBytes); err != nil {
t.Fatalf("generateTOTPCode: HMAC write: %v", err)
}
h := mac.Sum(nil)
offset := h[len(h)-1] & 0x0F
binCode := (int(h[offset]&0x7F)<<24 |
int(h[offset+1])<<16 |
int(h[offset+2])<<8 |
int(h[offset+3])) % int(math.Pow10(6))
return fmt.Sprintf("%06d", binCode)
}
const testIssuer = "https://auth.example.com"
func newTestServer(t *testing.T) (*Server, ed25519.PublicKey, ed25519.PrivateKey, *db.DB) {
@@ -47,8 +73,9 @@ func newTestServer(t *testing.T) (*Server, ed25519.PublicKey, ed25519.PrivateKey
cfg := config.NewTestConfig(testIssuer)
v := vault.NewUnsealed(masterKey, priv, pub)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := New(database, cfg, priv, pub, masterKey, logger)
srv := New(database, cfg, v, logger)
return srv, pub, priv, database
}
@@ -620,8 +647,9 @@ func TestRenewToken(t *testing.T) {
acct := createTestHumanAccount(t, srv, "renew-user")
handler := srv.Handler()
// Issue a short-lived token (2s) so we can wait past the 50% threshold.
oldTokenStr, claims, err := token.IssueToken(priv, testIssuer, acct.UUID, nil, 2*time.Second)
// Issue a short-lived token (4s) so we can wait past the 50% threshold
// while leaving enough headroom before expiry to avoid flakiness.
oldTokenStr, claims, err := token.IssueToken(priv, testIssuer, acct.UUID, nil, 4*time.Second)
if err != nil {
t.Fatalf("IssueToken: %v", err)
}
@@ -630,8 +658,8 @@ func TestRenewToken(t *testing.T) {
t.Fatalf("TrackToken: %v", err)
}
// Wait for >50% of the 2s lifetime to elapse.
time.Sleep(1100 * time.Millisecond)
// Wait for >50% of the 4s lifetime to elapse.
time.Sleep(2100 * time.Millisecond)
rr := doRequest(t, handler, "POST", "/v1/auth/renew", nil, oldTokenStr)
if rr.Code != http.StatusOK {
@@ -793,6 +821,46 @@ func TestLoginLockedAccountReturns401(t *testing.T) {
// TestRenewTokenTooEarly verifies that a token cannot be renewed before 50%
// of its lifetime has elapsed (SEC-03).
// TestExtractBearerFromRequest verifies that extractBearerFromRequest correctly
// validates the "Bearer" prefix before extracting the token string.
// Security (PEN-01): the previous implementation sliced at a fixed offset
// without checking the prefix, accepting any 8+ character Authorization value.
func TestExtractBearerFromRequest(t *testing.T) {
tests := []struct {
name string
header string
want string
wantErr bool
}{
{"valid", "Bearer mytoken123", "mytoken123", false},
{"missing header", "", "", true},
{"no bearer prefix", "Token mytoken123", "", true},
{"basic auth scheme", "Basic dXNlcjpwYXNz", "", true},
{"empty token", "Bearer ", "", true},
{"bearer only no space", "Bearer", "", true},
{"case insensitive", "bearer mytoken123", "mytoken123", false},
{"mixed case", "BEARER mytoken123", "mytoken123", false},
{"garbage 8 chars", "XXXXXXXX", "", true},
{"token with spaces", "Bearer token with spaces", "token with spaces", false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
if tc.header != "" {
req.Header.Set("Authorization", tc.header)
}
got, err := extractBearerFromRequest(req)
if (err != nil) != tc.wantErr {
t.Errorf("wantErr=%v, got err=%v", tc.wantErr, err)
}
if !tc.wantErr && got != tc.want {
t.Errorf("token = %q, want %q", got, tc.want)
}
})
}
}
func TestRenewTokenTooEarly(t *testing.T) {
srv, _, priv, _ := newTestServer(t)
acct := createTestHumanAccount(t, srv, "renew-early-user")
@@ -816,3 +884,91 @@ func TestRenewTokenTooEarly(t *testing.T) {
t.Errorf("expected eligibility message, got: %s", rr.Body.String())
}
}
// TestTOTPMissingDoesNotIncrementLockout verifies that a login attempt with
// a correct password but missing TOTP code does NOT increment the account
// lockout counter (PEN-06 / DEF-08).
//
// Security: incrementing the lockout counter for a missing TOTP code would
// allow an attacker to lock out a TOTP-enrolled account by repeatedly sending
// the correct password with no TOTP code — without needing to guess TOTP.
// It would also penalise well-behaved two-step clients.
func TestTOTPMissingDoesNotIncrementLockout(t *testing.T) {
srv, _, priv, database := newTestServer(t)
acct := createTestHumanAccount(t, srv, "totp-lockout-user")
handler := srv.Handler()
// Issue a token so we can call the TOTP enroll and confirm endpoints.
tokenStr, claims, err := token.IssueToken(priv, testIssuer, acct.UUID, nil, time.Hour)
if err != nil {
t.Fatalf("IssueToken: %v", err)
}
if err := srv.db.TrackToken(claims.JTI, acct.ID, claims.IssuedAt, claims.ExpiresAt); err != nil {
t.Fatalf("TrackToken: %v", err)
}
// Enroll TOTP — get back the base32 secret.
enrollRR := doRequest(t, handler, "POST", "/v1/auth/totp/enroll", totpEnrollRequest{
Password: "testpass123",
}, tokenStr)
if enrollRR.Code != http.StatusOK {
t.Fatalf("enroll status = %d, want 200; body: %s", enrollRR.Code, enrollRR.Body.String())
}
var enrollResp totpEnrollResponse
if err := json.Unmarshal(enrollRR.Body.Bytes(), &enrollResp); err != nil {
t.Fatalf("unmarshal enroll: %v", err)
}
// Decode the secret and generate a valid TOTP code to confirm enrollment.
// We compute the TOTP code inline using the same RFC 6238 algorithm used
// by auth.ValidateTOTP, since auth.hotp is not exported.
secretBytes, err := auth.DecodeTOTPSecret(enrollResp.Secret)
if err != nil {
t.Fatalf("DecodeTOTPSecret: %v", err)
}
currentCode := generateTOTPCode(t, secretBytes)
// Confirm enrollment.
confirmRR := doRequest(t, handler, "POST", "/v1/auth/totp/confirm", map[string]string{
"code": currentCode,
}, tokenStr)
if confirmRR.Code != http.StatusNoContent {
t.Fatalf("confirm status = %d, want 204; body: %s", confirmRR.Code, confirmRR.Body.String())
}
// Account should now require TOTP. Lower the lockout threshold to 1 so
// that a single RecordLoginFailure call would immediately lock the account.
origThreshold := db.LockoutThreshold
db.LockoutThreshold = 1
t.Cleanup(func() { db.LockoutThreshold = origThreshold })
// Attempt login with the correct password but no TOTP code.
rr := doRequest(t, handler, "POST", "/v1/auth/login", map[string]string{
"username": "totp-lockout-user",
"password": "testpass123",
}, "")
if rr.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for missing TOTP, got %d; body: %s", rr.Code, rr.Body.String())
}
// The error code must be totp_required, not unauthorized.
var errResp struct {
Code string `json:"code"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &errResp); err != nil {
t.Fatalf("unmarshal error response: %v", err)
}
if errResp.Code != "totp_required" {
t.Errorf("error code = %q, want %q", errResp.Code, "totp_required")
}
// Security (PEN-06): the lockout counter must NOT have been incremented.
// With threshold=1, if it had been incremented the account would now be
// locked and a subsequent login with correct credentials would fail.
locked, err := database.IsLockedOut(acct.ID)
if err != nil {
t.Fatalf("IsLockedOut: %v", err)
}
if locked {
t.Error("account was locked after TOTP-missing login — lockout counter was incorrectly incremented (PEN-06)")
}
}

102
internal/server/vault.go Normal file
View File

@@ -0,0 +1,102 @@
// Vault seal/unseal REST handlers for MCIAS.
package server
import (
"net/http"
"git.wntrmute.dev/kyle/mcias/internal/audit"
"git.wntrmute.dev/kyle/mcias/internal/middleware"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
// unsealRequest is the request body for POST /v1/vault/unseal.
type unsealRequest struct {
Passphrase string `json:"passphrase"`
}
// handleUnseal accepts a passphrase, derives the master key, decrypts the
// signing key, and unseals the vault. Rate-limited to 3/s burst 5.
//
// Security: The passphrase is never logged. A generic error is returned on
// any failure to prevent information leakage about the vault state.
func (s *Server) handleUnseal(w http.ResponseWriter, r *http.Request) {
if !s.vault.IsSealed() {
writeJSON(w, http.StatusOK, map[string]string{"status": "already unsealed"})
return
}
var req unsealRequest
if !decodeJSON(w, r, &req) {
return
}
if req.Passphrase == "" {
middleware.WriteError(w, http.StatusBadRequest, "passphrase is required", "bad_request")
return
}
// Derive master key from passphrase.
masterKey, err := vault.DeriveFromPassphrase(req.Passphrase, s.db)
if err != nil {
s.logger.Error("vault unseal: derive key", "error", err)
middleware.WriteError(w, http.StatusUnauthorized, "unseal failed", "unauthorized")
return
}
// Decrypt the signing key.
privKey, pubKey, err := vault.DecryptSigningKey(s.db, masterKey)
if err != nil {
// Zero derived master key on failure.
for i := range masterKey {
masterKey[i] = 0
}
s.logger.Error("vault unseal: decrypt signing key", "error", err)
middleware.WriteError(w, http.StatusUnauthorized, "unseal failed", "unauthorized")
return
}
if err := s.vault.Unseal(masterKey, privKey, pubKey); err != nil {
s.logger.Error("vault unseal: state transition", "error", err)
middleware.WriteError(w, http.StatusConflict, "vault is already unsealed", "conflict")
return
}
ip := middleware.ClientIP(r, nil)
s.writeAudit(r, model.EventVaultUnsealed, nil, nil, audit.JSON("source", "api", "ip", ip))
s.logger.Info("vault unsealed via API", "ip", ip)
writeJSON(w, http.StatusOK, map[string]string{"status": "unsealed"})
}
// handleSeal seals the vault, zeroing all key material. Admin-only.
//
// Security: The caller's token becomes invalid after sealing because the
// public key needed to validate it is no longer available.
func (s *Server) handleSeal(w http.ResponseWriter, r *http.Request) {
if s.vault.IsSealed() {
writeJSON(w, http.StatusOK, map[string]string{"status": "already sealed"})
return
}
claims := middleware.ClaimsFromContext(r.Context())
var actorID *int64
if claims != nil {
acct, err := s.db.GetAccountByUUID(claims.Subject)
if err == nil {
actorID = &acct.ID
}
}
s.vault.Seal()
ip := middleware.ClientIP(r, nil)
s.writeAudit(r, model.EventVaultSealed, actorID, nil, audit.JSON("source", "api", "ip", ip))
s.logger.Info("vault sealed via API", "ip", ip)
writeJSON(w, http.StatusOK, map[string]string{"status": "sealed"})
}
// handleVaultStatus returns the current seal state of the vault.
func (s *Server) handleVaultStatus(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"sealed": s.vault.IsSealed()})
}

View File

@@ -0,0 +1,171 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
func TestHandleHealthSealed(t *testing.T) {
srv, _, _, _ := newTestServer(t)
srv.vault.Seal()
req := httptest.NewRequest(http.MethodGet, "/v1/health", nil)
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("health status = %d, want 200", rr.Code)
}
var resp map[string]string
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode health: %v", err)
}
if resp["status"] != "sealed" {
t.Fatalf("health status = %q, want sealed", resp["status"])
}
}
func TestHandleHealthUnsealed(t *testing.T) {
srv, _, _, _ := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/v1/health", nil)
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("health status = %d, want 200", rr.Code)
}
var resp map[string]string
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode health: %v", err)
}
if resp["status"] != "ok" {
t.Fatalf("health status = %q, want ok", resp["status"])
}
}
func TestVaultStatusEndpoint(t *testing.T) {
srv, _, _, _ := newTestServer(t)
// Unsealed
req := httptest.NewRequest(http.MethodGet, "/v1/vault/status", nil)
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status code = %d, want 200", rr.Code)
}
var resp map[string]bool
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp["sealed"] {
t.Fatal("vault should be unsealed")
}
// Seal and check again
srv.vault.Seal()
req = httptest.NewRequest(http.MethodGet, "/v1/vault/status", nil)
rr = httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status code = %d, want 200", rr.Code)
}
resp = nil
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
if !resp["sealed"] {
t.Fatal("vault should be sealed")
}
}
func TestSealedMiddlewareAPIReturns503(t *testing.T) {
srv, _, _, _ := newTestServer(t)
srv.vault.Seal()
req := httptest.NewRequest(http.MethodGet, "/v1/accounts", nil)
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusServiceUnavailable {
t.Fatalf("sealed API status = %d, want 503", rr.Code)
}
var resp map[string]string
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp["code"] != "vault_sealed" {
t.Fatalf("error code = %q, want vault_sealed", resp["code"])
}
}
func TestSealedMiddlewareUIRedirects(t *testing.T) {
srv, _, _, _ := newTestServer(t)
srv.vault.Seal()
req := httptest.NewRequest(http.MethodGet, "/dashboard", nil)
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusFound {
t.Fatalf("sealed UI status = %d, want 302", rr.Code)
}
loc := rr.Header().Get("Location")
if loc != "/unseal" {
t.Fatalf("redirect location = %q, want /unseal", loc)
}
}
func TestUnsealBadPassphrase(t *testing.T) {
srv, _, _, _ := newTestServer(t)
// Start sealed.
v := vault.NewSealed()
srv.vault = v
body := `{"passphrase":"wrong-passphrase"}`
req := httptest.NewRequest(http.MethodPost, "/v1/vault/unseal", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusUnauthorized {
t.Fatalf("unseal with bad passphrase status = %d, want 401", rr.Code)
}
}
func TestSealAlreadySealedNoop(t *testing.T) {
srv, _, priv, _ := newTestServer(t)
// Seal via API (needs admin token)
adminToken, _ := issueAdminToken(t, srv, priv, "admin")
req := httptest.NewRequest(http.MethodPost, "/v1/vault/seal", nil)
req.Header.Set("Authorization", "Bearer "+adminToken)
rr := httptest.NewRecorder()
srv.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("seal status = %d, want 200", rr.Code)
}
var resp map[string]string
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp["status"] != "sealed" {
t.Fatalf("seal response status = %q, want sealed", resp["status"])
}
// Vault should be sealed now
if !srv.vault.IsSealed() {
t.Fatal("vault should be sealed after seal API call")
}
}

View File

@@ -8,6 +8,9 @@ import (
"crypto/subtle"
"encoding/hex"
"fmt"
"sync"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
// CSRFManager implements HMAC-signed Double-Submit Cookie CSRF protection.
@@ -21,17 +24,67 @@ import (
// - The form/header value is HMAC-SHA256(key, cookieVal); this is what the
// server verifies. An attacker cannot forge the HMAC without the key.
// - Comparison uses crypto/subtle.ConstantTimeCompare to prevent timing attacks.
// - When backed by a vault, the key is derived lazily on first use after
// unseal. When the vault is re-sealed, the key is invalidated and re-derived
// on the next unseal. This is safe because sealed middleware prevents
// reaching CSRF-protected routes.
type CSRFManager struct {
key []byte
mu sync.Mutex
key []byte
vault *vault.Vault
}
// newCSRFManager creates a CSRFManager whose key is derived from masterKey.
// newCSRFManager creates a CSRFManager with a static key derived from masterKey.
// Key derivation: SHA-256("mcias-ui-csrf-v1" || masterKey)
func newCSRFManager(masterKey []byte) *CSRFManager {
return &CSRFManager{key: deriveCSRFKey(masterKey)}
}
// newCSRFManagerFromVault creates a CSRFManager that derives its key lazily
// from the vault's master key. When the vault is sealed, operations fail
// gracefully (the sealed middleware prevents reaching CSRF-protected routes).
func newCSRFManagerFromVault(v *vault.Vault) *CSRFManager {
c := &CSRFManager{vault: v}
// If already unsealed, derive immediately.
mk, err := v.MasterKey()
if err == nil {
c.key = deriveCSRFKey(mk)
}
return c
}
// deriveCSRFKey computes the HMAC key from a master key.
func deriveCSRFKey(masterKey []byte) []byte {
h := sha256.New()
h.Write([]byte("mcias-ui-csrf-v1"))
h.Write(masterKey)
return &CSRFManager{key: h.Sum(nil)}
return h.Sum(nil)
}
// csrfKey returns the current CSRF key, deriving it from vault if needed.
func (c *CSRFManager) csrfKey() ([]byte, error) {
c.mu.Lock()
defer c.mu.Unlock()
// If we have a vault, re-derive key when sealed state changes.
if c.vault != nil {
if c.vault.IsSealed() {
c.key = nil
return nil, fmt.Errorf("csrf: vault is sealed")
}
if c.key == nil {
mk, err := c.vault.MasterKey()
if err != nil {
return nil, fmt.Errorf("csrf: %w", err)
}
c.key = deriveCSRFKey(mk)
}
}
if c.key == nil {
return nil, fmt.Errorf("csrf: no key available")
}
return c.key, nil
}
// NewToken generates a fresh CSRF token pair.
@@ -40,12 +93,16 @@ func newCSRFManager(masterKey []byte) *CSRFManager {
// - cookieVal: hex(32 random bytes) — stored in the mcias_csrf cookie
// - headerVal: hex(HMAC-SHA256(key, cookieVal)) — embedded in forms / X-CSRF-Token header
func (c *CSRFManager) NewToken() (cookieVal, headerVal string, err error) {
key, err := c.csrfKey()
if err != nil {
return "", "", err
}
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
return "", "", fmt.Errorf("csrf: generate random bytes: %w", err)
}
cookieVal = hex.EncodeToString(raw)
mac := hmac.New(sha256.New, c.key)
mac := hmac.New(sha256.New, key)
mac.Write([]byte(cookieVal))
headerVal = hex.EncodeToString(mac.Sum(nil))
return cookieVal, headerVal, nil
@@ -57,7 +114,11 @@ func (c *CSRFManager) Validate(cookieVal, headerVal string) bool {
if cookieVal == "" || headerVal == "" {
return false
}
mac := hmac.New(sha256.New, c.key)
key, err := c.csrfKey()
if err != nil {
return false
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(cookieVal))
expected := hex.EncodeToString(mac.Sum(nil))
// Security: constant-time comparison prevents timing oracle attacks.

View File

@@ -460,7 +460,12 @@ func (u *UIServer) handleSetPGCreds(w http.ResponseWriter, r *http.Request) {
// Security: encrypt the password with AES-256-GCM before storage.
// A fresh random nonce is generated per call by SealAESGCM; nonce reuse
// is not possible. The plaintext password is not retained after this call.
enc, nonce, err := crypto.SealAESGCM(u.masterKey, []byte(password))
masterKey, err := u.vault.MasterKey()
if err != nil {
u.renderError(w, r, http.StatusInternalServerError, "internal error")
return
}
enc, nonce, err := crypto.SealAESGCM(masterKey, []byte(password))
if err != nil {
u.logger.Error("encrypt pg password", "error", err)
u.renderError(w, r, http.StatusInternalServerError, "internal error")
@@ -864,7 +869,12 @@ func (u *UIServer) handleCreatePGCreds(w http.ResponseWriter, r *http.Request) {
}
// Security: encrypt with AES-256-GCM; fresh nonce per call.
enc, nonce, err := crypto.SealAESGCM(u.masterKey, []byte(password))
masterKey, err := u.vault.MasterKey()
if err != nil {
u.renderError(w, r, http.StatusInternalServerError, "internal error")
return
}
enc, nonce, err := crypto.SealAESGCM(masterKey, []byte(password))
if err != nil {
u.logger.Error("encrypt pg password", "error", err)
u.renderError(w, r, http.StatusInternalServerError, "internal error")

View File

@@ -145,7 +145,12 @@ func (u *UIServer) handleTOTPStep(w http.ResponseWriter, r *http.Request) {
}
// Decrypt and validate TOTP secret.
secret, err := crypto.OpenAESGCM(u.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
masterKey, err := u.vault.MasterKey()
if err != nil {
u.render(w, "login", LoginData{Error: "internal error"})
return
}
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
if err != nil {
u.logger.Error("decrypt TOTP secret", "error", err, "account_id", acct.ID)
u.render(w, "login", LoginData{Error: "internal error"})
@@ -208,7 +213,12 @@ func (u *UIServer) finishLogin(w http.ResponseWriter, r *http.Request, acct *mod
// Login succeeded: clear any outstanding failure counter.
_ = u.db.ClearLoginFailures(acct.ID)
tokenStr, claims, err := token.IssueToken(u.privKey, u.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
privKey, err := u.vault.PrivKey()
if err != nil {
u.render(w, "login", LoginData{Error: "internal error"})
return
}
tokenStr, claims, err := token.IssueToken(privKey, u.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
if err != nil {
u.logger.Error("issue token", "error", err)
u.render(w, "login", LoginData{Error: "internal error"})
@@ -255,7 +265,8 @@ func (u *UIServer) finishLogin(w http.ResponseWriter, r *http.Request, acct *mod
func (u *UIServer) handleLogout(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(sessionCookieName)
if err == nil && cookie.Value != "" {
claims, err := validateSessionToken(u.pubKey, cookie.Value, u.cfg.Tokens.Issuer)
pubKey, _ := u.vault.PubKey()
claims, err := validateSessionToken(pubKey, cookie.Value, u.cfg.Tokens.Issuer)
if err == nil {
if revokeErr := u.db.RevokeToken(claims.JTI, "ui_logout"); revokeErr != nil {
u.logger.Warn("revoke token on UI logout", "error", revokeErr)

View File

@@ -0,0 +1,81 @@
// UI handlers for vault unseal page.
package ui
import (
"net/http"
"git.wntrmute.dev/kyle/mcias/internal/audit"
"git.wntrmute.dev/kyle/mcias/internal/middleware"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
// UnsealData is the view model for the unseal page.
type UnsealData struct {
Error string
}
// handleUnsealPage renders the unseal form, or redirects to login if already unsealed.
func (u *UIServer) handleUnsealPage(w http.ResponseWriter, r *http.Request) {
if !u.vault.IsSealed() {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
u.render(w, "unseal", UnsealData{})
}
// handleUnsealPost processes the unseal form submission.
//
// Security: The passphrase is never logged. No CSRF protection is applied
// because there is no session to protect (the vault is sealed), and CSRF
// token generation depends on the master key (chicken-and-egg).
func (u *UIServer) handleUnsealPost(w http.ResponseWriter, r *http.Request) {
if !u.vault.IsSealed() {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
if err := r.ParseForm(); err != nil {
u.render(w, "unseal", UnsealData{Error: "invalid form data"})
return
}
passphrase := r.FormValue("passphrase")
if passphrase == "" {
u.render(w, "unseal", UnsealData{Error: "passphrase is required"})
return
}
// Derive master key from passphrase.
masterKey, err := vault.DeriveFromPassphrase(passphrase, u.db)
if err != nil {
u.logger.Error("vault unseal (UI): derive key", "error", err)
u.render(w, "unseal", UnsealData{Error: "unseal failed"})
return
}
// Decrypt the signing key.
privKey, pubKey, err := vault.DecryptSigningKey(u.db, masterKey)
if err != nil {
// Zero derived master key on failure.
for i := range masterKey {
masterKey[i] = 0
}
u.logger.Error("vault unseal (UI): decrypt signing key", "error", err)
u.render(w, "unseal", UnsealData{Error: "unseal failed"})
return
}
if err := u.vault.Unseal(masterKey, privKey, pubKey); err != nil {
u.logger.Error("vault unseal (UI): state transition", "error", err)
http.Redirect(w, r, "/login", http.StatusFound)
return
}
ip := middleware.ClientIP(r, nil)
u.writeAudit(r, model.EventVaultUnsealed, nil, nil, audit.JSON("source", "ui", "ip", ip))
u.logger.Info("vault unsealed via UI", "ip", ip)
http.Redirect(w, r, "/login", http.StatusFound)
}

View File

@@ -2,6 +2,7 @@ package ui
import (
"crypto/ed25519"
"fmt"
"time"
"git.wntrmute.dev/kyle/mcias/internal/token"
@@ -16,5 +17,9 @@ func validateSessionToken(pubKey ed25519.PublicKey, tokenStr, issuer string) (*t
// issueToken is a convenience method for issuing a signed JWT.
func (u *UIServer) issueToken(subject string, roles []string, expiry time.Duration) (string, *token.Claims, error) {
return token.IssueToken(u.privKey, u.cfg.Tokens.Issuer, subject, roles, expiry)
privKey, err := u.vault.PrivKey()
if err != nil {
return "", nil, fmt.Errorf("vault sealed: %w", err)
}
return token.IssueToken(privKey, u.cfg.Tokens.Issuer, subject, roles, expiry)
}

View File

@@ -14,7 +14,6 @@ package ui
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
"encoding/json"
@@ -33,6 +32,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/middleware"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/vault"
"git.wntrmute.dev/kyle/mcias/web"
)
@@ -62,9 +62,7 @@ type UIServer struct {
cfg *config.Config
logger *slog.Logger
csrf *CSRFManager
pubKey ed25519.PublicKey
privKey ed25519.PrivateKey
masterKey []byte
vault *vault.Vault
}
// issueTOTPNonce creates a random single-use nonce for the TOTP step and
@@ -108,8 +106,12 @@ func (u *UIServer) dummyHash() string {
// New constructs a UIServer, parses all templates, and returns it.
// Returns an error if template parsing fails.
func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) (*UIServer, error) {
csrf := newCSRFManager(masterKey)
//
// The CSRFManager is created lazily from vault key material when the vault
// is unsealed. When sealed, CSRF operations fail, but the sealed middleware
// prevents reaching CSRF-protected routes (chicken-and-egg resolution).
func New(database *db.DB, cfg *config.Config, v *vault.Vault, logger *slog.Logger) (*UIServer, error) {
csrf := newCSRFManagerFromVault(v)
funcMap := template.FuncMap{
"formatTime": func(t time.Time) string {
@@ -212,6 +214,7 @@ func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed255
"policies": "templates/policies.html",
"pgcreds": "templates/pgcreds.html",
"profile": "templates/profile.html",
"unseal": "templates/unseal.html",
}
tmpls := make(map[string]*template.Template, len(pageFiles))
for name, file := range pageFiles {
@@ -226,14 +229,12 @@ func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed255
}
srv := &UIServer{
db: database,
cfg: cfg,
pubKey: pub,
privKey: priv,
masterKey: masterKey,
logger: logger,
csrf: csrf,
tmpls: tmpls,
db: database,
cfg: cfg,
vault: v,
logger: logger,
csrf: csrf,
tmpls: tmpls,
}
// Security (DEF-02): launch a background goroutine to evict expired TOTP
@@ -299,6 +300,11 @@ func (u *UIServer) Register(mux *http.ServeMux) {
}
loginRateLimit := middleware.RateLimit(10, 10, trustedProxy)
// Vault unseal routes (no session required, no CSRF — vault is sealed).
unsealRateLimit := middleware.RateLimit(3, 5, trustedProxy)
uiMux.HandleFunc("GET /unseal", u.handleUnsealPage)
uiMux.Handle("POST /unseal", unsealRateLimit(http.HandlerFunc(u.handleUnsealPost)))
// Auth routes (no session required).
uiMux.HandleFunc("GET /login", u.handleLoginPage)
uiMux.Handle("POST /login", loginRateLimit(http.HandlerFunc(u.handleLoginPost)))
@@ -365,7 +371,12 @@ func (u *UIServer) requireCookieAuth(next http.Handler) http.Handler {
return
}
claims, err := validateSessionToken(u.pubKey, cookie.Value, u.cfg.Tokens.Issuer)
pubKey, err := u.vault.PubKey()
if err != nil {
u.redirectToLogin(w, r)
return
}
claims, err := validateSessionToken(pubKey, cookie.Value, u.cfg.Tokens.Issuer)
if err != nil {
u.clearSessionCookie(w)
u.redirectToLogin(w, r)

View File

@@ -17,7 +17,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/config"
"git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
const testIssuer = "https://auth.example.com"
@@ -48,7 +48,8 @@ func newTestUIServer(t *testing.T) *UIServer {
cfg := config.NewTestConfig(testIssuer)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
uiSrv, err := New(database, cfg, priv, pub, masterKey, logger)
v := vault.NewUnsealed(masterKey, priv, pub)
uiSrv, err := New(database, cfg, v, logger)
if err != nil {
t.Fatalf("new UIServer: %v", err)
}
@@ -319,7 +320,7 @@ func issueAdminSession(t *testing.T, u *UIServer) (tokenStr, accountUUID string,
if err := u.db.SetRoles(acct.ID, []string{"admin"}, nil); err != nil {
t.Fatalf("SetRoles: %v", err)
}
tok, claims, err := token.IssueToken(u.privKey, testIssuer, acct.UUID, []string{"admin"}, time.Hour)
tok, claims, err := u.issueToken(acct.UUID, []string{"admin"}, time.Hour)
if err != nil {
t.Fatalf("IssueToken: %v", err)
}
@@ -645,7 +646,7 @@ func issueUserSession(t *testing.T, u *UIServer) string {
if err := u.db.SetRoles(acct.ID, []string{"user"}, nil); err != nil {
t.Fatalf("SetRoles: %v", err)
}
tok, claims, err := token.IssueToken(u.privKey, testIssuer, acct.UUID, []string{"user"}, time.Hour)
tok, claims, err := u.issueToken(acct.UUID, []string{"user"}, time.Hour)
if err != nil {
t.Fatalf("IssueToken: %v", err)
}

67
internal/vault/derive.go Normal file
View File

@@ -0,0 +1,67 @@
package vault
import (
"crypto/ed25519"
"errors"
"fmt"
"git.wntrmute.dev/kyle/mcias/internal/crypto"
"git.wntrmute.dev/kyle/mcias/internal/db"
)
// DeriveFromPassphrase derives the master encryption key from a passphrase
// using the Argon2id KDF with a salt stored in the database.
//
// Security: The Argon2id parameters used by crypto.DeriveKey exceed OWASP 2023
// minimums (time=3, memory=128MiB, threads=4). The salt is 32 random bytes
// stored in the database on first run.
func DeriveFromPassphrase(passphrase string, database *db.DB) ([]byte, error) {
salt, err := database.ReadMasterKeySalt()
if errors.Is(err, db.ErrNotFound) {
return nil, fmt.Errorf("no master key salt in database (first-run requires startup passphrase)")
}
if err != nil {
return nil, fmt.Errorf("read master key salt: %w", err)
}
key, err := crypto.DeriveKey(passphrase, salt)
if err != nil {
return nil, fmt.Errorf("derive master key: %w", err)
}
return key, nil
}
// DecryptSigningKey decrypts the Ed25519 signing key pair from the database
// using the provided master key.
//
// Security: The private key is stored AES-256-GCM encrypted in the database.
// A fresh random nonce is used for each encryption. The plaintext key only
// exists in memory during the process lifetime.
func DecryptSigningKey(database *db.DB, masterKey []byte) (ed25519.PrivateKey, ed25519.PublicKey, error) {
enc, nonce, err := database.ReadServerConfig()
if err != nil {
return nil, nil, fmt.Errorf("read server config: %w", err)
}
if enc == nil || nonce == nil {
return nil, nil, fmt.Errorf("no signing key in database (first-run requires startup passphrase)")
}
privPEM, err := crypto.OpenAESGCM(masterKey, nonce, enc)
if err != nil {
return nil, nil, fmt.Errorf("decrypt signing key: %w", err)
}
priv, err := crypto.ParsePrivateKeyPEM(privPEM)
if err != nil {
return nil, nil, fmt.Errorf("parse signing key PEM: %w", err)
}
// Security: ed25519.PrivateKey.Public() always returns ed25519.PublicKey,
// but we use the ok form to make the type assertion explicit and safe.
pub, ok := priv.Public().(ed25519.PublicKey)
if !ok {
return nil, nil, fmt.Errorf("signing key has unexpected public key type")
}
return priv, pub, nil
}

127
internal/vault/vault.go Normal file
View File

@@ -0,0 +1,127 @@
// Package vault provides a thread-safe container for the server's
// cryptographic key material with seal/unseal lifecycle management.
//
// Security design:
// - The Vault holds the master encryption key and Ed25519 signing key pair.
// - All accessors return ErrSealed when the vault is sealed, ensuring that
// callers cannot use key material that has been zeroed.
// - Seal() explicitly zeroes all key material before nilling the slices,
// reducing the window in which secrets remain in memory after seal.
// - All state transitions are protected by sync.RWMutex. Readers (IsSealed,
// MasterKey, PrivKey, PubKey) take a read lock; writers (Seal, Unseal)
// take a write lock.
package vault
import (
"crypto/ed25519"
"errors"
"sync"
)
// ErrSealed is returned by accessor methods when the vault is sealed.
var ErrSealed = errors.New("vault is sealed")
// Vault holds the server's cryptographic key material behind a mutex.
// All three servers (REST, UI, gRPC) share a single Vault by pointer.
type Vault struct {
mu sync.RWMutex
masterKey []byte
privKey ed25519.PrivateKey
pubKey ed25519.PublicKey
sealed bool
}
// NewSealed creates a Vault in the sealed state. No key material is held.
func NewSealed() *Vault {
return &Vault{sealed: true}
}
// NewUnsealed creates a Vault in the unsealed state with the given key material.
// This is the backward-compatible path used when the passphrase is available at
// startup.
func NewUnsealed(masterKey []byte, privKey ed25519.PrivateKey, pubKey ed25519.PublicKey) *Vault {
return &Vault{
masterKey: masterKey,
privKey: privKey,
pubKey: pubKey,
sealed: false,
}
}
// IsSealed reports whether the vault is currently sealed.
func (v *Vault) IsSealed() bool {
v.mu.RLock()
defer v.mu.RUnlock()
return v.sealed
}
// MasterKey returns the master encryption key, or ErrSealed if sealed.
func (v *Vault) MasterKey() ([]byte, error) {
v.mu.RLock()
defer v.mu.RUnlock()
if v.sealed {
return nil, ErrSealed
}
return v.masterKey, nil
}
// PrivKey returns the Ed25519 private signing key, or ErrSealed if sealed.
func (v *Vault) PrivKey() (ed25519.PrivateKey, error) {
v.mu.RLock()
defer v.mu.RUnlock()
if v.sealed {
return nil, ErrSealed
}
return v.privKey, nil
}
// PubKey returns the Ed25519 public key, or ErrSealed if sealed.
func (v *Vault) PubKey() (ed25519.PublicKey, error) {
v.mu.RLock()
defer v.mu.RUnlock()
if v.sealed {
return nil, ErrSealed
}
return v.pubKey, nil
}
// Unseal transitions the vault from sealed to unsealed, storing the provided
// key material. Returns an error if the vault is already unsealed.
func (v *Vault) Unseal(masterKey []byte, privKey ed25519.PrivateKey, pubKey ed25519.PublicKey) error {
v.mu.Lock()
defer v.mu.Unlock()
if !v.sealed {
return errors.New("vault is already unsealed")
}
v.masterKey = masterKey
v.privKey = privKey
v.pubKey = pubKey
v.sealed = false
return nil
}
// Seal transitions the vault from unsealed to sealed. All key material is
// zeroed before being released to minimize the window of memory exposure.
//
// Security: explicit zeroing loops ensure the key bytes are overwritten even
// if the garbage collector has not yet reclaimed the backing arrays.
func (v *Vault) Seal() {
v.mu.Lock()
defer v.mu.Unlock()
// Zero master key.
for i := range v.masterKey {
v.masterKey[i] = 0
}
v.masterKey = nil
// Zero private key.
for i := range v.privKey {
v.privKey[i] = 0
}
v.privKey = nil
// Zero public key (not secret, but consistent cleanup).
for i := range v.pubKey {
v.pubKey[i] = 0
}
v.pubKey = nil
v.sealed = true
}

View File

@@ -0,0 +1,149 @@
package vault
import (
"crypto/ed25519"
"crypto/rand"
"sync"
"testing"
)
func generateTestKeys(t *testing.T) ([]byte, ed25519.PrivateKey, ed25519.PublicKey) {
t.Helper()
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("generate key: %v", err)
}
mk := make([]byte, 32)
if _, err := rand.Read(mk); err != nil {
t.Fatalf("generate master key: %v", err)
}
return mk, priv, pub
}
func TestNewSealed(t *testing.T) {
v := NewSealed()
if !v.IsSealed() {
t.Fatal("NewSealed() should be sealed")
}
if _, err := v.MasterKey(); err != ErrSealed {
t.Fatalf("MasterKey() error = %v, want ErrSealed", err)
}
if _, err := v.PrivKey(); err != ErrSealed {
t.Fatalf("PrivKey() error = %v, want ErrSealed", err)
}
if _, err := v.PubKey(); err != ErrSealed {
t.Fatalf("PubKey() error = %v, want ErrSealed", err)
}
}
func TestNewUnsealed(t *testing.T) {
mk, priv, pub := generateTestKeys(t)
v := NewUnsealed(mk, priv, pub)
if v.IsSealed() {
t.Fatal("NewUnsealed() should not be sealed")
}
gotMK, err := v.MasterKey()
if err != nil {
t.Fatalf("MasterKey() error = %v", err)
}
if len(gotMK) != 32 {
t.Fatalf("MasterKey() len = %d, want 32", len(gotMK))
}
}
func TestUnsealFromSealed(t *testing.T) {
mk, priv, pub := generateTestKeys(t)
v := NewSealed()
if err := v.Unseal(mk, priv, pub); err != nil {
t.Fatalf("Unseal() error = %v", err)
}
if v.IsSealed() {
t.Fatal("should be unsealed after Unseal()")
}
gotPriv, err := v.PrivKey()
if err != nil {
t.Fatalf("PrivKey() error = %v", err)
}
if !priv.Equal(gotPriv) {
t.Fatal("PrivKey() mismatch")
}
}
func TestUnsealAlreadyUnsealed(t *testing.T) {
mk, priv, pub := generateTestKeys(t)
v := NewUnsealed(mk, priv, pub)
if err := v.Unseal(mk, priv, pub); err == nil {
t.Fatal("Unseal() on unsealed vault should return error")
}
}
func TestSealZeroesKeys(t *testing.T) {
mk, priv, pub := generateTestKeys(t)
// Keep references to the backing arrays so we can verify zeroing.
mkRef := mk
privRef := priv
v := NewUnsealed(mk, priv, pub)
v.Seal()
if !v.IsSealed() {
t.Fatal("should be sealed after Seal()")
}
// Verify the original backing arrays were zeroed.
for i, b := range mkRef {
if b != 0 {
t.Fatalf("masterKey[%d] = %d, want 0", i, b)
}
}
for i, b := range privRef {
if b != 0 {
t.Fatalf("privKey[%d] = %d, want 0", i, b)
}
}
}
func TestSealUnsealCycle(t *testing.T) {
mk, priv, pub := generateTestKeys(t)
v := NewUnsealed(mk, priv, pub)
v.Seal()
mk2, priv2, pub2 := generateTestKeys(t)
if err := v.Unseal(mk2, priv2, pub2); err != nil {
t.Fatalf("Unseal() after Seal() error = %v", err)
}
gotPub, err := v.PubKey()
if err != nil {
t.Fatalf("PubKey() error = %v", err)
}
if !pub2.Equal(gotPub) {
t.Fatal("PubKey() mismatch after re-unseal")
}
}
func TestConcurrentAccess(t *testing.T) {
mk, priv, pub := generateTestKeys(t)
v := NewUnsealed(mk, priv, pub)
var wg sync.WaitGroup
// Concurrent readers.
for range 50 {
wg.Add(1)
go func() {
defer wg.Done()
_ = v.IsSealed()
_, _ = v.MasterKey()
_, _ = v.PrivKey()
_, _ = v.PubKey()
}()
}
// Concurrent seal/unseal cycles.
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
v.Seal()
mk2, priv2, pub2 := generateTestKeys(t)
_ = v.Unseal(mk2, priv2, pub2)
}()
}
wg.Wait()
}

View File

@@ -307,6 +307,18 @@ components:
error: rate limit exceeded
code: rate_limited
VaultSealed:
description: |
The vault is sealed. The server is running but has no key material.
Unseal via `POST /v1/vault/unseal` before retrying.
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
example:
error: vault is sealed
code: vault_sealed
paths:
# ── Public ────────────────────────────────────────────────────────────────
@@ -314,12 +326,17 @@ paths:
/v1/health:
get:
summary: Health check
description: Returns `{"status":"ok"}` if the server is running. No auth required.
description: |
Returns server health status. Always returns HTTP 200, even when the
vault is sealed. No auth required.
When the vault is sealed, `status` is `"sealed"` and most other
endpoints return 503. When healthy, `status` is `"ok"`.
operationId: getHealth
tags: [Public]
responses:
"200":
description: Server is healthy.
description: Server is running (check `status` for sealed state).
content:
application/json:
schema:
@@ -327,6 +344,7 @@ paths:
properties:
status:
type: string
enum: [ok, sealed]
example: ok
/v1/keys/public:
@@ -369,6 +387,121 @@ paths:
description: Base64url-encoded public key bytes.
example: 11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo
/v1/vault/status:
get:
summary: Vault seal status
description: |
Returns whether the vault is currently sealed. Always accessible,
even when sealed. No auth required.
Clients should poll this after startup or after a 503 `vault_sealed`
response to determine when to attempt an unseal.
operationId: getVaultStatus
tags: [Public]
responses:
"200":
description: Current vault seal state.
content:
application/json:
schema:
type: object
required: [sealed]
properties:
sealed:
type: boolean
example: false
/v1/vault/unseal:
post:
summary: Unseal the vault
description: |
Provide the master passphrase to derive the encryption key, decrypt
the Ed25519 signing key, and unseal the vault. Once unsealed, all
other endpoints become available.
Rate limited to 3 requests per second per IP (burst 5) to limit
brute-force attempts against the passphrase.
The passphrase is never logged. A generic `"unseal failed"` error
is returned for any failure (wrong passphrase, vault already unsealed
mid-flight, etc.) to avoid leaking information.
operationId: unsealVault
tags: [Public]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [passphrase]
properties:
passphrase:
type: string
description: Master passphrase used to derive the encryption key.
example: correct-horse-battery-staple
responses:
"200":
description: Vault unsealed (or was already unsealed).
content:
application/json:
schema:
type: object
properties:
status:
type: string
enum: [unsealed, already unsealed]
example: unsealed
"400":
$ref: "#/components/responses/BadRequest"
"401":
description: Wrong passphrase or key decryption failure.
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
example:
error: unseal failed
code: unauthorized
"429":
$ref: "#/components/responses/RateLimited"
/v1/vault/seal:
post:
summary: Seal the vault (admin)
description: |
Zero all key material in memory and transition the server to the
sealed state. After this call:
- All subsequent requests (except health, vault status, and unseal)
return 503 `vault_sealed`.
- The caller's own JWT is immediately invalidated because the public
key needed to verify it is no longer held in memory.
- The server can be unsealed again via `POST /v1/vault/unseal`.
This is an emergency operation. Use it to protect key material if a
compromise is suspected. It does **not** restart the server or wipe
the database.
operationId: sealVault
tags: [Admin — Vault]
security:
- bearerAuth: []
responses:
"200":
description: Vault sealed (or was already sealed).
content:
application/json:
schema:
type: object
properties:
status:
type: string
enum: [sealed, already sealed]
example: sealed
"401":
$ref: "#/components/responses/Unauthorized"
"403":
$ref: "#/components/responses/Forbidden"
/v1/auth/login:
post:
summary: Login
@@ -1148,7 +1281,7 @@ paths:
`pgcred_accessed`, `pgcred_updated`, `pgcred_access_granted`,
`pgcred_access_revoked`, `tag_added`, `tag_removed`,
`policy_rule_created`, `policy_rule_updated`, `policy_rule_deleted`,
`policy_deny`.
`policy_deny`, `vault_sealed`, `vault_unsealed`.
operationId: listAudit
tags: [Admin — Audit]
security:
@@ -1530,3 +1663,5 @@ tags:
description: Requires admin role.
- name: Admin — Policy
description: Requires admin role. Manage policy rules and account tags.
- name: Admin — Vault
description: Requires admin role. Emergency vault seal operation.

View File

@@ -36,6 +36,7 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/internal/server"
"git.wntrmute.dev/kyle/mcias/internal/token"
"git.wntrmute.dev/kyle/mcias/internal/vault"
)
const e2eIssuer = "https://auth.e2e.test"
@@ -73,7 +74,8 @@ func newTestEnv(t *testing.T) *testEnv {
cfg := config.NewTestConfig(e2eIssuer)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := server.New(database, cfg, priv, pub, masterKey, logger)
v := vault.NewUnsealed(masterKey, priv, pub)
srv := server.New(database, cfg, v, logger)
ts := httptest.NewServer(srv.Handler())
t.Cleanup(func() {
@@ -225,9 +227,11 @@ func TestE2ETokenRenewal(t *testing.T) {
e := newTestEnv(t)
acct := e.createAccount(t, "bob")
// Issue a short-lived token (2s) directly so we can wait past the 50%
// Issue a short-lived token (10s) directly so we can wait past the 50%
// renewal threshold (SEC-03) without blocking the test for minutes.
oldToken, claims, err := token.IssueToken(e.privKey, e2eIssuer, acct.UUID, nil, 2*time.Second)
// 10s gives ample headroom: we sleep 6s (>50%), leaving 4s for the HTTP
// round-trip before expiry — eliminating the race that plagued the 2s token.
oldToken, claims, err := token.IssueToken(e.privKey, e2eIssuer, acct.UUID, nil, 10*time.Second)
if err != nil {
t.Fatalf("IssueToken: %v", err)
}
@@ -235,8 +239,8 @@ func TestE2ETokenRenewal(t *testing.T) {
t.Fatalf("TrackToken: %v", err)
}
// Wait for >50% of the 2s lifetime to elapse.
time.Sleep(1100 * time.Millisecond)
// Wait for >50% of the 10s lifetime to elapse.
time.Sleep(6 * time.Second)
// Renew.
resp2 := e.do(t, "POST", "/v1/auth/renew", nil, oldToken)

View File

@@ -199,12 +199,15 @@ paths:
/v1/health:
get:
summary: Health check
description: Returns `{"status":"ok"}` if the server is running. No auth required.
description: |
Returns `{"status":"ok"}` if the server is running and the vault is
unsealed, or `{"status":"sealed"}` if the vault is sealed.
No auth required.
operationId: getHealth
tags: [Public]
responses:
"200":
description: Server is healthy.
description: Server is healthy (may be sealed).
content:
application/json:
schema:
@@ -212,8 +215,87 @@ paths:
properties:
status:
type: string
enum: [ok, sealed]
example: ok
/v1/vault/status:
get:
summary: Vault seal status
description: Returns `{"sealed": true}` or `{"sealed": false}`. No auth required.
operationId: getVaultStatus
tags: [Vault]
responses:
"200":
description: Current seal state.
content:
application/json:
schema:
type: object
properties:
sealed:
type: boolean
/v1/vault/unseal:
post:
summary: Unseal the vault
description: |
Accepts a passphrase, derives the master key, and unseals the vault.
Rate-limited to 3 requests per second, burst of 5.
No auth required (the vault is sealed, so no tokens can be validated).
operationId: unsealVault
tags: [Vault]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [passphrase]
properties:
passphrase:
type: string
description: Master passphrase for key derivation.
responses:
"200":
description: Vault unsealed successfully.
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: unsealed
"401":
description: Unseal failed (wrong passphrase).
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/v1/vault/seal:
post:
summary: Seal the vault
description: |
Seals the vault, zeroing all key material in memory.
Requires admin authentication. The caller's token becomes invalid
after sealing.
operationId: sealVault
tags: [Vault]
security:
- bearerAuth: []
responses:
"200":
description: Vault sealed successfully.
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: sealed
/v1/keys/public:
get:
summary: Ed25519 public key (JWK)

31
web/templates/unseal.html Normal file
View File

@@ -0,0 +1,31 @@
{{define "unseal"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Unseal Vault — MCIAS</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="login-wrapper">
<div class="login-box">
<div class="brand-heading">MCIAS</div>
<div class="brand-subtitle">Vault is Sealed</div>
<div class="card">
{{if .Error}}<div class="alert alert-error" role="alert">{{.Error}}</div>{{end}}
<form id="unseal-form" method="POST" action="/unseal">
<div class="form-group">
<label for="passphrase">Master Passphrase</label>
<input class="form-control" type="password" id="passphrase" name="passphrase"
autocomplete="off" required autofocus>
</div>
<div class="form-actions">
<button class="btn btn-primary" type="submit" style="width:100%">Unseal</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
{{end}}