Security Architecture
Security Architecture¶
Huitzo prioritizes the "Security Nightmare" of third-party code execution through a multi-stage isolation strategy and comprehensive security model.
Authentication¶
JWT Access Tokens¶
All authenticated API requests use short-lived JWT access tokens:
- Algorithm: HS256 (symmetric, configurable via
HUITZO_JWT_ALGORITHM) - Lifetime: 30 minutes by default (
access_token_expire_minutes, configurable viaHUITZO_ACCESS_TOKEN_EXPIRE_MINUTES). Tokens minted for theadminandownerroles are deliberately shorter-lived — a fixed 15 minutes (ADMIN_TOKEN_TTL_SECONDSinapps/backend/src/backend/auth/jwt.py), not configurable, so a privileged credential ages out faster than a member's. - Signed with:
HUITZO_JWT_SECRET_KEY(must be cryptographically random in production)
JWT Payload:
{
"sub": "<user_id>",
"tenant_id": "<tenant_id>",
"role": "member|admin|owner",
"sid": "<sessions.id>",
"iat": 1707999100,
"exp": 1708000000,
"type": "access"
}
The core identity carries no tier (saas-extension-contract §3.5 — the core has no tier concept; D-024 CR27 dropped the legacy tenant tier column and the personal membership tier, ADR-041 C7). The SaaS-contributed rate-limit middleware resolves the acting tenant's plan itself per request (no plan row is payg). A plan change therefore takes effect on the next request (after the plan cache re-prime) — not on the next token refresh. See Rate Limiting below.
Session-bound access tokens¶
Every access token names the sessions row that issued it in its sid claim.
Login, registration, first-boot setup, refresh, refresh-cookie, tenant switch
and POST /auth/reauth all mint through the one membership gate
(auth/mint_gate.py), and
each passes the session it created or rotated. A token without a sid claim is
not a valid access token.
A valid signature is not enough. On every JWT-authenticated request the auth
middleware also checks, in one indexed lookup on the auth_bootstrap plane
(auth/session_binding.py),
that:
| Check | Fails when |
|---|---|
the sid session exists and expires_at is in the future |
logout, logout-all, password change or reset, admin session revoke, membership removal, user or tenant deletion, refresh-chain expiry |
the session belongs to the token's sub and its acting tenant is the token's tenant_id |
a token is replayed against another user's or another tenant's session |
| the user is active, and both the user's home tenant and the acting tenant are active | deactivation of the user or of either tenant |
Any failure is 401 (Invalid or expired token). A database error during
the check is 503: the check fails closed, it never admits a token it could
not verify.
Cache bound. Each backend process keeps successful checks in memory for at
most 15 seconds (at most 10,000 entries, least recently used evicted
first). Failed checks are never cached. Deleting a session or deactivating a
user or tenant therefore ends every access token tied to it within 15 seconds,
on every process, without any write-through step. Every endpoint that deletes
sessions (logout, tenant switch, /auth/reauth, password change or reset,
admin revoke, deactivation, user, account or tenant deletion, membership
removal) also drops the matching entries in the process that served it, so
that process refuses at once.
What this closes. A token signed with the key but not issued by a login has no live session behind it and is refused. Deleting a user's sessions ends their access tokens too; they no longer live out their remaining TTL.
API keys are unchanged. An sk-huitzo- key is not a JWT and carries no
session: it is checked against api_keys on every request (revoked keys and
inactive owners are refused, see API Keys).
Step-up uses the session's last authentication¶
require_recent_auth (in
auth/dependencies.py)
compares sessions.reauth_at, not the token's iat, with its window
(default 900 s). reauth_at is the last time the caller proved their password
on that session:
| Action | reauth_at |
|---|---|
| Login, registration, first-boot setup | set to now on the new session |
POST /auth/reauth (password checked) |
set to now on the token's sid session |
POST /auth/refresh, /auth/refresh-cookie, /auth/switch-tenant |
carried forward unchanged |
A token with a fresh iat therefore does not pass a step-up route when its
session last saw a password more than the window ago. The read is uncached so a
re-auth on one process is honoured by every process at once. API-key callers
have no session and are always refused with admin_reauth_required. The
dashboard's re-auth modal reacts to the same error code, so the client contract
is unchanged.
Refresh Tokens¶
Refresh tokens are opaque random strings (two concatenated UUID4 hex values). They are:
- Stored server-side: Hashed with HMAC-SHA256 in the
sessionstable - Lifetime: 7 days
- Single-use, with grace window: Each refresh generates a new refresh token (rotation). The just-rotated prior hash is retained in
sessions.previous_token_hashfor a short grace window (see Refresh Rotation Grace Window) so concurrent refresh calls from two tabs or a network retry do not log the user out. - Revocable: Logout invalidates the session, its refresh token and, within the session-check cache bound, every access token minted on it
- Last authentication:
sessions.reauth_atrecords when the password was last checked on the session (Step-up)
Refresh Rotation Grace Window¶
The /api/v1/auth/refresh (CLI/SDK) and /api/v1/auth/refresh-cookie
(dashboard) endpoints rotate the refresh token on every call. Pure
single-use rotation is destructive: any second caller still presenting
the prior cookie value — a second browser tab, a near-simultaneous
visibility-triggered refresh in the same tab, a transport-level retry of
the first call — sees its hash unmatched and is logged out. Issue #569
caught this regression of the proactive-refresh fix from #538.
The fix is a short server-side grace window. The sessions row tracks
two hashes, not one:
| Column | Meaning |
|---|---|
refresh_token_hash |
The currently issued refresh-token hash. Always populated. |
previous_token_hash |
The hash of the prior refresh token, the one this rotation just superseded. Nullable; populated by a rotation, cleared when the grace window elapses or on logout. |
previous_token_expires_at |
Wall-clock end of the grace window for previous_token_hash. Nullable. Set to now() + 30s on rotation. |
Lookup precedence on every refresh request:
- Match against
refresh_token_hash(the normal path). On match: rotate normally — move the matched hash intoprevious_token_hash, generate a new token and store its hash inrefresh_token_hash, setprevious_token_expires_at = now() + grace. - Otherwise, match against
previous_token_hashonly whenprevious_token_expires_at > now()(the replay path). On match: rotate the current value as if it had been the matched one — save the currentrefresh_token_hashas the newprevious_token_hash, generate a new token, and set a fresh grace window. The replayer ends up with a unique current cookie value. - Otherwise, 401 + clear the
huitzo_refreshcookie.
The replay path's "save current as the new previous" rule (not "keep
the old previous") preserves the token held by the tab that performed
the first rotation. Both tabs converge: each concurrent request that
took the grace path produces its own current cookie, the browser's
shared cookie jar applies the last Set-Cookie to land, and the most
recent server-side previous_token_hash continues to cover the
remaining tab until that tab's next refresh. This bounds the steady
state to at most one extra rotation per concurrent refresh burst — no
cascading logouts, no unbounded ping-pong.
The grace window is not a security relaxation: the prior hash is honoured only inside a 30-second wall-clock window, on a server-side column that is wiped on logout and on any rotation older than the window. It does not extend refresh-token lifetime, does not change the 7-day cap, and does not allow a previously revoked token to come back to life (logout truncates the row).
Implementation: apps/backend/src/backend/api/v1/auth.py::refresh_from_cookie
and apps/backend/src/backend/api/v1/auth.py::refresh share the same
lookup precedence. Migration 030_session_refresh_grace_window adds
the two columns.
Logout Session Boundary¶
Logout is a hard session boundary: when a user signs out, no state from their session may remain visible to the next user in the same browser tab. This is enforced on both the server and the client.
| Layer | What logout clears |
|---|---|
| Server | The refresh-token row in sessions (revoked); access tokens minted on it fail the session check within 15 s |
| Client — in-memory (auth) | API client access token; useAuthStore user / session slice |
| Client — in-memory (data) | All seven data-store slices (dashboards, monitor, devSessions, integrations, integrationsRegistry, terminal, walletStatus) plus the two panel-preference stores (monitorPanel, terminalPopup) reset to their initial state |
| Client — TanStack Query | The module-level QueryClient cache is cleared, cancelling in-flight queries and dropping every cached response |
| Client — localStorage | All keys under the huitzo: namespace are removed, plus the two persist-middleware keys (huitzo-monitor-panel, huitzo-terminal-popup) that live outside that namespace |
| Navigation | Hard navigation to a same-origin path (default /login) — soft navigation cannot unmount module-scope singletons or in-flight fetches |
The huitzo-theme localStorage key is treated as user-agent preference (not
session state) and survives logout. Pack-secret values are server-side only
and are never written to the client; they need no client-side clear.
The redirectTo option is constrained to same-origin paths (must start
with a single / and reject protocol-relative //, backslash quirks, and
absolute URLs). This blocks CWE-601 open-redirect at the contract layer so
no caller can accidentally turn logout into a phishing vector.
Anti-pattern: clearing only the auth store's slice and relying on React
Router for navigation. Soft navigation does not unmount component trees that
hold cached data, and module-scope singletons (the QueryClient) survive
re-renders. This is the failure mode that necessitates the table above.
Implementation: apps/dashboard/src/stores/session.ts::clearAllUserState
(invoked from useAuthStore.logout()).
Client-Side Token Refresh¶
The dashboard combines reactive and proactive refresh so a long-idle
tab does not bounce the user to /login on the next click.
| Trigger | When it fires | Outcome |
|---|---|---|
| Reactive | Inside request() if the in-memory token is within 30s of expiry |
Awaits a refresh before sending the request |
| Proactive timer | After every successful refresh or login, schedules a setTimeout for (expiresAt − now − 2min) |
Rotates the token silently before any user-triggered request needs it |
| Tab refocus | visibilitychange listener (attached on login) when the tab becomes visible AND the token is within 2 min of expiry |
Refreshes immediately, covering background-tab timer throttling |
| Cross-tab adopt | Sibling tab broadcasts a freshly minted token on the huitzo-auth BroadcastChannel |
Receiving tab adopts the token into memory and re-arms its timer without any network call |
| Logout | useAuthStore.logout() |
Cancels the proactive timer and detaches the visibility listener via cancelRefreshTimer(). The listener re-attaches on the next successful login. |
The 2-minute pre-expiry window absorbs network jitter without consuming
refresh tokens too aggressively. Concurrent refresh requests within a
single tab dedupe via the refreshPromise field on the API client; the
proactive timer therefore safely overlaps with reactive flushes inside
one tab.
Across tabs, the in-tab refreshPromise cannot serialize — two
tabs of the same origin share a cookie jar but not a JS heap. Because
every refresh rotates the shared huitzo_refresh cookie, N tabs
each firing their own refresh concurrently race: one wins, the losers
present a superseded token past the ~30s grace and 401 →
clearTokens() → /login. Opening a second tab was the most
reproducible trigger, since a fresh tab boots with accessToken ===
null and immediately hydrates via /auth/refresh-cookie.
The client therefore coordinates refresh across the whole origin using
two platform APIs (both feature-detected; absence degrades gracefully
to the per-tab refreshPromise behavior above):
- Web Locks API —
doRefreshTokenruns insidenavigator.locks.request("huitzo-refresh", { mode: "exclusive" }, …), so at most one tab rotates the cookie at a time. Inside the lock the tab re-checks whether it already holds a fresh, non-expired token (adopted from a sibling, below) and skips the network call if so. In the common case this means only one tab performs the rotation and the rest adopt its broadcast; the lock's essential guarantee, though, is that any rotations are serialized rather than concurrent — the dangerous race is parallel rotation, which the lock eliminates outright (see the grace-window note below for the residual serialized case). - BroadcastChannel (
huitzo-auth) — on a successful refresh or login the tab posts{ type: "token", accessToken, expiresAt }. Sibling tabs adopt it into their in-memory token and re-arm their proactive timer without a network call. A{ type: "logout" }message is posted only from the explicitlogout()path so a user logout in one tab tears down the others; an incidental refresh 401 never broadcasts logout (a sibling may still hold a valid token).
To stop an in-flight refresh from silently resurrecting a session that
was just torn down, the client keeps a monotonic session epoch
bumped on every logout (local or an adopted remote-logout broadcast).
doRefreshToken captures the epoch before it starts and discards its
result — no token stored, no token broadcast — if the epoch changed
while the request was in flight. The BroadcastChannel is also re-opened
on pageshow after a back/forward-cache restore so a restored tab keeps
hearing token/logout broadcasts.
Because both navigator.locks queue-release and BroadcastChannel
delivery are asynchronous, a second tab can occasionally acquire the
lock before it has processed a sibling's just-posted token message and
perform its own (serialized) rotation. The
refresh rotation grace window is the
backstop for that residual serialized-rotation case and for the
harder-to-test transport-retry case (browser extensions, devtools,
mid-flight visibility events) where the lock/broadcast optimization may
not apply.
Failure handling. A failed proactive refresh logs a console.warn
for support correlation, then returns silently. The access token has
already been cleared (by doRefreshToken's !response.ok branch), but
the HttpOnly refresh cookie is unaffected. The next user-triggered
request therefore goes through the reactive path, which retries the
refresh — succeeding silently on a transient blip, or falling through
to clearTokens() → /login on a persistent failure. A single network
hiccup at the proactive trigger point costs one extra refresh attempt,
not an immediate redirect.
Session lifetime on open tabs. Because each refresh rotates the refresh token (resetting the 7-day server-side clock), a tab left open in the foreground keeps the proactive timer running indefinitely and the session never expires from inactivity. Operators relying on a hard idle timeout must enforce it server-side — for example via a scheduled job that invalidates sessions older than N days regardless of recent rotation, or by adding an absolute-age claim to the refresh-token row. Relying on the client-side rotation chain to terminate is not sufficient. A closed laptop remains bounded by the 7-day refresh-cookie lifetime because no JS context exists to fire the proactive timer.
Implementation: apps/dashboard/src/lib/api.ts::scheduleProactiveRefresh,
cancelRefreshTimer, refreshOnVisibilityIfNearExpiry, and the lazy
attach/detach pair attachVisibilityListener /
detachVisibilityListener. The listener is attached on first successful
setAccessToken and detached by cancelRefreshTimer; it re-attaches on
the next login. Cross-tab coordination lives in
apps/dashboard/src/lib/cross-tab-auth.ts (runExclusive,
createAuthChannel, feature detection) and is wired into
doRefreshToken (the exclusive lock, in-lock re-check, and session-epoch
abort guard), setAccessToken (token broadcast), logout (epoch bump +
logout broadcast), and the attachAuthChannel /
registerChannelLifecycleListeners / handleAuthBroadcast trio on the
API client.
Bundle Auth Backstop¶
Embedded dashboard bundles do not use the Hub's ApiClient. They talk to the API
through @huitzo/dashboard-sdk, whose transport calls globalThis.fetch
directly. Bundles published against dashboard-sdk < 0.5.0 snapshot
context.token once at mount, so when the Hub rotates the access token (every
~13-28 minutes, without re-mounting the bundle) the bundle keeps presenting a
credential the server has already expired, and its requests start returning
401 Invalid or expired token.
The bundle auth backstop is a same-origin fetch wrapper installed by the
Hub shell that repairs those requests. It is a compatibility layer for bundles
already in the wild; the durable fix is the SDK's per-request token accessor
(see Token lifetime contract).
Scope — the backstop touches a request only when every condition holds:
| Condition | Reason |
|---|---|
Resolved URL origin equals window.location.origin |
Never leak a Hub credential to a third-party host |
Pathname starts with /api/v1/ |
Only Hub API traffic |
Pathname does not start with /api/v1/auth/ |
Auth endpoints own their own credential semantics; the backstop must never interfere with login, refresh, or logout |
An Authorization header is already present and is Bearer <three-segment JWT> |
The backstop repairs a credential, it never adds one |
Everything else — cross-origin requests, non-API paths, requests with no
Authorization header, API keys (sk-huitzo-…), non-Bearer schemes — passes
through to the original fetch untouched.
Pre-flight repair. Before dispatch, the backstop compares the request's
bearer JWT against the Hub's current in-memory access token. It substitutes the
Hub's token only when both decode to the same sub (user id) claim and the
two strings differ. A different sub, or a sub that cannot be decoded from
either side, leaves the request untouched — the backstop repairs staleness, it
never re-points a request at a different identity.
401 replay (at most once). If an in-scope request comes back 401, the
backstop inspects a clone of the body:
detail.error === "admin_reauth_required"→ the original response is returned unchanged. That is a step-up challenge, not an expiry, and it belongs to the shell's re-auth modal.- Otherwise it awaits
ApiClient.refreshAccessToken()— the same single-flight promise the Hub's own requests use, so N concurrent 401s from a polling dashboard collapse into one cookie rotation — and replays the request once with the fresh token. The replay's response is returned whatever its status. - If the refresh fails for any reason, the original 401 is returned unchanged.
Replay requires a replayable body. A string/URL input is replayable when
init.body is absent or a string; a Request input is replayed from a clone
taken before dispatch. A streaming or already-consumed body (ReadableStream,
FormData, Blob, bodyUsed === true) is not replayed — the original 401 is
returned.
What the backstop never does. It never calls clearTokens(), never
navigates (window.location), never posts a logout broadcast, never retries more
than once, and never logs a token. A persistently failing bundle request
surfaces as a plain 401 to the bundle; session teardown stays the exclusive
responsibility of the Hub's own request path.
Install order. apps/dashboard/src/main.tsx installs the backstop before
installRateLimitResponseObserver(), so the rate-limit observer wraps the
backstop and therefore observes the final (possibly replayed) response rather
than the intermediate 401. Both are installed at module scope, before any React
render, because an SDK client captures globalThis.fetch when the bundle mounts.
Relation to _withAuthRetry. ApiClient._withAuthRetry is the Hub's own
in-client 401 recovery: it knows the request's shape, can raise the admin step-up
challenge, and falls through to clearTokens() → /login on a dead session. The
backstop is strictly narrower in what it may do — no step-up, no session
teardown — but not in what it sees: ApiClient calls the global fetch
against the same-origin /api/v1 base, so Hub requests traverse the backstop
too. For them the pre-flight comparison is a no-op (they already carry the
current token), and a server-side expiry 401 is repaired by the backstop
first: it refreshes through the shared single-flight promise and replays, so
_withAuthRetry usually receives the successful replay and its own reactive
branch does not run. admin_reauth_required 401s pass through the backstop
untouched and still reach the step-up challenge. When the refresh fails, the
backstop returns the original 401 and _withAuthRetry makes its own (second)
refresh attempt before routing to /login — one redundant refresh call on an
already-dead session, deliberately accepted so _withAuthRetry keeps sole
ownership of teardown.
Implementation: apps/dashboard/src/lib/bundle-auth-backstop.ts, with the JWT
helpers in apps/dashboard/src/lib/jwt-claims.ts.
Password Hashing¶
User passwords are hashed with bcrypt using automatically generated salts. The bcrypt work factor uses the library default (currently 12 rounds).
Canonical Email Identity¶
users.email is the login identity. An address that reaches the database in
two different cases becomes two different identities with two different password
hashes — a login, a password change, or a reset keyed on one case then silently
misses the other row. That is the failure mode behind
#1187 ("my password stopped
working") and #1189 (a reset
that enqueued nothing and logged nothing).
Pydantic's EmailStr is not sufficient on its own: it lowercases only the
domain, so [email protected] validates and arrives as
[email protected] — still non-canonical in the local part.
The invariant, in four layers:
| Layer | Guarantee | Where |
|---|---|---|
| One canonicalizer | Exactly one function defines "canonical" — strip() then lower(). Every request model carrying a user identity annotates its field with the shared NormalizedEmail type; no endpoint re-implements it. |
core/validators.py |
| Shape guard | CHECK (email = lower(email) AND email !~ '\s') (ck_users_email_canonical), added validated — reaching that revision proves every existing row is canonical, and a future non-normalizing writer fails loudly at INSERT instead of quietly minting a shadow identity. |
migration 0016 |
| Exact lookup | Because the column is canonical by database invariant, every users lookup is a plain email = :canonical_value. That IS the case-insensitive lookup — and unlike lower(email) = … it is index-backed under RLS (see below). |
api/v1/auth.py, api/v1/organizations.py, manage.py, auth/staff_bootstrap.py |
| Collision guard | Functional unique index uq_users_email_lower on lower(email) — two case-variant registrations can never both land, including on a database that predates the CHECK. Belt-and-braces only; it does not back the lookups. |
migration 0003, re-asserted by 0016 |
# pseudocode — the identity boundary
request body -> NormalizedEmail (strip + lower) # one canonicalizer
-> users.email = :value # exact match on a canonical column
-> INSERT users(email=:value) # CHECK + UNIQUE(lower) enforce
Why the lookups are not lower(email) = …¶
A case-insensitive lookup written as lower(users.email) = :value is the
obvious shape, and it is the wrong one here — on the production security
posture it silently degrades to a sequential scan.
PostgreSQL will only use a clause as an index qual when the clause is
LEAKPROOF or sits at the relation's minimum security level
(restriction_is_securely_promotable). users carries FORCE ROW LEVEL
SECURITY and both huitzo_app and huitzo_auth are NOBYPASSRLS, so the RLS
policy predicate occupies security level 0 and the application's WHERE clause
is pushed to level 1. pg_proc.proleakproof is false for lower(text) and
true for texteq, so:
| Clause | Role | Plan |
|---|---|---|
lower(email) = :v |
table owner / superuser (CI, staging) | Index Scan using uq_users_email_lower |
lower(email) = :v |
NOBYPASSRLS app role (production) |
Seq Scan, RLS predicate re-evaluated per row — including the member_visible_users correlated subplan |
email = :v |
NOBYPASSRLS app role |
Index Scan using users_email_key, RLS predicate applied as a filter to the single matched row |
This is the staging-superuser blind spot
again: migrations and integration tests connect as a superuser, RLS is bypassed,
and EXPLAIN there shows the index scan you expected. Only production gets the
seq scan — on POST /auth/login and POST /auth/forgot-password, which are
unauthenticated.
Since the CHECK makes canonicality a database invariant, email = :canonical
and lower(email) = :canonical select exactly the same rows, so the exact form
is chosen everywhere. coupons.bound_email carries the same canonical CHECK
(ck_coupons_bound_email_canonical), so a coupon binding compares exactly too.
The two invite tables that lacked the invariant were dropped by the invite fold
(D-024 CR77), which canonicalized their addresses into bound_email.
Consequences worth knowing:
- The registration duplicate-check now resolves a case variant before the
INSERT, so a case-variant signup returns the intended
409 Email already registeredinstead of surfacing a unique-violation as a 500. - The self-hosted first-boot bootstrap (
POST /setup/bootstrap-admin) is one-shot and returns409 setup_already_completedforever after. A mixed-case admin address written there used to be a permanent lockout (login normalizes, the stored row does not, comparison is case-sensitive) recoverable only by hand-editing the database. The canonicalizer closes that. - Deployments are not migrated to
citext: it requires a server-side extension preload (azure.extensions) that Azure Flexible Server does not grant to the app role. The canonical-column invariant is the portable equivalent. - The CHECK is deliberately not
email = lower(btrim(email)): PostgreSQL's one-argumentbtrimstrips only U+0020, so[email protected]<TAB>would pass that guard, index as itself, and never again match a lookup for[email protected]— the #1187 lockout surviving its own fix.email !~ '\s'is strictly stronger thanstr.strip()for the ASCII whitespace class; Unicode separators such as NBSP are rejected earlier, byEmailStrformat validation.
Password-reset log events¶
The reset flow must never log a raw address or a raw token. It emits an
HMAC-free SHA-256 sidecar — the first 12 hex characters of
sha256(email) — which is enough to correlate a support report against the logs
without storing the PII:
| Event | Emitted when | Fields |
|---|---|---|
password_reset_lookup_miss |
The background task's user lookup found no row — the request is a dead end | email_hash |
password_reset_email_enqueued |
The delivery task was handed to the broker | email_hash, template_id |
password_reset_email_enqueue_failed |
The broker rejected/timed out the hand-off | email_hash, template_id |
password_reset_lookup_miss is the diagnostic that was missing: before it, an
unknown-email reset produced zero log output, so an operator could not tell a
genuinely unregistered address from a case-mismatched one. It is emitted inside
the BackgroundTask that runs after the 202 is written, so it changes neither
the response body nor its timing — the no-enumeration property is untouched.
API Keys (Machine-to-Machine)¶
API keys enable CI/CD pipelines and scripts to authenticate without interactive
login. Format: sk-huitzo-<64 hex chars> (256-bit entropy via secrets.token_hex(32)).
- Hashing: argon2id (OWASP-recommended parameters via
argon2-cffi) - Storage: Only the argon2id hash is persisted; plaintext returned once at creation
- Scopes:
["commands:execute"](v1 allowlist, validated at creation) - Lookup: By
key_prefix(first 16 chars), then constant-time argon2id verification - Revocation: Soft-delete via
revoked_attimestamp - Audit:
last_used_atupdated fire-and-forget on each use - Self-management: Keys cannot create, list, or revoke other keys (JWT required)
- Role binding:
UserContext.roleis hardcoded to"member"for every API-key request, regardless of the owning user's actual role. This is the no-privilege-escalation-via-key invariant — possession of a key never grants admin/owner powers. - No tier on the identity: the API-key
UserContextcarries no tier — the core has no tier concept (saas-extension-contract §3.5, D-024 CR27). When the SaaSRateLimitMiddlewareis mounted (SaaS-entitled deployments only), it resolves the acting tenant's plan itself per request, so a key's traffic is limited at that plan's budgets without any tier being threaded through the identity.
Auth Middleware Flow¶
Request
│
├─ Path in PUBLIC_PATHS? → Skip auth → call_next()
│
├─ Missing/malformed Authorization header? → 401
│
├─ Token starts with "sk-huitzo-"?
│ ├─ Format invalid (not 64 hex after prefix)? → 401
│ ├─ Hash lookup → no match or revoked? → 401 (no JWT fallthrough)
│ └─ Match → UserContext(role="member", _from_api_key=True) → call_next()
│
└─ Decode JWT
├─ Invalid/expired, or no sid claim → 401
├─ Session check (sid live, bound to sub + tenant_id, user and tenants active)
│ ├─ Fails → 401
│ └─ Database error → 503
└─ Valid → UserContext(user_id, tenant_id, role, session_id) → call_next()
The sk-huitzo- prefix is checked before JWT decode — cheaper and avoids
timing-oracle confusion between key and token failures.
Public Paths (no authentication required):
| Path | Purpose |
|---|---|
/health, /health/* |
Health checks |
/metrics |
Prometheus metrics |
/docs, /openapi.json, /redoc |
API documentation |
/api/v1/auth/register |
User registration |
/api/v1/auth/login |
User login |
/api/v1/auth/refresh |
Token refresh (body-based, CLI/SDK) |
/api/v1/auth/refresh-cookie |
Token refresh (cookie-based, dashboard) |
/api/v1/auth/verify-email |
Email verification (the single-use token is the credential; /send and /status stay authenticated) |
/api/v1/billing/webhook |
Stripe webhook (signature-verified) |
/api/v1/telemetry |
CLI telemetry ingestion |
Tenant Isolation¶
Database Level — Row-Level Security (RLS)¶
PostgreSQL Row-Level Security provides tenant isolation at the database level. Every tenant-scoped table has RLS policies enforced via SET LOCAL:
-- Enable RLS on tenant-scoped tables
ALTER TABLE pack_data ENABLE ROW LEVEL SECURITY;
ALTER TABLE pack_data FORCE ROW LEVEL SECURITY;
-- Tenant isolation policy
CREATE POLICY tenant_isolation ON pack_data
FOR ALL TO app_user
USING (tenant_id = current_setting('app.tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);
How RLS context is set:
Every database session begins with:
SET LOCAL app.tenant_id = '<tenant_id>';
This is transaction-scoped (SET LOCAL) so it cannot leak between requests. The get_session(tenant_id=...) context manager handles this automatically.
Bootstrap policies: Tables consumed by unauthenticated auth flows carry additional auth_bootstrap_* policies that work without tenant context: users (SELECT/INSERT/UPDATE), sessions (SELECT/INSERT/UPDATE/DELETE) and api_keys (SELECT). Each command exists because a specific bootstrap flow needs it — e.g. registration inserts the user and session, password reset updates users.hashed_password, and token refresh rotates the sessions row. Note the refresh path's SELECT … FOR UPDATE makes the sessions UPDATE policy load-bearing even for the read: PostgreSQL only returns locked rows that also pass an UPDATE policy's USING expression, so a missing UPDATE policy silently turns every refresh into a 401 (issue #1116) rather than an error.
Empty-string-safe bootstrap predicate (restricted-role hard requirement)¶
The login / register / API-key paths open a session with SET LOCAL app.auth_context = 'auth_bootstrap' and do not set app.tenant_id (there is no tenant yet). The auth_bootstrap_* and startup_bootstrap_* policies must therefore recognise the "no tenant context" state. The only correct predicate for that is:
-- pseudocode — empty-string-safe "no tenant context" check
USING (app_current_tenant_id() IS NULL AND current_setting('app.auth_context', true) = 'auth_bootstrap')
A naive current_setting('app.tenant_id', true) IS NULL is wrong on a pooled connection: a custom GUC defaults to the empty string (not NULL) after the first SET LOCAL on that connection (see apps/backend/alembic/versions/0001_baseline.py and ADR-023 §D7). Once a connection has served any tenant request, app.tenant_id = '', the raw IS NULL returns FALSE, and the bootstrap read/insert silently matches no rows — breaking login under the restricted huitzo_app role even though it "works" as a superuser (RLS bypassed). app_current_tenant_id() wraps the value in NULLIF(..., '') (plus a regex guard since migration 036), so it returns NULL for both "never set" and ''. Every bootstrap policy uses this helper form; the restricted-role regression (tests/integration/db/test_restricted_role_auth.py) locks it in by exercising the login path as huitzo_app under the pooled empty-string state.
Admin RLS Sentinel¶
Platform-staff admin endpoints (/api/v1/admin/*, /api/v1/metrics/*) need to read across tenants — for example, listing every user or computing the cross-tenant signup funnel. Granting these endpoints BYPASSRLS would erase the audit story for cross-tenant reads.
Instead, an explicit sentinel value is used. Admin-context database sessions set:
-- pseudocode — admin sentinel
SET LOCAL app.tenant_id = '__admin__';
Each admin-readable table carries an additional policy:
-- pseudocode — admin read policy
CREATE POLICY admin_read ON <table>
FOR SELECT TO huitzo_app
USING (current_setting('app.tenant_id', true) = '__admin__');
The sentinel '__admin__' is intentionally not a UUID, so it cannot collide with any real tenant id. The with_admin_context dependency (PR-PR04 in apps/backend/src/backend/auth/dependencies.py) is the only application-side path that sets it; every use writes a row to admin_audit_log per the roadmap audit hook. Cross-tenant writes are not granted by this policy — admin writes go through normal application logic that sets per-target-tenant context, so an admin "revoke user X's sessions" is recorded against X's tenant scope, not the admin sentinel.
This pattern keeps RLS as the single source of truth for cross-tenant access while making the staff-vs-tenant distinction visible in every query plan.
Multi-Tenancy Model¶
| Layer | Isolation Mechanism |
|---|---|
| Database | PostgreSQL RLS policies per table |
| Storage | pack_data keyed by tenant_id + pack_id + key |
| Files | Separate directories: tenant/{tenant_id}/... |
| Logs | tenant_id included in all structured log entries |
| Tokens | tenant_id embedded in JWT payload |
Tables Without RLS¶
tenants is intentionally NOT RLS-protected: webhook handlers update it, and beat tasks list every tenant from it or ask a reaper tenant function (see Background (beat) sessions). Access to it goes through explicit authorization checks (e.g., require_role("owner", "admin")) instead of RLS.
users is RLS-protected (FORCE ROW LEVEL SECURITY). Access outside a row's own tenant context goes through named policies: auth_bootstrap_* for login, registration and password reset (the app connects as huitzo_app; the huitzo_auth role is provisioned but unused), member_visible_users for members homed in another tenant, whole rows (ADR-028), admin_read_users for the __admin__ sentinel, and cron_dispatch_users_select for per-user schedule dispatch (ADR-030).
Background (beat) sessions¶
A Celery beat task has no request and no tenant. It reaches tenant-scoped rows in one of two ways:
| Pattern | Session | Use it when |
|---|---|---|
| Cron sentinel | get_session(auth_context="cron_dispatch"), which sets app.tenant_id = '__cron__' |
The table has a cron_dispatch_* policy for each kind of statement the task runs (SELECT, UPDATE, DELETE), as the command scheduler's discovery reads do |
| Per-tenant sweep | List tenant ids from tenants, then one get_session(tenant_id=...) per tenant |
Any other tenant-scoped table, as in the pipeline-checkpoint reaper |
| Scoped per-tenant sweep | Ask a reaper tenant function (no tenant context) which tenants have a candidate row, then one get_session(tenant_id=...) per returned tenant |
A frequent reaper whose candidate rows sit in few tenants: the stale pipeline-run, stale spec-job, stale site-job, runner orphan and approval expiry reapers |
The sentinel is not a bypass. app_current_tenant_id() returns NULL for '__cron__', so on a table without a cron_dispatch_* policy the session matches none of any tenant's own rows; only rows that a policy admits regardless of tenant, such as public dashboards, stay visible. Reads, updates and deletes then succeed and touch nothing, while an insert normally fails its WITH CHECK. Under the production NOBYPASSRLS role that quiet result is easy to miss, and a superuser never sees it because it bypasses RLS. For that reason the checkpoint reaper deleted nothing in production until #1270, and the Integration probe pass still probes nothing (#1880). A new sweep over a tenant-scoped table either sweeps per tenant or adds a narrow cron_dispatch_* policy, reviewed like any cross-tenant grant, and a live certificate runs it as the application role.
Privileged DB role boot guard¶
Every policy above holds only while the application connects as a NOSUPERUSER NOBYPASSRLS role. A superuser or a BYPASSRLS role skips RLS entirely, and nothing fails: every tenant simply sees every row. A DSN pasted into the wrong variable (an admin URL, or a backup role's URL) would do exactly that. So the backend and the worker refuse to start unless they can verify that the role behind HUITZO_DATABASE_URL is not, and cannot SET ROLE to, a SUPERUSER or BYPASSRLS role. (Table ownership is a third way around RLS on a table without FORCE ROW LEVEL SECURITY; this guard does not check it, which is why the runtime and admin URLs are separate roles.)
Where it runs. In the processes that serve tenants, and nowhere else:
| Process | Hook | On refusal |
|---|---|---|
| Backend, app build | _bootstrap_async (the uvicorn --factory backend.main:bootstrap entry), once the database answers and before the first write as the runtime role |
Raises; uvicorn exits non-zero |
| Backend, lifespan | The FastAPI lifespan, once the database answers and before anything is served (also covers a registry-free backend.main:app) |
Raises; uvicorn exits non-zero |
| Worker | celeryd_init in the main process, after the environment preflight and before the pool forks, so the children do not each query |
SystemExit(78) (EX_CONFIG) for every failure, because Celery's signal dispatcher swallows any other exception and boots anyway |
A standalone celery beat does not fire celeryd_init and is not checked: it schedules from a file (--schedule) and only publishes to the broker, while the tasks it enqueues run on a checked worker. An embedded -B beat runs inside a worker that already was. The check never runs at engine creation, in get_settings(), in Alembic, in python -m backend.manage, in the self-hosted app-role step (backend.self_hosted.app_role) or in the deploy preflight. Those run as the admin role by design: the customer bundle's run-only migrate service connects as the POSTGRES_USER superuser. The superuser blind spot described above therefore remains for migrations, integration tests and ad-hoc EXPLAIN sessions only: a booted backend or worker can no longer run as a superuser.
The check. One dedicated connection to HUITZO_DATABASE_URL (no pool, 10-second bound on the connect, the statements and the whole attempt) reads the login role, then every SUPERUSER or BYPASSRLS role it can act as:
-- pseudocode — the probe, catalog-qualified so search_path cannot substitute pg_roles
SELECT current_user;
SELECT privileged roles FROM pg_catalog.pg_roles
WHERE (rolsuper OR rolbypassrls)
AND (session_user or current_user is a MEMBER of it);
Membership matters: neither attribute is inherited, but SET ROLE reaches it, so GRANT huitzo TO huitzo_app is refused ('huitzo_app' can SET ROLE to 'huitzo', which has SUPERUSER). Checking session_user too catches a privileged login hidden behind a role connection setting. Implementation: apps/backend/src/backend/db_role_guard.py.
A refusal is logged at ERROR with event=privileged_db_role_refused, the role name and the attributes it can reach (SUPERUSER, BYPASSRLS), and tells the operator to point HUITZO_DATABASE_URL at the application role (huitzo_app).
A role that cannot be verified is refused. Only a database that is unavailable is waited for: a transport failure (refused, unreachable, DNS, timeout, a connection lost mid-probe) or a server that answers but cannot serve yet (SQLSTATE class 08, 53300, 57P01-57P03). It is tried five times, waiting 1, 2, 4 and 8 seconds between attempts, the await_database schedule. If it is still unavailable, or the probe fails with any other database or connection error (bad credentials, a TLS or certificate failure, a client configuration error, a missing database, a broken query; SQLAlchemy-wrapped errors are classified by the driver error underneath), the process refuses to start with event=privileged_db_role_unverified. In the backend, bad credentials surface earlier: await_database pings the runtime URL first and raises after its own retries, before the guard runs. An unexpected bug in the probe propagates as-is in the backend, which still fails the boot; the worker exits 78 and logs the same event at CRITICAL. Messages name the error type and SQLSTATE, never the error text, which can echo a DSN. A worker started before its database is up therefore exits and is restarted by its restart policy instead of serving unchecked for its whole life; it could not run tasks without the database anyway.
If the worker's settings model does not build, which the environment preflight lets through only with HUITZO_DEBUG=true, there is no URL to probe and the worker check is skipped with a WARNING.
The admin role warns only. When HUITZO_DATABASE_ADMIN_URL is set to a different URL, its role is probed in a single attempt, without retries, with the same catalog query. A privileged admin role logs a WARNING (event=privileged_db_admin_role) and boots: on the customer bundle the admin role is the POSTGRES_USER superuser on purpose. An admin URL that fails with a database or connection error logs a WARNING (event=privileged_db_admin_role_unverified) and boots too, since the runtime never uses it. Neither path relaxes the runtime role check.
Local escape hatch. HUITZO_ALLOW_PRIVILEGED_DB_ROLE=true lets a developer boot against a superuser test database. It is honoured only together with HUITZO_DEBUG=true and outside HUITZO_DEPLOYMENT_MODE=cloud, and logs a WARNING on every boot (event=privileged_db_role_allowed). Otherwise it is ignored and the refusal says so. No shipped compose file or CI job sets it.
Shipped stacks. The customer bundle, the reference compose, the air-gap proof of concept (deploy/poc-airgap/docker-compose.airgap.yml, run by airgap-rehearsal.yml) and the Helm recipe in deploy/k8s/README.md put huitzo_app in HUITZO_DATABASE_URL, with the POSTGRES_USER superuser as the admin role only. The customer bundle, the PoC and the Helm recipe set the role's password with the one-shot app-role step (backend.self_hosted.app_role) after the migrations; the reference compose sets it by hand (deploy/compose/README.md, step 5). The claims-triage demo compose in the packs/demo-packs submodule still connects as the superuser and is refused until its own PR moves it; it is tracked in #1473 (ROADMAP-1473 C5). The escape hatch is never the fix for a stack that still connects as the superuser.
Tests: apps/backend/tests/test_db_role_guard.py (refusal per attribute and through membership, plain role, retry and refusal of an unavailable database, immediate refusal of other probe failures, admin warnings, escape hatch, worker entry point, app-build and lifespan wiring), apps/backend/tests/integration/db/test_privileged_db_role_guard_live.py (temporary roles on a real server: a BYPASSRLS role refused by the lifespan and the worker entry point, the superuser refused by the lifespan, a member of the BYPASSRLS role refused by check_db_roles, a plain role booting the lifespan beside a superuser admin URL, warning only, and booting the worker entry point), and apps/worker/tests/test_db_role_guard_wiring.py (the celeryd_init receiver exits the worker).
Coupon Security¶
Coupons are the only admission and invite credential (ADR-042). Legacy access codes (32-bit HUITZO-XXXX-XXXX strings) were voided and their table dropped by the access-code fold (D-024 CR78, D15); staff and tenant invites were folded into coupons by CR77. Security considerations:
- Entropy: a code is 26 base32 characters, at least 128 bits (D3). The raw code is shown once, in the mint response. Only its SHA-256 hash and a four-character prefix are stored; no response, audit row or log line carries it afterwards.
- RLS from day one:
couponsandcoupon_redemptionsare FORCE RLS per the D4 matrix, with a dedicatedcoupon_admincontext for staff. - Mint rights: platform staff mint at
/api/v1/admin/coupons(recent auth). Tenant owners and admins mint onlytenant.joincoupons for their own tenant at/api/v1/tenant/coupons, bound to one email and single-use, under the rank rule (D5). A coupon whose credit exposure exceeds 5,000 is unredeemable until a different staff user approves it. - No oracle: unknown, expired, exhausted, revoked, unapproved and wrong-email codes, a full tenant, and an email that already has an account on the registration path all return the same
400 coupon_invalid(D6). The real reason goes to a structured log. One refusal is named: a signed-in redeemer who already redeemed a still-live coupon up to its per-user limit gets400 coupon_already_redeemed. It is reachable only by someone who holds a redemption of that coupon, so it confirms nothing to anyone else, and it is rate-limited like every other attempt. - Required for registration: while
HUITZO_REQUIRE_SIGNUP_COUPONis on (the default),/auth/registerneeds a coupon carryingaccount.create. - Audit: every mint, approval and revocation writes an
admin_audit_logrow; every redemption writes acoupon_redemptionsrow.
Stripe Webhook Security¶
Stripe webhooks bypass JWT authentication and use Stripe signature verification instead:
stripe.Webhook.construct_event(
payload=raw_body,
sig_header=request.headers["stripe-signature"],
secret=settings.stripe_webhook_secret,
)
- Signature algorithm: Stripe uses HMAC-SHA256 with a per-endpoint webhook secret
- Timestamp tolerance: Stripe SDK rejects events older than 5 minutes (replay protection)
- No JWT required: The
/api/v1/billing/webhookpath is inPUBLIC_PATHS - Idempotency: Webhook handlers are designed to be idempotent (safe to replay)
Rate Limiting¶
Tier rate limiting is a SaaS-extension concern (huitzo_ext_saas): the
RateLimitMiddleware is mounted only on a saas-entitled deployment. A
self-hosted OS has no tier limiter — only the core's per-IP throttle on select
auth endpoints (the public login/register/reset flows plus a few credential-verifying
authenticated ones like change-password / reauth) and the static deployment quota (saas-extension-contract
§3.5). The limiter uses Redis INCR/EXPIRE fixed-window counters keyed by user
(or anonymous IP), endpoint class, and time window:
# pseudocode — key scheme
rl:{endpoint_class}:{user_id_or_anon_ip}:{window_index}
Every per-tenant, per-user and per-IP budget lives in Redis, never only in one process's memory, so it holds across every backend process and replica. (A process may also keep its own count under a shared one, to bound its own memory; those are listed in shared limits.) The core's fixed windows, the runner channel's per-tenant token bucket and the concurrency leases (inline command executions, gateway calls), with each one's Redis-outage policy (closed for the abuse-sensitive auth limits, open with a warning for ordinary per-tenant limits), are in shared limits.
Endpoint classes¶
Instead of one broad bucket, each request is classified into one of five classes (first match wins), each with its own Redis bucket so a burst on one cannot starve another. The class selects the window and which tier budget applies.
| Class | Window | Budget (per tier) | Covers |
|---|---|---|---|
auth_session |
60s | max(120, requests/min) |
authenticated /auth/me, /auth/validate, /auth/logout (exactly these) — a high floor so session hydration never 429s. Credential mutations (change-password, reauth) are deliberately NOT here — they fall to interactive_write + a per-IP throttle |
bundle_asset |
60s | max(300, requests/min), per user, never pooled; unlimited stays unlimited |
GET /api/v1/dashboards/{scope}/{name}/bundle/... — a dashboard's own bundle files, so loading a dashboard never spends (or is refused by) the read budget its polling uses (W4-3) |
dashboard_read |
60s | requests/min |
every other GET/read: catalogs, license/billing status, API-key list, monitor / dev-session / runner status |
interactive_write |
60s | requests/min (separate bucket) |
mutations: settings, API-key create/revoke, billing checkout/portal, admin writes |
command_execution |
3600s | commands/hour |
POST /commands/{ns}, MCP tool calls (/mcp**), pipeline execute/resume |
Tier limits¶
The limiter resolves the acting tenant's plan: no plan row means payg,
and the budgets come from PLAN_CATALOG. D-024 CR27 deleted the personal
membership tiers (free/starter/pro/scale, the operator-set
developer_preview) and their budgets
(ADR-041 C7). The
anonymous arm is IP-keyed under the payg label.
commands_per_hour is unlimited on every plan (D-024 CR25): the wallet
reservation is the spend control. See
plan-based rate budgets.
Design decisions¶
- Simple counters (not sliding window):
INCR+EXPIREfor simplicity. Acceptable for launch; upgrade to sliding window post-launch if needed. - Plan resolved per request: the middleware reads the acting tenant's plan through the serve-stale plan cache. A double failure (cache and database) resolves to
payg, the lowest budgets, so an outage can only tighten limits, never elevate them. No personal tier is read (D-024 CR27; ADR-041 E3). - Fail-open vs fail-closed by class: a Redis outage fails open for the interactive classes (
auth_session/bundle_asset/dashboard_read/interactive_write) so it never logs users out or wedges the dashboard, but fails closed forcommand_execution— never grant unlimited compute during an outage (Value 2.7, Security by Default). - Kill switch:
HUITZO_RATE_LIMIT_ENABLED=falsedisables all rate limiting. - PAYG toggle (D-11): the per-tier arm (
check_rate_limit/TIER_LIMITS, covering both the per-user AND the anonymous/IP-keyed call sites) defaults ON. It used to derive OFF fromHUITZO_PAYG_ENABLED AND HUITZO_CREDITS_ENABLED;HUITZO_CREDITS_ENABLEDwas removed with ADR-019's Ledger A (migrationsaas_0014, 2026-08-24), and since production ran it OFF the derivation already evaluated to ON there — so the default preserves production behaviour rather than silently disarming a live limiter during a refactor. ADR-036 §10's justification for turning the arm off is a substitution ("the wallet's zero-balance enforcement is the access policy instead"); the substitute it named — the Ledger-A metering pre-flight gate — no longer exists, and the ADR-035 reservation gate that replaced it refuses on BALANCE, not on request COUNT, so it does not bound an authenticated user's request rate. Adopting the substitution is therefore an owner decision, taken by settingHUITZO_PAYG_RATE_LIMIT_ENABLED=falseexplicitly. The enterprise pooled arm (check_pooled_rate_limit) is untouched — a separate lane, out of scope for D-11. With the arm ON, payg commands are unlimited: the legacy 5 commands/hour cap went with the personal-wallet model (D-024 CR25, removed 2026-10-09), so this flag only bounds per-minute request rate. - Exempt paths: the limiter mirrors
AuthMiddlewareexactly — the exactPUBLIC_PATHSset and thePUBLIC_PATH_PREFIXESprefixes (/api/v1/feed/,/api/v1/setup/,/api/v1/branding/assets/,/api/v1/internal/runner/). Health/metrics/docs/OpenAPI and these prefix-public machine/anon paths are never rate-limited here. - Observability: every denial increments
huitzo_rate_limit_denials_total{tier, endpoint_class, method}and emits a structuredrate_limit_deniedlog carrying the request id and reset time (no token/PII).
Trusted-proxy contract¶
Every per-IP limit keys on one value, produced by one helper:
backend.ratelimit._get_client_ip
(ADR-042 D9). No other
module parses a forwarding header for a rate-limit key.
| Input | Honoured when | Why |
|---|---|---|
| Transport peer (the socket address) | Always the default key | It cannot be forged by the client |
X-Real-IP |
Only when the transport peer is inside HUITZO_TRUSTED_PROXY_CIDRS and the value is a valid IP |
The edge overwrites it with $remote_addr |
X-Forwarded-For |
Never by the backend | Its leftmost entry is client-controlled. Only the dashboard edge reads it, and only from a listed proxy, to restore the client (below) |
- The transport peer is captured before any rewrite. uvicorn's
ProxyHeadersMiddlewarereplacesscope["client"]with the leftmostX-Forwarded-Forentry when it trusts the peer, and production trusts every peer (HUITZO_TRUSTED_PROXY_HOSTS=["*"]). A pure ASGI middleware mounted outside it records the real peer first.HUITZO_TRUSTED_PROXY_HOSTSkeeps governing scheme and host only. Every uvicorn launch passes--no-proxy-headers: uvicorn's own CLI wrapper would otherwise sit outside the whole app, ahead of the peer capture, and rewritescope["client"]fromX-Forwarded-Forfor a loopback peer. - Addresses are canonicalised. An IPv4-mapped IPv6 address
(
::ffff:a.b.c.d) is unwrapped to IPv4 for the peer and the header alike, so it matches IPv4 CIDRs and shares the IPv4 bucket. A scoped IPv6 address (fe80::1%x) is rejected, because its zone id is free text that would mint unbounded keys. - The default trusts private proxy ranges only.
HUITZO_TRUSTED_PROXY_CIDRSdefaults to loopback, RFC 1918 and IPv6 unique-local (127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,::1/128,fc00::/7), the ranges a Docker bridge uses. nginx on the bridge therefore names the client and each client keeps its own bucket, with no operator setting. A public peer is never trusted. An explicit[]keys every limit on the peer, which puts every client behind a proxy in one bucket (ADR-042 D9 amendment, 2026-09-28). - Operator duty. Make the edge set
X-Real-IPto the true client address. Behind a CDN or HTTPS proxy,$remote_addris the proxy hop unless the edge restores the client IP (real_ipconfiguration; for the dashboard image,HUITZO_EDGE_TRUSTED_PROXIES, below). A backend port published on the host is reached through Docker's userland proxy, whose peer is the bridge gateway, inside the default range: when that port is reachable beyond the host, narrowHUITZO_TRUSTED_PROXY_CIDRSto nginx's address so a client that bypasses the edge cannot pick its own bucket. The production overlay publishes:8000, so production needs this check (the host firewall blocks:8000, or the list is narrowed); see plan D-5. - The edge sets
X-Real-IPon every backend location, including the public ones no limiter reads today (/health,/metrics,/docs), so a later limit on them cannot inherit a client-supplied header. - The dashboard edge restores the client from listed proxies only. Behind
an HTTPS proxy (the customer compose's Caddy profile, a load balancer), the
dashboard nginx's peer is the proxy, so
$remote_addralone would put every user of the install in the proxy's bucket. At container start the dashboard image renders nginxreal_ipconfiguration fromHUITZO_EDGE_TRUSTED_PROXIES, a comma-separated list of IP addresses or CIDRs: oneset_real_ip_fromper entry,real_ip_header X-Forwarded-For,real_ip_recursive on. nginx then takes the rightmostX-Forwarded-Forentry that is not a listed proxy as the client and sends it asX-Real-IP. The list is of addresses, not a hop count, so a client cannot widen it by adding entries. Empty (the default) trusts nothing:X-Real-IPis the TCP peer, so a dashboard published without a proxy cannot be spoofed. The container refuses to start on a malformed entry, a hostname, or a prefix wider than/8(IPv4) or/16(IPv6), such as0.0.0.0/0or::/0. From a listed peer, nginx also passes that proxy'sX-Forwarded-Proto(httporhttps) instead of its own$scheme; from any other peer it sends$scheme. The customer compose gives Caddy a fixed address onhuitzo-network, and on the first run with--domaininstall.shsets the variable to that address alone (one hop); a later run warns when it is empty or does not list Caddy. A second hop (a load balancer whose CIDR is added to the list) restores the client only if that proxy forwards the load balancer'sX-Forwarded-For; the shipped Caddyfile trusts no upstream, so Caddy replaces it, and in front of Caddy the load balancer's address is the client. With--external-tlsand a proxy on the same host, the listed address is thehuitzo-networkgateway, which trusts every process on the host that can reach the dashboard's port. The backend is unchanged: it readsX-Real-IPfrom its trusted peers and neverX-Forwarded-For(ADR-042 D9 note, 2026-10-15).
# pseudocode — client IP for rate limiting
peer = transport peer recorded before ProxyHeadersMiddleware
if peer in trusted_proxy_cidrs and X-Real-IP is a valid IP:
return X-Real-IP
return peer
Registration abuse limits¶
POST /api/v1/auth/register carries a per-IP limit
(HUITZO_REGISTER_IP_RATE_LIMIT_PER_MINUTE, default 5 per 60s, 429) and a
platform-wide hourly breaker (HUITZO_REGISTER_HOURLY_CAP, default 100
successful registrations, 503). Both fail closed: a Redis outage answers
503. So do login, password change, forgot and reset, reauth, coupon redeem
and verification send; ordinary per-tenant limits fail open
(shared limits). A 2s Redis
socket timeout makes an unresponsive Redis count as an outage. The
HUITZO_RATE_LIMIT_ENABLED kill switch still disables them. Every coupon
refusal returns one body and status (400 coupon_invalid), so the endpoint is
not a code-state oracle
(ADR-042 D10, coupon security).
Rate limit headers and the 429 body¶
Successful responses with a finite budget carry the budget headers; a denial adds
a window-correct Retry-After (≈60s for the per-minute classes, up to 3600s for
command_execution) and a structured body.
| Header | Description |
|---|---|
X-RateLimit-Limit |
The budget for this class/window |
X-RateLimit-Remaining |
Remaining requests in the current window |
X-RateLimit-Reset |
Epoch second the window resets |
Retry-After |
Seconds until reset (429 responses only) |
// 429 body
{
"success": false,
"error": {
"code": "rate_limited",
"message": "Rate limit exceeded for dashboard_read; retry after 42s.",
"endpoint_class": "dashboard_read",
"limit": 60,
"remaining": 0,
"reset": 1708000060,
"retry_after": 42
}
}
The dashboard client treats a 429 as a transient backoff signal, never a logout:
checkAuth() preserves an already-hydrated session on a 429/5xx from /auth/me
(only a true 401 clears it), and polling loops honour Retry-After.
Secrets Management¶
Three-Tier Model¶
| Tier | Scope | Example | Storage |
|---|---|---|---|
| Platform | Infrastructure | Database URL, JWT secret | Environment variables |
| Pack | Per-pack config | API keys for integrations | huitzo.yaml manifest |
| User | Per-user per-pack | Personal API keys | Encrypted in database |
Platform secrets are managed via environment variables and have no pack-facing SDK accessor. That is an API-surface contract, not on its own an enforced boundary — every call of a pack command (single commands on every surface, pipeline stages, nested command bodies) runs in ADR-039's scrubbed-environment child process (no in-process pack code), which removes the trivial os.environ read; with the sandbox helper present it also runs the child under a separate UID that cannot read /proc/<ppid>/environ (ADR-039 Sandbox UID), and without the helper a same-uid adversary recovers the credential anyway (pinned by test_same_uid_child_can_read_the_platform_dsn_via_proc_ppid_environ). Without the helper, an untrusted pack must be treated as holding platform secrets. See Isolation Strategy for the current state and remaining hardening path and Secrets Management for the pack-author framing.
Pack secrets are defined in the pack manifest and configured per-deployment.
User secrets (v0.2+) will be encrypted at rest with AES-256-GCM, scoped to user + pack, and accessible only via ctx.secrets. "Scoped to pack" is enforced by two independent checks — the tenant/user visibility predicate on every query, and the declared-name gate that refuses any secret the executing pack's own manifest does not name, before the query runs. See Tier 3 scoping.
Database role secrets on the customer bundle¶
The customer bundle (deploy/customer/) gives every database role its own
random 32-byte password, generated by install.sh:
HUITZO_DB_SUPERUSER_PASSWORD (the huitzo superuser, used by postgres and
migrate), HUITZO_DB_APP_PASSWORD (the huitzo_app runtime role) and
HUITZO_DB_BACKUP_PASSWORD (the huitzo_backup role of the backup service,
which also holds HUITZO_DB_BACKUP_AUDIT_PASSWORD for huitzo_backup_audit;
backup service). Knowing the runtime
role's password no longer yields the superuser, and only the one-shot migrate
service receives the superuser URL as HUITZO_DATABASE_ADMIN_URL: backend,
worker and beat, which run pack code, never hold it
(Which service holds the admin URL).
The run-only backup-restore service holds the same credential as
HUITZO_DATABASE_RESTORE_URL and runs no pack code. An install from before the
split is migrated by the next install.sh run, which rotates both roles before
it rewrites .env
(Database role passwords).
The development compose (deploy/compose/docker-compose.yml) publishes
PostgreSQL on 5432 with huitzo/huitzo and is never for customers
(Development compose).
Pack Data Plaintext Storage Policy¶
The pack_data table stores pack state as unencrypted PostgreSQL JSONB. RLS provides tenant isolation but not confidentiality — any row is readable by anyone with direct database access.
Policy: Packs MUST NOT store secrets, API keys, tokens, or credentials in ctx.storage. Sensitive values must use ctx.secrets instead.
Enforcement (partial): The storage backend rejects save() calls where the data dict contains keys ending with _token, _secret, _password, _credential, or _credentials (checked recursively). _key is deliberately not on the list: it matched benign identifiers such as idempotency_key and redacted legitimate results (#1321). This catches the most common accidental cases.
# pseudocode
if any field in data matches *_token, *_secret, *_password, *_credential, *_credentials:
raise StorageError("use ctx.secrets for sensitive values")
Known enforcement gap: The suffix check is heuristic. A pack can still store secrets under non-conventional field names (e.g., auth, bearer, creds). Column-level encryption is required to close this gap fully.
Tracking: Column-level encryption for
pack_data.valueis a planned post-v0.2 requirement. Until then, pack authors are responsible for not placing secrets in storage.
Column-level encryption¶
Selected sensitive columns are encrypted at rest with AES-256-GCM via the
EncryptedString SQLAlchemy TypeDecorator
(apps/backend/src/backend/core/models/encrypted_type.py).
- Algorithm: AES-256-GCM with a fresh 96-bit random nonce per write.
Ciphertext is stored as
<nonce_b64>:<ciphertext_b64>in aTEXTcolumn. Each write produces a distinct ciphertext — the encoding does not leak equality. - Key source:
HUITZO_SECRETS_ENCRYPTION_KEY(64-char hex = 32 bytes). The same key keys the HMAC-SHA256 lookup hashing unlessHUITZO_SECRETS_LOOKUP_HASH_KEYis set, which pins the lookup-hash key so a key rotation does not change any stored hash. - Tamper detection: GCM's authenticator tag guarantees integrity. On
decrypt,
cryptography.exceptions.InvalidTag,binascii.Error, andUnicodeDecodeErrorare caught, a warning is logged (no PII), and the field returnsNone. A single corrupted row cannot crash aSELECT. - Type safety:
process_bind_paramrejects non-strinputs withTypeErrorbefore encrypting — no silent coercion.
Equality lookups via HMAC-SHA256 sidecar: Randomized AES-GCM means
WHERE encrypted_col = ? cannot work. For columns that need equality
lookups (e.g. Stripe webhook customer_id → user) we add a sibling
*_lookup_hash VARCHAR(64) column populated with
hmac.new(key, value.utf-8, sha256).hexdigest() and a btree index on it.
The application keeps the two columns in sync via a SQLAlchemy @validates
hook on the model, and lookups are rewritten to compare the hash.
Why HMAC sidecar, not AES-SIV: AES-256-SIV requires a 64-byte key; the existing platform key is 32 bytes. The sidecar pattern stays within the 32-byte envelope, keeps ciphertext indistinguishable under chosen-plaintext attack (AES-GCM is IND-CPA, AES-SIV is not), and remains auditable.
Current users:
| Column | Encrypted type | Lookup hash |
|---|---|---|
users.stripe_customer_id |
EncryptedString (AES-256-GCM) |
users.stripe_customer_id_lookup_hash (HMAC-SHA256) |
See apps/backend/src/backend/core/models/user.py for the User model and
the @validates("stripe_customer_id") sync hook.
Column encryption key rotation¶
HUITZO_SECRETS_ENCRYPTION_KEY can be rotated without losing data. Three
pieces make that work:
1. A two-key read path. HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS (optional,
64-char hex, must differ from the current key) is a second, decrypt-only key:
the incoming key during the first rollout deploy, then the key being retired.
Every decrypt tries the current key first and the previous key second; every
encrypt uses the current key only. Both the backend and the worker read both
keys, so between deploying a new key and re-keying the data, a value sealed
under the old key still reads. This applies to every format sealed under the
column key:
| Stored value | Format | AAD |
|---|---|---|
Every EncryptedString column (platform_secrets.value_encrypted, the SaaS extension's Stripe customer ids and tax id, …) |
<nonce_b64>:<ciphertext_b64> |
none |
llm_providers.api_key_ciphertext |
<nonce_b64>:<ciphertext_b64> |
llm_provider_key:v1:<provider name> |
integrations.secrets_encrypted blobs, schemes aes_gcm_aad_v2 / aes_gcm_aad_v1 |
JSON blob {ciphertext, nonce, scheme} |
per scheme, see AAD identity rotation |
fernet_v1 integration blobs are sealed under the separate
HUITZO_SSH_ENCRYPTION_KEY and are outside this rotation.
2. A pinned lookup-hash key. HMAC lookup hashes (*_lookup_hash
columns, and the SaaS ledger's payment and refund reference hashes) are
compared, not decrypted, and several of them have no stored plaintext to
recompute from. Re-keying them is therefore not possible, so the lookup-hash
key never rotates: HUITZO_SECRETS_LOOKUP_HASH_KEY is set to the ORIGINAL
column key before the first rotation and stays set for the life of the
deployment. Settings refuse to load when ..._PREVIOUS is set without it,
because a deployment that rotated the column key without pinning the lookup key
would silently stop matching every stored hash (webhook routing, refund
dedupe).
3. A one-transaction re-key command. python -m backend.manage
rekey-secrets decrypts every value listed above with the previous key and
re-seals it with the current key, keeping each value's format, scheme and AAD
(a v1 blob stays v1 under the same AAD; only the key changes). The command
reads both keys from the environment only, never from arguments.
- Discovery.
EncryptedStringcolumns are found from the ORM metadata: every core model, plus each installed extension'smodelsmodules. A table the database does not hold (an extension whose migrations never ran) is reported and skipped. The reverse fails closed: if the database holds an extension's lineage (alembic_version_<name>) that the running image cannot load, the run (dry run included) refuses and names that extension, because its encrypted columns would stay under the old key. - Fail closed, all or nothing. Every new value is computed before the first write. A value that decrypts under neither key aborts the whole run and names the table, column and row id, never the value or the secret name. The run is one transaction, so an abort writes nothing.
- Idempotent. A value that already decrypts under the current key is counted and left alone, so a re-run, or a table partly written by the app after the new key was deployed, re-keys only what is still old.
- Row-level security. It runs as the table owner (the migration admin
URL), lifts
FORCE ROW LEVEL SECURITYfor the transaction on the tables that carry it, and setsrow_security = off, so a role that would still be filtered fails loudly instead of re-keying a subset. --dry-rundecrypts everything, checks the lookup-hash key and reports per-table counts, then rolls back.- Lookup-hash check. For every
EncryptedStringcolumn with a<column>_lookup_hashsidecar, the run (dry run included) recomputes the HMAC with the pinned lookup-hash key and aborts on the first stored hash it does not reproduce. The runbook runs a dry run against the edited configuration before any service restarts on it, so a mis-setHUITZO_SECRETS_LOOKUP_HASH_KEYis caught before it breaks equality lookups.
Rollout. The new key reaches every reader before any writer uses it: one
deploy puts it in the decrypt-only ..._PREVIOUS slot, a second swaps the two
keys. A single deploy would let a restarted replica seal a value that a replica
not yet restarted cannot read. The shipped compose stacks and Helm chart
forward both rotation variables to every process holding the key (deployment
caveats are in the
runbook's notes).
Limits of this rotation. It re-keys ciphertext; it does not retire the
original key. That key stays configured as HUITZO_SECRETS_LOOKUP_HASH_KEY,
so:
- pre-rotation backups remain decryptable with material still on every host;
- lookup hashes remain keyed by the original key, so if that key leaked, a holder of a database copy can test guessed Stripe ids against the hashes;
- the original key bytes stay both an AES-GCM key (for old backups) and the HMAC key, so key separation is not restored.
A rotation forced by a suspected key compromise must therefore also expire or re-encrypt older backups. Rotating the lookup-hash key itself (versioned hash columns with a dual-hash read window, re-derived where plaintext exists) is deferred: several hashes have no stored plaintext to re-derive from.
The operator procedure is the runbook's
rotate the column encryption key.
Implementation: apps/backend/src/backend/core/secrets_rekey.py.
Stripe Customer ID Plaintext Storage¶
Resolved in alembic revision 020 —
users.stripe_customer_idis now encrypted at rest via AES-256-GCM, with an HMAC-SHA256 sidecar (stripe_customer_id_lookup_hash) preserving indexed equality lookups for webhook handlers. See Column-level encryption.
Defense-in-depth mitigations that remain in force:
- The field is never returned in any API response (enforced via dedicated response schemas in billing.py)
- Database access is restricted to service-account credentials; no direct public access
- Stripe API calls require the platform's secret key in addition to the customer ID
Isolation Strategy¶
Phase 1: Docker Containerization (Current)¶
The backend and worker never import a pack. Every call of a pack command — single commands on every surface, pipeline stages and the bodies of nested ctx.commands calls — runs in a per-execution CHILD PROCESS under ADR-039 (no in-process pack code), with no switch back to in-process execution, whose own environment is scrubbed to an allowlist (no platform DSN, no decrypted-secret preload in the child's os.environ — see the ADR's §(f)). Where the image ships the sandbox helper (the backend and worker images both install it; ADR-039 Sandbox UID), the child runs under a separate huitzo-sandbox UID with no capabilities and no-new-privs, so the parent's /proc/<ppid>/environ and its 0700/0600 files are closed to it. The isolation-confinement CI job proves this on both worker targets; the backend images install the same helper through the same script. That is a boundary for the parent's credentials only, not between tenants (one sandbox UID for all) and not for the network. Without the helper it is NOT a confinement boundary, on any surface, and must not be treated as one: the child then runs under the SAME uid as the parent, with no PID-namespace or filesystem separation, so a same-uid adversary trivially routes around the env-scrub — test_same_uid_child_can_read_the_platform_dsn_via_proc_ppid_environ (apps/backend/tests/test_commands_isolation_hub_escape.py) pins that a pack recovers the parent's real exec-time credentials via /proc/<ppid>/environ (not gated by Yama ptrace_scope), test_backend_metering_internals_are_importable_inside_the_child pins that backend/backend.metering import cleanly inside the child (shared interpreter and site-packages), and test_tenant_a_child_can_read_tenant_bs_venv_by_absolute_path pins that there is no filesystem confinement at all. The container remains the unit of resource limiting and filesystem scoping; it is not a boundary between a pack and the platform's own environment on ANY surface, which is why platform credentials must still be treated as reachable by any pack the operator installs wherever the helper is missing (see Secrets Management). A distinct uid per tenant, or a PID namespace per execution, is unbuilt; the sandbox UID closes the parent-credential read, not cross-tenant reach.
Security Evolution: As Huitzo moves toward a public marketplace, Docker isolation may not be sufficient for high-trust environments. Goal: Transition from Docker to microVMs (e.g., Firecracker) for pack execution. Reason: MicroVMs provide hardware-level isolation, ensuring a malicious Pack cannot read host environment variables or escape to the host kernel.
Authorization¶
Role-Based Access Control¶
| Role | Capabilities |
|---|---|
member |
Execute commands, manage own account, publish packs under org scope |
admin |
+ Manage org members, view metrics, delete the tenant's packs and dashboards, grant other tenants access to them |
owner |
+ Billing management, delete organization, full admin access |
Role checks use the require_role() dependency:
@router.get("/admin-only")
async def admin_endpoint(user: UserContext = Depends(require_role("owner", "admin"))):
...
Role-Based Data Visibility¶
Beyond capability gating, role determines the scope of data visibility for tenant-scoped resources:
| Resource | member scope |
admin / owner scope |
|---|---|---|
Command executions (/monitor/executions) |
Own executions only | All tenant executions |
Dev sessions (/dev-sessions GET) |
Own sessions only | All tenant sessions |
Design rationale: Admin and owner roles carry operational responsibility for their tenant. Tenant-wide observability (e.g., seeing stuck executions, orphaned sessions) is a necessary operational capability. This is explicitly authorized and scoped to the tenant — it does not extend across tenant boundaries.
Cross-tenant isolation is absolute: PostgreSQL RLS enforces tenant_id on all tenant-scoped tables. No role — including admin and owner — can read data from a different tenant. This invariant is enforced at the database level and cannot be bypassed by application code.
Security invariants:
| Invariant | Enforcement point |
|---|---|
| Member never sees another member's executions or sessions | Application layer (user_id filter on list endpoints) |
| Admin/owner sees all executions and sessions in their tenant | Intentional policy; scoped to tenant |
| No data is visible across tenants | PostgreSQL RLS (tenant_id = app.tenant_id policy on every table) |
| Heartbeat/stop require session ownership | Application layer (user_id match on lookup, returns 404 if mismatch) |
| Only admin/owner can kill executions or revoke sessions | require_role("admin", "owner") dependency |
| Only admin/owner can delete a pack or dashboard, or grant another tenant access to one | Role check in each handler after the ownership check (_MANAGE_ROLES, ADR-025, #1185); API keys always act as member |
See System Monitor and Dev Sessions for per-resource access control tables.
Subscription-Based Access Control¶
No tier or plan is carried in the JWT — the core has no tier concept
(saas-extension-contract §3.5; D-024 CR27 dropped the legacy tenant tier) and
UserContext has no tier field. On a saas-entitled deployment the
RateLimitMiddleware resolves the acting tenant's plan per request (no plan
row is payg). The resolved plan determines:
- Rate limits (see Rate Limiting above)
- Feature access (future: premium-only commands)
- Command execution quotas
Code Protection (Self-Hosted)¶
- Nuitka compilation: Platform compiled to optimized binary
- Pack signing: Hash verification prevents tampering
- License validation: offline Ed25519 verification of a signed
license.json(read fromHUITZO_LICENSE_PATH, default/etc/huitzo/license.json) against an embedded trusted public key — no network (see ADR-007 / ADR-008)
Context Injection¶
Every command receives a Context object with deployment-aware services:
@dataclass
class Context:
# Identity
user_id: UUID
tenant_id: UUID
session_id: UUID
correlation_id: str
# Deployment
deployment_mode: DeploymentMode = DeploymentMode.CLOUD
# Services (backend selected based on deployment_mode)
storage: StorageBackend
llm: LLMService
email: EmailService
files: FileService
http: HTTPService
log: LogService
Commands can check ctx.deployment_mode to adjust behavior, though most commands should work identically across all modes. The correlation_id enables distributed tracing across command execution.
HTTP Integration Threat Model¶
When a tenant configures an HTTP integration, the integration's base_url
host is unconditionally permitted for outbound requests issued by that
tenant's packs (in addition to any allowed_domains declared in the pack
manifest or the integration). The implication is that a tenant who can
write integration config can direct any pack they install to issue HTTPS
requests to whatever host they name.
These guardrails still hold and run before the base_url-host permit:
- Cloud metadata blocklist — requests to
169.254.169.254(AWS / Azure IMDS),metadata.google.internal(GCP), and100.100.100.200(Alibaba) are rejected even if a tenant sets one of those asbase_url. SSRF to cloud instance credentials is not reachable. - Private-address check — a host that is, or resolves to, a loopback,
RFC 1918, link-local, unique-local, reserved or multicast address is
refused, a
base_urlsuch ashttps://10.0.0.5/included, in every deployment mode. The platform connects to an address the check vetted, not to the name, so a name cannot answer the check with a public address and the connection with an internal one (#1963). Environment proxies are not used forctx.http, since a proxy would resolve the name again. - HTTPS-only — a
base_urlstarting withhttp://passes the config-layer validator (^https?://accepts both schemes) and can be stored, but it is blocked at request time by the SDK's_check_domain, before the host is contacted. Plain-HTTP downgrade is not reachable from pack code regardless of the stored value. - Every redirect hop — the platform runs these checks and the allowlist again on each request it sends, so a redirect target is checked the same way as the first URL (SDK Integrations — Redirects).
- Tenant scoping — integration rows are filtered by
tenant_idin the resolver, so one tenant'sbase_urlcannot be read or invoked by another tenant's command.
What is not blocked and is accepted under this threat model:
- What a permitted redirect carries — a redirect that keeps the method
(307, 308, or a 301 answering anything but a POST) sends the request body
again, and headers other than
AuthorizationandCookiego to the next host when it passes the checks. The CLI's local sandbox does not check redirects at all (huitzo pack dev,huitzo pack execorhuitzo sandbox startwith--local-keys, #1873). See SDK Integrations — Redirects. - Credentials embedded in a
base_url— if a tenant setsbase_url=https://user:pass@host, the userinfo is still sent with the request. It no longer reaches an error message or the retry log prefix: those carry only scheme, host, port and path (Error message hygiene). Tenants are still advised to usebearer_token/basic_authintegration secrets instead, which are applied at request time rather than embedded in the URL.
Pack developers consuming this model: see
SDK Integrations — Relative Paths and base_url
for the public-facing contract and the SDK's enforcement order.
Error message hygiene¶
An exception's .message is reachable by the caller (REST error body, command
result) and by the logs (commands/executor.py logs a HuitzoError with
exc_info=True). So it never holds anything the caller supplied or anything
internal to the infrastructure (#1876, #1743). A message is a fixed sentence
plus the exception class and, for an OSError, its errno name
(huitzo_core.safe_text.exc_label). The raise keeps from exc.
- HTTP integration: every
HTTPErrormessage and the retry log prefix name the request asscheme://host[:port]/path. The query string (where API keys travel as?api_key=), userinfo and fragment are dropped, and so is the text of the underlyinghttpxexception, which can repeat the URL. The error'surlattribute is the same stripped form. - Storage (
ctx.storage,ctx.files, S3): the message names the operation and the exception class, never the SQL statement, bound parameters, server file path or driver text. - Database and email integrations: driver errors are reduced to the class
name. A database message never carries a resolved address. An
ssl_cabundle, or a deployment Postgres TLS file or setting, that cannot be used is reported with a fixed sentence, without the path or the errno, which would tell a tenant whether a file exists on the server; the class and errno name go to the server log (db.ssl_ca_unloadable,db.pg_tls_settings_unusable). The SendGrid response body is not echoed. - LLM providers (the OpenAI and Anthropic wire adapters, including the
Azure-hosted routes that reach them through a
WireEndpoint; local AI completion, streaming and model management; the routing backend): the message is a fixed sentence plus the upstream HTTP status or the transport exception's class. The upstream response body (organisation and project ids, quota state), the raw transport text and the local model server's address are not echoed; they go to the server log through the shared log redactor (below). A failure of the local model server is raised asLLMErrorwhatever the transport raised; every caller (the routing backend, the local AI admin routes, the provider catalog, the health check) already handlesLLMError. - Structured LLM output: when the model's answer does not match the
requested schema, the message names the schema and the failure count (the
in-process path also lists the failing field paths and the attempt count),
never the model's output. A field path is checked position by position against
the schema: a component keeps its name only when the model at that exact
position declares that field; a dict key or list index is shown as
<item>and a key the model invented (an extra key underextra="forbid") as<extra>, even when it equals a field name declared elsewhere. After a position the walk cannot follow (a union of several types, for example), every later component is a placeholder. The pydantic text, which quotes that output (input_value=), is not echoed in process or across the isolation boundary (commands/isolation/proxies.py); the log gets the same field paths or pydantic's rule names. - Pipeline stages: a failed stage's
error.messageinpartial_results, thePipelineErrormessage (/api/v1/pipelines, its SSEerrorevent and the storedpipeline_runs.error) and the async worker's run record carry the same textcommand_executions.error_messagestores for that exception (command-raised errors): an SDK error's caller-facing text, the rule summary of a pydantic failure, a platform-written refusal's own text (a permission denial; credentials in such text are redacted; a malformed command ref gets a fixed sentence that never quotes the ref; the stage that fails on it logs the ref once, redacted), or for any other exception a fixed sentence naming its class (<class>: the command failed; its message is not stored). So another pack's stage internals do not reach the pipeline's caller through a failure the executor wraps. The raw text goes to the server log through the shared log redactor, with the stage index and name and without a traceback (a chained cause would carry the same text unredacted).error.typeis unchanged. - Server log lines that keep an error's raw detail (the pipeline stage line,
the LLM provider and local model server lines) go through one redactor,
huitzo_core.safe_text.redact_log_text. It removes the API key and credential header values it is given, in every form error text carries them (raw, URL-encoded, stripped, and escaped as h11 quotes a rejected header), then bearer tokens (the whole RFC 6750 token68 value,+,/,~and=padding included) and basic credentials, known token shapes, URL userinfo and the value of every credential-named parameter (token=,apikey=,secret=,password=,sig=,secret_key,private_key,access_keyand the other credential key names in any form, includingaws_secret_access_key; any otherkeyparameter, bare or compound such ascache_key, in itskey=assignment form only, sokey: Field requiredkeeps its text). Every pattern runs over the whole input and the cut is the last step (4096 characters by default; 500 for an upstream response body, 512 for a malformed command ref): callers pass the whole text, never a pre-cut slice. An input longer than 64 KiB is scanned up to that bound; the rest, with any unfinished token the bound cuts through, is replaced by[TRUNCATED], never logged partly scanned. It never raises, including on text or a key with an unpaired surrogate.
Still open under #1743: relayed upstream bodies (HTTPError.response_body),
the SDK commands service, a PipelineError a stage raises itself, which the
executor passes through as a nested pipeline's failure without re-rendering it,
and full-traceback logging of a failed command or pipeline task elsewhere
(commands/executor.py, the async pipeline task's outer handler).
Production Security Checklist¶
| Item | Required | Notes |
|---|---|---|
HUITZO_JWT_SECRET_KEY |
Cryptographically random, 256+ bits | |
HUITZO_AUDIT_PEPPER |
Cryptographically random, 32+ chars (admin audit log redaction pepper) | |
HUITZO_DEBUG=false |
Disables debug endpoints | |
| HTTPS termination | TLS 1.2+ at load balancer/reverse proxy | |
| Database password | Strong, unique password | |
| Runtime database role | HUITZO_DATABASE_URL logs in as a NOSUPERUSER NOBYPASSRLS role (huitzo_app) |
The backend and the worker refuse to start otherwise (boot guard) |
| Redis authentication | requirepass in production |
|
| Stripe webhook secret | Per-endpoint, verify signatures | |
| Rate limiting enabled | HUITZO_RATE_LIMIT_ENABLED=true |
|
| Trusted proxy range | Edge sets X-Real-IP; HUITZO_TRUSTED_PROXY_CIDRS narrowed to nginx's address if :8000 is reachable beyond the host |
The private-range default covers nginx on a Docker bridge; [] buckets every client behind the proxy together (contract) |
| Edge trusted proxies | Behind an HTTPS proxy, HUITZO_EDGE_TRUSTED_PROXIES on the dashboard lists that proxy's address (the customer compose's Caddy profile sets it) |
Empty trusts nothing; unset behind a proxy, every user shares the proxy's login bucket (contract) |
| Signup coupons required | HUITZO_REQUIRE_SIGNUP_COUPON=true (the default); staff mint account.create coupons |
Related Documentation¶
- Architecture Overview - High-level platform architecture
- Deployment Modes - Mode comparison
- Storage Backends - Storage isolation
- Self-Hosting Guide - Deployment security
- Billing Guide - Subscription tiers and Stripe integration