Repository navigation
Releases
7.1.0
Added
confirmation_token(ctoken_...) optional request field onPOST /api/v1/orders/{order_id}/payas an alternative topayment_method_token(pm_...): clients must send exactly one of the two (422 otherwise), both are included in the idempotency request fingerprint, and the in-process mock provider acceptsctoken_card_*equivalents of itspm_card_*test cards.- Every consent record (registration, consent changes, marketing changes in the profile) carries
privacy_policy_version, the version of the privacy policy in force at that moment, so that which text a person agreed to can be shown (GDPR Art. 7(1)). It is inconsent_historyofGET /api/v1/legal/consent-status; records written before 7.1.0 have it as null. - Security audit events on the
app.auditlogger: failed logins (with the reason, server side only), refresh token replays, admin requests that change something and admin routes refused to non-admins, password resets, logouts and personal data export and deletion requests. Ids only, no emails or tokens; see docs/OPERATIONS.md. - The 409
insufficient-stockresponse ofPOST /api/v1/cart/itemsandPUT /api/v1/cart/items/{product_id}now carriesavailable(units in stock) andrequested(the requested line total). rate_limit.exceededaudit event (WARNING) for every request refused with 429 by the rate limiter, with the operation (method and route template) and the limit that applied; nothing about the caller.- JSON log lines carry
stack_infowhen a record was logged withstack_info=True. BCRYPT_WAIT_TIMEOUT_SECONDS(default 10): a request that waits that long for a password hashing slot is answered 503service-overloadedwithRetry-After: 5instead of queueing without limit. Affects register, login, password reset confirmation and account deletion under a flood of password checks.- Stripe Radar early fraud warnings (
radar.early_fraud_warning.createdandradar.early_fraud_warning.updated) are recorded per payment and shown to admins:GET /api/v1/orders/{order_id}/paymentslists them under each payment'sfraud_warnings, andGET /api/v1/admin/paymentshas ahas_fraud_warningfield and ahas_fraud_warning=true|falsefilter. Nothing changes automatically: the order, its payment status and its refunds are untouched and no refund is issued. The webhook endpoint must be subscribed to the two new event types.
Upgrade notes
BCRYPT_ROUNDSabove 15 is refused at startup (it was accepted up to bcrypt's own 31). Each step doubles the cost of every login: 16 is about 5 s a hash. A deployment with a value above 15 must lower it.- The HTTP API is unchanged. Operators who traced with
OTEL_*and an image built withINSTALL_TELEMETRY=trueget no spans after the upgrade, and the build argument is ignored; remove both from the deployment.
Removed
ESSENTIAL_COOKIESandCOOKIE_CONSENT_EXPIRE_DAYSsettings: the application sets only the guest cart cookie (notsession,csrf_tokenor a consent cookie).- The
RELOADsetting. Nothing read it: uvicorn's auto-reload followsDEBUG(on in development). Setting it has no effect, as before. - OpenTelemetry tracing:
app/core/telemetry.py, thetelemetryextra, theINSTALL_TELEMETRYbuild argument of the image and the OpenTelemetry SDK, exporter and instrumentation packages (with protobuf and wrapt, which only they needed).OTEL_*variables are no longer read.opentelemetry-apistays in the lock as a dependency of FastAPI itself; without an SDK it does nothing. Logs keeprequest_idand thetrace_idof an incomingtraceparent, in the API and in Celery tasks. A single API and worker are debugged by these ids and the slow statement log; distributed tracing pays off across several services, which this project does not have. RedisService.update_cart/delete_cartandAsyncRedisService.update_cart/delete_cart, which nothing in the application called. Internal only; no API change.
Changed
- The order email sent when an order is created now says the order was received and is awaiting payment (
Order #<id> received - awaiting payment); a successful payment sends its own "payment received, order confirmed" email instead of the generic order-status-update email. POST /api/v1/orders/{order_id}/paynow creates and confirms a PaymentIntent in a single StripePaymentIntent.create(..., confirm=True)call using the attempt's provider idempotency key (no separate:confirmcall or key for new attempts). Legacyunknownattempts created before 7.1.0 that already hold an unconfirmed PaymentIntent id still complete viaconfirmwith the:confirmkey on retry.- Legal documents (
privacy-policy.md,terms-of-service.md,cookie-policy.md) moved from inline strings inapp/api/v1/legal.pyto versioned Markdown files underapp/legal/(version1.1, effective2026-11-28), overridable viaLEGAL_DOCS_DIR, and corrected outdated or inaccurate statements (removed the closed EU Online Dispute Resolution platform reference, fixed Directive 2011/83/EU Art. 13(1) refund timing and the account age wording in terms, added recipients, GDPR Chapter V transfer safeguards and Art. 18 restriction right in the privacy policy, and aligned the cookie policy with the guest cart cookie only). - Privacy policy
1.2(effective2026-12-01) adds the GDPR Art. 13(2)(e) statutory/contractual requirement and the consequences of not providing data, the Art. 13(2)(f) statement that no automated decision-making or profiling with legal effect takes place, a table tying each purpose to its legal basis, and separate retention for account data and accounting records. - Email bodies are rendered from Jinja2 HTML templates under
app/templates/email/withautoescape=TrueandStrictUndefinedviaapp/services/email/templates.py(addingjinja23.1.6), replacing f-strings and manualhtml.escapecalls inapp/services/email/messages.py. - Security headers: tighten
Permissions-Policyto the OWASP Secure Headers Project baseline (headers_add.json, 2026-11-23) and addbase-uri 'none'; form-action 'none'to the APIContent-Security-Policy(base-uri 'self'; form-action 'self'on docs pages). - Structured logging: uvicorn's own server and error lines (
UVICORN_LOG_CONFIGpassed touvicorn.run) are written as one-line JSON to stdout, andJSONFormatterkeeps non-ASCII characters unescaped (ensure_ascii=False). - The application is built by
app.main.create_app()(the module still exposesapp = create_app(), souvicorn app.main:appis unchanged), and logging is configured when the application starts, in its lifespan, not whenapp.mainis imported. A server started with--lifespan offtherefore keeps Python's default logging. - A stored cart that cannot be read (corrupt, or written in an incompatible format) is no longer lost: the next cart change keeps the old raw value under
<cart key>:unreadablewith the cart's TTL and logs a WARNING (an account cart by its account id, a guest cart without its id). It used to be replaced by an empty cart and overwritten. - PostgreSQL in Compose logs statements of 500 ms or more with their duration and SQL text, without bound values (
log_min_duration_statement=500ms,log_parameter_max_length=0); see docs/OPERATIONS.md. - Images: uv 0.13.9 in the app image (was 0.13.6); the PostgreSQL 18.6 and Redis 8.8 (8.8.4) base images on their current digests (rebuilt 2026-11-11 and 2026-11-12).
- CI: uv 0.13.9, astral-sh/setup-uv v10.4.0, Trivy 0.76.2, the service images on the new digests. The log is shorter: quiet
uv syncanduv export, no list of the expected skips in the test job, coverage tables only for files below 100%, one Trivy database download per run instead of three, without a progress bar or a table of clean packages, no build record artifact, andalembic upgrade headin the test setup prints only when it fails. The run page shows the coverage table (files below 100%), and the test job lists its tests slower than one second. - CI
docker-build: after the Trivy scan, startdocker-compose.yml(db,redis,migrate,api) inproductionmode (.env.examplewith secrets generated for the run, the Stripe provider and an https frontend, so the deployment startup checks run too) and probe/livezand/readyz.
Fixed
- The Celery worker and beat start again in the Docker image. kombu's Redis transport imports
packagingwithout declaring it, and the OpenTelemetry packages removed in this release were what installed it, so both services exited at startup withModuleNotFoundError: No module named 'packaging'(the API was not affected).packagingis now a direct dependency, and the CI compose smoke test starts the worker and beat and fails if either is restarted. POST /api/v1/orders/{order_id}/refundandPOST /api/v1/admin/payments/{payment_id}/refundnow record each refund request inrefund_attemptsbefore calling Stripe: retries with the sameIdempotency-Keyresend the exact amount sent first (reusing a key with a different amount answers 409idempotency-key-in-usewithout calling Stripe), and retries of an unresolved attempt past 23 hours are refused with 409payment-attempt-unresolvedinstead of risking a duplicate refund.- Long
Idempotency-Keyheaders (up to the 255-character API limit) no longer exceed Stripe's 255-character limit when prefixed with the flow and order id (or suffixed with:confirmon/pay):_provider_idempotency_keykeeps the plain format whenever{kind}-order-{order_id}:{client_key}:confirmfits in 255 characters and otherwise hashesclient_keywith SHA-256 ({kind}-order-{order_id}:sha256:{digest}). POST /api/v1/orders/{order_id}/payandPOST /api/v1/orders/{order_id}/checkout-sessionno longer re-send an unresolved (unknown) attempt to Stripe after 23 hours (a margin under Stripe's 24-hour idempotency-key reten...
v7.0.0
A MAJOR release: an admin update that sets stock_quantity on a product or variant now needs If-Match with the current ETag (428 otherwise), so a form read before some sales can no longer undo them; GET /api/v1/admin/products/{product_id} gives that ETag, deactivated products included. The personal data export is now a zip archive built by a Celery worker and downloaded after login (F-42); a deletion request removes it at once. An open dispute's status no longer moves back on out-of-order Stripe events, product listings with search_query count under the search limit (F-19), and the Checkout Session response answers expires_at. stripe-python 17.1.0, and CI cut to four jobs with local checks in pre-commit. No migration. Tested in CI on PostgreSQL 18.6 and Redis 8.8; the servers were not audited again.
Upgrade notes
- Breaking for admin clients:
PUTandPATCHof/api/v1/admin/products/{id}and of/api/v1/admin/products/{id}/variants/{variant_id}that setstock_quantitynow requireIf-Matchwith the current ETag; without it, or with*, the answer is 428 Precondition Required (RFC 6585) and nothing changes. Read the ETag fromGET /api/v1/admin/products/{id}(new; it shows deactivated products too) orGET /api/v1/admin/products/{id}/variants/{variant_id}(or the previous update's response) and send it; on 412, refetch and retry. Updates withoutstock_quantityare unchanged. This is why 7.0.0 is a major release. - A personal data export is now a zip archive downloaded after login, no longer the data inside the mail. The frontend must serve the page the ready mail links to,
<FRONTEND_URL>/account/data-export/<request_id>, which downloadsGET /api/v1/legal/data-export/{request_id}with the user's token. docker-compose.ymladds thegdpr_exportsvolume onapiandcelery-worker(created bydocker compose up); the two must run on one host. New settingGDPR_EXPORT_DIR(defaultexports,/app/exportsin the image).
Added
GET /api/v1/admin/products/{product_id}: an admin reads one product, deactivated ones included, asGET /products/{id}shows it, with the ETag that a product update checks inIf-Match.GET /api/v1/legal/data-export/{request_id}: the account that requested an export downloads its zip archive (account, addresses, orders with their lines, payments, refunds as JSON) forGDPR_EXPORT_EXPIRY_HOURS(24). 409 while it is being built, 404 when it failed, expired or belongs to another account.- Celery tasks
build_gdpr_export(builds the archive, then mails that it is ready) andcleanup_expired_gdpr_exports(hourly, deletes expired archives). POST /api/v1/orders/{order_id}/checkout-sessionanswersexpires_at: when the hosted page stops taking payment (created_atplusCHECKOUT_SESSION_EXPIRE_MINUTES), the same instant sent to Stripe.- A deletion request (
request_typedeletion) deletes the account's export archives at once, without recovery; a build still running for the account keeps nothing and sends no mail.
Changed
- Dependencies: Celery 5.7.0 (kombu 5.7.0), stripe 17.1.0, FastAPI 0.165.0, SQLAlchemy 2.1.9, pydantic 2.14.4 (pydantic-settings 2.16.3), psycopg 3.3.9, python-multipart 0.0.34, email-validator 2.4.0, anyio 4.16.0, httpx2 2.16.2, ruff 0.17.6, hypothesis 6.170.17, coverage 7.17.3, mypy 2.4.1.
- Stripe: stripe-python 17.1.0 pins API version
2026-11-18.endive(a monthly Endive release; the SDK changelog lists additions and type changes only). Its one breaking change, API keys no longer kept in pickled Stripe objects, does not apply: the application does not pickle them. Create a new webhook endpoint with that version; see docs/OPERATIONS.md. - python-dateutil 3.0.0 -> 2.9.0.post0: Celery 5.7.0 requires exactly
python-dateutil==2.9.0.post0. dateutil is used only by Celery and freezegun; the application keeps time in UTC, and the time zone test matrix passed on 2.9 before it was removed. - CI is 4 jobs instead of 11:
lint(Ruff, mypy, module length, pip-audit),test(SQLite, both coverage gates),integration(whole suite, timing-sensitive database tests and real-Redis parity on the PostgreSQL 18 and Redis 8.8 images Compose deploys, then the previous release on the new migrations) anddocker-build(three images, Trivy). Runs on pushes and pull requests only, no longer weekly; a new push to a pull request cancels its older run; every job has a timeout; checkouts keep no credentials. - Bandit is replaced by Ruff's
Srules overapp/(the rules Bandit rates low stay off, as in the medium-severity Bandit run); the accepted bind address is marked# noqa: S104. - gitleaks moved from CI to a pre-commit hook:
.pre-commit-config.yaml, run byprek(new dev dependency, 0.5.11), with zizmor, Ruff,uv lock --checkand generic file checks. Install once per clone withuv run prek install. - Age rule: one week for every dependency, base images, actions and hooks included (was two weeks for those). Updates are made by hand;
.github/dependabot.ymlis removed. - Coverage records which test ran each line (pytest-cov
--cov-context=testin CI), shown bycoverage html. .github/scripts/migration_compat.shleaves out the old release's migration test files by file (--ignore) instead of seven test ids; one of the ids no longer existed.POST /api/v1/legal/data-requestwithexport: request ids areexport_<32 hex digits>; while an export is being built or can be downloaded, a new export request answers its id and builds nothing; when the task cannot be queued the answer is 503 (Retry-After: 30).
Removed
- CI jobs
benchmark(and.github/scripts/benchmark_ab.sh), the 7-time-zone matrix (naive local time is rejected by Ruff's DTZ rules), PostgreSQL 16 and 17 runs (PostgreSQL 18 is the supported server),secrets(now a pre-commit hook), the CycloneDX SBOM artifact and the coverage XML artifact.
Fixed
- The data export loaded the whole account into the API worker's memory and mailed it as one message, without any limit: a large account cost the worker that much memory on every request, and a mail too large for the mail servers was lost although the request counted as done. The 3.0.0 size cap had been removed with the old export route in 4.0.0 (F-42). The archive is now written in batches by a Celery worker, and one export per account is built at a time.
- An open dispute could show a stale status: Stripe does not deliver events in order, and a
charge.dispute.createdorcharge.dispute.funds_withdrawn(needs_response) that arrived aftercharge.dispute.updated(under_review) moved the stored status back. An open status now only moves forward (inquiry, chargeback, appeal); an event with an earlier one is acknowledged and ignored, as a late event for a closed dispute already was. The order was on hold either way; only the status and evidence shown to the admin and the customer were stale. Found by the stateful payment test.
Security
- An admin could overwrite stock moved by orders: a product or variant update set
stock_quantityto the value the admin's form had read, andIf-Matchwas optional, so sales made since were undone and the shop could sell stock it no longer had. A stock change now needsIf-Matchwith the current ETag (428 otherwise, 412 when stale). - A product listing with
search_query(GET /api/v1/products?search_query=) runs the same text match asGET /api/v1/products/searchbut was counted underRATE_LIMIT_DEFAULT(300/minute), five times the search limit. Both are now counted together underRATE_LIMIT_SEARCH(60/minute); a listing without a search term keeps the default limit (F-19).
v6.2.0
A MINOR release: each Stripe dispute's evidence state is stored and shown in the admin payments view, the dispute appeal statuses are published, and a webhook stored while the broker was down reaches its order within about a minute of the broker's return instead of 20 (F-CHAOS-3 from the November 2026 audit). The long route and payment modules were split by job under new CI limits on module length and function size, with no route, response or behaviour changed. One migration (0c86df1cbf98, five nullable columns): run it before starting the new image. The fixes were tested in the test suite; the servers were not audited again after them.
Upgrade notes
- The
sweep_stripe_eventsbeat task runs every minute instead of every 5. No new setting. - Migration
0c86df1cbf98adds five nullable columns topayment_disputes(evidence deadline and state). Rundocker compose --profile migrate run --rm migratebefore starting the new image.
Added
- Each dispute stores what Stripe reports about its evidence (
Dispute.evidence_details): the deadline (due_by), whether evidence was staged and submitted, whether it is past due, how many times it was submitted and how (manual,smart_disputes,not_submitted). Updated on everycharge.dispute.*event; disputes stored before this release show nothing until their next event. The admin payments view (GET /api/v1/orders/{order_id}/payments) shows it per dispute asevidence(null until reported). - OpenAPI: a dispute's
statuslists Stripe's appeal stage,appeal_needs_responseandappeal_under_review(API 2026-09-30.endive and later). Such a dispute was already treated as open (order on hold, no refund); only the published values were missing.
Fixed
- A Stripe webhook stored while the Celery broker (Redis) was unreachable was applied only about 20 minutes later: the sweeper re-queued an event only once it had been unchanged for
STRIPE_EVENT_SWEEP_AFTER_MINUTES, a wait meant for messages lost in other ways and for events backing off between retries. In the November 2026 audit, a payment confirmed during a 75 s Redis freeze reached its order 21 minutes later (F-CHAOS-3). When the webhook route or an admin replay cannot publish an event, the event is now marked (last_error: "Not enqueued: ...", visible in the admin's webhook event list) and the sweeper publishes it on its next run, then clears the mark; a payment confirmed that way reaches its order within about a minute of the broker's return. Unmarked events keep the 20-minute wait, so a long queue gets no duplicate messages.
Changed
- Dependency age rule for Python packages: one week instead of two (
[tool.uv] exclude-newer, Dependabot's uv cooldown). Over the last year every yanked release of a locked package was replaced within 4 days and no release found to be bad was found within 14 days, while 30 security fixes waited a week longer. Images, GitHub Actions and tools keep two weeks. - CI fails when a module under
app/passes 800 lines. The longest ones were split by job: the order routes intoapp/api/v1/orders/andapp/api/v1/admin/andapp/api/v1/users/packages, the payment helpers the routes and the webhook processing share intoapp/services/payment/, and the GDPR redaction of stored Stripe events intoapp/services/stripe_event_redaction.py. No route, response or behaviour changed. - Ruff now limits function size in
app/: complexity 15, branches 15, statements 60 (C901, PLR0912, PLR0915). The one function past them, the Stripe webhook'sapply_event, now looks up the payment attempt and hands the event to one handler per event type; what each event does is unchanged. - Test tooling: pytest 9.1.1 -> 9.2.0, pytest-benchmark 5.3.0 -> 5.3.1 (held back in 6.0.0 and 6.1.0 by the two-week rule).
Security
- dnspython 2.9.1 -> 2.9.2: CVE-2026-128089 (GHSA-vvf4-9x63-8xvv), excessive memory and CPU use when parsing a crafted WKS record from zone-file text. The app does not parse zone files (dnspython is loaded by email-validator, with the deliverability check off), so no exposure is known; upgraded all the same.
- OpenTelemetry 1.45.1 -> 1.45.2 (instrumentation 0.66b1 -> 0.66b2): CVE-2026-126360 (GHSA-mf5v-w3w3-f6cg), quadratic-time parsing of a crafted
traceparentvalue inTraceContextTextMapPropagator.extract(). Conforming HTTP header values cannot carry the newline the attack needs, and the app's other carrier, Celery task headers, is written by the app itself, so no exposure is known; upgraded all the same. 1.45.2 was released on 2026-10-29.
Documentation
docs/OPERATIONS.md: a failed/readyzcheck means the dependency did not answer this instance within 2 s (a saturated instance can fail one probe while the database is healthy); remove an instance only after several consecutive failures.- Load and chaos audit report: corrections from a re-verification of every numeric claim against the raw data.
docs/API.mddescribes the disputeevidenceand the appeal statuses;SECURITY.mdthe one-week age rule for Python packages;docs/TESTING.mdthe module-length and function-size checks.
v6.1.0
A MINOR release: the fixes from an external load, concurrency, chaos and perimeter audit of 6.0.0 on two 2-vCPU servers (report), two new settings (REDIS_SOCKET_TIMEOUT, REDIS_SOCKET_CONNECT_TIMEOUT), and an OpenAPI document that now names every header and shared cause a client can meet. No route, field or parameter was removed or changed in a way a client must follow. The fixes were tested in the test suite; the servers were not audited again after them.
Upgrade notes
- New settings
REDIS_SOCKET_TIMEOUTandREDIS_SOCKET_CONNECT_TIMEOUT(seconds, 1.0 each by default): a Redis command or connection that does not answer in time fails instead of waiting redis-py's default 5 s. - The API no longer writes uvicorn's access log; one JSON line per request comes from the
app.accesslogger instead (method, path, route, status, duration, client address, request id). Log pipelines that parsed uvicorn's text line need the new fields. - Responses no longer carry a
Serverheader. - Stripe: stripe-python 16.1.0 pins API version
2026-10-28.endive(only additions within Endive). Create a webhook endpoint with that version; see docs/OPERATIONS.md.
Fixed
dispute_statuson orders: as soon as any dispute existed, every order of every customer showed the status of the newest dispute in the whole table (the subquery was not correlated to the order's payments). Each order now shows its own (F-BUG-1).- With
WORKERSabove 1 every response on a reused connection waited about 40 ms: uvicorn's shared listener left Nagle's algorithm on for the connections the workers accepted. The workers now setTCP_NODELAYon every connection (F-PERF-1). Verified by a socket-level test; the latency through the proxy was not measured again. - A frozen Redis held catalog requests for about 15 s at the median (redis-py's 5 s socket timeout per command, no timeout set by the app); both Redis clients now give up after 1 s by default (F-CHAOS-1). Not measured again on a server.
- An order's
shipping_addresscopy tookis_defaultand its timestamps from the live address book entry; the copy now hasis_defaultfalse and the order'screated_at. - Two concurrent admin refunds of the same flagged payment: the loser got Stripe's refusal as an error; it is now a 409 "This payment has already been fully refunded".
- Celery's own lines (task received, succeeded, failed; beat's "Sending due task") were not written although the worker and beat ran with
--loglevel=info, so periodic tasks could not be traced in the logs; they now go through the application's JSON logging at the worker's--loglevel. - Emails had no
DateorMessage-IDheader and no plain-text part; they now have both headers and a text/plain part generated from the HTML. RateLimitandRateLimit-Policywere sent only on responses a route returned itself; every counted response, 4xx included, now carries them, and the failed-login 429 names its own policy.HEADon the health probes answered aContent-Lengthof 0; it now matches GET.- Country normalisation of addresses was not a fixed point for a value that title-cases to two characters ("ß" to "Ss", then "SS" on the next read). Not reachable through the API (a country has at least two characters), found by the response round-trip property test.
Changed
- A provider failure that leaves a payment attempt
unknownlogs one WARNING line with the error class, Stripe's request id, the HTTP status, the provider code and a hash of the idempotency key. - OpenAPI:
RateLimitandRateLimit-Policyare declared on every 429 andWWW-Authenticateon every 401; where a route describes its own 400, 401 or 503, the description also names the causes every route shares (a body that is not JSON, a bad token, the in-flight limit). A problem body carriesretry_afterwheneverRetry-Afteris set. - CORS exposes
Location(the 201 of a POST) and allows theX-Request-IDrequest header. - Documentation: the webhook API version, the worst case of the Stripe timeouts (about 16 s and 31 s observed against a theoretical 76.5 s), a table of Redis key TTLs, how to find PaymentIntents left unconfirmed after a lost provider answer, and the audit report with its charts.
- Dependencies: stripe 16.1.0, pydantic 2.14.2, hypothesis 6.170.14, dnspython 2.9.1, wrapt 2.5.2, python-dateutil 3.0.0 (used only by Celery and freezegun; the application keeps time in UTC). Held back: pytest 9.2 (pytest-benchmark 5.3.1 passes the two-week rule on 2026-11-15).
v6.0.0
A MAJOR release: three request bodies changed (API clients must update, see "Migrating API clients"), and the Docker Compose stack moves to PostgreSQL 18, whose data volume layout a 15 volume cannot be started with (see "Upgrading a deployment"). It also closes the remaining findings of the 2026-11-10 review, tightens the type and lint configuration, and documents every route's outcomes in the OpenAPI document.
Migrating API clients
POST /api/v1/orders/{order_id}/pay: the body is now{"amount": "25.00", "currency": "USD", "payment_method_token": "pm_..."}payment_method_tokenis required (a body without it is a 422; Stripe refused a confirm without a payment method anyway, so such a request was never paid in production).order_id(the order is the one in the path) andpayment_method(always Stripe) must no longer be sent: a body with them is a 422extra_forbidden.currencystays optional. The response is unchanged and still carriesorder_idandpayment_method("stripe").POST /api/v1/admin/categories:metadatais no longer accepted (it was never stored); category responses no longer carrymetadata,product_countorchildren_count(always{}and 0 before).POST /api/v1/legal/data-request:request_typeother thanexportordeletionis a 422 from the schema (it was a 400 from the route).- Sessions: a refresh token family ends
REFRESH_SESSION_MAX_DAYS(default 30) after the login that started it, however often it is refreshed. After thatPOST /api/v1/users/refreshanswers the same 401 as for an expired refresh token, and the client logs in again. Before, a session refreshed at least weekly never ended.
Upgrading a deployment
- PostgreSQL 15 to 18:
docker-compose.ymlbuilds the database fromdocker/postgres/Dockerfile(postgres:18.6-alpineplus Alpine security updates) and mounts the volume on/var/lib/postgresql. An existing 15 volume is refused at start; move the data with a dump and restore, step by step in docs/OPERATIONS.md. Supported servers are now PostgreSQL 16, 17 and 18. - Redis 7 to 8.8, built from
docker/redis/Dockerfile(redis:8.8-alpineplus Alpine security updates). 8.8 is the newest release redis-py 8.1 supports. - Run the migrations (
docker compose --profile migrate run --rm migrate): revisionf180919aaf3badds a CHECK onpayments.status, a partial unique index allowing one active default address per user (older duplicate defaults are resolved first, the newest kept),payments.reconciled_at, and a partial index for the unpaid-order sweep. It stops without changing anything if a payment row has a status outside the known values. docker compose up -d --build: the db and redis images are built locally now.- New setting
REFRESH_SESSION_MAX_DAYS(default 30, at leastREFRESH_TOKEN_EXPIRE_DAYS).
Fixed
- An erasure request cancels the account's new, unpaid orders, returns their stock and closes their open payment attempts at Stripe. The deactivated owner could still pay one and get an order behind 403 on every route.
- An erasure request no longer deadlocks against an order being placed by the same account: it takes the user's row lock first, as
POST /ordersdoes. - GDPR request mails are sent after the response: a mail failure can no longer turn a recorded request into a 500, and the client does not wait for SMTP.
- Changing the default address: two concurrent changes of one user's addresses could deadlock on PostgreSQL (a 500); they now run one after the other. Updating an address so that it equals another active one is a 409 (it was a 500), and the database allows one active default address per user.
- Reconciliation checks the window's payments least recently reconciled first (
payments.reconciled_at), so aboveRECONCILIATION_MAX_PAYMENTSattempts in the window the older ones are no longer skipped for ever. payments.statusis checked by the database against the values the code writes.POST /admin/payments/{id}/refundno longer returns Stripe's refusal text to the client; it is logged, as on the order refund route.- The mock payment provider refuses to confirm a PaymentIntent without a payment method, as Stripe does; it used to pay with a default card.
Changed
- The OpenAPI document states every status code each route answers with its cause, the limits and defaults a client meets (payment window, minimum charge, unpaid-order cap, rate limits, token lifetimes, cart limits, sorting values), and the 6.0.0 changes on the routes concerned.
docs/API.mdhas a table of these limits. - Images: the app image applies Debian security updates at build time, and the database and Redis images Alpine's, so a fix is not waited for until the official images are rebuilt; Docker Compose builds every image without layer cache (
no_cache), so those updates run on each--buildinstead of being taken from a cached layer. CI scans the three built images with Trivy 0.76.1 and runs weekly on a schedule as well; uv 0.13.6. - CI tests PostgreSQL 16, 17 and 18 (the whole suite on 18) and Redis 8.8. Dependabot watches the three Dockerfiles and holds Python to 3.13.
- Stricter mypy (
warn_return_any,warn_unreachable,disallow_any_generics, extra error codes, fully typed payment layer and tasks) and ruff (logging, broad-except, comprehension, return, pytest-style and pylint rules, a ban on the sync Redis client outside the worker) settings; the code was fixed to pass them. - Dependencies: FastAPI 0.162.0 (Starlette 1.10.0), SQLAlchemy 2.1.6, alembic 1.20.1, stripe 16.0.1, pydantic-settings 2.16.2, ruff 0.17.3, hypothesis 6.170.13, coverage 7.17.0, httpx2 2.16.0, tzdata 2026.6; setup-uv 10.3.3 in CI. Held back: pytest 9.2 (pytest-benchmark 5.3.0 does not run on it; 5.3.1 does, and is too new under the two-week rule) and python-dateutil 3.0 (a major release of a Celery dependency that changes time zone behaviour).
- Documentation: accepted limitations of the 2026-11-10 review, the GDPR scope, reconciliation and rate-limiter limits are recorded in
docs/LIMITATIONS.md;docs/OPERATIONS.mdhas going-live notes for Stripe and the 6.0.0 upgrade.
Removed
- The
update_product_statstask and its schedule: it cached best sellers in Redis under a key nothing read. - The unused synchronous Redis client the API process created at start.
5.1.0
A MINOR release: fixes from a full review of payments, orders, configuration and the catalog, with new settings (RATE_LIMIT_CONSENT, SMTP_TLS_VERIFY, DOCKER_API_BIND) and two refund statuses newly published in the OpenAPI document. No route, field or parameter was removed.
Upgrade notes: ENVIRONMENT=staging and production now refuse to start with EMAIL_PROVIDER=logging or SMTP_TLS_VERIFY=false; EMAIL_PROVIDER accepts only smtp and logging; CHECKOUT_SESSION_EXPIRE_MINUTES must be at least 31. Development and test accept the logging provider and a mail catcher with a self-signed certificate (SMTP_TLS_VERIFY=false).
Fixed
- A flagged second charge refunded through
POST /admin/payments/{id}/refundkeeps its manual-review flag in the database, which marks it as the charge that did not pay the order. Clearing it made the refund's webhook mark the paid order refunded, and the order's ownPOST /orders/{id}/refundthen picked the already refunded charge, so the charge that paid the order could no longer be refunded through the API. The API still reportsrequires_manual_review=falseonce such a charge is fully refunded (admin payment list and its filter, order payments view), and the admin route records the refund under the order's lock, like every refund event. - The expiry sweep no longer cancels and restocks an order that its customer paid for while the webhook was late or had failed: when Stripe refuses to expire a session or cancel a PaymentIntent, the attempt is read back, and one that is paid or being paid keeps the order for the webhook and for reconciliation. An attempt Stripe does not know at all still counts as closed.
- Cancelling an order (admin
PUT/PATCH /orders/{id}/status, customerPOST /orders/{id}/cancel) closes its open payment attempts at Stripe after the commit. A Checkout Session of a cancelled order used to stay payable for its whole lifetime while its stock was back on sale. - A new payment attempt (
/payor/checkout-sessionwith a newIdempotency-Key) on an order placed more thanUNPAID_ORDER_EXPIRE_MINUTESago is answered 409. A fresh attempt now and then kept an unpaid order, and its stock, out of the expiry sweep for good. A retry with the key of an earlier attempt is still served. - A
/checkout-sessionkey whose request died before Stripe answered is sent to Stripe again once older thanPAYMENT_ATTEMPT_STALE_AFTER_MINUTES, as on/pay. Every retry used to be answered 409 withRetry-Afterfor ever. - Two
POST /ordersof one account run one after the other (aFOR NO KEY UPDATElock on the user's row). With different keys they used to read the same cart and the same count of unpaid orders: eight parallel requests placed eight orders from one cart and passedMAX_PENDING_ORDERS_PER_USER. A short window remains between the first request's commit and the emptying of the cart in Redis. - An order whose total is below Stripe's minimum charge for the store currency (0.50 USD, 0.50 EUR, 0.30 GBP and the other currencies Stripe lists) is answered 422 and takes no stock. It used to be placed, hold its stock until it expired, and fail at every
/pay. A currency without a published minimum is left to Stripe. - A refund is recorded with Stripe's own status. The live provider folds
canceledandrequires_actionintopending, so a refund canceled at once was counted as money on its way back.RefundResponse.statuspublishes the five values Stripe documents. - Reconciliation goes on when another run (the daily task and an admin's run for one order) records the same new difference first: the payment counts as an error. The unique index used to stop the task with the rest of the window unchecked, or answer 500 on the admin route.
- SMTP STARTTLS verifies the server certificate and host name.
smtplibused an unverified context by default, so anyone on the path to the mail server could readSMTP_PASSWORDand every reset link. A relay with a private CA is trusted throughSSL_CERT_FILE/SSL_CERT_DIR. EMAIL_PROVIDERissmtporlogging; a misspelt value used to select the logging provider silently.CHECKOUT_SESSION_EXPIRE_MINUTESmust be at least 31: the session'sexpires_atis counted from the attempt's creation, so 30 fell below Stripe's 30-minute minimum by the time of the call.- The consent history stores at most 512 characters of the User-Agent, and consent changes are limited per user (
RATE_LIMIT_CONSENT, default10/hour, one count shared byPOST /legal/consentandPUT/PATCH /users/mewhen they changemarketing_consent). Each change used to add an entry with the whole header (up to 16 KiB) without limit, to a row loaded on every authenticated request. The history itself is never trimmed: it is the evidence of consent. - The privacy policy, terms of service and cookie policy carry a fixed version and effective date (2026-11-10) instead of the time of the request, and the terms state prices in
STORE_CURRENCYinstead of "EUR including VAT". GET /products?in_stock=truefollows the variants of a product that has an active one (in stock when an active variant has stock), and a boolean characteristic filter (true/false) matches on PostgreSQL and SQLite.str(True)matched neither.- A load-shed 503 carries the CORS headers: CORSMiddleware now sits outside the in-flight limit, so a browser sees the 503 and its
Retry-Afterinstead of an opaque network error.
Added
SMTP_TLS_VERIFY(defaulttrue):falseskips the certificate check for a local mail catcher; refused in staging and production.RATE_LIMIT_CONSENT(default10/hour).DOCKER_API_BINDindocker-compose.yml: the host address the API port is published on (default every interface;127.0.0.1when the reverse proxy runs on the same host).
Changed
- On
docker stopthe API finishes requests in flight for up to 90 s (timeout_graceful_shutdowninmain.py), and Docker waits 100 s (stop_grace_period) before SIGKILL. A/paycall can wait on Stripe about 76 s in the worst case; Docker's default of 10 s cut it off. - Unused code removed:
PasswordUpdate, bothTokenPayloadschemas,CategoryUpdate, and the unused Redis session helpers.
5.0.0
Major release: the published operationIds were shortened (69 renamed), so clients generated from the OpenAPI spec get new method names. No route, parameter or payload was removed or changed on the wire.
Added
- has_variants and variants on GET /products/{id}; has_variants on /products and /products/search.
- dispute_status on orders (customer view, history, admin list) and a has_dispute filter on GET /admin/orders.
- A fully typed OpenAPI contract: enums, cookie, ETag, X-Request-ID and rate-limit headers.
Fixed
- Checkout payments settle from payment_intent.succeeded when checkout.session.completed is lost; a decline on the hosted page leaves the attempt untouched.
- Refunds made through /refund are recorded with source admin.
- A correct If-Match on a product with variants no longer answers 412.
- Provider error text is no longer echoed to clients.
A lost Stripe dispute only flags the order; stock and status stay for the manager to correct.
4.1.2
A PATCH release: it fixes the Celery worker's healthcheck in docker-compose.yml and the benchmark check in CI. No change to the application code or the API.
Fixed
- The
celery-workerhealthcheck runs undertimeout 9. Each check starts a whole Celery process (70-120 MB); one that outlived the 10 s healthcheck timeout was counted as failed but left running, so on a CPU-starved host the checks piled up, about 30 MB more every 10 s, until the kernel killed the worker for memory. Found by a load test on a 2 vCPU server; with the fix the same setup held at about 120 MB. A test pins that the check ends itself before Docker's own timeout.
Changed
- The
benchmarkCI job times the base commit and HEAD one after the other on the same runner (.github/scripts/benchmark_ab.sh) and fails when a median on HEAD is more than 35% slower. It used to compare with a baseline saved by an earlier run onmain, which came from another runner: six reruns of the 4.1.1 commit landed on three CPU models whose medians differed by up to 2.26 times, and three of the six failed the 80% gate with no change to the code. On one runner, six runs of unchanged code put HEAD within 6% of the base on the CPU benchmarks and within 22% on the request benchmarks.
Full list: CHANGELOG.md, compare: v4.1.1...v4.1.2
4.1.1
A PATCH release: it fixes the entity-tag header parser and two faults of the migration environment, and adds checks to CI. No API change, no new endpoint or setting.
Fixed
app/core/etag.pyparsesIf-MatchandIf-None-Matchin one pass: it finds the quoted tags with a simple pattern and checks only the text between them. CodeQL alert 8 flagged the expression that validated the whole header as polynomial ReDoS; timing showed linear growth, so it was not exploitable, but that expression is gone. Hypothesis tests check that the parser accepts and rejects exactly what it did.migrations/env.pydisposes the database engine it creates, avoiding leaked connections when running Alembic in-process.migrations/env.pyno longer disables the application's loggers.fileConfigdefaulted todisable_existing_loggers=True, so a process that ran migrations itself lost its own logs from then on; random test order exposed it. A caller with its own logging can skipalembic.ini's logging withconfig.attributes["configure_logger"] = False.- Throwaway PostgreSQL databases from migration tests use the session naming convention (
ecom_pgtests_<epoch>_<hex>), allowing the stale database sweep to clean them up.
Added
- Static security analysis CI job
sastrunning Bandit 1.9.4 offline onapp/. - Migration compatibility CI job
migration-compat: the newest tagged release's database tests of orders, payments, checkout, carts, refunds, users and addresses, run against the current migrations on PostgreSQL 15; it ends at once whenmigrations/is unchanged since that tag. Also a PostgreSQL migration round-trip test (tests/integration/test_postgres_migration_roundtrip.py) intest-postgres. - Benchmark CI job
benchmarkcomparing hot path performance against the newest baseline frommain, failing when a median is more than 80% slower. - Dev dependencies
mypy,pytest-socket,pytest-randomly, andpytest-benchmark. - Mutation testing rerun on this release: 3,434 mutants, 98.7% detected. 31 of the 74 first-run survivors were gaps in the tests and are killed by new tests; the other 43 are equivalent.
Changed
- The
lintCI job now includes type checking withmypy(0 errors across 80 files);app/was annotated for it without a behaviour change. - The one Bandit finding,
HOST = "0.0.0.0"inapp/core/config.py, is marked# nosec B104with the reason: inside a container the port mapping decides what is exposed. - Test suite execution runs in randomized order by default via
pytest-randomly, printing the seed used for reproducibility. - Network access in the test suite is blocked by default via
pytest-socket, allowing only local and loopback connections.
Full list: CHANGELOG.md, compare: v4.1.0...v4.1.1
v4.1.0
v4.1.0
Closes the findings of three independent audits of 4.0.3. MINOR: two new admin
endpoints and two settings; no response field removed. One migration.
Money: a charge can no longer be taken for an order cancelled and restocked
while its customer could still pay; flagged charges can be listed and refunded;
stale refund events no longer rewind a settled refund. Checkouts no longer
deadlock. Orders keep their product and address snapshots. GDPR erasure,
export and webhook redaction work at volume. See CHANGELOG.md.
Verified: 16 of 16 CI jobs. 6,568 cases, PostgreSQL 15, 16, 18, real Redis, 7 time
zones, Windows and Linux, live Stripe test mode, 100 percent on the payment layer.