Skip to content

Latest commit

 

History

History
383 lines (337 loc) · 125 KB

security.md

File metadata and controls

383 lines (337 loc) · 125 KB

Security

What Vukem does by default to protect applications, mapped to the OWASP Top 10:2025, and what remains the application's responsibility. Reporting vulnerabilities in Vukem itself: SECURITY.md.

Principles

  1. Secure by default, explicit to loosen. Unsafe behaviour needs an opt-out with a visible name (InsecureSkipX, AddInsecureBypassPattern), never a missing opt-in.
  2. Fail closed. If a check cannot be performed (store down, key missing, policy not registered), the request is denied.
  3. Refuse to boot when misconfigured. Missing APP_KEY in production, debug in production, wildcard CORS with credentials: boot error, not a warning.
  4. Stdlib crypto only. crypto/* and golang.org/x/crypto; no custom algorithms.
  5. Small dependency surface so supply-chain risk stays auditable.

OWASP Top 10:2025 mapping

A01:2025 — Broken Access Control (includes SSRF)

Default Check
Routes are public unless wrapped in auth.Required(); vukem route:list shows the middleware of every route so unprotected routes are visible (TestRoutesListsMiddlewareNames, TestCommands (route:list)) [x]
Policies resolved by Go type; unregistered policy = deny (fail closed), not allow (TestSecurity_A01_UnregisteredPolicyDenies); a T value with no policy of its own uses the *T policy on a copy, never any other type's (TestValueSubjectUsesPointerPolicy) [x]
DenyAsNotFound() to avoid leaking resource existence (IDOR enumeration) (TestGatesAndPolicies) [x]
Row-level tenancy (tenancy) fails closed: a tenant that is missing, unresolvable or not the user's is a 404 (never 403, so ids cannot be probed) and the handler never runs (TestSecurity_A01_CrossTenantPathIs404, TestSecurity_A01_NonMemberAndFailuresAre404, FuzzMiddleware); Scope returns only the context tenant's rows and matches nothing without one (TestSecurity_A01_CrossTenantReadReturnsNothing, TestSecurity_A01_MissingTenantScopeMatchesNothing); Assign stamps the context tenant on insert, overrides the input and refuses without a tenant (TestSecurity_A01_InsertTakesTheContextTenant) [x]
Query builder scopes (Scope(ownedBy(user))) and route-level Authorize make ownership checks one line (TestCtxAuthorizeAndTemplateCan, TestAuthorize) [x]
Mass assignment impossible by construction: models are filled from explicit request structs (Bind[T]), never from raw maps (TestBindFromTags, TestSecurity_A01_AdminMassAssignment) [x]
CORS deny-by-default; * with credentials refused at boot (TestSecurity_A01_CORS) [x]
archive.Zip takes no path and returns derived keys, so a user-supplied archive's entry name can never reach a file operation; an escaping raw name (.., absolute, drive letter) is refused before the key is derived, and control or direction-changing characters in a key are refused because the name reaches the metadata (TestSecurity_A01_ArchiveTakesNoPath, TestZipRefusesUnsafeAndOverlongNames) [x]
Static files and uploads served through os.Root (no ../ traversal); dotfiles and files under dot directories never served; storage.Handler responses carry a sandbox CSP so uploaded HTML/XML cannot script the app origin (inline PDF viewers may need a download link) (TestSecurity_A01_StaticRejectsTraversal, TestSecurity_A01_StorageTraversal, TestSecurity_A01_StorageHandlerHidesDotPaths) [x]
Static site generation (ssg) accepts only absolute URL paths. A scheme, host, query, fragment, NUL, backslash or .. segment (including %2e%2e) is rejected before OutDir is created, and the output is written through os.Root, so a symlink or junction inside OutDir cannot redirect a write outside it and no directory is created through one (TestSecurity_A01_SSGRejectsTraversal, TestSecurity_A01_SSGDoesNotCreateDirectoriesThroughLinks); pages whose output files collide on a case-insensitive file system, segments ending in a dot or space and Windows device names are refused (TestSecurity_A01_SSGRefusesCollidingPaths) [x]
Static site generation replaces OutDir atomically and only when it is empty or was generated by ssg before; a foreign directory is never replaced and a symlink or junction as OutDir is refused with ssg.ErrEscape, so nothing is written through it (TestSecurity_A01_SSGRefusesToReplaceForeignDirectory, TestSecurity_A01_SSGRefusesSymlinkOutDir) [x]
orm.Upsert/UpsertMany never revive a soft-deleted row: a conflict with a trashed row is ErrConflict ("Restore it first") for the update, default and do-nothing forms; OrWhere filters are grouped so Find(pk) can never match another row (TestSecurity_A01_UpsertNeverRevivesTrashedRows, TestSecurity_A01_OrFilterCannotEscapeKey); join, group-by, select-as, UpdateOnly, upsert and WhereHas column and relation names must belong to the model, and raw fragments cannot carry column markers (TestSecurity_A03_JoinRejectsUnknownColumn, TestSecurity_A03_GroupByRejectsUnknownColumn, TestSecurity_A03_SelectAsRejectsUnknownColumnAndAlias, TestSecurity_A03_UpdateOnlyRejectsUnknownColumn, TestSecurity_A03_UpsertRejectsUnknownColumns, TestSecurity_A03_WhereHasRejectsUnknownRelation, TestSecurity_A03_WhereOuterRejectsUnknownColumn, TestSecurity_A03_WhereRawRejectsColumnMarkers, TestSecurity_A03_RawFragmentsCannotCarryMarkers) [x]
broadcast.Subscribe with a PresenceStore fails closed: when the shared store errors the subscription is refused instead of joining untracked (TestSecurity_A01_SubscribeFailsClosedWhenPresenceStoreFails); s3.URL rejects traversal in keys (TestSecurity_A01_URLRejectsTraversal) [x]
The vukem studio SQL explorer builds SQL only from names the schema catalog lists: a table, sort or filter column outside it is refused before any statement is sent, identifiers are quoted by the dialect, values are bound parameters, operators come from a fixed table and LIKE escapes %, _ and ! (TestSecurity_A03_StudioRejectsUnknownIdentifiers, TestSecurity_A03_StudioEscapesLikeWildcards, TestGridSQL, TestAPICellsHoldingHTMLAreJSONText). The console runs one statement (a quote, comment or dollar-quote the checker cannot follow is refused) and, without write mode, only a read (SELECT, WITH, SHOW, EXPLAIN, DESCRIBE, TABLE, VALUES, never with INTO; DDL is refused by that check because MySQL and MariaDB commit implicitly before it and so end a read-only transaction; it also refuses a call to a function that locks, sleeps, signals, sets a value or reads a server file, such as pg_sleep, pg_terminate_backend, GET_LOCK, SLEEP, LOAD_FILE or load_extension, by a per-dialect deny list that is a second layer and not exhaustive), inside a read-only transaction that always rolls back (PostgreSQL, MySQL) or on the read-only reader connection (SQLite; an in-memory database needs write mode), cuts results at 1000 rows and 30 s, and with --write only an explicit write switch commits, on success, with an audit line that holds the size of the statement and no row values (TestSecurity_A01_StudioConsoleIsReadOnly, TestReadOnlyStatement, TestSecurity_A01_StudioConsoleRefusesMultipleStatements, TestSecurity_A01_StudioConsoleRefusesInMemoryReadOnly, TestAPIQueryRejectsWriteWithoutFlag, TestAPIQueryWriteIsAtomicAndNeedsTheSwitch, TestAPIQueryWriteWithFlagIsAuditedWithoutTheStatement, TestConsoleTruncatesAt1000Rows); a database error never reaches the interface, and the server log holds only its class, never the statement or the driver text (TestAPIQueryErrorsHideTheDatabase, TestConsoleLogsNeverHoldTheStatementOrAValue); row editing (insert, update, delete) exists only with --write (without it the routes answer 404 and the interface shows no edit control), only on a table with a primary key, changes exactly one row or rolls back, needs the primary key typed back to delete, takes column names only from the catalog and never changes the primary key, coerces each value by the declared column type before any SQL is sent (a bad value, NULL on a NOT NULL column and binary columns are refused), never offers a cut or binary value for editing, audits every attempt with names and counts but no values, and rides on the session cookie and the cross-origin check of every other request (TestAPIWriteRoutesAbsentWithoutFlag, TestSecurityAPISQLWriteNeedsAPrimaryKey, TestSecurityAPISQLDeleteNeedsTheTypedKeyAndIsAudited, TestSecurityAPISQLWriteRejectsUnknownColumnsAndBadValues, TestAPIWriteAudited, TestSecurityAPI, TestCoerce); the row export is capped like the other exports and neutralizes spreadsheet formulas in CSV (TestAPIExportRows) [x]
The vukem studio MongoDB and Redis explorers take fixed filters and command lists: a Mongo filter refuses operator fields and object values, escapes regular expressions and blocks server-side JavaScript ($where, $function, $accumulator) and write stages ($out, $merge, which need --write); Redis runs only listed commands (write commands need --write, some subcommands are restricted, and EVAL, FUNCTION, CONFIG, FLUSH* and KEYS are never allowed) and scans instead of KEYS; both consoles are refused at the HTTP boundary too, whatever the interface checked first; exports neutralize spreadsheet formulas and every write is audited without its values, the console of Redis recording only the command name and the argument count (TestSecurity_A03_StudioMongoRejectsOperatorFields, TestSecurity_A03_StudioMongoRejectsObjectValues, TestSecurity_A03_StudioMongoEscapesRegex, TestSecurity_A03_StudioMongoBlocksServerJS, TestSecurity_A01_StudioMongoBlocksWriteStagesReadOnly, TestSecurity_A01_StudioRedisAllowsOnlyListedCommands, TestSecurity_A01_StudioRedisWriteCommandsNeedWriteFlag, TestSecurity_A01_StudioRedisSubcommandsRestricted, TestSecurity_A04_StudioRedisNeverUsesKEYS, TestSecurityConsoleRefusalsThroughTheAPI, TestSecurity_A03_StudioExportNeutralizesFormulas, TestAPIWriteAudited, TestAPIMongoWrite, TestAPIRedisConsoleAuditsOnlyTheCommandName, TestAPIWriteRoutesAbsentWithoutFlag, TestAPIWriteNeedsConfirm) [x]
Signed URLs (HMAC, expiry) for temporary downloads and email verification (TestSecurity_A01_SignedURLTampering) [x]
signed.Signer.Token/Open sign opaque payloads (cursors) with HMAC-SHA256 under the URL keys and their rotation; a changed payload or signature, another key, a signed-URL MAC (domain-separated) or a token over 8 KiB is ErrInvalid, compared in constant time (TestSecurity_A08_TokenRejectsTampering) [x]
signed.New and social.New panic on a key shorter than 32 bytes, so an empty key (e.g. an ignored app.DeriveKey error) never produces forgeable HMACs (TestSecurity_A04_SignedRefusesWeakKeys, TestSecurity_A04_SocialRefusesWeakKeys) [x]
Client IP (c.IP(), used by rate limits, login throttles and logs) reads X-Forwarded-For only from TrustedProxies peers, across every header line, right to left; a non-IP entry falls back to the peer address (TestSecurity_A01_IPIgnoresSpoofedForwardedFor) [x]
TRUSTED_PROXIES (comma-separated CIDRs or IPs) and vukem.WithTrustedProxies (prefixes from code, such as contrib/cloudflare.Ranges(); an invalid prefix refuses the boot, TestSecurity_A01_TrustedProxiesFromOption) are the only sources of trusted proxies in apps built by vukem.New; unset trusts nobody, so a spoofed X-Forwarded-For from any peer is ignored (TestSecurity_A01_TrustedProxiesFromEnv); a /0 entry (0.0.0.0/0, ::/0) logs a warning at boot (TestTrustedProxiesWarnsOnCatchAll). Client IPs from headers are returned in one canonical form (IPv4-mapped addresses unmapped, IPv6 compressed and lowercased) so rate-limit keys cannot be varied by spelling [x]
With APP_ENV=production and TRUSTED_PROXIES empty, the first request from a private, CGNAT (100.64.0.0/10) or loopback peer that carries X-Forwarded-For or X-Real-IP logs one WARN per process (its text contains every client shares one rate-limit bucket): the app is most likely behind a proxy, so c.IP() is the proxy address for every client. The header is only detected, never trusted, and later requests log nothing (TestSecurity_A09_WarnsOnceOnProxyHeadersWithoutTrustedProxies) [x]
contrib/cloudflare: CF-Connecting-IP counts only through CLIENT_IP_HEADER from Cloudflare's embedded ranges (WithTrustedProxies(cloudflare.Ranges()...)); OriginLock answers 403 to every peer outside Cloudflare's ranges and the allow list, reading the peer address only (TestSecurity_A05_OriginLockRefusesDirectRequests); cloudflare.Headers reads country, Ray ID and bot headers only from a Cloudflare peer and drops malformed values (TestSecurity_A01_VisitorHeadersOnlyFromCloudflare); CachePolicy never marks a response cacheable at the edge when the request carries Authorization or Cookie, the response sets a cookie or its own Cache-Control, or the status is not 200 (TestSecurity_A01_CachePolicySkipsPersonalResponses); Purger errors never contain the API token (TestPurger); Access accepts only RS256 tokens signed by the team's keys for the configured issuer and AUD tag and not expired, and denies when the keys cannot be fetched (TestSecurity_A07_AccessJWTRejected, TestSecurity_A07_AccessFailsClosedWithoutKeys, TestNewAccessRefusesUnsafeConfig); a downloaded range list that does not parse, is empty or holds a /0 is an error (TestFetchRanges, FuzzParseRanges) [x]
web.ClientIP(r) gives plain middleware the c.IP() answer with the same trusted-proxy rules, and trusts no proxy without services on the context (TestSecurity_A01_ClientIPFollowsTrustedProxies); security/crawlers.Verifier accepts a crawler only when the reverse DNS name is a subdomain of the engine's documented domains and its forward lookup gives the IP back, fails closed on every DNS error, bounds lookups by a timeout and caches results per IP in a capped map (TestSecurity_A07_CrawlerNeedsForwardConfirmedReverseDNS, TestVerifierCaches) [x]
CLIENT_IP_HEADER (web.Services.ClientIPHeader, e.g. X-Real-IP) replaces X-Forwarded-For as the client IP source but is read only from TRUSTED_PROXIES peers, and only when it holds exactly one line with one IP; otherwise c.IP() is the peer address. A bad header name, a list header (X-Forwarded-For, Forwarded) or a missing TRUSTED_PROXIES refuses the boot (TestSecurity_A01_ClientIPHeaderOnlyFromTrustedProxies, TestSecurity_A01_ClientIPHeaderFromEnv, TestSecurity_A02_TrustedProxiesMisconfigurationRefusesBoot) [x]
ratelimit.ByIP keys IPv4 per address (IPv4-mapped IPv6 counts as IPv4) and IPv6 per network, /64 by default (RATE_LIMIT_IPV6_PREFIX, 1–128, web.Services.IPv6Prefix, where 0 or an out-of-range value means /64; ratelimit.IPKey for custom keys, used by the login and two-factor throttle keys of the examples and scaffolds), because one client usually owns a whole /64 and could take a fresh address, and a fresh bucket, on every request; a prefix outside 1–128 refuses the boot; behind a reverse proxy with TRUSTED_PROXIES unset, c.IP() is the proxy's address, so ratelimit.ByIP puts every client in one bucket and one noisy client can lock out the rest (set TRUSTED_PROXIES; production boots log a warning when a proxy header is seen from a private peer) (TestSecurity_A06_ByIPGroupsIPv6ByPrefix, TestSecurity_A06_RateLimitIPv6RotationSharesBucket, TestSecurity_A06_RateLimitIPv6PrefixFromEnv, TestIPKey, TestSecurity_A02_TrustedProxiesMisconfigurationRefusesBoot) [x]
Open redirects: web.SafeRedirect and c.Back accept only relative paths and same-host URLs, and check the resulting path before and after http.Redirect cleans it, so //evil.com, /\evil.com, /./\evil.com, /./\/..# and https://app//evil.com fall back (TestSecurity_A01_SafeRedirectBlocksOpenRedirects, FuzzSafeRedirect) [x]
The devtools dashboard (/_vukem) answers only a loopback peer with a loopback Host and no proxy headers, X-Forwarded-Proto, X-Forwarded-Port and Via included (which also defeats DNS rebinding); others get a plain 404. DEVTOOLS_INSECURE_ALLOW_REMOTE=true lifts the check (TestSecurity_A01_DevtoolsLoopbackOnly) [x]
middleware.LoopbackOnly(port) admits a loopback peer with no proxy header, Host exactly localhost, 127.0.0.1 or [::1] on the given port, and an Origin, when sent, that is the same kind of http origin; everything else gets 403 (TestSecurity_A01_LoopbackOnlyRefusesRebindingHostsAndOrigins) [x]
SSRF: httpclient.Safe() dialer rejects loopback, private, link-local and metadata (169.254.169.254) addresses after DNS resolution, including IPv6 forms that embed or translate IPv4 (IPv4-mapped, -compatible and -translated, NAT64, 6to4, Teredo), ignores proxy environment variables, limits redirects and re-checks each hop; it is the client for app features that fetch user-supplied URLs (the framework itself fetches none); an Options.WrapTransport wrapper (tracing) sits above the dialer check, so a delegating wrapper cannot bypass it, and a wrapper returning nil fails every request with ErrNilTransport instead of falling back to http.DefaultTransport (TestSecurity_A01_SSRFAddresses, TestSecurity_A01_SSRFLoopbackAndRedirect, TestSecurity_A01_SSRFWrappedTransport, TestSecurity_A01_SSRFNilWrapTransportFailsClosed) [x]
GraphQL mutations never run over GET (405 with Allow: POST), so links and image tags cannot change state; POST requires application/json (TestSecurity_A01_GraphQLMutationsRequirePOST) [x]
Idempotency keys are scoped to the caller, so a reused key never replays another user's response (TestSecurity_A01_IdempotencyScopedToCaller); by default the scope is the authenticated principal (auth.Principal), so a rotated token keeps its keys and a request without that principal (a revoked token) cannot replay them, else a SHA-256 of Authorization, never the raw credential (TestSecurity_A01_IdempotencyScopedToPrincipal); guard and user id are length-prefixed so no pair collides with another (TestSecurity_A01_IdempotencyScopeHasNoSeparatorCollisions), and an auth.Tokens prefix is stripped before hashing (id and secret kept) so it cannot fork a token's scope (TestSecurity_A01_IdempotencyTokenPrefixDoesNotForkScope), and a key with an empty scope (anonymous or cookie session without Scope) is refused with 400 (TestSecurity_A01_IdempotencyRefusesAnonymousScope); a store outage refuses the request instead of risking a duplicate (TestSecurity_A04_IdempotencyFailsClosed); a replay sends only the stored representation headers (Content-Type and IdempotencyOptions.ReplayHeaders), never the first request's Set-Cookie, request id or rate-limit headers (TestSecurity_A01_IdempotencyReplayKeepsPerRequestHeaders); Set-Cookie, Authorization, Proxy-Authorization, Proxy-Authenticate and WWW-Authenticate are dropped even when listed in ReplayHeaders (TestSecurity_A01_IdempotencyNeverReplaysCredentialHeaders) [x]
drivers/s3 presigned GET/PUT URLs sign the validated key and expire after 1 s to 7 days; anything outside that range is refused (TestSecurity_A01_S3PresignExpiryBounded) [x]
drivers/s3 PresignPutWith signs Content-Type and Content-Length: an upload with another type or size is rejected with 403 (TestSecurity_A01_S3PresignPutBindsTypeAndSize) [x]
WebSocket upgrades (drivers/websocket) are same-origin only: a browser Origin outside the request host and the explicit AllowedOrigins allowlist gets 403 before the handler runs; AllowedOrigins("*") or a malformed pattern refuses every upgrade; accepting any origin needs InsecureSkipOriginCheck() (TestSecurity_A01_WebSocketOriginChecked) [x]
Broadcast channels (broadcast, SSE and drivers/websocket transports) fail closed: private and presence channels need a matching rule and a user, public channels must be declared, a rule error or gate denial (including 404) answers 403, and an SSE request with one refused channel streams nothing; channel names are limited to 128 characters of A-Z a-z 0-9 _ - = @ . : with no empty dot segment such as private-user. (400 otherwise, and Publish refuses them too), so lists, topics and frames cannot be forged (TestSecurity_A01_BroadcastPrivateChannelsAuthorized, in both modules) [x]
GraphQL subscriptions (contrib/graphql) authorize like the rest of the app: graphql.ServeWS runs on the same-origin drivers/websocket upgrade, connection_init goes through the OnConnect hook (an error closes with 4403) and no operation runs before connection_ack (4401); FromBroadcast subscribes with broadcast.Server.Subscribe in the operation's context, so a channel denied by its rule, or a client without a user, fails the subscription with FORBIDDEN and receives no events (TestSecurity_A01_GraphQLSubscriptionsAuthorized) [x]
Admin panel (admin): every route requires the guard, the panel ability (admin) and the policy ability for the action (viewAny, view, create, update, delete); a missing ability, policy or authorizer is a 403, and guests are sent to login (TestSecurity_A01_AdminRequiresAuthAndPolicy, TestSecurity_A01_AdminRequiresAbility); its forms are CSRF-checked with the session-token fallback (TestSecurity_A01_AdminCSRF); custom actions (Resource.Actions) need the policy ability named after the action on every record, go through a CSRF-checked confirmation, and a bulk selection with one denied, missing or malformed record (or more than 100 ids) runs nothing (TestSecurity_A01_AdminActionsRequirePolicy); opt-in hardening fails closed: Config.TwoFactor false or erroring is a 403 (TestSecurity_A07_AdminRequiresTwoFactor), a session older than Config.MaxSessionAge is invalidated and sent to login (TestSecurity_A07_AdminMaxSessionAge), a session idle past Config.IdleTimeout without a guarded admin request is invalidated (TestSecurity_A07_AdminIdleTimeout), and a client IP outside Config.AllowCIDRs (or unparsable) is a 403 before any login redirect (TestSecurity_A01_AdminAllowCIDRs); Panel.Guard is that stack for routes the app registers beside the panel (TestSecurity_A01_AdminGuardCoversCustomRoutes) [x]
Admin panel hardening switches (admin): Config.DenyStatus 404 answers an IP outside Config.AllowCIDRs as Not Found, hiding the panel (TestSecurity_A01_AdminDenyStatusHidesPanel); Config.TwoFactorRedirect must be a local path and redirects only on a clean false, an erroring 2FA lookup stays 403 (TestSecurity_A07_AdminTwoFactorRedirect); Panel.TrackIdle ends idle panel sessions on the routes it wraps and leaves sessions that never used the panel untouched (TestSecurity_A07_AdminTrackIdle); Panel.Clock applies the idle and absolute caps to every request of a user holding the panel ability, panel visited or not, and never writes the session of other visitors (TestSecurity_A07_AdminClockCoversEveryAdminRequest); Config.TwoFactorFlash needs TwoFactorRedirect (TestSecurity_A07_AdminTwoFactorRedirectFlash) [x]
llms.txt (llmstxt): titles, notes and the summary cannot inject Markdown (line breaks flattened, control and format characters dropped, link brackets escaped), URLs must be absolute http(s) or root-relative and are percent-escaped, nothing from a Doc reaches a header, and llms-full.txt is size-capped and never sends a Content error to the client (TestSecurity_A03_LLMsTxtMarkdownInjection) [x]
Admin forms write only z schema keys: every primary-key column (one or a composite key), timestamps, hidden, read-only and unknown fields are never assigned; a schema key for a primary-key column or a timestamp is a boot error (TestSecurity_A01_AdminMassAssignment, TestCompositeKeyURLMatchesEveryColumn) [x]
Inertia Config.SharedType makes the adapter fail closed: inertia.New refuses a Config.Shared key the struct does not declare, and a request that adds one with inertia.Share (including middleware such as flags.Share, which shares flags) answers 500 instead of sending an untyped prop; the response does not name the key, the log does (TestSecurity_A01_InertiaSharedTypeFailsClosed). Declare every shared key in the struct when you set it; a dotted key is checked by its first segment [x]
Feature flags (flags): a flag locked in code always has its code default, whatever is stored (globally or for a scope) and whichever unlocked copy reads it, and Set/Put/Reset refuse it with ErrLocked (TestSecurity_A01_LockedFlagsKeepCodeDefault); the admin Flags page and its writes need the manageFlags ability and the CSRF check, and a crafted write to a locked flag is a 403 and a flags.locked_write security event (TestSecurity_A01_AdminFlagsRequireAbilityAndRespectLocks); views and Inertia receive only the allowlisted flags passed to Expose/Share (TestSecurity_A01_FlagsExposeOnlyAllowlist); scopes are validated (a-z 0-9 : . _ -, 1-191 bytes) on read (default) and write (ErrInvalid) (TestInvalidScopeReadsDefault, TestSetPutReset) [x]
The vukem bench --ui dashboard answers a loopback peer with a loopback Host, no proxy header and no cross-site request, listens on 127.0.0.1 only, and has no control: every route is a GET TestSecurity_A01_BenchUIRejectsNonLoopbackPeer, TestSecurity_A01_BenchUIRejectsProxyHeaders, TestSecurity_A01_BenchUIRejectsForeignHost, TestSecurity_A01_BenchUIRejectsCrossSiteRequests, TestSecurity_A01_BenchUIIsReadOnly
vukem update never rewrites a project file beyond go.mod, go.sum, package.json and the lockfile: with --check or --dry-run nothing at all, otherwise also .vukem/upgrade/; registry answers are size-bounded and JS versions are exact, never pre-release TestSecurity_A01_UpdateNeverWritesProjectFiles

App responsibility: call Authorize in every handler that touches owned data; scope queries by tenant/user.

A02:2025 — Security Misconfiguration

Default Check
An unset or empty APP_ENV is production (TestSecurity_A05_MissingAppEnvIsProduction, TestSecurity_A05_MissingAppEnvBootsAsProduction), so a deploy that forgets it gets the production checks and defaults, never the development ones; the vukem new scaffolds write APP_ENV=development to .env and vukem doctor warns when it is missing [x]
Boot refuses: a missing APP_KEY in production or when APP_ENV is unset/empty (only an explicit development/test tolerates it, or an app built with WithKeyOptional, or warmup mode, which never boots providers nor serves (Boot and Run return ErrWarmupRun; a warmup app's Router or Handler must never be exposed): codegen:* commands; key-derived features still fail closed there), a short or malformed one anywhere (TestSecurity_A02_ProductionRequiresAppKey, TestSecurity_A02_WarmupToleratesOnlyAMissingKey), an APP_ENV other than development, test or production (a typo would skip every production check), APP_DEBUG=true with APP_ENV=production, CORS wildcard + credentials, cookies without Secure in production (TestSecurity_A02_BootRefusesMisconfiguration, TestSecurity_A01_CORS, TestSecurity_A02_ConfigChecks) [x]
@file:<path> secrets (Docker/Kubernetes) resolve in .env files and in the process environment; an unreadable reference (missing file, directory, device or FIFO, more than 1 MiB, empty path, references disabled) is a config.Load error (and a flags.New error for FLAG_*), never a default or the literal reference; a FIFO or terminal is refused before it is opened, so it cannot block the boot. Trust boundary: configuration values (process environment and .env files) are trusted operator input. @file: applies to every variable the app reads, follows symlinks, and resolves a relative path against the process working directory, so whoever can set an environment variable can make the app read any regular file the process can read. Write @@file: for a literal value that starts with @file: (one leading @ is removed). (TestSecurity_A02_ProcessEnvFileRefFailsClosed, TestSecurity_A02_ProcessEnvFileSecrets, TestSecurity_A02_FlagFileRefReadErrorFailsClosed, TestSecurity_A02_FileRefRefusesFIFOWithoutBlocking, TestLoadSourceFileRefEscape) [x]
Feature flags: FLAG_<NAME> for a locked flag, a FLAG_<NAME> value of the wrong kind, a FLAG_* key in .env files that names no registered flag, and invalid or duplicate flag names stop vukem.New (TestSecurity_A02_LockedFlagEnvOverrideIsBootError, TestNewRejectsMisconfiguration, TestFlagsFromConfig) [x]
An invalid TRUSTED_PROXIES entry, or TRUST_FORWARDED_PROTO=true without TRUSTED_PROXIES, refuses the boot (TestSecurity_A02_TrustedProxiesMisconfigurationRefusesBoot); X-Forwarded-Proto: https turns on HSTS only from a trusted peer and only as a single header line; SecureHeadersConfig.Validate refuses TrustForwardedProto without TrustedProxies (TestSecurity_A02_TrustForwardedProtoOnlyFromTrustedProxies, TestSecurity_A02_ForwardedProtoOnlyFromTrustedProxies); web.Ctx.IsHTTPS, which builds Inertia's X-Inertia-Location, follows the same rule (TestSecurity_A02_IsHTTPSTrustsOnlyProxies) [x]
SecureHeaders built without TrustedProxies trusts no peer for X-Forwarded-Proto, so any client can no longer turn HSTS on by claiming https; Validate and the app boot already refuse the combination, and the middleware fails closed even when it skipped them (TestSecurity_A02_ForwardedProtoNeedsTrustedProxies) [x]
HSTS on plain-HTTP requests is off by default. HSTS_FORCE=true (SecureHeadersConfig.HSTSForce) is an explicit opt-in for TLS proxies whose range cannot be trusted: HSTS on every response that reaches SecureHeaders, validated in every environment (a boot error unless APP_URL is https://) and applied only in production (a boot warning otherwise, TestHSTSForceWarnsOutsideProduction); Validate refuses it with HSTS disabled (TestSecurity_A02_HSTSForce, TestSecurity_A02_HSTSForceFromEnv, TestSecurity_A02_TrustedProxiesMisconfigurationRefusesBoot) [x]
http.Server always has ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, MaxHeaderBytes (TestSecurity_A02_ServerTimeouts) [x]
Request headers are capped at 64 KiB (DefaultMaxHeaderBytes, not Go's 1 MiB: less memory per connection, still above what browsers send and nginx/Node.js forward); HTTP_MAX_HEADER_BYTES sets 4096–1048576 and anything else refuses the boot; larger requests get 431 (TestSecurity_A02_MaxHeaderBytes, TestSecurity_A02_TrustedProxiesMisconfigurationRefusesBoot) [x]
Security headers middleware on by default: X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, X-Frame-Options: DENY + CSP frame-ancestors 'none', Cross-Origin-Opener-Policy: same-origin, Strict-Transport-Security (HTTPS only, configurable) (TestSecurity_A02_SecureHeaders, TestPageWorksUnderTheDefaultSecureHeaders) [x]
Content-Security-Policy builder with per-request nonces ({{ cspNonce }}), starter ships a strict policy; Vite tags get the nonce (TestSecurity_A02_ViteTagsCarryNonce) [x]
Analytics (analytics package) is off until configured and adds only the enabled providers' exact origins to the CSP; GA4 starts with every Consent Mode v2 signal denied and loads gtag.js only after consent (TestSecurity_A02_AnalyticsConsentDeniedByDefault); every env value is validated at boot and escaped in the tags (TestSecurity_A05_AnalyticsEscapesConfig) [x]
boost:mcp database_query accepts one SELECT/WITH/EXPLAIN statement without write keywords, INTO or calls to file, backend-control, sleep and extension functions, and runs it on a read-only connection (SQLite query_only, read-only transactions elsewhere) (TestSecurity_A05_BoostQueryIsReadOnly, TestSecurity_A05_BoostQueryRefusesSideEffectingSelects) [x]
The Inertia page object is embedded as JSON with <, >, & and / escaped, so prop data cannot close its <script> (TestSecurity_A05_InertiaPageScriptCannotBreakOut) [x]
The default CSP is nonce-only for scripts and styles (no 'unsafe-inline', 'unsafe-eval' or *); SecureHeadersConfig.CSPSources adds origins or 'sha256-…' hashes per directive but refuses 'unsafe-*' keywords (except 'wasm-unsafe-eval', accepted only in script-src, script-src-elem and worker-src, never in the default policy), static nonces, \ and non-ASCII characters, * hosts (*, *:*, https://*), wildcards over fewer than two labels (*.com), any host wildcard in script directives, and unsafe schemes (scheme-only sources only as https:/data:/blob: in img-src/media-src/font-src and https:/wss: in connect-src); a new directive starts from its CSP fallback (script-src-elem from script-src, keeping the nonce); Validate reports refusals at boot, SecureHeaders drops them with one warning; ReportURI must be an https URL without credentials or a single-/ path and adds report-uri/report-to; CSPPaths gives a path prefix its own full policy (longest prefix, whole path segments, matched on the cleaned path, so /worker never covers /workerfoo or /app/../worker), and an invalid entry is dropped to the default policy (TestSecurity_A02_DefaultCSPNonceOnly, TestSecurity_A02_CSPSourcesRefuseUnsafe, TestSecurity_A02_WasmUnsafeEvalIsOptIn, TestSecurity_A02_CSPPaths, TestSecurity_A02_CSPPathsInvalidIsDropped) [x]
Vukem's built-in pages (status/error pages for 404, 405, 403, 422, 500, the htmx fragment, the development debug page) render under the default nonce-only CSP: no style= or on*= attributes, and every <style> carries the request nonce (TestSecurity_A02_BuiltinErrorPagesUnderCSP) [x]
DefaultMiddlewareWith options only extend or skip what they name: the SecureHeaders result is validated at boot, bypass patterns must be valid ServeMux patterns, CSRF bypasses are logged, and Stateless keeps CSRF on (TestSecurity_A02_DefaultMiddlewareWithRefusesBadOptions, TestDefaultMiddlewareWithStateless); APIMiddlewareWith validates its SecureHeaders result the same way (TestSecurity_A02_APIMiddlewareWithRefusesBadOptions) [x]
The CSP allows the Vite dev server origin only while its hot file exists outside production; the origin must be a bare http(s)://host:port so it cannot inject directives (TestSecureHeadersDevServer, TestSecurity_A05_ViteRejectsUnsafeHotURL) [x]
archive.Zip refuses an archive on the uncompressed size its central directory declares, per entry and in total, without inflating anything, and Entry.Open is bounded by that declared size; two entries resolving to one key are refused rather than silently overwritten (TestSecurity_A05_ArchiveEntriesCannotExceedTheirDeclaredSize, TestZipRefusesABombOnItsDeclaredSize, TestZipRefusesCollidingKeys) [x]
Server-sent event fields (id, event, data) cannot carry CR/LF into new fields (TestSecurity_A05_SSEFieldInjection) [x]
vukem migrate in production refuses a pending migration that drops a table or a column (a Rebuild that leaves a column out included) unless --allow-destructive is passed; it reads the statements the migration generates, Schema.Raw included, and a development or test environment is not gated (TestSecurity_A05_MigrateRefusesDestructiveInProduction, TestDestructive) [x]
Maintenance mode stores only the SHA-256 of the bypass secret; the bypass cookie is an HMAC (key derived from APP_KEY) bound to that secret, HttpOnly, SameSite=Lax, Secure in production; an unreadable state file keeps the app down (TestSecurity_A01_MaintenanceBypassNeedsSecret) [x]
JWTs: algorithm pinned per key (no none, no HMAC/public-key confusion), exp required, weak keys refused (TestSecurity_A04_JWTAlgorithmConfusion); with a RemoteJWKS or any jwt.SharedKeySet (keys an identity provider shares across its clients) Audience and Issuer are required: Verifier.Err() reports the gap, jwt.NewGuard panics at boot on it, and Verify refuses every token with a bare jwt.ErrInvalid; VerifyOptions.Nonce (opt-in) binds an ID token to its sign-in (TestSecurity_A07_JWTNonceBinding); InsecureSkipAudience / InsecureSkipIssuer opt out (TestSecurity_A07_RemoteJWKSRequiresAudienceAndIssuer); refresh tokens stored hashed, single use, reuse revokes the family (TestSecurity_A07_RefreshConcurrentRotationSingleWinner); jwt.Guard fails closed like the token guard: a key set outage (jwt.ErrKeysUnavailable) or a user lookup error other than not found answers 503 problem+json without the cause, never 401, and auth.Required does not fall through to the next guard (TestSecurity_A04_JWTGuardOutageIs503, TestSecurity_A04_JWTGuardOutageStopsRequired); a token whose header carries a crit member (even empty) is refused, since no critical extension is understood (RFC 7515 4.1.11, TestSecurity_A04_JWTRejectsCriticalHeaders); OIDC ID tokens are held to the same rule (TestSecurity_A07_IDTokenChecks) [x]
Stripe: the API key is never printed (TestSecurity_A09_StripeKeyRedacted); webhooks need a valid Stripe-Signature within ±5 minutes and each event id is processed once (TestSecurity_A08_StripeWebhookSignature); a Connect webhook must verify against one of the configured Secrets and an empty secret is a boot error (TestSecurity_A08_StripeConnectWebhookSecrets); Stripe-Account must be an acct_ id (transfer, reversal and refund ids tr_/trr_/re_/pyr_ + alphanumerics) and an Idempotency-Key printable ASCII up to 255 bytes, or the call fails before anything is sent (TestSecurity_A03_StripeRequestHeadersValidated); Call paths must start with /v1/ or /v2/ without dot segments, query, fragment or control characters (TestSecurity_A03_StripeCallPathValidated); platform-only Connect methods (v1 and v2 accounts, account and login links, transfers and transfer reversals) refuse a connected-account scope (TestSecurity_A01_StripePlatformOnlyRefusesAccountScope) [x]
install:billing: POST /stripe/webhook runs outside sessions and CSRF but only with a verified Stripe-Signature, each event once, and answers 503 without a signing secret; access comes from webhooks (Checkout payment_status gated), never the success page; Subscribed/OnPlan deny on a missing user or a database error; missing Stripe settings stop production at boot; the API base URL can only be overridden in tests (TestSecurity_A08_BillingWebhookOutsideCSRFButSigned) [x]
The Vite hot file is ignored in production (TestSecurity_A02_ViteHotFileIgnoredInProduction) and must hold an http(s) URL (TestSecurity_A05_ViteRejectsUnsafeHotURL) [x]
Route.SecretParams(names...) writes {name} instead of the value of those path parameters in every log line of the request (request line, handler error log, security-event log and security.Event.Path); web.LogPath(r) gives the redacted path to app logs (TestSecurity_A09_SecretParamsNeverLogged); Router.SecretPaths(patterns...) does the same for a path served outside registered routes, such as a UseServer webhook (TestSecurity_A09_SecretPathsNeverLogged); the install:auth scaffolds mark token on the reset route (TestSecurity_A09_ScaffoldSecretParams) [x]
Debug error page only in development; production errors never include stack traces, SQL or config (TestSecurity_A02_DebugPageOffInProduction); the debug page redacts credentials and escapes error text and source (TestSecurity_A09_DebugPageRedactsSecrets) [x]
Admin pages run under a strict CSP: embedded htmx and CSS, no inline scripts, styles or handlers, Cache-Control: no-store, and a strict policy when the app sent none (TestSecurity_A02_AdminStrictHeaders) [x]
vukem about prints effective security settings (secrets redacted) to review deployments (TestCommands (about)) [x]
Devtools (vukem.WithDevtools(), DEVTOOLS=true) is a boot error with APP_ENV=production (TestSecurity_A02_DevtoolsRefusedInProduction) [x]
No default credentials, no sample admin user, .env git-ignored, .env.example without secrets (TestSecurity_A02_StarterShipsNoSecrets) [x]
The starter Dockerfile runs as a non-root user and sets no secrets; its .dockerignore keeps .env and .env.* out of the build context (TestSecurity_A02_DockerIgnoresSecrets) [x]
Destructive commands (migrate:fresh, migrate:reset, db:wipe, db:seed) require --force in production (TestSecurity_A02_DestructiveCommandsNeedForce); db:seed checks it after parsing the seeder names and flags, before any seeder runs, a --class without a name is a usage error instead of selecting every seeder, and a seeder cannot define its own --force, --class, --help or -h flag (TestSecurity_A02_SeederFlagsCannotShadowForce, TestSeedCommandSelectsSeedersAndPassesFlags) [x]
/openapi.json (vukem.ServeOpenAPI) and the API reference UI (apidocs.Serve) are not served in production unless OPENAPI_IN_PRODUCTION=true, or one route opts in with vukem.OpenAPIOptions.InProduction / apidocs.Config.InProduction (TestSecurity_A02_OpenAPIOffInProduction, TestSecurity_A02_APIDocsOffInProduction); the vendored Scalar bundle is pinned by SHA-256 and runs with telemetry and remote fonts off [x]
The API reference page keeps a nonce-only CSP (no 'unsafe-inline' styles): Scalar's run-time <style> elements get the request nonce and only plain size/overflow style attributes go through the CSSOM (anything else, and all HTML from the OpenAPI document, stays blocked except an attribute that is exactly numeric --line-count/--line-digits variables; TestPageShim runs the shim against hostile values with Node.js when installed; TestBrowser_APIDocsNoCSPViolations loads the page in headless Chromium and fails on any CSP console error); the page policy (apidocs.CSP) only adds data: fonts and every other route keeps the default policy (TestSecurity_A02_APIDocsCSPNonceOnly) [x]
GraphQL (contrib/graphql): in production the explorer page is not registered and __schema / __type introspection is rejected unless InsecureExplorerInProduction / InsecureIntrospectionInProduction opt in; the explorer is embedded (no CDN) and runs under its own nonce CSP (TestSecurity_A02_GraphQLExplorerOffInProduction); a handler built with Schema.Handler rejects introspection unless HandlerConfig.Introspection opts in (TestSecurity_A02_GraphQLHandlerIntrospectionOptIn) [x]
JSON-RPC (jsonrpc): batches over MaxBatch are refused whole, bodies over MaxBodyBytes are a 413, deep nesting is a parse error (TestSecurity_A04_JSONRPCBatchLimit, TestSecurity_A04_JSONRPCDeepNesting); internal errors and panics are logged and answered as -32603 without detail (TestSecurity_A05_JSONRPCInternalErrorsHidden); a failing Guard stops the method, notifications included (TestSecurity_A01_JSONRPCGuards) [x]
MCP (mcp): the HTTP endpoint refuses an Origin that is not listed (403, TestSecurity_A05_MCPOrigin), refuses to start without a Verifier unless InsecureNoAuth is set or with a Resource that is not an absolute URL (TestSecurity_A05_MCPWeakConfigRefused), answers 401 with a WWW-Authenticate that points at the protected resource metadata, refuses wrong-audience and expired tokens and tokens in the query string, and exposes the verified TokenInfo only through the context (TestSecurity_A01_MCPAuth); scoped tools stay shut without a token (TestSecurity_A01_MCPScopedToolsShut); requestState is HMAC-signed and bound to the caller, the method, the target and the arguments, so an input_required answer cannot be replayed on another request (TestSecurity_A01_MCPRequestStateBound); header and body must agree (TestSecurity_A04_MCPHeaderMismatch); oversized, malformed, batched and deeply nested messages are refused on both transports and FuzzHTTPHandler covers the HTTP parser (TestSecurity_A04_MCPMalformedAndOversized, TestSecurity_A04_MCPStdioRobustness); a tool panic or error returns a bare -32603 and is logged, never shown (TestSecurity_A05_MCPToolErrorsHidden) [x]
OAuth server (oauth): codes are single use and bound to client, redirect URI, PKCE challenge and resource, and replay revokes the grant (TestSecurity_A07_CodeReplayRevokesTheGrant); PKCE S256 is required and a wrong verifier burns the code (TestSecurity_A07_PKCE); redirect URIs match exactly and an invalid one is never redirected to (TestSecurity_A01_RedirectURIAndOpenRedirect); resource is required, allow-listed and bound (TestSecurity_A01_ResourceIsRequiredAndBound); concurrent refresh reuse lets one use win and revokes the grant (TestSecurity_A07_ConcurrentRefreshReuse, TestSecurity_A07_RefreshReuseAndRevocation); alg: none, HMAC confusion, foreign keys, issuers and audiences are refused (TestSecurity_A02_AccessTokenAlgorithms); the consent form is bound to user and request by an HMAC token (TestSecurity_A01_ConsentCSRF); client secrets compare in constant time (TestSecurity_A07_ClientAuthentication); metadata document fetches refuse loopback, private, link-local, IPv6 and IPv4-mapped addresses and follow no redirects (TestSecurity_A10_MetadataDocumentSSRF); a metadata-document client never gets an authorization error redirected before sign-in and consent, only a 400 (TestSecurity_A01_MetadataClientPreConsentErrorsDoNotRedirect); no token, code or verifier reaches a log or an error (TestSecurity_A09_NoSecretsInLogsOrErrors); weak configuration is a boot error (TestSecurity_A05_ConfigRefusesWeakSetup) [x]
Telegram bot (contrib/telegram): the webhook needs a secret token of the allowed alphabet (no handler is built without one, TestSecurity_A05_WebhookRefusesWeakSecrets), compares it in constant time before reading the body, bounds the body and accepts only JSON (TestSecurity_A07_WebhookSecretAndLimits); the bot token is removed from errors, transport errors and logs (TestSecurity_A09_TokenNeverInErrorsOrLogs) [x]
GraphQL arguments are checked with their validate tags, nested input objects (and lists of them) included (TestSecurity_A03_GraphQLValidatesNestedInputs) [x]
gRPC server reflection (grpc.Reflection, contrib/grpc) is not served in production unless GRPC_INSECURE_REFLECTION_IN_PRODUCTION=true (TestSecurity_A02_GRPCReflectionOffInProduction) [x]
A separate gRPC port (grpc.Serve, grpc.Server, contrib/grpc) without TLS is refused in production unless GRPC_INSECURE_CLEARTEXT=true or ServerOptions.InsecureCleartext, independent of HTTP_H2C; an invalid value fails boot (ErrCleartextInProduction, ErrInvalidInsecureCleartext, TestSecurity_A02_GRPCServerCleartextInProductionNeedsOptIn) [x]
The app server with TLS_CERT_FILE/TLS_KEY_FILE or WithTLSConfig refuses TLS below 1.2 (a lower MinVersion is a boot error) and has no plaintext listener unless TLS_REDIRECT_ADDR is set, which redirects to the https APP_URL, never to the request's Host (TestSecurity_A02_HTTPSServesH2AndRefusesWeakTLS, TestSecurity_A01_TLSRedirectUsesAppURL) [x]
HTTP/3 (contrib/http3) needs a certificate (ErrNoTLS) and negotiates TLS 1.3 only, per QUIC; Alt-Svc is advertised only while it runs (TestSecurity_A02_HTTP3OnlyTLS13) [x]
Checks that need a cache every server sees (OnOneServer() tasks, RATE_LIMIT_STORE=cache) trust only stores that declare it: cache.Shared asks cache.Sharer (memory false, database and Redis true), looks through Unwrap() cache.Store wrappers, and treats any other store as not shared, so a metrics or tracing wrapper around the memory cache is refused at boot (schedule.ErrLocksNotShared, a RateLimiters error) instead of running a task on every server or keeping one budget per process (TestSecurity_A02_UnknownCacheStoreIsNotShared, TestSecurity_A02_OnOneServerRefusesUndeclaredStore, TestSecurity_A02_RateLimitCacheNeedsSharedStore) [x]
Lazy store functions (WithCacheStoreFunc, WithSessionStoreFunc, WithQueueDriverFunc) fall back to the configured CACHE_STORE / SESSION_DRIVER / QUEUE_CONNECTION store only when they return vukem.ErrUseDefault or single %w wraps of it (e.g. REDIS_URL unset), logged at WARN in production; any other error, one joined with the sentinel (errors.Join, several %w), a nil store, or a store returned with the sentinel fails the accessor, so a configured but broken Redis is a boot error or a failing readiness check, never a silent switch to per-process stores; the fallback cache keeps its cache.Sharer answer, so memory still refuses OnOneServer() and RATE_LIMIT_STORE=cache (TestSecurity_A02_LazyStoreFuncErrorNeverFallsBack, TestSecurity_A02_LazyStoreFuncJoinedErrorDoesNotFallBack, TestLazyStoreFuncsRejectStoreWithUseDefault, TestSecurity_A02_RateLimitCacheNeedsSharedStore, TestScheduleOnOneServerNeedsSharedCache) [x]
The compose template (internal/cli/standards/compose.yaml.tmpl) and the framework's .config/compose.yaml publish every port bound to 127.0.0.1:<host>:<container>, so the dev Postgres (default credentials) and Mailpit are not reachable from the network; a bare mapping fails the test, which checks every ports: entry in flow and block style (TestSecurity_A02_ComposeTemplateBindsLoopback) [x]
vukem bench:run builds its app on a disposable environment: APP_ENV=test, memory cache, rate limiter and queue, cookie sessions, the array mailer, and the URLs and keys of Redis, S3, Telegram and the mail APIs emptied TestSecurity_A05_BenchEnvIsolatesEveryService
The vukem bench --ui dashboard token is 32 random bytes and the page title never shows credentials, a query or a fragment TestSecurity_A02_BenchUITokenIsRandom, TestSecurity_A02_BenchUITitleNeverCarriesCredentials
vukem db keeps the password out of the client command line (PGPASSWORD in the environment; -print never shows it), needs -force in production, and refuses mysql:// and mariadb:// until their password handling is verified TestSecurity_A02_DBConsoleKeepsPasswordOutOfArgv, TestSecurity_A05_DBConsoleNeedsForceInProduction
vukem studio (contrib/studio) answers only a loopback peer with a loopback Host, no proxy headers and a same-origin POST; the one-time URL token (random, spent by the first request that carries it: a copied URL opens nothing) becomes a session cookie that is Secure over TLS, every response sends a strict CSP and the interface, a React build served from embedded static files, carries no inline script, style or event handler (TestBuiltUIIsCSPClean), and with APP_ENV=production it refuses to start (also with --write) unless --allow-production is set; credentials are never printed (TestSecurity_A01_StudioRejectsNonLoopbackPeer, TestSecurity_A01_StudioRejectsProxyHeaders, TestSecurity_A01_StudioRejectsForeignHost, TestSecurity_A01_StudioRejectsCrossOriginPost, TestSecurity_A07_StudioRequiresSessionToken, TestSecurity_A07_StudioTokenBecomesCookie, TestSecurity_A07_StudioTokensAreRandom, TestSecurity_A07_StudioTokenIsSingleUse, TestSecurity_A05_StudioSendsStrictCSP, TestBuiltUIIsCSPClean, TestLegacyPagesAreGone, TestSecurity_A05_StudioRefusesProduction, TestSecurity_A05_StudioWriteInProductionNeedsAllowProduction, TestSecurity_A09_StudioNeverPrintsCredentials) [x]
drivers/turso never quotes the auth token or the remote URL in an error or a log line, even when the SDK echoes them (TestSecurity_A02_TursoErrorsNeverQuoteTokenOrURL) [x]

App responsibility: terminate TLS (or run behind a proxy that does), set APP_URL to the https origin, set TRUSTED_PROXIES to the proxy's network (and TRUST_FORWARDED_PROTO=true when it terminates TLS).

A03:2025 — Software Supply Chain Failures

Default Check
Core depends only on the stdlib, modernc.org/sqlite and golang.org/x/crypto; heavy drivers are separate modules (opt-in) (enforced by .golangci.yml depguard core and the module split in go.work) [x]
go.sum checksum database verification (Go default) — never disabled (process: Go default, no GONOSUMDB/GOFLAGS override in the repo or CI) [x]
govulncheck v1.9.0 on every push and pull request, in task ci (task vuln), in the pre-push hook and weekly on every module (core, drivers/*, contrib/*, examples/*); generated apps pin it too (CI: vuln job in ci.yml; lefthook.yml pre-push govulncheck; vuln.yml weekly cron; TestNewProjectEndToEnd) [x]
Dependabot for Go modules and GitHub Actions; actions pinned by commit SHA; OpenSSF Scorecard (process: .github/dependabot.yml, SHA-pinned uses: in every workflow, scorecard.yml) [x]
Releases built by GoReleaser with checksums and SBOM; signed artifacts (cosign, keyless) (process: .config/goreleaser.yaml checksum, sboms, signs; release.yml) [x]
vukem upgrade (CLI self-update) talks HTTPS to GitHub only, over hosts github.com, api.github.com and *.githubusercontent.com, and refuses a redirect anywhere else (TestSecurity_A10_SelfUpgradeRefusesNonGitHubRedirect, TestSecurity_A10_SelfUpgradeHostPolicy); it installs only stable vX.Y.Z releases, never a draft, pre-release or suffixed tag (TestSecurity_A08_SelfUpgradeRefusesPrerelease); the archive must match its checksums.txt SHA-256, and a mismatch or missing entry installs nothing, with the cosign signature of checksums.txt also verified when cosign is on PATH (TestSecurity_A08_SelfUpgradeRefusesChecksumMismatch); downloads are size-capped (TestSecurity_A10_SelfUpgradeCapsDownloadSize); GITHUB_TOKEN is sent only as a bearer header and never printed (TestSecurity_A08_SelfUpgradeTokenNeverPrinted) [x]
htmx is vendored with a pinned version and checksum verified by a test; no CDN by default (TestVendoredHTMX) [x]
depguard blocks driver and contrib modules and denied packages in core; other new dependencies go through the dependency policy review (enforced by .golangci.yml depguard core) [x]
Starters pin dependency versions in go.mod / go.sum and pin govulncheck v1.9.0 with a tool directive (go tool govulncheck ./...; the templ starter pins templ the same way) (TestNewProjectEndToEnd, TestNewAPIProjectEndToEnd, TestNewTemplProjectEndToEnd) [x]
Generated projects scan for leaked secrets with Betterleaks v1.9.0: .betterleaks.toml (default rules plus APP_KEY, vk_ API tokens, Stripe sk_/rk_ keys and whsec_ secrets; placeholder values allowlisted, never paths), a pre-commit hook on staged changes (skipped with a message when the binary is missing), a CI job that downloads the release by exact version and sha256, and vukem doctor. Live validation against providers stays off (TestStarterBetterleaksRules, TestStarterBetterleaksScan, TestNewStandardsFlags) [x]

App responsibility: keep running govulncheck, review dependency updates, protect CI secrets.

A04:2025 — Cryptographic Failures

Default Check
Passwords: argon2id (m=64 MiB, t=1, p=4) with PHC strings; bcrypt supported; automatic rehash on login (TestArgon2PHCFormat, TestPasswordRehashOnLogin, TestBcryptMigrationAndLimits) [x]
Randomness only from crypto/rand (rand.Text() for tokens); math/rand blocked in security packages by lint (enforced by .golangci.yml depguard crypto-randomness) [x]
Session cookies and encrypted cookies: AES-256-GCM, keys derived with HKDF from APP_KEY (distinct info per purpose) (TestSecurity_A08_TamperedCookieRejected, TestKeyDerive, TestSecurity_A04_AppCryptUsesDerivedKey) [x]
Database sessions stored under SHA-256(session id): reading the sessions table yields no usable cookie, and a stored key is never accepted as an id; rows written before v0.24 by clear id keep working until they expire and are re-keyed on their first load; a legacy row deleted before its re-key is not accepted (TestSecurity_A04_SessionIDsStoredHashed, TestSQLStoreMigratesClearIDs, TestSQLStoreLegacyRowDeletedDuringRekey) [x]
API tokens stored as SHA-256 hashes; plain token shown once (TestSecurity_A04_TokensStoredHashed); RevokeFor(ctx, userID, id) and RevokeAll(ctx, userID) revoke only the owner's tokens, so a dashboard "revoke" cannot be used for IDOR (TestSecurity_A01_TokenRevokeScopedToOwner); revocation sets revoked_at and keeps the row for the audit trail (List shows it), and Find refuses a revoked token after the same digest comparison a valid one pays, an unknown id comparing against a placeholder digest; an access_tokens table without revoked_at refuses every token until auth.TokensRevokedAtMigration runs (TestSecurity_A07_RevokedTokenRejected, TestTokensRevokedAtMigration); a failing token or user lookup answers 503, never 401, and a missing revoked_at column is logged once with the migration to add (TestSecurity_A04_TokenGuardStoreFailureIs503); on such a table revoking deletes the rows instead, so it never fails (TestTokensRevokeOnLegacyTable); Prune never deletes a live token, whatever the cutoff (TestTokensPruneKeepsLiveTokens); the install:auth password reset, email verification and provider-verified social link revoke the user's tokens with Tokens.RevokeAll in their transaction, never deleting them (TestSecurity_A07_ProvingTheEmailEndsSquatterAccess); Tokens.Prefix (the install:auth scaffold sets vk_) starts newly issued tokens so secret scanners can match leaked ones, while tokens issued without it or under an earlier prefix stay valid and the secret alone decides (TestSecurity_A04_TokenPrefixForSecretScanning) [x]
SMTP_INSECURE=true (no STARTTLS) is a mailer error when APP_ENV=production and SMTP_HOST is not loopback, so reset and verification links never leave in clear text from a copied development setting (TestSecurity_A04_SMTPInsecureRefusedInProduction) [x]
PostgreSQL URLs to a host that is not loopback or a unix socket get sslmode=verify-full when they carry no sslmode, so pgx's silent plaintext fallback (prefer) never applies; an explicit sslmode (for example sslmode=disable on a private network) always wins, and errors never echo the URL (TestSecurity_A04_PostgresRemoteDefaultsToVerifiedTLS in drivers/postgres) [x]
Redis redis:// URLs to a host that is not loopback are refused unless they carry insecure_plaintext=true; rediss:// is the way to a remote Redis, and parse errors never echo the URL (TestSecurity_A04_RedisRemoteRequiresTLS in drivers/redis) [x]
Constant-time comparisons (subtle.ConstantTimeCompare, hmac.Equal) for tokens, signatures, CSRF tokens (process: security-review.md audit of == on secrets; FuzzVerifyHMAC, FuzzConstructEvent) [x]
app.Crypt (crypt package): AES-256-GCM with random nonces, key derived with HKDF from APP_KEY; versioned tokens carry a key id; additional data binds a token to its purpose; tampering, unknown keys and wrong additional data all fail with crypt.ErrInvalid (TestSecurity_A04_TamperingRejected, TestSecurity_A04_AssociatedDataMismatchRejected, TestSecurity_A04_AppCryptUsesDerivedKey) [x]
Without APP_KEY (explicit APP_ENV=development/test only; development logs a warning at boot) every key-derived feature fails closed instead of deriving from empty key material: config.Key.Derive panics, app.DeriveKey returns config.ErrKeyMissing, app.Crypt is nil and returns crypt.ErrNoKey (or panics on Encrypt), cookie sessions are a boot/first-use error, the DB gets no encrypter (orm.ErrNoEncrypter), and the maintenance bypass cookie is disabled (TestSecurity_A04_MissingKeyFailsClosed, TestSecurity_A04_ZeroKeyNeverDerives, TestSecurity_A04_NilEncrypterFailsClosed, TestSecurity_A01_MaintenanceBypassNeedsKey) [x]
Key rotation via APP_PREVIOUS_KEYS (procedure, vukem key:rotate): old keys only open or verify, everything new is sealed or signed with APP_KEY, and a malformed entry is a boot error. It covers every APP_KEY-derived feature end to end: app.Crypt (encrypted cookies, orm.Encrypted columns, queued mail), cookie sessions with their CSRF token and flash data (re-sealed with the new key on the next request), the maintenance bypass cookie (re-issued), and signed URLs and social login state through app.DerivePreviousKeys + WithPreviousKeys; once the old key is removed its values fail closed (TestSecurity_A04_KeyRotationEndToEnd, TestSecurity_A04_KeyRotation, TestSecurity_A04_AppCryptRotatesWithPreviousKeys, TestSecurity_A04_EncryptedColumnKeyRotation, TestSecurity_A04_ResealRotatesEncryptedColumns, TestSecurity_A04_CookieSessionKeyRotation, TestSecurity_A04_SignedURLKeyRotation, TestSecurity_A04_SocialStateKeyRotation, TestSecurity_A04_MaintenanceBypassKeyRotation); signed and social previous keys shorter than 32 bytes panic like the current key (TestSecurity_A04_SignedRefusesWeakKeys, TestSecurity_A04_SocialRefusesWeakKeys) [x]
Encrypted cookies (app.Crypt.SetCookie/Cookie): cookie name authenticated, HttpOnly, SameSite=Lax and Secure over TLS by default (TestSecurity_A04_EncryptedCookieDefaults, TestSecurity_A04_EncryptedCookieCannotMoveBetweenNames) [x]
orm.Encrypted[T] column type for sensitive fields: table and column authenticated, never stored in plaintext, fails closed without an encrypter (TestSecurity_A04_EncryptedColumnStoresNoPlaintext, TestSecurity_A04_EncryptedColumnFailsClosed) [x]
TLS: Go's secure defaults (TLS 1.2+, hybrid post-quantum key exchange in Go 1.26+); no option to disable verification without InsecureSkipVerify naming (enforced by .golangci.yml gosec G402) [x]
drivers/mysql: without tls= in DATABASE_URL, every non-loopback host gets TLS with a verified certificate (TestSecurity_A04_MySQLRemoteRequiresTLS) [x]
config.Secret redacts secrets in logs, JSON and %v (TestSecurity_A04_SecretRedaction) [x]
Queued mail (mailer.SendLater, app.MailLater): the rendered message is stored in the job sealed with app.Crypt (additional data binds it to the mail job), so reset links, tokens and addresses never sit in the jobs tables, queue:failed output or logs in clear text; a tampered payload fails the job instead of sending (TestSecurity_A04_QueuedMailPayloadIsEncrypted); clear-text mail jobs are refused unless QUEUE_ALLOW_LEGACY_MAIL=true (upgrade window, warning per job) (TestSecurity_A04_PlaintextMailJobRefusedByDefault). Known limit: the additional data is fixed, so write access to the jobs table allows replaying a sealed mail [x]
drivers/s3 refuses a plain http:// endpoint unless S3_INSECURE_HTTP=true (local S3-compatible server only) (TestSecurity_A04_S3RequiresTLS) [x]
TELEGRAM_API_URL must be https outside development and test (the bot token travels in the request path), without credentials, query or fragment; a bad value fails boot and the error never echoes it (TestSecurity_A04_TelegramAPIURLRequiresHTTPS) [x]
loadtest caps a run (1 hour, 360 million requests, 100,000 requests per second, 10,000 workers and users, 5 minutes per request), a threshold on a request name that does not exist fails instead of passing, and the dashboard allows 4 event streams, each write with a deadline TestSecurity_A04_BenchEnforcesCaps, TestSecurity_A04_BenchThresholdUnknownScopeFails, TestSecurity_A04_BenchUICapsSSEConnections, TestSecurity_A04_BenchUIStreamWritesHaveADeadline

A05:2025 — Injection

Default Check
Query builder always uses bound parameters; identifiers (columns, tables) validated against model metadata, never interpolated from input (TestSecurity_A05_QueryBuilderRejectsInjection, TestSecurity_A05_SchemaRejectsBadIdentifiers, FuzzWhereColumn) [x]
WhereRaw needs one bound argument per placeholder; gosec (G201/G202) flags SQL built by string concatenation (TestSecurity_A05_QueryBuilderRejectsInjection; enforced by .golangci.yml gosec) [x]
API query conventions (filter, sort, include, fields) are allowlists; unknown values → 400 (TestSecurity_A05_QueryConventionsRejectUnknownColumns); ?page capped at 1000 (api.MaxPage) and each filter list at 100 values (api.MaxFilterValues), 400 above (TestSecurity_A04_QueryBoundsPageAndFilterLists) [x]
orm Paginate and CursorPaginate clamp perPage to 1..orm.DefaultMaxPerPage (100), so a per_page passed through from a request cannot load a whole table in one call; Query.MaxPerPage(n) changes the bound per query and api.PerPage(def, max) sets it to the endpoint's maximum (TestSecurity_A04_PaginateCapsPerPage) [x]
orm single-model writes (Update, Delete, ForceDelete, Restore) filter on every primary key column (orm.CompositeKeyer) and fail with orm.ErrKeyNotUnique when the key matched more than one row, so a model declaring part of a composite key cannot silently rewrite or delete sibling rows; inside a transaction the error rolls the write back (TestSecurity_A04_NonUniqueKeyWriteFails) [x]
Admin list sort, filter[...] and search only reach SQL for allowlisted columns (unknown ones are ignored) and values are bound parameters (TestSecurity_A05_AdminSortAndSearchAllowlisted) [x]
html/template contextual auto-escaping for HTML, attributes, JS and URLs; template.HTML usage flagged in review; custom view functions (view.Config.Funcs, WithViewFuncs) cannot replace built-ins such as csrfField or cspNonce (boot error) (TestSecurity_A05_FragmentsEscapeAttributes, TestSecurity_A02_StarterViewsRespectCSP, TestSecurity_A03_CustomFuncsCannotReplaceBuiltins) [x]
JSON request detection (middleware.JSONOnly, c.IsJSON) parses the media type: only application/json and application/*+json count, so a CORS-simple text/plain; x=+json body cannot pass as JSON without a preflight (TestSecurity_A05_JSONOnlyRejectsSimpleContentTypes) [x]
JSON responses escape <, >, & (encoding/json/v2 with the v1 HTML-escape options); Inertia page data escapes / inside <script> (TestSecurity_A05_InertiaPageScriptCannotBreakOut) [x]
JSON request bodies (c.Input, c.BindJSON, web.PeekJSON) are decoded with encoding/json/v2. A duplicate object member name or invalid UTF-8 inside a string is rejected (400). Unknown struct fields stay a 422 from BindJSON. Numbers in a generic map stay json.Number (TestSecurity_A05_JSONDecodeRejectsDuplicateNamesAndInvalidUTF8) [x]
CSV exports (export.CSV, export.WriteCSV) write every cell starting with =, +, -, @, tab or CR, or with =, +, -, @ after leading spaces, line breaks or quotes, with a leading ' so spreadsheets show it as text (plain decimal numbers excepted); export.InsecureRawCells() opts out (TestSecurity_A05_ExportCSVFormulaInjection) [x]
Download names (export.ContentDisposition, c.Download) keep only the last path element and lose control (C0, C1, U+2028/2029), format (bidi, zero-width) and Windows-reserved characters and trailing dots; Windows device names (CON, NUL, COM1…) get a _ prefix; non-ASCII names get an RFC 5987 filename*, so a name cannot add headers or parameters (TestSecurity_A05_ExportFilenameHeaderInjection, TestSecurity_A05_DownloadFilename); c.Download sets the header only once the file opened; exports are sent with Cache-Control: no-store [x]
Mail headers built with net/mail (no header injection); file names sanitised; attachment content types parsed and re-formatted (TestSecurity_A05_MailHeaderInjection) [x]
React Email templates (mail.React) are exported as html/template pages: every prop is escaped for its HTML context, URLs filtered (TestSecurity_A03_ReactPropsEscaped) [x]
No shell execution in the framework; os/exec usage in CLI generators never passes user input through a shell (enforced by .golangci.yml gosec G204) [x]
Validator rejects invalid UTF-8 and control characters in string fields by default (TestString) [x]
Devtools mail previews render in an <iframe sandbox srcdoc> with the HTML escaped, under a page CSP without any script source, so mail HTML never runs inline (TestSecurity_A05_DevtoolsMailPreviewIsSandboxed) [x]
Uploads (upload): the type is detected from the content (http.DetectContentType), never the client's Content-Type, and the file extension must match it; per-file and per-request sizes → 413, file and field counts bounded (nameless parts count too, TestSecurity_A06_UploadNamelessPartsBounded); stored names are random, so client file names (../, \, absolute paths) never reach a storage path; rejected requests leave no files (TestSecurity_A05_UploadValidation); storage.PutUploaded needs a non-empty UploadRules.Types (an empty list is an error, never "any type", TestSecurity_A05_PutUploadedRequiresTypes); upload.Verify (direct uploads) only opens or deletes keys Presign could have issued, a random name under Rules.Dir (TestSecurity_A01_DirectVerifyOnlyIssuedKeys) [x]
Image uploads: upload.Images caps the declared width × height at 25 megapixels (Rules.MaxPixels), read from the JPEG/PNG/GIF/WebP header without decoding pixels, in Receive, Save and direct-upload Verify; a file of those types without a readable header is rejected and deleted (TestSecurity_A05_UploadImagePixelLimit) [x]
Thumbnails (contrib/imaging): the decoder is chosen from the content, the declared dimensions are checked against MaxPixels before decoding, the source size is bounded by MaxBytes, and re-encoding strips metadata after the JPEG EXIF orientation is applied; failures write nothing (TestSecurity_A05_ThumbnailRefusesBombsAndJunk, TestSecurity_A05_ThumbnailRefusesBombHeaders, TestThumbnailSniffsContentNotName, TestThumbnailAppliesEXIFOrientation, FuzzOrientation) [x]
Locale input (query, cookie, session, Accept-Language) is used only when it is a well-formed tag (language[-Script][-REGION]) of an available catalog; anything else falls back, so raw input never reaches headers, lookups or file paths (TestSecurity_A05_LocaleInputRejected) [x]
vukem bench:run never opens the configured database: it boots the app on a new temporary SQLite file and removes it, refuses --database-url in production (or when the environment cannot be read) and asks for --yes for any database that is not a temporary SQLite file TestSecurity_A05_BenchRunNeverUsesConfiguredDatabase, TestSecurity_A05_BenchRunRefusesDatabaseURLInProduction, TestSecurity_A05_BenchRunProductionCheckFailsClosed, TestSecurity_A05_BenchRunDatabaseURLNeedsConfirmation
The vukem bench --ui dashboard and the --report file hold no inline script or style and no external resource, the page script only sets textContent, and scenario names are escaped in the report TestSecurity_A05_BenchUISendsStrictCSP, TestSecurity_A05_BenchUIHasNoInlineCode, TestSecurity_A03_BenchUIScriptNeverUsesInnerHTML, TestSecurity_A05_BenchReportIsSelfContained, TestSecurity_A03_BenchReportEscapesNames
Generated code never runs what a comment or a name holds: the doc comment of a TypeScript or Go API client has the route pattern and the summary reduced to one line with */ neutralized, so a pattern or summary cannot close the comment or start a line of code (TestSecurity_A03_TypeScriptClientCommentCannotBeClosed, TestSecurity_A03_GoClientCommentCannotBeBroken), and codegen:models refuses a package name (-pkg, or the directory of -o) that is not a Go identifier (TestSecurity_A03_CodegenModelsRefusesPackageNameThatIsNotAnIdentifier); property, route and component names reach TypeScript only as quoted strings or as identifiers built from letters and digits [x]
APP_PROBLEM_BASE_URL, the prefix of the type member of every problem, is validated at boot: only an http or https URL with a host is accepted, with no credentials, query or fragment (so no javascript: or data: URI reaches a client that renders type as a link), a trailing slash is dropped, and the error does not repeat the value (TestSecurity_A05_ProblemBaseURLIsValidatedAtBoot) [x]

A06:2025 — Insecure Design

Default Check
upload.Rules.Types refuses a media type http.DetectContentType cannot produce (image/avif, image/heic, image/heif, image/jxl, image/tiff) instead of accepting a rule that would match nothing; application/octet-stream is the explicit opt-in for a service with its own sniffer (TestRulesRefuseAnUndetectableType, TestDetectableTypesAreActuallyDetectable) [x]
Opinionated, reviewed flows generated by install:auth / install:api (reset tokens single-use, also across concurrent resets, and expiring; a reset ends remembered sessions and API tokens; email verification signed; re-confirm password for sensitive actions; POST /api/v1/tokens grants only the abilities the request asks for out of the generated apiv1.Abilities(), never "*", and nothing when the field is omitted) (generated TestPasswordReset, TestRegisterAndVerifyEmail, TestTwoFactorDisableNeedsPassword, TestAPITokenWithoutAbilityIsRefused, TestAPITokenRejectsUnknownAbility, run by TestNewProjectEndToEnd / TestNewInertiaProjectEndToEnd) [x]
Bot challenge (challenge, opt-in): challenge.Middleware checks unsafe requests only; a missing, wrong, replayed (timeout-or-duplicate), oversized (> 4096 bytes), other-hostname or, with SiteVerify.Action set, other-action token is a 422 validation error on challenge and a challenge.failed event, and a provider that cannot answer (network, non-200, rejected or missing secret) is a 503 and a challenge.unavailable event, never a pass (TestSecurity_A07_ChallengeFailsClosed); SiteVerify calls the provider through httpclient.Safe [x]
Turnstile (challenge.TurnstileConfig, challenge.StepUp, opt-in, off until both TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY are set; one without the other fails Validate): the secret is a config.Secret and never appears in logs or errors (TestSecurity_A09_TurnstileSecretNeverLogged); a provider outage denies (503) unless TURNSTILE_INSECURE_FAIL_OPEN, which never covers a bad token or a rejected secret and logs challenge.fail_open (TestTurnstileVerify); the step-up clearance cookie is HttpOnly, Secure, SameSite=Lax, HMAC-signed with an APP_KEY-derived key, expires after TTL and is bound to the client's IPv4 /24 or IPv6 /48 and User-Agent hash, so it cannot be forged or replayed from another network or tool (TestSecurity_A07_StepUpClearanceCannotBeForgedOrMoved, TestStepUpClearance); the interstitial is noindex and no-store and redirects only to local paths (TestStepUpInterstitial, TestStepUpRejections, TestLocalPath) [x]
Rate limits on login, password reset, token issuance by default (TestSecurity_A07_AuthScaffoldDefaults, generated TestLoginLogoutAndThrottle); auth.ThrottleKeys(emailField) supplies the login keys (per normalized email and IP, per email alone, and per IP across all emails in the install:auth scaffold and the examples (TestSecurity_A07_LoginThrottledPerIP)) (TestSecurity_A07_LoginThrottle); the email is read as Ctx.Input reads it, and an unreadable one falls into a per-IP bucket (TestSecurity_A07_LoginThrottleParserDifferential); an email over 254 bytes (RFC 5321) is keyed by its SHA-256 instead of embedded, so both buckets still count it per account, and ratelimit.Memory stores any key over 128 bytes as its SHA-256, so a large body cannot make the limiter retain megabytes per request (TestSecurity_A07_LoginThrottleBoundsOversizedEmail, TestMemoryHashesLongKeys) [x]
ratelimit.Middleware keys by client IP unless told otherwise and denies when its store fails (503); ByToken is meant for routes behind auth.Required (the install:api scaffold limits by IP first), so made-up bearer tokens cannot each get a fresh bucket; a window of zero or less is one second, so a misconfigured limit never panics or denies all traffic, and the Redis limiter reports the rate its script enforces (at most one request per millisecond) in RateLimit-Limit (TestMemoryDegenerateWindow, TestRateLimiterNormalisesWindow in drivers/redis, TestSecurity_A06_RateLimitIgnoresUnverifiedTokens, TestSecurity_A06_RateLimitMiddlewareFailsClosed) [x]
Shared rate limits without Redis: RATE_LIMIT_STORE=cache counts fixed windows in the app cache (CACHE_STORE=database on SQLite, PostgreSQL or MySQL), whose Increment is atomic across servers, so N instances share one budget instead of N; a store error denies the request (503); an unknown RATE_LIMIT_STORE, or cache over the per-process memory cache (including a cache.Memory passed with WithCacheStore/WithCacheStoreFunc, directly or behind an Unwrap wrapper, and any store cache.Shared does not report as shared), is a boot error, never a silent fallback to per-process limits; every window key is hashed, so no client key can forge another's bucket (TestSecurity_A06_RateLimitWindowStoreFailsClosed, TestSecurity_A02_UnknownRateLimitStoreFails, TestSecurity_A02_RateLimitCacheNeedsSharedStore, TestSecurity_A07_RateLimitKeysDoNotCollide, TestRateLimitWindowSharedAcrossServers in drivers/postgres) [x]
Request body size limits (http.MaxBytesReader) on every route, the innermost limit wins (a route or upload.Rules.MaxSize may raise the router default; a declared Content-Length over it fails on the first read); multipart limits; form key nesting limited to 16 levels, JSON nesting bounded by encoding/json; MethodOverride remembers a *http.MaxBytesError from an urlencoded body so a later web.Parse answers 413 instead of 422 on the empty form (a route-level limit is too late for that body: set it in the server stack) (TestSecurity_A06_BodyLimit, TestSecurity_A06_BodyLimitInnermostWins, TestSecurity_A06_MethodOverrideKeepsTighterLimit, TestSecurity_A06_MethodOverrideRemembersMaxBytes, TestSecurity_A06_InputRejectsOversizedForm, TestFormToMapDepthLimit, TestSecurity_A06_UploadNamelessPartsBounded) [x]
Multipart uploads that spill to temporary files are removed when the handler returns, whether it succeeds, fails or panics, because net/http only cleans the form of the connection's own request and handlers get a copy; the CSRF token fallback and ratelimit.Middleware (whose key may read the form, as auth.ThrottleKeys does) remove them too when they answer 403 or 429 (TestSecurity_A06_MultipartTempFilesRemoved, TestSecurity_A06_CSRFRejectRemovesMultipartFiles, TestSecurity_A06_RateLimitRemovesMultipartFiles) [x]
WebSocket messages are capped at 32 KiB (websocket.ReadLimit; larger closes with 1009), every write has a timeout, pings drop peers that stop answering, and app shutdown closes sockets with 1001 instead of waiting on them (TestSecurity_A06_WebSocketReadLimit) [x]
QR payloads (contrib/qrcode) longer than 2048 bytes are rejected before encoding, and the HTTP handler does not echo the payload (TestSecurity_A06_QRRejectsOversize). A prerendered page (ssg) over 8 MiB is not written (TestSecurity_A06_SSGRefusesOversizeBody) [x]
Upload scanning fails closed: with upload.Rules.Scanner files stay in a dot-named quarantine path until scanned, infected files are deleted (422) and an unreachable scanner rejects the upload (503); tus and presigned-upload handlers refuse to boot without an Authorize hook (TestReceiveScansBeforeFilesBecomeVisible, TestClamAVUnavailableFailsClosed, TestTusConfigIsValidatedAtBoot, TestDirectRequiresAuthorize) [x]
Transactions with rollback-on-error/panic (db.Tx) so multi-step operations are atomic (TestTxCommitRollbackPanic) [x]
Threat model of each subsystem recorded in its doc before BETA; security review gate in PLAN.md (B.5.2) (process: security-review.md) [x]
GraphQL operations are bounded before any resolver runs: depth 12, complexity 1000 (list arguments first/last/limit multiply cost, their SDL default when the query omits them: TestSecurity_A06_GraphQLComplexityUsesSDLDefaults), 30 aliases, 10000 tokens, 1 MiB body; introspection (__schema, __type) counts toward aliases and complexity, nests at most 16 levels and resolves at most 200000 fields, so fragment chains over __Type cannot grow the response exponentially (TestSecurity_A06_GraphQLIntrospectionBounded, TestSecurity_A06_GraphQLIntrospectionFieldCap); persisted-query allowlist mode runs only listed documents and fails closed without a store (TestSecurity_A06_GraphQLDepthAndComplexityLimits, TestSecurity_A06_GraphQLAllowlistOnly) [x]
GraphQL subscriptions are bounded: every WebSocket and SSE document goes through the same parse, validation, limits and persisted-query checks as HTTP; a socket that does not send connection_init within 10s is closed (4408); one connection runs at most 32 operations (TOO_MANY_REQUESTS beyond); introspection is off over the socket unless WSConfig.Introspection (TestSecurity_A06_GraphQLSubscriptionsBounded) [x]
GraphQL automatic persisted queries are stored only after the document parses and validates, only on POST, and only up to MaxDocumentBytes (default 64 KiB); the in-memory store is also bounded by total bytes (16 MiB), so anonymous clients cannot fill it with garbage or evict listed documents with oversized ones (TestSecurity_A06_PersistedQueryStoredOnlyWhenValid, TestSecurity_A06_PersistedQuerySizeCapped) [x]

A07:2025 — Authentication Failures

Default Check
Session id regenerated on login and privilege change (anti-fixation); invalidated on logout (TestSecurity_A07_SessionRegeneratedOnLogin, TestSecurity_A07_SessionInvalidatedOnLogout) [x]
When the session guard cannot load the signed-in user for a reason other than "not found" (database down), auth.Required answers 503 and keeps the session instead of logging the user out or treating them as a guest (TestSecurity_A04_SessionKeptWhenUserLookupFails) [x]
Cookies: HttpOnly, Secure, SameSite=Lax, __Host- prefix over HTTPS (TestSecurity_A07_SessionCookieFlags, TestSecurity_A02_ConfigChecks) [x]
Idle and absolute session timeouts (TestAbsoluteLifetimeAndTouch, TestSessionLifecycleAllStores) [x]
Server-side sessions record their user (web.SessionUserKey, set by SessionGuard.Login); the owner is namespaced by guard ("<guard>:<id>", SessionGuard.SessionUserID) and backfilled for older sessions on their next authenticated request (TestSessionUserKeyBackfilled). Manager.RevokeOthers(ctx, owner, keepID) ends every other session of the owner on database, memory and Redis stores (TestStoreConformance, drivers/redis TestSessionStoreConformance) and returns session.ErrRevokeUnsupported for cookie sessions and stores without user tracking (TestSecurity_A07_RevokeOtherSessions); a request in flight during the revocation cannot write its session back, since existing sessions are only updated (TestSecurity_A07_RevokedSessionNotResurrected). The install:auth scaffold calls it on password reset (all sessions) and when 2FA is turned on (all but the current one, after the recovery codes are flashed; a failure is logged as session.revoke_failed) (TestSecurity_A07_AuthScaffoldRevokesOtherSessions, generated TestPasswordResetEndsOtherSessions) [x]
Users implementing auth.SessionVersioner have their session version recorded on login; SessionGuard signs out a session whose version no longer matches the user's, on every session driver (encrypted cookies included), and treats an unreadable recorded version as stale (none counts as 0); a stale session is invalidated whole, and NewSessionGuard panics when only *U implements SessionVersioner (the check would silently never run) (TestSecurity_A07_SessionVersionEndsSessions, TestSessionGuardRejectsPointerSessionVersioner). RefreshSession and Logout delete the request's remember-me token only when it belongs to the signed-in user (TestRememberTokenDeletedOnlyForItsUser). The install:auth scaffold bumps users.session_version in the password reset transaction and when 2FA is turned on, keeping the current session with SessionGuard.RefreshSession (TestSecurity_A07_AuthScaffoldRevokesOtherSessions, generated TestPasswordResetEndsOtherSessions on the database and cookie drivers) [x]
SessionGuard.Impersonate is time-bounded and fails closed: an expired or unreadable deadline ends the whole session, nesting and self-impersonation are refused, the session id is regenerated, no remember-me token is issued, the actor's remember-me token and cookie are removed (an expired impersonation never falls back to them), and StopImpersonating restores the actor only while its session version still matches (TestSecurity_A01_ImpersonationIsBoundedAndReversible, TestSecurity_A01_ImpersonationExpiresClosed, TestSecurity_A01_ImpersonationExpiryIgnoresRememberMe, TestSecurity_A07_StopImpersonatingChecksActorSessionVersion) [x]
Remember-me tokens are hashed with the session version they were issued under and rejected once the user's version changes, so a stolen remember cookie stops signing in after a password reset or 2FA enable; RefreshSession re-issues the current device's token, and the scaffold also deletes the user's tokens when ending their other sessions (TestSecurity_A07_RememberTokenBoundToSessionVersion) [x]
The Redis session store keys sessions by SHA-256 of the id (also in the owner and per-user index keys), so reading the keyspace yields no session cookie; keys saved under the clear id are moved on first load, and a logout racing the move does not write the session back (drivers/redis TestSecurity_A04_RedisSessionIDsStoredHashed, TestRedisSessionLegacyDeletedDuringRekey) [x]
Manager.RevokeSession(ctx, owner, handle) ends only a session of that owner: a handle of another user's session, or anything that is not a handle, gives ErrSessionNotFound; the handle listed by Manager.UserSessions is derived from the hashed storage key and loads nothing (TestUserSessionsListsAndRevokesByHandle) [x]
Session lists record no user agent or IP unless SESSION_RECORD_CLIENT=true (session.Config.RecordClient); then the user agent is stripped of control and format runes and capped at 256 bytes, and the IP truncated to IPv4 /24 or IPv6 /48 (TestSecurity_A04_SessionClientInfoOptIn, TestRecordClientStripsControlRunes) [x]
Credential check hashes a dummy password when the user does not exist (timing-safe, no user enumeration) (TestSecurity_A07_DummyHashOnUnknownUser) [x]
Generic error messages on login and password reset ("If the email exists…") in every locale (TestSecurity_A07_LoginErrorsDoNotRevealUsers, TestSecurity_A07_TranslatedLoginErrorsDoNotRevealUsers, generated TestPasswordReset) [x]
Password reset answers alike for known and unknown emails, and the scaffold queues the reset mail (SendLater) so the response time does not reveal accounts; needs QUEUE_CONNECTION=database (memory loses queued mail on restart; with sync the mail is sent inline) (TestSecurity_A07_PasswordResetAnswersAlike, generated TestPasswordResetAnswersAlike, run by TestNewProjectEndToEnd / TestNewInertiaProjectEndToEnd) [x]
Sign-up (install:auth) answers alike for new and existing emails: same redirect to /register/check-email, no validation error, no login before verification; an existing address gets a notice mail (at most one per hour per address, cache counter keyed by a SHA-256 of the address) and nothing is created; both paths hash the password and queue one mail; the signed verification link needs the login of its account (signed out it leads to /login, which comes back to it) and answers 403 to another signed-in user; a cache error skips the notice and is logged, never returned (TestSecurity_A07_SignupCacheOutageIsNoOracle, generated TestRegisterSurvivesCacheOutage); sign-up is rate limited per IP and per address hash, alike for new and existing addresses (TestSecurity_A07_SignupRateLimited, generated TestRegisterThrottle) (TestSecurity_A07_SignupIsEnumerationSafe, generated TestRegisterAndVerifyEmail, TestRegisterDoesNotRevealAccounts, run by TestNewProjectEndToEnd / TestNewInertiaProjectEndToEnd) [x]
Scaffolded signed-in pages need a verified email (auth.Verified on the dashboard, 2FA settings and billing; install:admin admins need a verified ADMIN_EMAILS address; POST /api/v1/tokens answers 403 to unverified users), so an account pre-registered with someone else's address grants nothing until its owner verifies it; unverified logins land on the verification notice (TestSecurity_A07_AuthScaffoldRequiresVerifiedEmail, generated TestUnverifiedUsersSeeTheNotice, TestAPITokenNeedsVerifiedEmail, TestAdminPanelAccess) [x]
Proving the address ends what was opened before it was proven: the verification link (Accounts.VerifyEmail) and a provider-verified social sign-in that links an unverified local account delete remember-me tokens, revoke API tokens (Tokens.RevokeAll, rows kept with revoked_at) and bump the session version in one transaction, then delete server-side sessions; the social link also replaces the password. The verification link carries a SHA-256 of the address and is void after an email change (TestSecurity_A07_ProvingTheEmailEndsSquatterAccess, generated TestVerificationEndsOtherSessions, TestVerificationLinkBoundToEmail, TestSocialLinkEndsSquatterAccess) [x]
install:auth --social creates and links accounts only by a provider-verified email; a provider that sends none (x) is refused with exit code 2 before any file is written, instead of wiring a sign-in button that can never create an account (TestSecurity_A07_SocialRefusesProvidersWithoutEmail) [x]
The install:auth verification link needs the login of the account it verifies: the route runs auth.Required, so a signed-out click leads to /login with the link kept as the intended URL (also through a 2FA challenge or a social sign-in); Verify then checks the signature (expired: back to the notice to send a new one; tampered: 403 and url.signature_invalid) and verifies only the signed-in user (403 for another account); an already verified account is not verified again, so no session ends. Whoever merely owns the mailbox cannot verify an account someone else created with the address (TestSecurity_A07_VerificationLinkRequiresLogin, generated TestRegisterAndVerifyEmail, TestVerificationEndsOtherSessions, TestExpiredVerificationLinkOffersANewOne, TestVerifiedLinkKeepsOtherSessions, run by TestNewProjectEndToEnd / TestNewInertiaProjectEndToEnd) [x]
Password rules in user code (app/requests/auth.go): at least 12 and at most 256 characters by default; argon2id has no 72-byte limit and hash.Bcrypt refuses longer passwords (TestSecurity_A07_AuthScaffoldDefaults, TestBcryptMigrationAndLimits) [x]
Login throttling per email + IP (5 per minute) and per account from any IP (20 per 10 minutes), keyed by the email normalized like the login schema (trimmed, lower case) so spaces and case open no new buckets (generated TestLoginLogoutAndThrottle, run by TestNewProjectEndToEnd / TestNewInertiaProjectEndToEnd); remember-me tokens rotated on use and single use even under concurrent replay, and consumed only after the user loads: a failing user store answers 503 and keeps the cookie and token (TestRememberMe, TestSecurity_A07_RememberTokenSingleUseUnderConcurrency, TestSecurity_A04_RememberTokenKeptWhenUserLookupFails) [x]
API tokens with expiry, abilities and revocation; last_used_at tracking (TestTokensAndAbilities) [x]
The token guard reads the token from Authorization: Bearer <token> only; TokenGuard.WithTokenHeaders("X-API-Key") is the explicit opt-in for other headers, and without it no other header is accepted (TestSecurity_A07_TokenHeadersClosedByDefault). A bearer Authorization always wins, a named header sent on several lines is skipped, and Authorization and Cookie are refused as names at wiring time (a token the browser attaches on its own would authenticate every cross-site request). Every named header is added to Vary on every response the guard sees, with or without a token, so a shared cache cannot serve one key's response to a request holding another; Authorization is kept out of Vary, since RFC 9111 §3.5 already stops shared caches from storing those responses (TestSecurity_A07_TokenHeadersAlwaysVary, TestTokenGuardExtraHeaders, TestTokenGuardVaryOnServedResponses) [x]

| Social login: PKCE, signed single-use state/nonce cookie, OIDC ID-token verification, redirect URL from config only (TestSecurity_A07_SocialStateMismatch, TestSecurity_A07_SocialReplayAndPKCE, TestSecurity_A07_IDTokenChecks); with Social.States set to the cache store (the install:auth --social scaffold does), a used state is recorded with an atomic Add until it expires, so a replayed callback is refused on every replica and after a restart (TestSecurity_A07_SocialReplayAcrossInstances); the store must be persistent and shared in production, since the bounded memory store can evict a used state, and a store outage refuses the callback with 503 (TestSecurity_A04_SocialStateStoreFailsClosed); a provider error parameter is logged as a sanitized code and answered with the fixed social.ErrProvider message, never reflected into the page (TestSecurity_A03_SocialProviderErrorNotReflected) | [x] | | TOTP 2FA (auth/totp, install:auth --2fa): a code works once per time step, also across concurrent requests (TestValidateWindowAndReplay and the generated TestTwoFactorLogin); recovery codes stored as hashes and single use (TestRecoveryCodes, generated TestTwoFactorRecoveryCodes); secret and hashes in orm.Encrypted columns, challenge/confirm/recovery-code regeneration/disable limited to 5 per minute per user + IP, disabling and regenerating recovery codes need the current password, so a hijacked session cannot mint codes past the second factor (TestSecurity_A07_TwoFactorScaffoldDefaults, generated TestTwoFactorThrottle, TestTwoFactorDisableNeedsPassword, TestTwoFactorRecoveryCodes); the scaffold refuses to install when it cannot enforce the code step at login (TestSecurity_A07_TwoFactorFailsClosedOnEditedLogin); with install:api, POST /api/v1/tokens needs the code or a recovery code too, whichever was installed first (generated TestAPITokenRequiresTwoFactor, TestTwoFactorPatchesMatchScaffolds). Generated tests run in TestNewProjectEndToEnd and TestNewInertiaProjectEndToEnd | [x] | | Argon2id hashers run at most Argon2Params.MaxConcurrent computations at once (default runtime.GOMAXPROCS(0)), so a burst of logins queues instead of reserving 64 MiB each; the limit belongs to the hasher, so create one and reuse it (TestSecurity_A04_Argon2idBoundsConcurrency) | [x] | | OIDC providers and jwt.RemoteJWKS need https for the issuer, every discovery endpoint and the JWKS URL (plain http only on loopback, or with the InsecureHTTP opt-out), and the discovery document's issuer must equal the configured one (a {tenantid} placeholder only has to keep the host) (TestSecurity_A02_OIDCIssuerRequiresHTTPS, TestSecurity_A02_OIDCEndpointsRequireHTTPS, TestSecurity_A07_OIDCDiscoveryIssuerMustMatch, TestSecurity_A02_RemoteJWKSRequiresHTTPS); the default HTTP clients also refuse a redirect that leaves https (or leaves a loopback host for plain http) and stop after 5 hops, while a client you supply needs the same CheckRedirect (TestSecurity_A02_SocialClientRefusesRedirectsToHTTP, TestSecurity_A02_SocialRedirectPolicy, TestSecurity_A02_RemoteJWKSRefusesRedirectsToHTTP) | [x] | | The social state cookie is __Host-social_<provider> (Secure, Path=/, no Domain), so a sibling subdomain cannot set it; InsecureCookies keeps the plain social_<provider> name (TestSecurity_A07_SocialStateCookieUsesHostPrefix, TestSecurity_A07_SocialStateCookieDeleteUsesHostPrefix) | [x] | | jwt.VerifyOptions.Types (opt-in) refuses tokens whose typ header is not listed, so an ID token cannot pass as an access token (TestSecurity_A07_VerifierChecksTyp); TOTP recovery codes carry 80 random bits (XXXX-XXXX-XXXX-XXXX) and codes issued in the older 50-bit format still verify (TestSecurity_A04_RecoveryCodesCarry80Bits, TestRecoveryCodes) | [x] | | Passkeys (auth/webauthn): challenge, origin (cross-origin iframes refused), RP ID hash, user presence and verification (required unless InsecureSkipUserVerification), credential id and user handle, signature and sign-count regression are checked; only attestation none and ES256, EdDSA and RS256 (at least 2048 bits) keys whose algorithm matches their key type are accepted; an empty stored challenge never matches; RelyingParty.Validate refuses origins outside the RP ID and http except on localhost (TestSecurity_A07_WebAuthnAssertionRejected, TestSecurity_A07_WebAuthnRegistrationRejected, TestSecurity_A07_WebAuthnRequiresUserVerificationByDefault, TestSecurity_A05_WebAuthnRelyingPartyValidate); the CBOR and authenticator-data parsers are fuzzed (FuzzDecodeCBOR, FuzzParseAuthData). install:auth --passkeys pulls each challenge from the session before verifying, needs the current password to add or remove a passkey (the password stays the recovery path), scopes deletion to the signed-in user, saves the sign count with a compare-and-set, throttles every endpoint and answers alike for every refused ceremony (TestSecurity_A07_PasskeyScaffoldDefaults, generated TestSecurity_A07_PasskeyChallengeIsSingleUse, TestSecurity_A07_PasskeyIsScopedToItsUser, TestSecurity_A07_PasskeyChangesNeedThePassword, run in TestNewProjectEndToEnd and TestNewInertiaProjectEndToEnd) | [x] | | The vukem bench --ui dashboard asks for a session token printed at start: the start URL works once and trades the token for an HttpOnly, SameSite=Strict cookie holding a separate random session id that expires, so the cookie, which travels to every service on localhost, is not the secret | TestSecurity_A07_BenchUIRequiresToken, TestSecurity_A07_BenchUITokenBecomesCookie, TestSecurity_A07_BenchUICookieIsNotTheToken, TestSecurity_A07_BenchUITokenWorksOnce |

A08:2025 — Software or Data Integrity Failures

Default Check
Signed and encrypted cookies (tampering detected) (TestSecurity_A08_TamperedCookieRejected, TestSecurity_A04_EncryptedCookieCannotMoveBetweenNames) [x]
Signed URLs and signed email-verification links (HMAC with expiry) (TestSecurity_A01_SignedURLTampering, generated TestRegisterAndVerifyEmail) [x]
Queue payloads are JSON mapped to registered job kinds — no reflection-based deserialization of arbitrary types (TestTimeoutPanicAndUnknownKind, TestRegisterAndDispatchErrors) [x]
CSRF protection with http.CrossOriginProtection (Fetch Metadata + Origin) on all unsafe methods; webhook bypasses must be declared (TestSecurity_A01_CrossOriginProtection); MiddlewareOptions.CrossOrigin opens one route to listed origins only (no sessions, no credentials, unlisted unsafe origins 403, no trust leak to other routes: TestSecurity_A01_CrossOriginRouteDoesNotTrustOriginGlobally); the routes match the method a form _method override selects, not the POST that carries it (TestSecurity_A01_CrossOriginUsesOverriddenMethod) [x]
CSRF token fallback (csrf.Config.TokenFallback, MiddlewareOptions.CSRFTokenFallback): unsafe requests without Sec-Fetch-Site/Origin that carry the session cookie (SessionCookie; any cookie when unset, failing closed) need the session token; combining the option with Stateless is a boot error (TestSecurity_A01_TokenFallbackSessionCookie, TestSecurity_A01_DefaultMiddlewareWithCSRFTokenFallback) [x]
Webhook signature verification helper (webhook.VerifyHMAC) (TestSecurity_A08_WebhookMiddleware, FuzzVerifyHMAC); webhook.HMAC returns a boot error for an empty secret or header, while the lenient webhook.Middleware refuses every request in that case (TestSecurity_A05_WebhookHMACRefusesEmptySecretAtBoot); webhook.Middleware and webhook.Standard answer a body over the limit, including one cut by an outer BodyLimit, with 413 and any other read error with 400 (TestSecurity_A08_WebhookReadErrorsAreNotBodyLimits) [x]
Standard Webhooks verification with a ±5 minute timestamp window against replays (TestSecurity_A08_StandardWebhooks); a malformed secret is a boot error; webhook.Dedupe runs each event id once per namespace (route pattern by default, so providers that reuse ids do not collide; never the raw request path, so a replay to another path is still a duplicate, TestSecurity_A08_WebhookDedupeIgnoresRawPath) and fails closed when its store is down (TestSecurity_A08_WebhookDedupe, TestSecurity_A04_WebhookDedupeFailsClosed) [x]
Outgoing webhooks (webhook.Sender): every attempt is signed with the Standard Webhooks scheme (verifiable with webhook.Standard), sent through httpclient.Safe so user-supplied endpoint URLs never reach loopback, private or metadata addresses (TestSecurity_A01_OutgoingWebhookSSRF), only over https unless InsecureAllowHTTP (TestSecurity_A04_OutgoingWebhookRequiresHTTPS), never unsigned (a missing or malformed secret fails the attempt), without following redirects (3xx is final); attempts store an error category, never the resolved address or TLS detail; jobs carry the endpoint id, not its URL or secret, and logs and errors omit URL, secret and payload (TestSecurity_A09_OutgoingWebhookLogsNoSecrets) [x]
Release artifacts with checksums, SBOM and signatures (process: .config/goreleaser.yaml, release.yml) [x]
Migrations tracked with checksums; a modified, already-applied migration is reported by migrate:status (TestMigratorChangedAndMissing, TestMigrateCommands) [x]

A09:2025 — Security Logging and Alerting Failures

Default Check
Structured slog request logs with request id, user id (when authenticated), route name, status, duration (TestLogger) [x]
Security events logged at WARN with a stable event attribute: auth.login_failed, auth.remember_rejected, authz.denied, csrf.rejected, ratelimit.exceeded, session.invalid, url.signature_invalid, webhook.signature_invalid, broadcast.denied, idempotency.key_reused, idempotency.unscoped (TestSecurity_A09_SecurityEventsAtWarn, TestSecurity_A08_TamperedCookieRejected, TestSecurity_A01_CrossOriginProtection) [x]
Request logs include the client IP (ip) and peer address (peer), which are personal data under LGPD/GDPR: app responsibility to set log retention or anonymization accordingly (TestLoggerRecordsPeerAndClientIP) [x]
Secrets, passwords, tokens and Authorization/Cookie headers redacted from logs (TestSecurity_A09_LoggerNeverLogsCredentials) [x]
The Mailtrap API token is a config.Secret: *mail.MailtrapError never carries the message body or the token (even when the API echoes it back) but may contain addresses quoted by the API; upstream error text is capped at 5 items of 200 characters with line breaks replaced; the default client does not follow redirects, so the token never goes to another host; a missing MAILTRAP_API_TOKEN with MAIL_MAILER=mailtrap is a boot error (TestSecurity_A09_MailtrapTokenRedacted) [x]
The Telegram bot token is a config.Secret; queued (OnError) and synchronous (SendSync, ContactSync) delivery errors redact it from transport errors, which carry the request URL (TestSecurity_A09_TelegramTokenRedacted, TestSecurity_A09_TelegramSyncErrorRedactsToken) [x]
drivers/s3 keeps the secret key and session token in config.Secret; formatting a config or disk and S3 errors never include them or a request signature (TestSecurity_A09_S3NeverLeaksCredentials) [x]
Log injection prevented: slog attribute encoding (no raw string concatenation) (TestRequestID, TestSecurity_A05_SSEFieldInjection) [x]
The admin audit log (admin_audit_logs: actor, resource, record, action, before/after of changed columns) never stores sensitive columns (json:"-", secret-like names matched anywhere (including hash, digest, salt, credential and *_key), with only known counters such as tokens_used exempt, Sensitive(...); TestSecurity_A09_AdminSensitiveColumnNames): they are recorded as redacted, without values, and never shown or echoed into forms (TestSecurity_A09_AdminAuditOmitsSensitive); hidden columns are recorded as redacted the same way, and entries written before a column became hidden or sensitive are redacted when read (TestSecurity_A09_AdminAuditRedactsHiddenColumns, TestSecurity_A09_AdminAuditRedactsOnRead) [x]
The admin audit page (/admin/_audit) lists only entries of resources the reader passes viewAny on (plus _flags with manageFlags); a filter for any other resource, or no readable resource, returns no entries (TestSecurity_A01_AdminAuditFilteredByResourcePolicy) [x]
Admin custom actions re-read every record with a row lock inside their transaction and check the policy on the locked row before Run, so a policy decision never applies to a stale copy and concurrent runs cannot both pass it (TestSecurity_A01_AdminActionAuthorizedOnLockedRecord) [x]
events.Listen[security.Event] hook to forward security events to alerting (email, Slack, SIEM) (TestSecurityEventsReachTheBus) [x]
Routine audit records (web.AuditEvent: payouts, role changes) logged at INFO with the security event envelope (event, method, path, request_id) and dispatched as security.Audit, a distinct type, so alerting on security.Event never sees them; a config.Secret attribute is logged masked (TestSecurity_A09_AuditEventsAtInfo). App responsibility: pass ids, not personal data (names, emails, documents), as attributes; the dispatched security.Audit carries the client IP, which is personal data under LGPD/GDPR, so set retention for wherever audit records are stored [x]
OpenTelemetry tracing module (drivers/otel) traces requests, propagates traceparent and adds trace_id / span_id to log records logged with the span's context (otel.LogHandler, installed on app.Log by the provider) (TestMiddleware_ServerSpanPerRequest, TestMiddleware_ExtractsTraceparentAndBaggage, TestLogHandler, TestProvider_CorrelatesRequestLogs) [x]
Trace spans (drivers/otel) record the route pattern, never the raw path or query string (TestSecurity_A09_OTelSpansOmitPathAndQuery) [x]
Outbound HTTP spans (drivers/otel Transport) record method, host, port and status, never the path or query string, and inject traceparent/baggage only with otel.WithClientPropagation(); database spans omit bound arguments (and the SQL text unless Config.QueryText), queue spans omit payloads, mail spans omit recipients, subject and body (TestSecurity_A09_OTelClientSpansOmitURLAndContext, TestObserver_Query, TestObserver_MailTransport) [x]
A malformed OTEL_EXPORTER_OTLP_*HEADERS (collector API keys) or other OTEL_* setting is a boot error that names the variable, never its value (TestSecurity_A09_OTelBadSettingsDoNotEchoHeaders) [x]
Devtools shows SQL as a normalized shape (literals replaced by ?) and bound arguments as types and lengths, never values; string literals in every form (escaped, double-quoted, PostgreSQL dollar-quoted) are stripped and SQL comments dropped, and request paths show Route.SecretParams values as {name}; job and event records carry kinds and types, not payloads (TestSecurity_A09_DevtoolsRedactsQueryArgs, TestSecurity_A09_DevtoolsHidesSecretParams, TestSecurity_A09_DevtoolsHidesSecretParamsWithInnerLogger, TestNormalizeSQL) [x]
The vukem bench report and JSON carry the class of a transport error (timeout, connection refused, eof, other), never its message, which can hold the URL TestSecurity_A09_BenchReportHasNoRawErrors

