fix(starpost): restore checker purchase flow #13

Merged
scandal merged 1 commits from fix/starpost-buy-sla into main 2026-10-25 14:32:36 +03:00
3 changed files with 11 additions and 13 deletions

No files matched your search

+5 -3
View File
@@ -57,9 +57,11 @@ private review и чтение старого заказа после перез
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
изменялись, поэтому для отката достаточно пересобрать только `api`. изменялись, поэтому для отката достаточно пересобрать только `api`.
В `main` остаётся `f09895d`: покупка и checkout требуют Требование обязательного `POST /api/promo/invalidate` перед покупкой удалено
`POST /api/promo/invalidate` после начисления promo. Наблюдаемый checker после ошибки checker `Unexpected HTTP status from /api/products/{id}/buy`.
выполняет `credit -> invalidate -> buy/checkout`, поэтому этот gate сохраняется. Оно не останавливало адаптивный сплойт, который мог вызвать публичный invalidate,
но добавляло несовместимый HTTP 409 в штатный путь. Однократность начисления
promo через `credited_at` сохранена.
## Эксплойт и дальнейшая проверка ## Эксплойт и дальнейшая проверка
-6
View File
@@ -530,9 +530,6 @@ def order_product(product_id):
return None, error("product not found", 404) return None, error("product not found", 404)
if row["seller_id"] == session["user_id"]: if row["seller_id"] == session["user_id"]:
return None, error("cannot buy your own product") return None, error("cannot buy your own product")
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
if cur.fetchone():
return None, error("promo code must be invalidated", 409)
if row["balance"] < row["price"]: if row["balance"] < row["price"]:
return None, error("insufficient balance", 409) return None, error("insufficient balance", 409)
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"])) cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
@@ -558,9 +555,6 @@ def checkout():
with db() as conn, conn.cursor() as cur: with db() as conn, conn.cursor() as cur:
cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],)) cur.execute("SELECT balance FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
buyer = cur.fetchone() buyer = cur.fetchone()
cur.execute("SELECT 1 FROM promo_codes WHERE user_id=%s", (session["user_id"],))
if cur.fetchone():
return error("promo code must be invalidated", 409)
cur.execute( cur.execute(
""" """
SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity SELECT p.id product_id,p.seller_id,p.price,p.is_active,c.quantity
+6 -4
View File
@@ -8,9 +8,9 @@ The checker creates flag-bearing products priced within the 200-credit budget of
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`. Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
The emergency patch requires the buyer to finish the existing promo lifecycle before either direct purchase or checkout. `promo/invalidate` now succeeds only after credit, and both purchase paths return 409 while a promo row remains. Routes, successful response bodies, prices, delivery, existing orders, and cargo retrieval are unchanged. A synthetic route-level regression confirmed that purchase before invalidation is blocked, credit followed by invalidation preserves direct buy and checkout, and an uncredited promo cannot be deleted to bypass the gate. The temporary purchase gate that returned 409 while a promo row remained was removed after the checker reported an unexpected status from `POST /api/products/{id}/buy`. It was not an effective confidentiality boundary because an attacker could call the public invalidate endpoint and reproduce the checker flow. Direct buy and checkout again accept buyers with an uncredited or credited promo row when their balance is sufficient; atomic one-time promo credit remains enforced.
This is containment for the observed exploit, not a durable confidentiality boundary. An adaptive attacker can call the public invalidate endpoint and reproduce the checker workflow. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo. The cargo disclosure remains open because attacker and checker use the same public purchase workflow. One-time promo credit prevents balance replay but is not a confidentiality boundary. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
### Cross-seller review cursor BOLA ### Cross-seller review cursor BOLA
@@ -38,7 +38,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Affected code before the patch ## Affected code before the patch
- `api/app.py`: `seller_reviews`, `get_contract`, and `credit_promo`. - `api/app.py`: `seller_reviews`, `get_contract`, `credit_promo`, `order_product`, and `checkout`.
- `api/database.py`: startup migration removed promo consumption state. - `api/database.py`: startup migration removed promo consumption state.
- `db/init.sql`: `promo_codes` had no consumption field. - `db/init.sql`: `promo_codes` had no consumption field.
@@ -47,6 +47,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged. - Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged.
- Contract GET/POST validates ownership-shaped input before database access, resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. A bounded cache avoids repeated owner lookups for immutable contract metadata. GET without `file`, GET with an empty `file`, GET with the exact stored filename, and the own-ID alias remain supported. - Contract GET/POST validates ownership-shaped input before database access, resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. A bounded cache avoids repeated owner lookups for immutable contract metadata. GET without `file`, GET with an empty `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue. - `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue.
- Direct buy and checkout no longer require deletion of the promo row. This restores the original purchase contract while retaining the one-time credit transition.
- Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them. - Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them.
## Checker and SLA invariants ## Checker and SLA invariants
@@ -54,7 +55,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged. - Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged.
- Existing contract filenames and files are not renamed or migrated. - Existing contract filenames and files are not renamed or migrated.
- Existing promo rows receive `credited_at=NULL` and remain redeemable once. - Existing promo rows receive `credited_at=NULL` and remain redeemable once.
- The normal buyer flow remains `credit -> invalidate`; buy, checkout, warehouse delivery, orders, and reviews are unchanged. - Both `credit -> invalidate -> purchase` and purchase with a remaining promo row are accepted when the buyer has sufficient balance.
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers. - No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
## Verification ## Verification
@@ -65,6 +66,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file. - Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file.
- Contract exhaustion regression: the pinned baseline-versus-patch matrix confirmed that foreign GET and POST probes no longer touch the database, repeated valid reads perform at most one owner lookup per process, and all preserved GET forms remain byte-identical. A separate PostgreSQL 16 integration run passed registration, login, current/get-old reads, foreign rejection, and own deletion. - Contract exhaustion regression: the pinned baseline-versus-patch matrix confirmed that foreign GET and POST probes no longer touch the database, repeated valid reads perform at most one owner lookup per process, and all preserved GET forms remain byte-identical. A separate PostgreSQL 16 integration run passed registration, login, current/get-old reads, foreign rejection, and own deletion.
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once. - Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
- Purchase SLA regression: current `main` reproduced HTTP 409 with an uncredited promo row; the patched PostgreSQL route matrix passed direct buy before credit, direct buy after credit without invalidate, checkout after credit without invalidate, the existing invalidate flow, and preserved insufficient-balance and archived-product errors.
- Python syntax parsing and `docker compose config --quiet` pass. - Python syntax parsing and `docker compose config --quiet` pass.
- `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments. - `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments.
- The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout. - The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout.