Spaces:
Running
Running
feat: add FL-MCP database persistence and ledger service with tests
Browse files- app/services/flmcp/db.py +8 -0
- app/services/flmcp/ledger.py +7 -0
- tests/test_flmcp.py +252 -196
app/services/flmcp/db.py
CHANGED
|
@@ -340,6 +340,14 @@ class DB:
|
|
| 340 |
cur.execute(
|
| 341 |
"CREATE UNIQUE INDEX IF NOT EXISTS accounts_auth ON accounts(auth_user_id)"
|
| 342 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
conn.commit()
|
| 344 |
finally:
|
| 345 |
conn.close()
|
|
|
|
| 340 |
cur.execute(
|
| 341 |
"CREATE UNIQUE INDEX IF NOT EXISTS accounts_auth ON accounts(auth_user_id)"
|
| 342 |
)
|
| 343 |
+
# Supabase publishes the public schema through its REST API; with RLS on and no
|
| 344 |
+
# policies the publishable key sees nothing. This service connects as the
|
| 345 |
+
# postgres role, which bypasses RLS.
|
| 346 |
+
for table in (
|
| 347 |
+
"accounts", "licenses", "devices", "lots",
|
| 348 |
+
"reservations", "entries", "webhook_events", "outbox",
|
| 349 |
+
):
|
| 350 |
+
cur.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
| 351 |
conn.commit()
|
| 352 |
finally:
|
| 353 |
conn.close()
|
app/services/flmcp/ledger.py
CHANGED
|
@@ -17,6 +17,8 @@ from typing import Any
|
|
| 17 |
from .errors import ApiError
|
| 18 |
from .plans import Config
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def _new_lot(
|
| 22 |
conn: Any,
|
|
@@ -152,6 +154,11 @@ def reserve(
|
|
| 152 |
raise ApiError(409, "idempotency_conflict", "that key was used for other operations")
|
| 153 |
return _view(conn, again, now)
|
| 154 |
cost = sum(prices.values())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
have = balance(conn, account_id, now)
|
| 156 |
if have < cost:
|
| 157 |
raise ApiError(
|
|
|
|
| 17 |
from .errors import ApiError
|
| 18 |
from .plans import Config
|
| 19 |
|
| 20 |
+
MAX_OPEN_HOLDS = 20 # unsettled reservations an account may have at once
|
| 21 |
+
|
| 22 |
|
| 23 |
def _new_lot(
|
| 24 |
conn: Any,
|
|
|
|
| 154 |
raise ApiError(409, "idempotency_conflict", "that key was used for other operations")
|
| 155 |
return _view(conn, again, now)
|
| 156 |
cost = sum(prices.values())
|
| 157 |
+
open_holds = conn.execute(
|
| 158 |
+
"SELECT COUNT(*) AS n FROM reservations WHERE account_id=? AND state='held'", (account_id,)
|
| 159 |
+
).fetchone()
|
| 160 |
+
if int(open_holds["n"] if isinstance(open_holds, dict) else open_holds[0]) >= MAX_OPEN_HOLDS:
|
| 161 |
+
raise ApiError(429, "too_many_holds", "settle or wait for open reservations before reserving more")
|
| 162 |
have = balance(conn, account_id, now)
|
| 163 |
if have < cost:
|
| 164 |
raise ApiError(
|
tests/test_flmcp.py
CHANGED
|
@@ -1,30 +1,57 @@
|
|
| 1 |
-
"""Tests for FL-MCP
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
import os
|
| 6 |
import secrets
|
| 7 |
import tempfile
|
| 8 |
import time
|
|
|
|
|
|
|
| 9 |
import pytest
|
|
|
|
| 10 |
from fastapi.testclient import TestClient
|
| 11 |
|
| 12 |
from app.main import app
|
| 13 |
-
from app.services.flmcp import keys, webhooks
|
| 14 |
from app.services.flmcp.db import DB
|
| 15 |
-
from app.services.flmcp.plans import load
|
| 16 |
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
fd, path = tempfile.mkstemp(suffix=".db")
|
| 21 |
os.close(fd)
|
| 22 |
monkeypatch.setenv("FLMCP_DB", path)
|
|
|
|
|
|
|
| 23 |
monkeypatch.setenv("FLMCP_ADMIN_TOKEN", "test-admin-secret-token")
|
| 24 |
monkeypatch.setenv("FLMCP_WEBHOOK_SECRETS", "stripe=stripe-test-secret,lemonsqueezy=lemon-secret")
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
os.remove(path)
|
| 30 |
except OSError:
|
|
@@ -32,224 +59,253 @@ def temp_db(monkeypatch):
|
|
| 32 |
|
| 33 |
|
| 34 |
@pytest.fixture
|
| 35 |
-
def client(
|
| 36 |
return TestClient(app)
|
| 37 |
|
| 38 |
|
| 39 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
key = keys.new_key()
|
| 41 |
-
assert key.startswith("FLMCP-")
|
| 42 |
-
|
| 43 |
-
assert
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
assert keys.normalize(bad_key) is None
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
-
def
|
| 58 |
-
res = client.
|
| 59 |
assert res.status_code == 200
|
| 60 |
data = res.json()
|
| 61 |
-
assert "
|
| 62 |
-
assert data["plan"] == "trial"
|
| 63 |
-
assert data["balance"] == 15
|
| 64 |
-
assert data["key"].startswith("FLMCP-")
|
| 65 |
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
)
|
| 77 |
-
assert
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
assert
|
| 88 |
-
|
| 89 |
-
assert
|
| 90 |
-
assert len(acc_data["devices"]) == 1
|
| 91 |
-
assert acc_data["devices"][0]["name"] == "Desktop-Win11"
|
| 92 |
|
| 93 |
|
| 94 |
def test_seat_limit_and_replace(client):
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
r1 = client.post(
|
| 101 |
-
"/api/v1/flmcp/activate",
|
| 102 |
-
json={"key": key, "name": "Device-1", "device_id": "dev-1"},
|
| 103 |
-
)
|
| 104 |
-
assert r1.status_code == 200
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
assert
|
| 112 |
-
prob = r2.json()
|
| 113 |
-
assert prob["code"] == "device_limit"
|
| 114 |
-
assert len(prob["devices"]) == 1
|
| 115 |
-
|
| 116 |
-
# Second device with replace succeeds
|
| 117 |
-
r3 = client.post(
|
| 118 |
-
"/api/v1/flmcp/activate",
|
| 119 |
-
json={"key": key, "name": "Device-2", "device_id": "dev-2", "replace": "Device-1"},
|
| 120 |
-
)
|
| 121 |
-
assert r3.status_code == 200
|
| 122 |
-
assert "token" in r3.json()
|
| 123 |
|
| 124 |
|
| 125 |
-
def
|
| 126 |
-
|
| 127 |
-
key
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
idem = secrets.token_hex(16)
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
)
|
| 141 |
-
assert
|
| 142 |
-
hold_data = res_hold.json()
|
| 143 |
-
rid = hold_data["id"]
|
| 144 |
-
assert hold_data["cost"] == 7
|
| 145 |
-
assert hold_data["balance"] == 8
|
| 146 |
-
|
| 147 |
-
# Retrying with same idem returns identical response (idempotent)
|
| 148 |
-
res_retry = client.post(
|
| 149 |
-
"/api/v1/flmcp/credits/reserve",
|
| 150 |
-
json={"ops": ["produce.compose", "mix.balance"], "idem": idem},
|
| 151 |
-
headers={"Authorization": f"Bearer {token}"},
|
| 152 |
-
)
|
| 153 |
-
assert res_retry.status_code == 200
|
| 154 |
-
assert res_retry.json()["id"] == rid
|
| 155 |
-
|
| 156 |
-
# Settle: only produce.compose (cost 5) succeeded, mix.balance (cost 2) failed and is refunded
|
| 157 |
-
res_settle = client.post(
|
| 158 |
-
f"/api/v1/flmcp/credits/{rid}/settle",
|
| 159 |
-
json={"done": ["produce.compose"]},
|
| 160 |
-
headers={"Authorization": f"Bearer {token}"},
|
| 161 |
-
)
|
| 162 |
-
assert res_settle.status_code == 200
|
| 163 |
-
settle_data = res_settle.json()
|
| 164 |
-
assert settle_data["charged"] == 5
|
| 165 |
-
assert settle_data["refunded"] == 2
|
| 166 |
-
# Balance should now be 15 - 5 = 10
|
| 167 |
-
assert settle_data["balance"] == 10
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def test_insufficient_credits(client):
|
| 171 |
-
t_res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "poor_user@flmcp.io"})
|
| 172 |
-
key = t_res.json()["key"]
|
| 173 |
-
token = client.post(
|
| 174 |
-
"/api/v1/flmcp/activate",
|
| 175 |
-
json={"key": key, "name": "PC", "device_id": "pc-1"},
|
| 176 |
-
).json()["token"]
|
| 177 |
-
|
| 178 |
-
# Attempt to reserve 20 credits when only 15 exist
|
| 179 |
-
# 4 * produce.compose = 20
|
| 180 |
-
# Ops must be distinct names in reserve API; but we can test with large op or multiple holds
|
| 181 |
-
idem1 = secrets.token_hex(16)
|
| 182 |
-
r1 = client.post(
|
| 183 |
-
"/api/v1/flmcp/credits/reserve",
|
| 184 |
-
json={"ops": ["produce.compose", "produce.flp", "mix.balance"], "idem": idem1},
|
| 185 |
-
headers={"Authorization": f"Bearer {token}"},
|
| 186 |
-
)
|
| 187 |
-
# 5 + 3 + 2 = 10 held; balance is 5
|
| 188 |
-
assert r1.status_code == 200
|
| 189 |
-
rid1 = r1.json()["id"]
|
| 190 |
-
client.post(
|
| 191 |
-
f"/api/v1/flmcp/credits/{rid1}/settle",
|
| 192 |
-
json={"done": ["produce.compose", "produce.flp", "mix.balance"]},
|
| 193 |
-
headers={"Authorization": f"Bearer {token}"},
|
| 194 |
-
)
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
json={"ops": ["produce.compose", "produce.flp"], "idem":
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
assert err["code"] == "insufficient_credits"
|
| 206 |
-
assert "topup_url" in err
|
| 207 |
|
| 208 |
|
| 209 |
def test_device_self_revoke(client):
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
"/api/v1/flmcp/activate",
|
| 214 |
-
json={"key": key, "name": "Studio-Laptop", "device_id": "laptop-1"},
|
| 215 |
-
).json()["token"]
|
| 216 |
|
| 217 |
-
rev_res = client.post("/api/v1/flmcp/devices/self/revoke", headers={"Authorization": f"Bearer {token}"})
|
| 218 |
-
assert rev_res.status_code == 204
|
| 219 |
|
| 220 |
-
|
| 221 |
-
acc = client.get("/api/v1/flmcp/account", headers={"Authorization": f"Bearer {token}"})
|
| 222 |
-
assert acc.status_code == 401
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
"
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
"period_start": now,
|
| 235 |
-
"period_end": now + 30 * 86400,
|
| 236 |
}
|
| 237 |
-
body_bytes = str(payload).replace("'", '"').encode("utf-8")
|
| 238 |
-
sig = webhooks.sign(secret, body_bytes, now)
|
| 239 |
|
| 240 |
-
res = client.post(
|
| 241 |
-
"/api/v1/flmcp/webhooks/stripe",
|
| 242 |
-
content=body_bytes,
|
| 243 |
-
headers={"Content-Type": "application/json", "X-Signature": sig},
|
| 244 |
-
)
|
| 245 |
-
assert res.status_code == 200
|
| 246 |
-
assert "license" in res.json()
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
assert
|
| 254 |
-
|
|
|
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for the FL-MCP licence API: Google/Supabase sign-in, trials, credits, rate limits, webhooks."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
+
import hashlib
|
| 6 |
+
import hmac
|
| 7 |
+
import json
|
| 8 |
import os
|
| 9 |
import secrets
|
| 10 |
import tempfile
|
| 11 |
import time
|
| 12 |
+
|
| 13 |
+
import jwt
|
| 14 |
import pytest
|
| 15 |
+
from cryptography.hazmat.primitives.asymmetric import ec
|
| 16 |
from fastapi.testclient import TestClient
|
| 17 |
|
| 18 |
from app.main import app
|
| 19 |
+
from app.services.flmcp import auth, keys, ratelimit, webhooks
|
| 20 |
from app.services.flmcp.db import DB
|
|
|
|
| 21 |
|
| 22 |
+
SUPABASE = "https://test-project.supabase.co"
|
| 23 |
+
_PRIVATE = ec.generate_private_key(ec.SECP256R1())
|
| 24 |
|
| 25 |
+
|
| 26 |
+
def token_for(email: str, sub: str | None = None, *, exp_in: int = 600, verified: bool = True,
|
| 27 |
+
issuer: str = f"{SUPABASE}/auth/v1") -> str:
|
| 28 |
+
now = int(time.time())
|
| 29 |
+
claims = {
|
| 30 |
+
"sub": sub or f"user-{email}", "email": email, "aud": "authenticated", "iss": issuer,
|
| 31 |
+
"iat": now, "exp": now + exp_in, "user_metadata": {"email_verified": verified},
|
| 32 |
+
}
|
| 33 |
+
return jwt.encode(claims, _PRIVATE, algorithm="ES256")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def hdr(email: str, **kw) -> dict:
|
| 37 |
+
return {"Authorization": f"Bearer {token_for(email, **kw)}"}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.fixture(autouse=True)
|
| 41 |
+
def _env(monkeypatch):
|
| 42 |
fd, path = tempfile.mkstemp(suffix=".db")
|
| 43 |
os.close(fd)
|
| 44 |
monkeypatch.setenv("FLMCP_DB", path)
|
| 45 |
+
monkeypatch.delenv("DATABASE_URL", raising=False)
|
| 46 |
+
monkeypatch.setenv("SUPABASE_URL", SUPABASE)
|
| 47 |
monkeypatch.setenv("FLMCP_ADMIN_TOKEN", "test-admin-secret-token")
|
| 48 |
monkeypatch.setenv("FLMCP_WEBHOOK_SECRETS", "stripe=stripe-test-secret,lemonsqueezy=lemon-secret")
|
| 49 |
+
monkeypatch.setenv("FLMCP_LS_VARIANTS", "111=pro,222=studio,333=pack_100")
|
| 50 |
+
monkeypatch.setattr(auth, "_signing_key", lambda _token: _PRIVATE.public_key())
|
| 51 |
+
DB(path)
|
| 52 |
+
ratelimit.reset()
|
| 53 |
+
yield
|
| 54 |
+
ratelimit.reset()
|
| 55 |
try:
|
| 56 |
os.remove(path)
|
| 57 |
except OSError:
|
|
|
|
| 59 |
|
| 60 |
|
| 61 |
@pytest.fixture
|
| 62 |
+
def client():
|
| 63 |
return TestClient(app)
|
| 64 |
|
| 65 |
|
| 66 |
+
def claim_trial(client, email="producer@gmail.com"):
|
| 67 |
+
res = client.post("/api/v1/flmcp/me/trial", headers=hdr(email))
|
| 68 |
+
assert res.status_code == 200, res.text
|
| 69 |
+
return res.json()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def activate(client, key, device="dev-00000001", name="PC", **extra):
|
| 73 |
+
return client.post("/api/v1/flmcp/activate", json={"key": key, "device_id": device, "name": name, **extra})
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ── keys ──────────────────────────────────────────────────────────────
|
| 77 |
+
|
| 78 |
+
def test_keys_checksum_catches_typos():
|
| 79 |
key = keys.new_key()
|
| 80 |
+
assert key.startswith("FLMCP-") and keys.normalize(key)
|
| 81 |
+
typo = key[:-1] + ("A" if key[-1] != "A" else "B")
|
| 82 |
+
assert keys.normalize(typo) is None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ── sign-in ───────────────────────────────────────────────────────────
|
| 86 |
+
|
| 87 |
+
def test_me_requires_a_session(client):
|
| 88 |
+
assert client.get("/api/v1/flmcp/me").status_code == 401
|
| 89 |
+
assert client.get("/api/v1/flmcp/me", headers={"Authorization": "Bearer garbage"}).status_code == 401
|
| 90 |
+
|
| 91 |
|
| 92 |
+
def test_rejects_expired_wrong_issuer_and_unverified(client):
|
| 93 |
+
assert client.get("/api/v1/flmcp/me", headers=hdr("a@gmail.com", exp_in=-10)).status_code == 401
|
| 94 |
+
assert client.get("/api/v1/flmcp/me", headers=hdr("a@gmail.com", issuer="https://evil.example/auth/v1")).status_code == 401
|
| 95 |
+
assert client.get("/api/v1/flmcp/me", headers=hdr("a@gmail.com", verified=False)).status_code == 403
|
|
|
|
| 96 |
|
| 97 |
+
|
| 98 |
+
def test_rejects_token_signed_with_another_key(client):
|
| 99 |
+
other = ec.generate_private_key(ec.SECP256R1())
|
| 100 |
+
now = int(time.time())
|
| 101 |
+
forged = jwt.encode(
|
| 102 |
+
{"sub": "x", "email": "a@gmail.com", "aud": "authenticated", "iss": f"{SUPABASE}/auth/v1", "exp": now + 60},
|
| 103 |
+
other, algorithm="ES256",
|
| 104 |
+
)
|
| 105 |
+
assert client.get("/api/v1/flmcp/me", headers={"Authorization": f"Bearer {forged}"}).status_code == 401
|
| 106 |
|
| 107 |
|
| 108 |
+
def test_me_creates_account_with_nothing_in_it(client):
|
| 109 |
+
res = client.get("/api/v1/flmcp/me", headers=hdr("new@gmail.com"))
|
| 110 |
assert res.status_code == 200
|
| 111 |
data = res.json()
|
| 112 |
+
assert data["license"] is None and data["balance"] == 0 and data["trial_used"] is False
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
+
# ── trial ─────────────────────────────────────────────────────────────
|
| 116 |
+
|
| 117 |
+
def test_trial_once_per_account(client):
|
| 118 |
+
first = claim_trial(client)
|
| 119 |
+
assert first["key"].startswith("FLMCP-") and first["balance"] == 15
|
| 120 |
+
assert first["license"]["plan"] == "trial" and first["trial_used"] is True
|
| 121 |
+
again = client.post("/api/v1/flmcp/me/trial", headers=hdr("producer@gmail.com"))
|
| 122 |
+
assert again.status_code == 409 and again.json()["code"] == "trial_used"
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_trial_blocks_disposable_email(client):
|
| 126 |
+
res = client.post("/api/v1/flmcp/me/trial", headers=hdr("bot@mailinator.com"))
|
| 127 |
+
assert res.status_code == 403 and res.json()["code"] == "email_not_allowed"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_trial_is_rate_limited_per_ip(client):
|
| 131 |
+
codes = [client.post("/api/v1/flmcp/me/trial", headers=hdr(f"u{i}@gmail.com")).status_code for i in range(5)]
|
| 132 |
+
assert codes[:3] == [200, 200, 200]
|
| 133 |
+
assert 429 in codes[3:]
|
| 134 |
|
| 135 |
+
|
| 136 |
+
def test_rate_limit_response_has_retry_after(client):
|
| 137 |
+
for i in range(3):
|
| 138 |
+
client.post("/api/v1/flmcp/me/trial", headers=hdr(f"v{i}@gmail.com"))
|
| 139 |
+
res = client.post("/api/v1/flmcp/me/trial", headers=hdr("v9@gmail.com"))
|
| 140 |
+
assert res.status_code == 429 and int(res.headers["Retry-After"]) >= 1
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ── activation, seats ─────────────────────────────────────────────────
|
| 144 |
+
|
| 145 |
+
def test_activate_and_account(client):
|
| 146 |
+
key = claim_trial(client)["key"]
|
| 147 |
+
res = activate(client, key, name="Desktop-Win11")
|
| 148 |
+
assert res.status_code == 200
|
| 149 |
+
body = res.json()
|
| 150 |
+
assert body["device_token"] and body["balance"] == 15 and body["plan"] == "trial"
|
| 151 |
+
acc = client.get("/api/v1/flmcp/account", headers={"Authorization": f"Bearer {body['device_token']}"})
|
| 152 |
+
assert acc.status_code == 200 and acc.json()["devices"][0]["name"] == "Desktop-Win11"
|
|
|
|
|
|
|
| 153 |
|
| 154 |
|
| 155 |
def test_seat_limit_and_replace(client):
|
| 156 |
+
key = claim_trial(client)["key"]
|
| 157 |
+
assert activate(client, key, "dev-00000001", "One").status_code == 200
|
| 158 |
+
blocked = activate(client, key, "dev-00000002", "Two")
|
| 159 |
+
assert blocked.status_code == 409 and blocked.json()["code"] == "device_limit"
|
| 160 |
+
assert activate(client, key, "dev-00000002", "Two", replace="One").status_code == 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
|
| 163 |
+
def test_activate_brute_force_is_limited(client):
|
| 164 |
+
bad = keys.new_key()
|
| 165 |
+
codes = [activate(client, bad, f"dev-{i:08d}").status_code for i in range(12)]
|
| 166 |
+
assert codes[0] == 404
|
| 167 |
+
assert codes[-1] == 429
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
|
| 170 |
+
def test_dashboard_can_revoke_a_seat(client):
|
| 171 |
+
key = claim_trial(client)["key"]
|
| 172 |
+
activate(client, key, "dev-aaaaaaaa", "Laptop")
|
| 173 |
+
me = client.get("/api/v1/flmcp/me", headers=hdr("producer@gmail.com")).json()
|
| 174 |
+
seat = me["devices"][0]["full_id"]
|
| 175 |
+
res = client.post("/api/v1/flmcp/me/devices/revoke", json={"device_id": seat}, headers=hdr("producer@gmail.com"))
|
| 176 |
+
assert res.status_code == 200 and res.json()["devices"] == []
|
| 177 |
|
| 178 |
+
|
| 179 |
+
def test_user_cannot_revoke_someone_elses_seat(client):
|
| 180 |
+
key = claim_trial(client, "owner@gmail.com")["key"]
|
| 181 |
+
activate(client, key, "dev-bbbbbbbb", "Owner-PC")
|
| 182 |
+
client.get("/api/v1/flmcp/me", headers=hdr("intruder@gmail.com"))
|
| 183 |
+
res = client.post("/api/v1/flmcp/me/devices/revoke", json={"device_id": "dev-bbbbbbbb"}, headers=hdr("intruder@gmail.com"))
|
| 184 |
+
assert res.status_code == 404
|
| 185 |
+
still = client.get("/api/v1/flmcp/me", headers=hdr("owner@gmail.com")).json()
|
| 186 |
+
assert len(still["devices"]) == 1
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_rotate_key_invalidates_the_old_one(client):
|
| 190 |
+
old = claim_trial(client)["key"]
|
| 191 |
+
new = client.post("/api/v1/flmcp/me/key/rotate", headers=hdr("producer@gmail.com")).json()["key"]
|
| 192 |
+
assert new != old
|
| 193 |
+
assert activate(client, old).status_code == 404
|
| 194 |
+
assert activate(client, new).status_code == 200
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_old_unauthenticated_endpoints_are_gone(client):
|
| 198 |
+
assert client.post("/api/v1/flmcp/user/lookup", json={"email": "a@gmail.com"}).status_code in (404, 405)
|
| 199 |
+
assert client.post("/api/v1/flmcp/user/generate-trial", json={"email": "a@gmail.com"}).status_code in (404, 405)
|
| 200 |
+
assert client.post("/api/v1/flmcp/devices/revoke", json={"key": "x", "device_id": "y"}).status_code in (404, 405)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# ── credits ───────────────────────────────────────────────────────────
|
| 204 |
+
|
| 205 |
+
def device_token(client, email="credit@gmail.com"):
|
| 206 |
+
key = claim_trial(client, email)["key"]
|
| 207 |
+
return {"Authorization": f"Bearer {activate(client, key).json()['device_token']}"}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_reserve_settle_and_idempotency(client):
|
| 211 |
+
h = device_token(client)
|
| 212 |
idem = secrets.token_hex(16)
|
| 213 |
+
body = {"ops": ["produce.compose", "mix.balance"], "idem": idem}
|
| 214 |
+
held = client.post("/api/v1/flmcp/credits/reserve", json=body, headers=h).json()
|
| 215 |
+
assert held["cost"] == 7 and held["balance"] == 8
|
| 216 |
+
retry = client.post("/api/v1/flmcp/credits/reserve", json=body, headers=h).json()
|
| 217 |
+
assert retry["id"] == held["id"] and retry["balance"] == 8
|
| 218 |
+
done = client.post(f"/api/v1/flmcp/credits/{held['id']}/settle", json={"done": ["produce.compose"]}, headers=h).json()
|
| 219 |
+
assert done["charged"] == 5 and done["refunded"] == 2 and done["balance"] == 10
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
+
|
| 222 |
+
def test_insufficient_credits_gives_topup_url(client):
|
| 223 |
+
h = device_token(client)
|
| 224 |
+
for _ in range(2):
|
| 225 |
+
r = client.post("/api/v1/flmcp/credits/reserve", json={"ops": ["produce.compose", "produce.flp", "mix.balance"], "idem": secrets.token_hex(8)}, headers=h)
|
| 226 |
+
if r.status_code == 200:
|
| 227 |
+
client.post(f"/api/v1/flmcp/credits/{r.json()['id']}/settle", json={"done": ["produce.compose", "produce.flp", "mix.balance"]}, headers=h)
|
| 228 |
+
res = client.post("/api/v1/flmcp/credits/reserve", json={"ops": ["produce.compose", "produce.flp"], "idem": secrets.token_hex(8)}, headers=h)
|
| 229 |
+
assert res.status_code == 402 and "topup_url" in res.json()
|
|
|
|
|
|
|
| 230 |
|
| 231 |
|
| 232 |
def test_device_self_revoke(client):
|
| 233 |
+
h = device_token(client, "revoker@gmail.com")
|
| 234 |
+
assert client.post("/api/v1/flmcp/devices/self/revoke", headers=h).status_code == 204
|
| 235 |
+
assert client.get("/api/v1/flmcp/account", headers=h).status_code == 401
|
|
|
|
|
|
|
|
|
|
| 236 |
|
|
|
|
|
|
|
| 237 |
|
| 238 |
+
# ── webhooks ──────────────────────────────────────────────────────────
|
|
|
|
|
|
|
| 239 |
|
| 240 |
+
def ls_post(client, payload: dict, secret="lemon-secret"):
|
| 241 |
+
raw = json.dumps(payload).encode()
|
| 242 |
+
sig = hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()
|
| 243 |
+
return client.post("/api/v1/flmcp/webhooks/lemonsqueezy", content=raw, headers={"Content-Type": "application/json", "X-Signature": sig})
|
| 244 |
|
| 245 |
+
|
| 246 |
+
def ls_sub(variant="111", email="buyer@gmail.com", sub_id="9001"):
|
| 247 |
+
return {
|
| 248 |
+
"meta": {"event_name": "subscription_created"},
|
| 249 |
+
"data": {"id": sub_id, "attributes": {
|
| 250 |
+
"user_email": email, "variant_id": int(variant), "status": "active",
|
| 251 |
+
"created_at": "2026-11-02T10:00:00.000000Z", "updated_at": "2026-11-02T10:00:00.000000Z",
|
| 252 |
+
"renews_at": "2026-12-02T10:00:00.000000Z",
|
| 253 |
+
}},
|
|
|
|
|
|
|
| 254 |
}
|
|
|
|
|
|
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
+
def test_lemonsqueezy_rejects_bad_signature(client):
|
| 258 |
+
assert ls_post(client, ls_sub(), secret="wrong").status_code == 401
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def test_lemonsqueezy_subscription_gives_licence_and_credits(client):
|
| 262 |
+
assert ls_post(client, ls_sub()).status_code == 200
|
| 263 |
+
me = client.get("/api/v1/flmcp/me", headers=hdr("buyer@gmail.com")).json()
|
| 264 |
+
assert me["license"]["plan"] == "pro" and me["balance"] == 300 and me["license"]["seats_allowed"] == 2
|
| 265 |
|
| 266 |
+
|
| 267 |
+
def test_lemonsqueezy_event_is_applied_once(client):
|
| 268 |
+
ls_post(client, ls_sub())
|
| 269 |
+
again = ls_post(client, ls_sub())
|
| 270 |
+
assert again.json().get("duplicate") is True
|
| 271 |
+
assert client.get("/api/v1/flmcp/me", headers=hdr("buyer@gmail.com")).json()["balance"] == 300
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def test_lemonsqueezy_pack_adds_credits(client):
|
| 275 |
+
ls_post(client, ls_sub())
|
| 276 |
+
pack = {
|
| 277 |
+
"meta": {"event_name": "order_created"},
|
| 278 |
+
"data": {"id": "5001", "attributes": {
|
| 279 |
+
"user_email": "buyer@gmail.com", "status": "paid", "created_at": "2026-11-02T11:00:00Z",
|
| 280 |
+
"first_order_item": {"variant_id": 333},
|
| 281 |
+
}},
|
| 282 |
+
}
|
| 283 |
+
assert ls_post(client, pack).status_code == 200
|
| 284 |
+
assert client.get("/api/v1/flmcp/me", headers=hdr("buyer@gmail.com")).json()["balance"] == 400
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def test_lemonsqueezy_cancel_keeps_access_until_period_end(client):
|
| 288 |
+
ls_post(client, ls_sub())
|
| 289 |
+
cancel = {"meta": {"event_name": "subscription_cancelled"},
|
| 290 |
+
"data": {"id": "9001", "attributes": {"updated_at": "2026-11-05T10:00:00Z"}}}
|
| 291 |
+
assert ls_post(client, cancel).status_code == 200
|
| 292 |
+
me = client.get("/api/v1/flmcp/me", headers=hdr("buyer@gmail.com")).json()
|
| 293 |
+
assert me["license"]["status"] == "canceled"
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def test_signed_in_user_is_linked_to_licence_bought_by_email(client):
|
| 297 |
+
ls_post(client, ls_sub(email="Buyer@Gmail.com"))
|
| 298 |
+
me = client.get("/api/v1/flmcp/me", headers=hdr("buyer@gmail.com", sub="google-sub-1")).json()
|
| 299 |
+
assert me["license"] is not None
|
| 300 |
+
other = client.get("/api/v1/flmcp/me", headers=hdr("buyer@gmail.com", sub="google-sub-2"))
|
| 301 |
+
assert other.status_code == 409
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def test_generic_webhook_still_verifies_timestamped_signature(client):
|
| 305 |
+
now = int(time.time())
|
| 306 |
+
payload = {"id": "evt_1", "type": "subscription.started", "email": "gen@gmail.com", "plan": "studio",
|
| 307 |
+
"ref": "sub_x", "period_start": now, "period_end": now + 86400 * 30}
|
| 308 |
+
raw = json.dumps(payload).encode()
|
| 309 |
+
res = client.post("/api/v1/flmcp/webhooks/stripe", content=raw,
|
| 310 |
+
headers={"Content-Type": "application/json", "X-Signature": webhooks.sign("stripe-test-secret", raw, now)})
|
| 311 |
+
assert res.status_code == 200
|