Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4870b401a | ||
|
|
393e7a13f4 | ||
|
|
e90414b4b8 | ||
|
|
7d52945c80 | ||
|
|
50233c1920 | ||
|
|
e2e5f02ac2 |
No files matched your search
@@ -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", "4", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "2", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
+3
-3
@@ -10,7 +10,6 @@ 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 (
|
||||
@@ -22,6 +21,7 @@ from database import (
|
||||
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__)
|
||||
@@ -175,7 +175,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, generate_password_hash(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, hash_password(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 +197,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 check_password_hash(user["password_hash"], data["password"]):
|
||||
if not user or not isinstance(data.get("password"), str) or not password_matches(user["password_hash"], data["password"]):
|
||||
return error("invalid credentials", 401)
|
||||
session.clear()
|
||||
session.update(user_id=user["id"], username=user["username"], role=user["role"])
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
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)
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
|
||||
API_DIR = Path(__file__).resolve().parents[1] / "api"
|
||||
sys.path.insert(0, str(API_DIR))
|
||||
|
||||
from passwords import hash_password, password_matches # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
password = "correct horse battery staple"
|
||||
|
||||
current_hash = hash_password(password)
|
||||
assert current_hash.startswith("pbkdf2:sha256:600000$")
|
||||
assert password_matches(current_hash, password)
|
||||
assert not password_matches(current_hash, password + "!")
|
||||
|
||||
legacy_hash = generate_password_hash(password, method="scrypt:32768:8:1")
|
||||
assert password_matches(legacy_hash, password)
|
||||
assert not password_matches(legacy_hash, password + "!")
|
||||
|
||||
print("password hash compatibility: ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
|
||||
TOKEN = "synthetic-local-token"
|
||||
CART_ITEMS = 20
|
||||
QUANTITY = 10
|
||||
|
||||
|
||||
def load_modules():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
os.environ["DATABASE_URL"] = "postgresql://unused"
|
||||
os.environ["SECRET_KEY"] = "synthetic-local-session-key"
|
||||
os.environ["WAREHOUSE_URL"] = "http://127.0.0.1:9"
|
||||
os.environ["WAREHOUSE_API_URL"] = "http://127.0.0.1:9"
|
||||
os.environ["WAREHOUSE_CALLBACK_TOKEN"] = TOKEN
|
||||
|
||||
api_dir = root / "api"
|
||||
sys.path.insert(0, str(api_dir))
|
||||
contracts = ModuleType("contracts")
|
||||
contracts.CONTRACT_DIR = root / "contracts"
|
||||
contracts.create_contract = lambda *args: "synthetic.pdf"
|
||||
sys.modules["contracts"] = contracts
|
||||
database = importlib.import_module("database")
|
||||
database.migrate = lambda: None
|
||||
api = importlib.import_module("app")
|
||||
|
||||
worker_path = root / "warehouse" / "worker.py"
|
||||
spec = importlib.util.spec_from_file_location("starpost_warehouse_poc", worker_path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError("cannot load warehouse worker")
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(worker)
|
||||
return api, worker
|
||||
|
||||
|
||||
class FakeCursor:
|
||||
def __init__(self):
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
self.buyer = {"balance": CART_ITEMS * QUANTITY, "buyer_created_at": timestamp}
|
||||
self.items = [
|
||||
{
|
||||
"product_id": product_id,
|
||||
"seller_id": 1000 + product_id,
|
||||
"price": 1,
|
||||
"is_active": True,
|
||||
"product_created_at": timestamp,
|
||||
"quantity": QUANTITY,
|
||||
}
|
||||
for product_id in range(1, CART_ITEMS + 1)
|
||||
]
|
||||
self.one = None
|
||||
self.many = []
|
||||
self.order_id = 0
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, traceback):
|
||||
return False
|
||||
|
||||
def execute(self, query, parameters=()):
|
||||
normalized = " ".join(query.split())
|
||||
self.one = None
|
||||
self.many = []
|
||||
if normalized.startswith("SELECT balance,created_at buyer_created_at"):
|
||||
self.one = self.buyer
|
||||
elif normalized.startswith("SELECT p.id product_id"):
|
||||
self.many = self.items
|
||||
elif normalized.startswith("INSERT INTO orders"):
|
||||
self.order_id += 1
|
||||
self.one = {"id": self.order_id}
|
||||
|
||||
def fetchone(self):
|
||||
return self.one
|
||||
|
||||
def fetchall(self):
|
||||
return self.many
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.fake_cursor = FakeCursor()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, traceback):
|
||||
return False
|
||||
|
||||
def cursor(self):
|
||||
return self.fake_cursor
|
||||
|
||||
|
||||
def main():
|
||||
api, worker = load_modules()
|
||||
starts = []
|
||||
|
||||
class FakeThread:
|
||||
def __init__(self, target, args, daemon):
|
||||
self.target = target
|
||||
self.args = args
|
||||
self.daemon = daemon
|
||||
|
||||
def start(self):
|
||||
starts.append((self.target, self.args, self.daemon))
|
||||
|
||||
worker.threading = SimpleNamespace(Thread=FakeThread)
|
||||
warehouse = worker.app.test_client()
|
||||
internal_statuses = []
|
||||
|
||||
def submit_jobs(orders):
|
||||
for order in orders:
|
||||
response = warehouse.post(
|
||||
"/jobs",
|
||||
json={"order_id": order["id"]},
|
||||
headers={"X-Warehouse-Token": TOKEN},
|
||||
)
|
||||
internal_statuses.append(response.status_code)
|
||||
|
||||
api.db = lambda: FakeConnection()
|
||||
api.submit_warehouse_jobs = submit_jobs
|
||||
api.app.config.update(TESTING=True)
|
||||
client = api.app.test_client()
|
||||
with client.session_transaction() as session:
|
||||
session.update(user_id=1, username="synthetic", role="buyer")
|
||||
|
||||
response = client.post("/api/cart/checkout", json={})
|
||||
document = response.get_json(silent=True) or {}
|
||||
orders = document.get("orders", [])
|
||||
result = {
|
||||
"external_checkout_requests": 1,
|
||||
"prepared_cart_items": CART_ITEMS,
|
||||
"orders_created": len(orders),
|
||||
"internal_jobs_accepted": internal_statuses.count(202),
|
||||
"jobs_retained": len(worker.jobs),
|
||||
"worker_threads_started": len(starts),
|
||||
"compose_pid_limit": 128,
|
||||
"checkout_status": response.status_code,
|
||||
}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
expected = CART_ITEMS * QUANTITY
|
||||
if response.status_code != 201 or len(orders) != expected:
|
||||
return 1
|
||||
if result["internal_jobs_accepted"] != expected:
|
||||
return 1
|
||||
if result["jobs_retained"] != expected or result["worker_threads_started"] != expected:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception as error:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Reference in new issue
Block a user