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¶
- Upgrade the root module and run
go mod tidy. - Convert constructors and registrations that now return
error. - Migrate custom authentication and idempotency stores to their atomic interfaces.
- Review every explicit security opt-out and resource limit below.
- Run the application's race, vulnerability, and integration gates.
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:
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.Secureis removed. Cookies are secure by default; isolated local HTTP development must setAllowInsecureCookie: true.- Replace
Manager.Save(w, session)withManager.SaveContext(ctx, w, session). - Impersonation audit callbacks now accept
context.Contextand returnerror. MountExitHandleron a POST route behind CSRF protection; the old query-parameter exit is ignored. - Password
MinScore: 0now selects the default score of 3. SetDisableStrengthCheck: trueto 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.keyas 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.TrustXFFis rejected. Install CIDR-gatedmiddleware.TrustProxybefore the limiter. Multi-replica deployments should provide a sharedOptions.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: truefor enqueue-only River clients. - Workflow dialing has a five-second default; set a positive
workflow.connect_timeoutwhen another finite bound is needed. - Replace
handler.OnComplete(callback)withhandler.OnComplete("stable-handler-id", callback)and handle duplicate-ID errors. Keep the identifier stable across restarts. - Pass
*Jobto TinyRegistry.SaveJob; generated ID and timestamp fields are written back to that value. - Handle the error returned by
tenancy.MemoryStore.Add. Extractors now returnTenantRefByID(...)orTenantRefBySlug(...), 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
HandlerWithOptionsand a boundedWithMaxRequestBodyBytesfor larger legitimate requests. Paging is capped at 1000 results. secrets.Fileaccepts confined regular files no larger than 64 KiB and requires a live context. Split larger data or use another backend.secrets.Staticsnapshots 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
MaxPathsmeans 1024; large bursts arrive as sorted split batches, andEventscloses after an upstream watcher error. - ETag middleware buffers at most 1 MiB by default. Larger or streaming
responses pass through without an ETag; use
ETagWithLimitfor a measured larger cap. - Trusted-proxy processing evaluates
X-Forwarded-Forright-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. UseNewProviderwith a caller context for cancellable discovery.
Resource bounds and unattended execution¶
- TUS uploads default to a 5 GiB
MaxSizeand a 15-minute sweep interval. An emptyScratchDiruses 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*Bytesfields 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
PublisherVerifierwithNewPublisherVerifier; 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
WakeContextorWakeToContextfor another deadline. - FASTA parsing defaults to 64 MiB input, 100,000 records, and 1 MiB lines.
Use
ParseFASTAContextwith explicit boundedFASTAOptionsfor 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
MaxSourceBytesorStrip.MaxBytesonly to a known positive bound.
Data and runtime semantics¶
- CDC startup now fails with
ErrNoHandlerwhen 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 typedOldValuesandNewValues; 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
DiffandMetadata. Keep values in a bounded JSON-like graph without functions, channels, unsafe values, non-string map keys, or mutable unexported fields. UseAllCheckedwhen a snapshot error must be reported; legacyAllreturns nil on failure. - SSE rejects carriage return, line feed, and NUL in event IDs and names.
WebRTC offers require exact
Content-Type: application/sdpwithout parameters.
Data and module changes¶
storage.Objectnow carries metadata and is not comparable. UseKeyor 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; prefermemory.Typed[K, V]for a stable typed contract. - Gemma writes
adapter.lora.h5, notlora.keras. Usegemma.ArtifactNameinstead of a literal. science/bio.DNASeqandRNASeqare removed. Construct Biogolinear.Seqvalues withalphabet.DNAoralphabet.RNAdirectly.- Replace requirements on
github.com/golusoris/golusoris/deploy/pulumiand/deploy/multiregionwith the consolidatedgithub.com/golusoris/golusoris/deploymodule. 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: