Skip to content

Migration guide — v0.13.0

v0.13.0 applies the current Praetor contract across every Go module and hardens authentication, HTTP, storage, jobs, model training, and update paths. It intentionally changes pre-1.0 APIs where the old shape could not report invalid configuration, make a state transition atomically, or carry a caller deadline.

Compile errors identify the signature changes. The secure-default changes later in this guide keep their signatures and therefore need a deliberate configuration review.

Upgrade sequence

  1. Upgrade the root module and run go mod tidy.
  2. Convert constructors and registrations that now return error.
  3. Migrate custom authentication and idempotency stores to their atomic interfaces.
  4. Review every explicit security opt-out and resource limit below.
  5. Run the application's race, vulnerability, and integration gates.
go get github.com/golusoris/golusoris@v0.13.0
go mod tidy
go test -race ./...
govulncheck ./...

Constructors now fail closed

The following constructors now return (value, error):

Package Constructor
auth/policy New
auth/lockout New
auth/linking New, NewWithClock
auth/session NewManager, NewMemoryStoreWithClock
ai/llm NewOpenAIClient
ai/llm/anthropic New
ai/llm/ollama New
notify/unsub New
notify/tracking New
httpx/cors New
webhooks/in Stripe, GitHub, GitHubLegacy, Slack, HMAC
db/bun New

Propagate the error before exposing the component:

// Before
mw := cors.New(opts)
client := llm.NewOpenAIClient(config)

// After
mw, err := cors.New(opts)
if err != nil {
    return err
}
client, err := llm.NewOpenAIClient(config)
if err != nil {
    return err
}

cors.New rejects credentials combined with a wildcard origin. Configure explicit origins when credentials are enabled.

Atomic authentication and idempotency stores

Custom stores must implement the new atomic operations. Restoring the split read/write APIs would reopen replay, ownership, or lost-update races.

Package Replace With
auth/magiclink Find then MarkUsed Consume(ctx, hash)
auth/recovery codes FindForUser then MarkUsed Consume(ctx, userID, hash)
auth/recovery tokens Find then MarkUsed Consume(ctx, hash)
auth/linking Save, Delete Claim, DeleteOwned
auth/lockout Set RecordFailure(ctx, key, now, opts)
idempotency Find, Save Claim, Commit, Release
// Before: two operations can race.
link, err := magicStore.Find(ctx, hash)
err = magicStore.MarkUsed(ctx, hash)

// After: consumption is one store operation.
link, err := magicStore.Consume(ctx, hash)

// Linking now proves ownership when deleting.
stored, err := identityStore.Claim(ctx, identity)
err = identityStore.DeleteOwned(ctx, userID, provider, subject)
err = linkingService.Unlink(ctx, userID, provider, subject)

Idempotency claims return a reservation token and state. Commit only with the matching token, release on handler or commit failure, and return conflict for in-flight or fingerprint-mismatched reuse. Keys now include method, host, target, tenant, and an optional principal scope:

opts.Scope = idempotency.NewScopeFunc(func(r *http.Request) (string, error) {
    return authenticatedPrincipal(r.Context()), nil
})

Request and response capture default to 1 MiB. Set positive MaxRequestBody and MaxResponseBody values when a route has a larger known bound.

Authentication and provider endpoints

reCAPTCHA v2 and v3 are explicit

NewRecaptcha(secret, client) is v2-only and rejects responses containing v3 score or action fields. Construct v3 verification with its policy:

verifier, err := captcha.NewRecaptchaV3(secret, client, 0.5, "login")
if err != nil {
    return err
}

The v3 verifier requires an exact action match and a finite score at or above the threshold. Provider non-2xx, oversized, malformed, or inconsistent responses fail closed.

Provider webhooks require verifiers

Postmark and SES inbound and bounce handlers now take authenticators:

postmarkHandler := inbound.Postmark(postmarkVerifier, handler)
sesHandler := inbound.SES(snsVerifier, handler)

Use notify/postmark.NewBasicAuthVerifier or an equivalent pinned verifier. A nil verifier rejects the request.

Other authentication changes

  • auth/session.Options.Secure is removed. Cookies are secure by default; isolated local HTTP development must set AllowInsecureCookie: true.
  • Replace Manager.Save(w, session) with Manager.SaveContext(ctx, w, session).
  • Impersonation audit callbacks now accept context.Context and return error. Mount ExitHandler on a POST route behind CSRF protection; the old query-parameter exit is ignored.
  • Password MinScore: 0 now selects the default score of 3. Set DisableStrengthCheck: true to disable strength scoring explicitly.
  • JWT HMAC keys must be at least the hash size, TTL must be at least one second, and parsed tokens require exp. Signers add expiry when absent.
  • Configure crypto.key as a hex-encoded 16, 24, or 32-byte key. The crypto module no longer derives it from JWT material or supplies a development key.
  • OAuth public clients must use PKCE S256 with a 43–128 character verifier. Register exact redirect URIs, allowed scopes, valid client IDs, and secrets for confidential clients. Authorization is GET-only and token exchange is POST-only.
  • httpx/ratelimit.Options.TrustXFF is rejected. Install CIDR-gated middleware.TrustProxy before the limiter. Multi-replica deployments should provide a shared Options.Store.

Lifecycle, context, and ownership changes

CertMagic

certmagic.New returns a lifecycle-owned *Manager, not a *tls.Config:

manager, err := certmagic.New(opts)
if err != nil {
    return err
}
if err := manager.Start(ctx); err != nil {
    return err
}
defer manager.Close()

tlsConfig := manager.TLSConfig()

The Fx module owns startup and shutdown when used. The returned TLS config advertises HTTP/2, HTTP/1.1, and the retained ACME TLS-ALPN challenge protocol.

Registrations and callbacks

  • Handle the error returned by jobs.Register.
  • Set jobs.producer_only: true for enqueue-only River clients.
  • Workflow dialing has a five-second default; set a positive workflow.connect_timeout when another finite bound is needed.
  • Replace handler.OnComplete(callback) with handler.OnComplete("stable-handler-id", callback) and handle duplicate-ID errors. Keep the identifier stable across restarts.
  • Pass *Job to Tiny Registry.SaveJob; generated ID and timestamp fields are written back to that value.
  • Handle the error returned by tenancy.MemoryStore.Add. Extractors now return TenantRefByID(...) or TenantRefBySlug(...), not an ambiguous string.

jobs/ui rejects empty or root prefixes. The old Options.User and Options.Password fields were ignored and are now rejected; wrap the handler with WithBasicAuth instead.

Secure defaults with unchanged signatures

Surface New behavior Caller action
API docs MCP /mcp is absent by default Set EnableMCP and a non-nil MCPAuthorize
HTTP retries Unsafe methods do not retry Send Idempotency-Key or explicitly set Retry.AllowUnsafe
HTTP server body Zero means a 10 MiB limit Set AllowUnlimitedBody only for an intentionally unlimited route
Storage listing Zero means 1000; values above 1000 fail Narrow the prefix or request a bounded limit
SMTP server AUTH Plaintext AUTH is disabled Configure TLS, or isolated-dev AllowInsecureAuth
SMTP sender Port 587 with TLS is the zero-value default Use isolated-dev AllowInsecurePlaintext for port 25
Outbound webhooks HTTPS and public destinations only; redirects refused Use local-only AllowInsecureHTTP or AllowPrivateNetwork opt-ins
Web Push Subscription endpoint must be absolute HTTPS Re-register invalid subscriptions
Postgres test containers testutil/pg fails the test at start when Options.Image is not repository:tag@sha256:<64 hex> Pin a custom image by digest, or leave Image empty for the repository pin

testutil/pg (Start, StartReplication, StartTimescale and DSN) validates Options.Image with the same rule as the repository pins: a tag alone or a digest alone is rejected before any container starts. Resolve the digest of a custom image with docker buildx imagetools inspect <image>:<tag> and pass <image>:<tag>@sha256:<digest>. The other testutil container helpers take no image override and always run their pinned digests.

notify.SMTPOptions.TLS is removed. Configure TLS through the secure default; AllowInsecurePlaintext is the explicit development escape hatch. Set SMTPOptions.Timeout when the default bound is not suitable.

storage.List returns one bounded page, so the old unbounded exhaustive listing behavior is unavailable. In v0.13.x, split large namespaces by prefix. From v0.14.0, pass the last key of a page as ListOptions.StartAfter to read the next page, or let storage.Walk loop over every page.

Storage keys now follow one backend-neutral canonical contract. Normalize persisted or generated keys to relative slash paths and preflight them with storage.CleanKey(key, storage.MaxKeyBytes) or storage.MustBeLocal. Local and S3 operations reject empty or absolute keys, dot traversal, duplicate separators, backslashes, control or Windows-invalid characters, trailing dots or spaces, Windows device names, internal .golusoris-* namespaces, and keys above 1024 bytes. S3 access and secret keys must be supplied together.

Additional credential and input hardening

  • HMAC secrets for API keys, magic links, recovery, tracking, and unsubscribe must be at least 32 bytes. Replace shorter secrets before construction; rotating them invalidates existing raw credentials. API-key issuance also rejects blank owners.
  • SCIM request JSON defaults to a 1 MiB cap, must contain exactly one value, and must declare the matching User or Group schema URI. Use HandlerWithOptions and a bounded WithMaxRequestBodyBytes for larger legitimate requests. Paging is capped at 1000 results.
  • secrets.File accepts confined regular files no larger than 64 KiB and requires a live context. Split larger data or use another backend. secrets.Static snapshots its input map.
  • External-client paths must remain relative and same-origin; base-URL userinfo and cross-origin redirects are rejected. Successful responses above 8 MiB return ErrResponseTooLarge; use a dedicated streaming client for larger payloads.
  • Filesystem watch options reject negative values. Zero MaxPaths means 1024; large bursts arrive as sorted split batches, and Events closes after an upstream watcher error.
  • ETag middleware buffers at most 1 MiB by default. Larger or streaming responses pass through without an ETag; use ETagWithLimit for a measured larger cap.
  • Trusted-proxy processing evaluates X-Forwarded-For right-to-left and strips forwarding headers from untrusted peers. Configure every trusted proxy CIDR, not only the edge.
  • OIDC discovery defaults to ten seconds, custom scope sets always include openid, and authorization URLs require nonempty state. Use NewProvider with a caller context for cancellable discovery.

