starpost: rotate secrets and close data leaks
This commit is contained in:
1 parent
4f70df55dd
commit
22c1906a67
11 files changed
+725
-61
No files matched your search
+41
-54
@@ -2,12 +2,10 @@ import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json as _json
|
||||
import mimetypes
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from flask import Flask, jsonify, request, send_file, session
|
||||
@@ -268,10 +266,21 @@ def credit_promo():
|
||||
if not isinstance(code, str) or not 1 <= len(code) <= 100:
|
||||
return error("invalid promo code")
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code.strip()))
|
||||
cur.execute(
|
||||
"UPDATE promo_codes SET credited_at=now() "
|
||||
"WHERE user_id=%s AND code=%s AND credited_at IS NULL RETURNING amount",
|
||||
(session["user_id"], code.strip()),
|
||||
)
|
||||
promo = cur.fetchone()
|
||||
if not promo:
|
||||
return error("promo code is unavailable", 409)
|
||||
cur.execute(
|
||||
"SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s",
|
||||
(session["user_id"], code.strip()),
|
||||
)
|
||||
promo = cur.fetchone()
|
||||
if not promo:
|
||||
return error("promo code is unavailable", 409)
|
||||
return jsonify(credited=0, code=code.strip())
|
||||
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
|
||||
return jsonify(credited=promo["amount"], code=code.strip())
|
||||
|
||||
@@ -614,13 +623,7 @@ def seller_reviews():
|
||||
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
|
||||
return f"{p}.{_sign(p)}"
|
||||
|
||||
def _parse_cursor(cur_token: str, lim_raw):
|
||||
try:
|
||||
lim = int(lim_raw) if lim_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
lim = None
|
||||
if lim is not None and lim <= 3:
|
||||
return _json.loads(_b64d(cur_token.split(".")[0]).decode())
|
||||
def _parse_cursor(cur_token: str):
|
||||
if "." not in cur_token:
|
||||
raise ValueError("missing signature")
|
||||
payload_b64, sig = cur_token.rsplit(".", 1)
|
||||
@@ -639,13 +642,15 @@ def seller_reviews():
|
||||
|
||||
if cursor:
|
||||
try:
|
||||
state = _parse_cursor(cursor, limit_raw)
|
||||
state = _parse_cursor(cursor)
|
||||
except Exception as exc:
|
||||
return error(f"invalid cursor: {exc}", 400)
|
||||
try:
|
||||
q_seller = int(state["seller_id"])
|
||||
q_private = bool(state["is_private"])
|
||||
q_private = state["is_private"]
|
||||
q_last = int(state["last_id"])
|
||||
if q_seller != session["user_id"] or not isinstance(q_private, bool):
|
||||
raise ValueError
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return error("invalid cursor payload", 400)
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
@@ -686,55 +691,37 @@ def seller_reviews():
|
||||
@app.route("/api/contract", methods=["GET", "POST"])
|
||||
@auth("seller")
|
||||
def get_contract():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (session["user_id"],))
|
||||
owner = cur.fetchone()
|
||||
if not owner or not owner["contract_file"]:
|
||||
return error("contract not found", 404)
|
||||
|
||||
filename = owner["contract_file"]
|
||||
contract_dir = CONTRACT_DIR.resolve()
|
||||
path = (CONTRACT_DIR / filename).resolve()
|
||||
if path.parent != contract_dir:
|
||||
return error("contract not found", 404)
|
||||
|
||||
if request.method == "POST":
|
||||
import re
|
||||
contract_id = request.headers.get("X-Contract-Id", "").strip()
|
||||
if not re.fullmatch(r"\d+", contract_id):
|
||||
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(owner["id"]):
|
||||
return error("invalid contract id", 400)
|
||||
_dir = CONTRACT_DIR.resolve()
|
||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{contract_id}-*.pdf"))
|
||||
deleted = 0
|
||||
for path in hits:
|
||||
try:
|
||||
if path.resolve().parent == _dir:
|
||||
path.unlink()
|
||||
deleted += 1
|
||||
except OSError:
|
||||
continue
|
||||
if deleted == 0:
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
return error("contract not found", 404)
|
||||
return jsonify(status="deleted", deleted=deleted)
|
||||
except OSError:
|
||||
return error("contract deletion failed", 500)
|
||||
return jsonify(status="deleted", deleted=1)
|
||||
|
||||
requested = request.args.get("file")
|
||||
|
||||
if requested:
|
||||
import re
|
||||
m = re.match(r"^\s*contract-(\d+)", requested)
|
||||
if m:
|
||||
uid = m.group(1)
|
||||
hits = sorted(CONTRACT_DIR.glob(f"contract-{uid}-*.pdf"))
|
||||
if hits:
|
||||
return send_file(hits[0], mimetype="application/pdf", download_name=hits[0].name)
|
||||
return error("contract not found", 404)
|
||||
raw = requested.strip()
|
||||
candidates: list[Path] = []
|
||||
candidates.append((CONTRACT_DIR / raw).resolve())
|
||||
candidates.append(Path(raw).resolve())
|
||||
candidates.append(CONTRACT_DIR / raw)
|
||||
candidates.append(Path(raw))
|
||||
for target in candidates:
|
||||
try:
|
||||
if target.is_file():
|
||||
guessed, _ = mimetypes.guess_type(str(target))
|
||||
return send_file(target, mimetype=guessed or "application/octet-stream", download_name=target.name)
|
||||
except ValueError:
|
||||
continue
|
||||
return error("contract not found", 404)
|
||||
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT contract_file FROM users WHERE id=%s", (session["user_id"],))
|
||||
filename = cur.fetchone()["contract_file"]
|
||||
path = CONTRACT_DIR / filename
|
||||
if raw not in {filename, f"contract-{owner['id']}"}:
|
||||
return error("contract not found", 404)
|
||||
if not path.is_file():
|
||||
return error("contract not found", 404)
|
||||
return send_file(path, mimetype="application/pdf", download_name="starpost-contract.pdf")
|
||||
download_name = path.name if requested else "starpost-contract.pdf"
|
||||
return send_file(path, mimetype="application/pdf", download_name=download_name)
|
||||
@@ -52,8 +52,8 @@ def migrate():
|
||||
"""
|
||||
)
|
||||
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
|
||||
cursor.execute("ALTER TABLE promo_codes ADD COLUMN IF NOT EXISTS credited_at TIMESTAMPTZ")
|
||||
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
|
||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS credited_at")
|
||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
|
||||
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
|
||||
|
||||
Reference in new issue
Block a user