starpost: contain prestaged cargo buyers

This commit is contained in:
scandalist-trash committed 2026-10-25 08:49:26 -04:00
1 parent b28069ecfc
commit b5bbafc664
4 files changed
+52 -16

No files matched your search

+37 -13
View File
@@ -13,7 +13,7 @@ from flask import Flask, jsonify, request, send_file, session
from werkzeug.security import check_password_hash, generate_password_hash
from contracts import CONTRACT_DIR, create_contract
from database import connect as db, migrate
from database import CARGO_PURCHASE_WINDOW_SECONDS, connect as db, migrate
from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN
from warehouse_client import get_health as get_warehouse_health
from warehouse_client import submit_jobs as submit_warehouse_jobs
@@ -29,7 +29,6 @@ app.config.update(
)
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
CARGO_PURCHASE_WINDOW_SECONDS = 2
migrate()
@@ -523,9 +522,28 @@ def update_cart_quantity(product_id):
return jsonify(ok=True, quantity=quantity)
def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, product_created_at):
cur.execute(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code,cargo_entitled) "
"VALUES(%s,%s,%s,'pending',%s,%s >= %s AND "
"CURRENT_TIMESTAMP <= %s + (%s * interval '1 second')) RETURNING id",
(
buyer_id,
product_id,
price,
tracking,
buyer_created_at,
product_created_at,
product_created_at,
CARGO_PURCHASE_WINDOW_SECONDS,
),
)
return cur.fetchone()["id"]
def order_product(product_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT p.*,u.balance FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
cur.execute("SELECT p.*,u.balance,u.created_at buyer_created_at FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
row = cur.fetchone()
if not row:
return None, error("product not found", 404)
@@ -536,8 +554,8 @@ def order_product(product_id):
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"], row["seller_id"]))
tracking = "ORB-" + secrets.token_hex(8).upper()
cur.execute("INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id", (session["user_id"], product_id, row["price"], tracking))
return {"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking}, None
order_id = create_order(cur, session["user_id"], product_id, row["price"], tracking, row["buyer_created_at"], row["created_at"])
return {"id": order_id, "status": "pending", "tracking_code": tracking}, None
@app.post("/api/products/<int:product_id>/buy")
@@ -554,11 +572,12 @@ def buy_product(product_id):
@auth("buyer")
def checkout():
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,created_at buyer_created_at FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
buyer = cur.fetchone()
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,
p.created_at product_created_at,c.quantity
FROM cart_items c JOIN products p ON p.id=c.product_id
WHERE c.buyer_id=%s ORDER BY c.created_at
""",
@@ -578,11 +597,16 @@ def checkout():
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"]))
for _ in range(item["quantity"]):
tracking = "ORB-" + secrets.token_hex(8).upper()
cur.execute(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code) VALUES(%s,%s,%s,'pending',%s) RETURNING id",
(session["user_id"], item["product_id"], item["price"], tracking),
order_id = create_order(
cur,
session["user_id"],
item["product_id"],
item["price"],
tracking,
buyer["buyer_created_at"],
item["product_created_at"],
)
orders.append({"id": cur.fetchone()["id"], "status": "pending", "tracking_code": tracking})
orders.append({"id": order_id, "status": "pending", "tracking_code": tracking})
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],))
submit_warehouse_jobs(orders)
return jsonify(orders=orders), 201
@@ -596,11 +620,11 @@ def buyer_orders():
"SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,"
"o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,"
"CASE WHEN o.status='delivered' "
"AND o.created_at <= p.created_at + (%s * interval '1 second') "
"AND o.cargo_entitled "
"THEN p.cargo ELSE NULL END cargo "
"FROM orders o JOIN products p ON p.id=o.product_id "
"WHERE o.buyer_id=%s ORDER BY o.id DESC",
(CARGO_PURCHASE_WINDOW_SECONDS, session["user_id"]),
(session["user_id"],),
)
return jsonify(cur.fetchall())
+10
View File
@@ -5,6 +5,7 @@ from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"]
CARGO_PURCHASE_WINDOW_SECONDS = 2
def connect():
@@ -28,6 +29,15 @@ def migrate():
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS cargo_entitled BOOLEAN")
cursor.execute(
"UPDATE orders o SET cargo_entitled="
"(o.created_at <= p.created_at + (%s * interval '1 second')) "
"FROM products p WHERE p.id=o.product_id AND o.cargo_entitled IS NULL",
(CARGO_PURCHASE_WINDOW_SECONDS,),
)
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET DEFAULT false")
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET NOT NULL")
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS promo_codes (
+1
View File
@@ -38,6 +38,7 @@ CREATE TABLE orders (
,warehouse_status TEXT NOT NULL DEFAULT 'queued'
,warehouse_job_id TEXT
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
,cargo_entitled BOOLEAN NOT NULL DEFAULT false
);
CREATE TABLE reviews (
id BIGSERIAL PRIMARY KEY,
+4 -3
View File
@@ -44,7 +44,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Minimal patch
- Emergency cargo containment returns delivered cargo only for orders created within two seconds of product creation. In 62 observed checker-like flows the purchase delay was 0.232-0.563 seconds. The order, warehouse, and historical read paths remain unchanged; late purchases return the existing order shape with `cargo=null`. This is a timing-based containment measure, not a durable authorization boundary.
- Emergency cargo containment records a `cargo_entitled` decision on every new order. The entitlement requires the buyer account to be created after the product and the order transaction to start within two seconds of product creation. In 62 observed checker-like flows the checker created a new buyer after the product and purchased after 0.232-0.563 seconds. A live purchase correlated with the reported theft used a buyer created roughly 124 seconds before the product, so an equivalent order created after deployment retains the normal delivered response but receives `cargo=null`. Both direct buy and checkout use the same order helper. Existing orders are backfilled with the previous two-second rule so their current/get-old behavior does not change. This is containment against pre-staged buyers, not a durable authorization boundary: an attacker that registers after publication can still race the checker.
- 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.
- `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.
@@ -53,7 +53,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Checker and SLA invariants
- Existing checker orders created inside the two-second window continue to reveal cargo after delivery and on later get-old checks. The rule is per order, so an earlier attacker order does not consume checker access.
- Existing orders retain their previous cargo visibility after migration. New checker orders whose buyer was created after the product and whose order transaction began inside the two-second window continue to reveal cargo after delivery and on later get-old checks. Entitlement is stored per order, so an earlier attacker order does not consume checker access.
- 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 promo rows receive `credited_at=NULL` and remain redeemable once.
@@ -69,6 +69,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
- 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.
- 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.
- Cargo entitlement regression: a disposable PostgreSQL 16 and patched Flask API matrix preserved a legacy delivered order through migration, returned `cargo=null` for a new order from a pre-staged buyer, preserved cargo for a new buyer through both direct buy and checkout, and preserved get-old. Only synthetic non-flag markers were used.
- 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.
- 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.
@@ -96,7 +97,7 @@ The local baseline reproducer started with a synthetic balance of 100 and two id
## Remaining gaps
- The exact checker scenario and flag-bearing field are not available, so signature/PDF, private review, and cargo hypotheses are code-derived rather than checker-confirmed.
- Full service-container rebuild, persistent-volume get-old, and checker status were not tested. The PostgreSQL route integration used a temporary database initialized from `db/init.sql` and synthetic contract files.
- The API image and disposable PostgreSQL integration were tested, but the full service Compose stack, the live persistent volume, and official checker status were not. The integration used a temporary database initialized from `db/init.sql` and synthetic contract files.
- The contract metadata cache is process-local. If an operator manually changes or restores `users.contract_file`, restart the API workers before verification so they reload that metadata.
- Bounded requests were sent only to the team vulnbox. No request was sent to Neo, Farm, farm-submit, Skipper, or another team.
- Deployment must rotate the existing PostgreSQL role password before recreating API/PostgreSQL containers; changing only `POSTGRES_PASSWORD` does not update an initialized volume.