Resource bounds and unattended execution

  • TUS uploads default to a 5 GiB MaxSize and a 15-minute sweep interval. An empty ScratchDir uses process-private temporary storage, so configure a stable scratch directory when resumability must survive a restart.
  • Enabled API-docs MCP requests validate arguments against the OpenAPI operation, keep redirects on the original origin, and cap responses at 1 MiB.
  • PDF parsing rejects a nil context, and PDF merging accepts at most 256 inputs. Pass a live context and split larger merges into bounded batches.
  • FCM construction requires exactly one service-account source, caps OAuth responses at 1 MiB, and gives a zero client timeout a ten-second bound. APNs P8 authentication keys must use ECDSA P-256.
  • LLM clients default to a finite HTTP timeout, 4 MiB response bodies, 64 KiB error bodies, and 1 MiB stream frames. Raise the corresponding positive Max*Bytes fields only for measured provider payloads.
  • Tiny runner timeout zero now means two hours. A canonical dataset root and image are required; mutable image references require AllowUnpinnedImage. Dataset, output, log, metric, temporary-file-system, and serialized-input budgets are enforced. Gemma and LiteRT expose matching explicit bounds.
  • Self-update accepts only newer strict semantic versions, exact platform archives and binary members, and authenticated checksum plus Sigstore data. Configure PublisherVerifier with NewPublisherVerifier; the default asset cap is 256 MiB and the operation timeout is ten minutes.
  • Wake-on-LAN convenience wrappers now time out after five seconds. Use WakeContext or WakeToContext for another deadline.
  • FASTA parsing defaults to 64 MiB input, 100,000 records, and 1 MiB lines. Use ParseFASTAContext with explicit bounded FASTAOptions for larger data.
  • Media/audio, Meilisearch, Typesense, and FCM response paths now apply finite zero-value bounds. Set positive limits for larger legitimate workloads.
  • Image-pipeline sources and storage image sanitization default to 32 MiB encoded input. Raise MaxSourceBytes or Strip.MaxBytes only to a known positive bound.

Data and runtime semantics

  • CDC startup now fails with ErrNoHandler when replication is configured without a consumer. Slot names must match [a-z0-9_]{1,63}, standby frequency must be 1–1000 Hz, and reconnect delay must not be negative. Handler failures leave the transaction unacknowledged and reconnect for at-least-once delivery, so handlers must be idempotent. Prefer typed OldValues and NewValues; legacy string maps are lossy.
  • Apply the updated outbox migration that adds next_attempt_at. A zero pending limit now means 100, negative limits fail, and values above 1000 are capped. Missing rows and nil failures are errors. Drainers use row locks and transactional River insertion for multi-replica at-least-once delivery; workers must remain idempotent.
  • PostgreSQL, SQLite, Timescale, and Bun construction now reject invalid pool, retry, timeout, duration, identifier, logger, and dependency values instead of coercing them. Fix the configuration rather than relying on a fallback.
  • Generated search filters reject unsafe field names and non-scalar values. Use letters, digits, underscore, and dot in field names and string, boolean, integer, unsigned-integer, or finite floating-point values. Typesense bulk indexing now fails when any per-document result fails or the result count differs from the request.
  • The audit memory store snapshots Diff and Metadata. Keep values in a bounded JSON-like graph without functions, channels, unsafe values, non-string map keys, or mutable unexported fields. Use AllChecked when a snapshot error must be reported; legacy All returns nil on failure.
  • SSE rejects carriage return, line feed, and NUL in event IDs and names. WebRTC offers require exact Content-Type: application/sdp without parameters.

Data and module changes

  • storage.Object now carries metadata and is not comparable. Use Key or another immutable identity for maps and equality.
  • Memory-cache keys preserve exact identity and the untyped cache surface accepts any. Custom adapters and mocks must do the same; prefer memory.Typed[K, V] for a stable typed contract.
  • Gemma writes adapter.lora.h5, not lora.keras. Use gemma.ArtifactName instead of a literal.
  • science/bio.DNASeq and RNASeq are removed. Construct Biogo linear.Seq values with alphabet.DNA or alphabet.RNA directly.
  • Replace requirements on github.com/golusoris/golusoris/deploy/pulumi and /deploy/multiregion with the consolidated github.com/golusoris/golusoris/deploy module. Package import paths remain unchanged.

Verification

After compilation succeeds, test negative and boundary paths for every custom store, verifier, explicit security opt-out, and raised resource bound. The repository's reference gate is:

make verify-all