App responsibility: ship logs to durable storage and configure alerts on the security events.

A10:2025 — Mishandling of Exceptional Conditions

Default Check
Central error handler (single place) maps errors to responses; handlers return error instead of writing partial responses (TestErrorHandlerProblemJSON, TestErrorHandlerAfterWrite) [x]
Recover middleware converts panics to 500, logs stack trace server-side, never to the client (TestSecurity_A10_RecoverHidesPanic) [x]
Fail closed: authorization errors, missing policies, rate limiter store failures and CSRF check errors deny the request; a session store failure drops the session (the user is signed out) instead of reusing data (TestSecurity_A01_UnregisteredPolicyDenies, TestSecurity_A06_RateLimitMiddlewareFailsClosed, TestSecurity_A01_CrossOriginProtection, TestSecurity_A04_IdempotencyFailsClosed); a feature flag read whose store or cache fails returns the default (code default or FLAG_<NAME>), never a stored value, and flags.Require answers 404 (TestSecurity_A10_FlagReadsFailClosed) [x]
db.Tx rolls back on error or panic; no partial writes (TestTxCommitRollbackPanic) [x]
Generic client messages (RFC 9457 problem details) without internals (CWE-209); errors/<status> views get the raw error as .Error only with Services.Debug (TestSecurity_A10_InternalErrorsNotLeaked, TestSecurity_A10_ErrorViewErrorOnlyInDebug); errs.HTTPError.Extensions (problem+json extension members) are sent for 4xx only, or for a 5xx only when the app opted in with HTTPError.WithExtensionsOn5xx() (the app-chosen type, title and message are shown then; the wrapped cause stays hidden), and never replace a standard member (TestSecurity_A10_ProblemExtensionsNotSentOn5xx, TestSecurity_A10_ProblemExtensionsOn5xxAreOptIn); the issues member of a 422 never carries the error a Refine or Custom callback returned (TestSecurity_A10_ValidationIssuesHideCallbackErrors) [x]
A unique violation (orm.ErrConflict, or the Mongo driver's ErrDuplicate) answers 409 with a generic message: the driver text, constraint and key value stay in the error chain and the server log, never in the response; the driver, not the error text, decides what is a violation (TestSecurity_A10_ConflictResponseHidesDriverText, TestConflictIgnoresErrorText) [x]
GraphQL scalar Parse errors reach the client only when they are a graphql.Error or a 4xx without a cause; any other error, wrapped issues and 5xx become the generic "invalid value" message of the scalar, and a query cost or page size cannot be negative or null to dodge the complexity bound (TestSecurity_A10_GraphQLScalarParseErrorsMasked, TestSecurity_A06_GraphQLComplexityPageSizeArguments) [x]
vukem serve runs view:check after each rebuild as a warning only: it never blocks or restarts the server, its output is capped and cut on a line boundary, and the check stops when the serve context is cancelled (TestSecurity_A04_ServeViewCheckOutputIsBounded, TestSecurity_A04_ServeViewCheckStopsWhenCancelled) [x]
Inertia error pages (inertia.Inertia.ErrorPage, installed by vukem.WithInertia) get only a client-safe message: the error's own message for 4xx, the status text for 5xx and for 4xx errors that only wrap a cause; field errors only for 4xx validation errors (a 5xx wrapping one gets none); causes, SQL, paths and 5xx messages stay in the server log; a page whose props fail to resolve falls back to the HTML page (TestSecurity_A10_InertiaErrorPageHidesInternals, TestErrorHandlerErrorPage) [x]
A Refine or Custom error that is not a z.FieldError reaches clients as the generic "The {field} field is invalid." (its text only in Issue.Err and the server log); z.Issues wrapped with another status (errs.Wrap(500, err) for internal data) are not turned into a 422 with field errors; a 5xx wrapping an *errs.ValidationError (errs.Wrap(500, verr)) sends no field errors either: the problem response, the form redirect-back and the JSON-RPC reply (-32603, no data.fields) treat it as a plain server error (TestSecurity_A10_RefineErrorTextNotLeaked, TestSecurity_A10_ZIssuesFailClosed, TestSecurity_A10_ServerErrorHidesWrappedValidation, TestSecurity_A10_JSONRPCServerErrorHidesWrappedValidation) [x]
Readiness probes (app.ReadyHandler(), /up?checks=1) report only ok/fail per check; error text (hosts, DSNs) and check panics are logged, never returned; every check has its own timeout, so a hung dependency cannot hang the probe, and while an abandoned run is still going the check fails at once instead of spawning another goroutine (TestSecurity_A10_ReadyHandlerHidesErrors, TestReadyHandlerPerCheckTimeout, TestSecurity_A10_HungHealthCheckRunsOnce) [x]
Missing/invalid parameters produce 400/422 with field errors, never zero-value defaults silently (CWE-234) (TestBindJSONErrors, TestParseJSONSuccessAndProblem) [x]
Timeouts on server, DB queries (context), outbound HTTP; rate limiting and quotas against resource exhaustion (TestSecurity_A02_ServerTimeouts, TestTimeout, TestLimitsAndAllowedServer, TestSecurity_A06_RateLimitMiddlewareFailsClosed) [x]
LOG_TRUNCATE_IP=true (middleware.LoggerOptions.TruncateIP) makes the request log write the /24 (IPv4, IPv4-mapped included) or /48 (IPv6) network in peer and ip instead of the address; off by default (TestSecurity_A09_LoggerTruncatesIPs) [x]
Repeated identical errors aggregated in logs to keep alerting useful: in production the default logger writes the first ERROR of a kind, counts repeats for LOG_DEDUP_WINDOW (1m) and writes one repeated summary with the count (logging.Dedup) (TestSecurity_A09_RepeatedErrorsAggregated, TestDedup, TestDedupConcurrent) [x]
RPC errors (contrib/grpc): unknown errors and panics reach clients as Internal "internal error", the cause and stack only in the server log, and a returned or wrapped *connect.Error with a server-fault code (Internal, Unknown, DataLoss, Unavailable) keeps its code but not its text; an *errs.HTTPError or errs.StatusCoder with a 5xx status keeps its mapped code (Internal, Unavailable, Unimplemented, DeadlineExceeded) but reaches clients as "internal error" (translated keyed messages included, and errs.Wrap(500, issues) gets no field violations) while the cause is logged at error level and only its Retry-After header becomes metadata; a message's Validate() error becomes InvalidArgument only for known validation errors (z.Issues, *errs.ValidationError, Field()/Reason() errors), anything else is masked and logged; a returned *connect.Error with another code, like a *graphql.Error, keeps its text as the app's explicit choice (TestSecurity_A10_GRPCInternalErrorsHidden, TestSecurity_A10_GRPCConnectErrorsMasked, TestSecurity_A10_GRPCServerHTTPErrorsMasked, TestSecurity_A10_GRPCServerHTTPErrorsLogged, TestSecurity_A10_GRPCValidateErrorsMasked, TestSecurity_A10_GRPCServerErrorHeadersAllowlisted); request messages are capped at 4 MiB (ResourceExhausted beyond, TestSecurity_A10_GRPCMessageSizeLimited) [x]
errcheck, nilerr, errorlint, forcetypeassert linters enforce handled errors in the framework itself (enforced by .golangci.yml) [x]
GraphQL resolver errors that are not client-safe (plain errors, 5xx, panics, serialization failures) are reported as Internal server error with code INTERNAL_SERVER_ERROR and logged; their text appears only with WithDebug(true); a 4xx error that wraps a cause (orm's unique-constraint conflict wraps the driver error) gets only its status text ; a 5xx *errs.HTTPError hides its (translated) message and any field errors it wraps; an argument Validate() error follows the same rules, so a plain error is masked and logged (TestSecurity_A10_GraphQLValidateErrorsMasked, TestSecurity_A10_GraphQLInternalErrorsMasked, TestSecurity_A10_GraphQLClientErrorsMasked, TestSecurity_A10_GraphQLServerHTTPErrorsMasked) [x]
vukem bench and loadtest send load to loopback hosts only: localhost, *.localhost and loopback IPs. Any other host needs -allow-remote <host> (exact match, a statement of ownership), the host is checked for every request, the connection itself is pinned to a loopback address (a name that resolves to an internal address, or a DNS answer that changes, is refused), redirects are never followed, URLs with credentials are refused, and a run is capped in duration, rate, workers, timeout and requests TestSecurity_A10_BenchRefusesNonLoopbackTarget, TestSecurity_A10_BenchAllowsLoopback, TestSecurity_A10_BenchAllowRemoteIsExactHost, TestSecurity_A10_BenchChecksEveryTargetHost, TestSecurity_A10_BenchPinsTheDialToLoopback, TestSecurity_A10_BenchDoesNotFollowRedirects, TestSecurity_A10_BenchRejectsURLCredentials, TestSecurity_A10_BenchScenarioClientRefusesRemoteHost, TestSecurity_A10_BenchCLIRefusesRemoteTarget

Apps without a persistent key

A stateless app (a desktop or standalone binary, a cookieless API) needs APP_KEY in production by default: the check is fail-closed on purpose, because a forgotten key must never boot with sessions or encryption silently disabled. MiddlewareOptions.Stateless drops the session middleware but does not lift the key requirement.

An app that uses no key-derived feature can say so with vukem.WithKeyOptional(): a missing APP_KEY then boots in any APP_ENV, production included. The declaration is explicit and per app, so a forgotten key in an app that does not declare it still refuses the boot. Nothing that needs the key is enabled by it: app.DeriveKey returns config.ErrKeyMissing (the message names WithKeyOptional), config.Key.Derive panics, app.Crypt is nil, cookie sessions refuse to start (a boot error with DefaultMiddleware; use SESSION_DRIVER=memory or database, or MiddlewareOptions.Stateless), the DB gets no encrypter and the maintenance bypass cookie is disabled. A malformed APP_KEY and every other production check (APP_DEBUG, devtools, CORS) still refuse the boot, and the development warning about the missing key is not logged (TestSecurity_A02_KeyOptionalIsExplicit, TestSecurity_A04_KeyOptionalKeepsKeyFeaturesClosed).

When nothing needs to survive a restart, generate an ephemeral key per process and hand it to the app before New: config.GenerateKey() returns a fresh APP_KEY value, so a WithEnvDefaults(map[string]string{"APP_KEY": config.GenerateKey()}) (or a WithSource built from it) boots in any APP_ENV. The cost is explicit: every value sealed or signed with it (encrypted cookies, signed URLs, queued mail payloads) stops opening after a restart, and a second instance cannot read the first one's. If that is not acceptable, set a persistent APP_KEY and keep it in the same secret store as the other secrets.

Key rotation

APP_KEY derives (HKDF, one label per purpose) every key the framework uses: app.Crypt (encrypted cookies, orm.Encrypted columns, queued mail payloads), cookie sessions (and so the CSRF token and flash data they carry), the maintenance bypass cookie, and the keys apps derive with app.DeriveKey (signed URLs, social login state). Remember-me tokens, API tokens and refresh tokens are stored as hashes and JWT keys are configured separately, so they do not depend on APP_KEY.

  1. Rotate. Locally, vukem key:rotate writes a new APP_KEY to .env and moves the old one to the front of APP_PREVIOUS_KEYS (no key is printed). In production, generate a key (vukem key:generate --show or ./app key:generate), then set APP_PREVIOUS_KEYS=<old APP_KEY>[,<older>...] and APP_KEY=<new key> in the secret store, and deploy every instance with both: an instance with only the old key cannot open what the others now write.
  2. Overlap window. Values sealed or signed with a previous key keep working: app.Crypt tokens, cookie sessions (re-sealed with the new key on the next request that reads them), the maintenance bypass cookie (re-issued), and signed URLs and social state for apps that pass app.DerivePreviousKeys(purpose, 32) to signed.Signer.WithPreviousKeys / social.Social.WithPreviousKeys (the install:auth scaffolds do). Everything new uses APP_KEY.
  3. Drain. Before removing the old key, wait for the longest lifetime of what it signed: SESSION_LIFETIME (cookie sessions not used since the rotation are not re-sealed), the TTL of signed links already sent (links signed without a TTL never expire, so they stop working), queued and failed mail jobs, 12 hours for maintenance bypass cookies, and the MaxAge of encrypted cookies. Re-seal orm.Encrypted columns with orm.Reseal[T] or the app command crypt:reseal (vukem.ResealCommand(orm.Reseal[models.User], ...)): it rewrites only values sealed with a previous key, compare-and-set so a concurrent save is never overwritten, and a value no key opens stops it with crypt.ErrInvalid (TestSecurity_A04_ResealRotatesEncryptedColumns, TestResealSkipsConcurrentWrites, TestResealFailsClosed); saving a row also re-seals its columns and re-seal other stored app.Crypt tokens with NeedsRotation / Rotate.
  4. Remove the old key from APP_PREVIOUS_KEYS. Whatever is still sealed with it fails closed: the session is empty (the user is signed out), signed links answer 403, mail jobs fail instead of sending, and encrypted columns return crypt.ErrInvalid.

A previous key still verifies cookie sessions and signed URLs, so whoever holds it can forge them for the whole window. After a leak, do not keep the leaked key in APP_PREVIOUS_KEYS in production: accept that sessions and links are invalidated, and re-encrypt stored data in a short maintenance window (or a one-off job) that has the leaked key, then drop it.

Security headers (defaults)

Header Value
Content-Security-Policy starter: default-src 'self'; script-src 'self' 'nonce-…'; style-src 'self' 'nonce-…'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'
Strict-Transport-Security max-age=63072000; includeSubDomains (HTTPS only)
X-Content-Type-Options nosniff
X-Frame-Options DENY
Referrer-Policy strict-origin-when-cross-origin
Cross-Origin-Opener-Policy same-origin
Permissions-Policy camera=(), microphone=(), geolocation=()

All configurable in config/http.go (MiddlewareOptions.SecureHeaders, APIMiddlewareOptions.SecureHeaders). The API stack (vukem.APIMiddleware) sends the same set, CSP included: on a JSON response the CSP and X-Frame-Options are inert, and they protect any HTML an API route might return. SecureHeaders runs before Maintenance on both stacks, so the maintenance 503 carries these headers too (TestSecurity_A05_MaintenanceResponseCarriesSecurityHeaders).

Building blocks

Package Use
httpclient.Safe(opts) outbound requests to user-supplied URLs: only public addresses (checked on the resolved IP at connect time, so DNS rebinding and redirects to internal hosts fail), http(s) only, timeouts, redirect and body limits (TestSecurity_A01_SSRF*)
app.Crypt / crypt.New(key, previous...) encryption with key rotation, encrypted cookies, orm.Encrypted[T] (subsystems.md)
signed.New(key) signed URLs with expiry, constant-time verification, 403 middleware, WithPreviousKeys for APP_KEY rotation (TestSecurity_A01_SignedURLTampering, TestSecurity_A04_SignedURLKeyRotation)
webhook.VerifyHMAC, webhook.Middleware incoming webhooks signed with HMAC-SHA256 (hex or base64, sha256= prefix), body size limit, 401 (TestSecurity_A08_WebhookMiddleware)
webhook.Sender, webhook.NewSecret outgoing webhooks: Standard Webhooks signatures, httpclient.Safe delivery from a queue job, retries with backoff, 410 stops, SQLDeliveryLog of attempts (TestSecurity_A01_OutgoingWebhookSSRF, TestSecurity_A04_OutgoingWebhookRequiresHTTPS, TestSecurity_A09_OutgoingWebhookLogsNoSecrets)
security.Event every web.SecurityEvent (login failures, authz.denied, CSRF, rate limits, bad signatures) is also dispatched on app.Events for alerting: events.Listen(app.Events, func(ctx, e security.Event) error {...})
security.Audit every web.AuditEvent (routine records at INFO, such as a payout recorded by an admin) is dispatched on app.Events as this distinct type: events.Listen(app.Events, func(ctx, a security.Audit) error {...})
depguard crypto-randomness math/rand is a lint error in auth, session, csrf, signed, crypt, social, webhook, config, uuid and ulid

Verification

  • Every default above names the test that asserts it (TestSecurity_<Category>_<Behaviour> where the row is security-specific, e.g. TestSecurity_A01_StaticRejectsTraversal) or the mechanism that enforces it (lint rule, CI job, release config), so go test -run TestSecurity ./... is the security regression suite.
  • Fuzz targets for parsers that see untrusted input (router patterns and request paths, .env, JSON and form binding, multipart, tus headers, upload names, cookie sessions, JWTs, crypt tokens, storage paths, locale tags, webhook and Stripe signatures, GraphQL documents) run for an hour each every week (fuzz.yml).
  • CI: gosec (via golangci-lint), govulncheck, CodeQL, OpenSSF Scorecard.
  • BETA gate B.5.2: security review against this document and ASVS 5.0 Level 2, with findings, residual risks and fuzzing results.

References