diff --git a/CHANGELOG.md b/CHANGELOG.md index 5529e34..6dfd3fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,30 @@ Versions follow [Semantic Versioning](https://semver.org/). --- +## [Unreleased] + +### Changed (breaking) +- `POST /api/register` and `POST /v1/keys/free-signup` never return `api_key` any more. Both answer + `202 {"status":"pending_confirmation"}`, identical for a new and for an already registered address (the 409 + `already_exists` of free-signup is gone, and so is `already_existed` on register). A confirmation link is mailed; + the key is mailed once the address is confirmed. Clients that read `api_key` from the response must stop doing so + (the `mcp-eu-ai-act` CLI is to be updated separately). +- Both endpoints share one IP limit of 5 requests per hour, counted in Redis (the per-process maps are removed; + register was 10 per hour). +- The 202 response carries no `upgrade_cta`. + +### Added +- `GET /v1/register/confirm` (page that reads the token from the URL fragment `#token=` and consumes nothing) and + `POST /v1/register/confirm {"token"}` (single use, 24 h, consumed atomically; a wrong, used or expired token is + a plain 400; limited to 20 attempts per IP per hour). The POST answers `{"status":"confirmed"}`. +- Per-address cap of 3 confirmation mails per 24 h (silent: same 202, no mail) and a global daily cap on + confirmation mails (`TL_REG_MAIL_DAILY_MAX`, default 500; over the cap the endpoints answer 503). +- Funnel event `register_requested`; `register_completion` and `signup_attributed` now fire at the confirm step. + +### Security +- Both endpoints answer 503 without Redis or without `TL_METRICS_SALT`, before any mail or key. +- Outgoing-mail logs carry a salted hash of the recipient instead of the address. + ## [1.13.0] — 2026-11-13 ### Added diff --git a/README.md b/README.md index 008c46a..9178f9b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Not a log. Not a trace. A proof. curl -X POST https://trust.arkforge.tech/v1/keys/free-signup \ -H "Content-Type: application/json" \ -d '{"email": "you@example.com"}' -# → {"api_key": "mcp_free_xxxx...", "plan": "free", "limit": "500 proofs/month"} +# → 202 {"status": "pending_confirmation"} (confirm your address from the email; the key is sent by email only) ``` [![Live](https://img.shields.io/badge/live-arkforge.tech-green)](https://trust.arkforge.tech/v1/health) @@ -78,7 +78,7 @@ See a live proof: [example transaction](https://trust.arkforge.tech/v1/proof/prf curl -X POST https://trust.arkforge.tech/v1/keys/free-signup \ -H "Content-Type: application/json" \ -d '{"email": "you@example.com"}' -# → {"api_key": "mcp_free_xxxx...", "plan": "free", "limit": "500 proofs/month"} +# → 202 {"status": "pending_confirmation"} (confirm your address from the email; the key is sent by email only) ``` ### Step 2 — Make a certified API call diff --git a/docs/design/TLREG.md b/docs/design/TLREG.md new file mode 100644 index 0000000..7612275 --- /dev/null +++ b/docs/design/TLREG.md @@ -0,0 +1,64 @@ +# TLREG: free API key delivered by email only, with address confirmation + +Status: implemented (R2), see CHANGELOG Unreleased. Follows TLCOSE-S. + +## Problem + +`POST /api/register` returns the new `api_key` in the JSON body. Anyone can type any address and receive a key bound to it +without owning the mailbox: quota farming by address, mail bombing of third parties, no proof of ownership. The +"already exists" branch already mails the key and no longer returns it; the "new key" branch does not. + +## Best known + +Standard double opt-in used by registries issuing tokens by mail (npm/PyPI email verification, Sigstore OIDC email claim): +no credential is issued before the address is proven. We match it; nothing here claims to go beyond. + +## Design + +1. `POST /api/register {email}`: validate, rate limit as today, store a pending record + `{email_hash, token_hash (sha256 of 32-byte random), expires_at = now + 24h}` in Redis (TTL 24h, key `reg_pending:{token_hash}`), + mail a confirmation link `https://trust.arkforge.tech/v1/register/confirm?token=...`. Response: `202 {"status":"pending_confirmation"}`, + identical whether the address is new or already has a key (no account enumeration). +2. `POST /v1/register/confirm {token}` (GET renders a one-button page that POSTs, so mail scanners prefetching links do not + consume the token): consume the token atomically (Redis GETDEL), create the key if none exists for the address, mail the key, + return `{"status":"confirmed"}` without the key. Existing key: resend it. +3. Per-address cap: at most 3 pending mails per address per 24h (counter in Redis), in addition to the per-IP cap. +4. Logs: salted hash of address only (reuse `TL_METRICS_SALT` helpers), never the address or the token. +5. Funnel events: `register_completion` and `signup_attributed` move to the confirm step; add `register_requested`. +6. CLI `mcp-eu-ai-act`: after `/api/register`, print "check your mailbox and confirm", stop expecting `api_key` in the response; + keep reading `already_existed` for backward compatibility during one release. + +## Revisions after review (Opus, 13/11) + +- Scope includes `POST /v1/keys/free-signup` (returns `api_key`, 409 reveals registered addresses; advertised in app.py:153, 3237, + 3482): same pending/confirm flow, same 202 for new and known addresses. Both endpoints share one code path. +- Pending record value holds the address in clear (Redis TTL 24h only, never logged); key is `reg_pending:{token_hash}`. +- One function `get_or_create_free_key(email)` does check + create under `_KEYS_LOCK` (no double key with several valid tokens); + test: two tokens for one address confirmed in parallel, one key. +- Fail closed: no Redis (`get_redis()` is None) or no `TL_METRICS_SALT` (`hash_identifier` returns "") = 503, no mail, no key. +- Token travels in the URL fragment (`#token=`), page reads it and POSTs; never in a query string (nginx/uvicorn access logs). +- 4th request per address within 24h: same 202, no mail, no address-specific 429 (no oracle). Both branches send a mail or both + go through a background task, so response time is not an oracle. +- Rate limits: replace the in-process IP map by the shared Redis counters (`signup_count` pattern, INCR+EXPIRE pipeline, salted key + `tl:reg_addr:{hash}`), plus a global daily cap on confirmation mails. Confirm POST gets its own rate limit. +- Logs: `email_notify._send_email` (l.66, 92, 100) and app.py:2194, 2209, 2214 stop logging the clear address (salted hash). + +## Out of scope + +Salting `proof_abuse:{ip}` and `client_ip_hash`, `GET /trial` redirect: separate tickets. + +## Tests (red first) + +- register response never contains `api_key`, for new and existing addresses, same shape for both. +- no key exists in storage before confirm; exactly one after. +- token single-use, expires after 24h, wrong token = 400 with no oracle. +- GET confirm does not consume the token; POST does. +- 4th request for one address in 24h sends no mail. +- no clear address or token in logs (caplog). +- no Redis -> 503; no salt -> 503; free-signup response has no `api_key`; 4th request same 202. +- update `tests/test_free_guard.py` and `tests/test_funnel_metrics.py` call sites. + +## Risks + +Mail deliverability becomes a hard dependency of onboarding (already true for key delivery). Breaking change for clients that read +`api_key` from the response: announced in CHANGELOG, major-visible in the CLI. diff --git a/scripts/deploy_trust_layer_prod.sh b/scripts/deploy_trust_layer_prod.sh index a58a287..1c38136 100755 --- a/scripts/deploy_trust_layer_prod.sh +++ b/scripts/deploy_trust_layer_prod.sh @@ -455,7 +455,7 @@ except Exception: fi # Both gates must pass. The security test runs first: its ephemeral key uses # a smoke.invalid email, swept by the teardown at the end of the smoke test. - if python3 "$SECURITY_TEST_SCRIPT" --url "$SMOKE_BASE_URL" 2>&1 | tee -a "$SMOKE_LOG" | tail -8 \ + if TRUST_LAYER_INTERNAL_SECRET="$SMOKE_INTERNAL_SECRET" python3 "$SECURITY_TEST_SCRIPT" --url "$SMOKE_BASE_URL" 2>&1 | tee -a "$SMOKE_LOG" | tail -8 \ && TRUST_LAYER_INTERNAL_SECRET="$SMOKE_INTERNAL_SECRET" \ TRUST_LAYER_SMOKE_WEBHOOK_SECRET="$SMOKE_WEBHOOK_SECRET" python3 "$SMOKE_TEST_SCRIPT" \ --base-url "$SMOKE_BASE_URL" \ diff --git a/scripts/security_smoke_test.py b/scripts/security_smoke_test.py index 2607603..350ba85 100644 --- a/scripts/security_smoke_test.py +++ b/scripts/security_smoke_test.py @@ -19,14 +19,12 @@ import argparse import json +import os import sys import time -import hmac -import hashlib -import secrets +import urllib.error import urllib.parse import urllib.request -import urllib.error from typing import Any # --------------------------------------------------------------------------- @@ -109,13 +107,15 @@ def run(base: str, existing_key: str = ""): free_key = existing_key print(f"\nUsing provided key: {free_key[:20]}...") else: - test_run_id = secrets.token_hex(4) - s, r = _request("POST", f"{base}/v1/keys/free-signup", - body={"email": f"sec-test-{test_run_id}@smoke.invalid"}) - free_key = r.get("api_key", "") + # free-signup no longer returns a key (address confirmation by email): take an + # ephemeral key from the admin smoke setup, swept by the smoke teardown. + internal_secret = os.environ.get("TRUST_LAYER_INTERNAL_SECRET", "") + s, r = _request("POST", f"{base}/v1/admin/smoke/setup", + headers={"X-Internal-Secret": internal_secret}) + free_key = r.get("free_key", "") if not free_key: print(f"{RED}FATAL: could not create test key (HTTP {s}). " - f"Use --key to provide an existing key.{RESET}") + f"Set TRUST_LAYER_INTERNAL_SECRET or use --key .{RESET}") sys.exit(2) print(f"\nTest key created: {free_key[:20]}...") @@ -124,25 +124,32 @@ def run(base: str, existing_key: str = ""): # ----------------------------------------------------------------------- section("1. Auth bypass") - s, r = _request("GET", f"{base}/v1/usage"); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage") + time.sleep(delay) check("No API key → 401", s, r, 401) - s, r = _request("GET", f"{base}/v1/usage", headers={"Authorization": "Bearer "}); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage", headers={"Authorization": "Bearer "}) + time.sleep(delay) check("Empty bearer token → 401", s, r, 401) - s, r = _request("GET", f"{base}/v1/usage", headers={"Authorization": "Basic dXNlcjpwYXNz"}); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage", headers={"Authorization": "Basic dXNlcjpwYXNz"}) + time.sleep(delay) check("Basic auth scheme → 401", s, r, 401) - s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": "mcp_pro_" + "a"*48}); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": "mcp_pro_" + "a"*48}) + time.sleep(delay) check("Non-existent key → 401", s, r, 401) - s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": "' OR '1'='1"}); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": "' OR '1'='1"}) + time.sleep(delay) check("SQL injection in key → 401", s, r, 401) - s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": "../../../etc/passwd"}); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": "../../../etc/passwd"}) + time.sleep(delay) check("Path traversal in key → 401", s, r, 401) - s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": free_key}); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/usage", headers={"X-Api-Key": free_key}) + time.sleep(delay) check("Valid free key → 200", s, r, 200) # ----------------------------------------------------------------------- @@ -218,7 +225,7 @@ def run(base: str, existing_key: str = ""): time.sleep(delay) time.sleep(delay) - big_payload = {"x" * 100: "y" * 100 for _ in range(50)} # ~10KB + big_payload = {"x" * 100: "y" * 100} # ~10KB s, r = _request("POST", f"{base}/v1/proxy", body={"target": "https://httpbin.org/post", "payload": big_payload, "currency": "eur"}, headers={"X-Api-Key": free_key}) @@ -263,13 +270,15 @@ def run(base: str, existing_key: str = ""): # No signature at all s, r = _request("POST", webhook_url, body={"type": "checkout.session.completed", "id": "evt_test_fake"}) - check("Webhook no signature → 400", s, r, 400); time.sleep(delay) + check("Webhook no signature → 400", s, r, 400) + time.sleep(delay) # Wrong signature s, r = _request("POST", webhook_url, body={"type": "checkout.session.completed", "id": "evt_test_fake"}, headers={"Stripe-Signature": "t=1234,v1=badhash"}) - check("Webhook bad signature → 400", s, r, 400); time.sleep(delay) + check("Webhook bad signature → 400", s, r, 400) + time.sleep(delay) # Stale timestamp (replay with >5min old timestamp) payload_str = json.dumps({"type": "invoice.paid", "id": "evt_replay_test"}) @@ -278,7 +287,8 @@ def run(base: str, existing_key: str = ""): s, r = _request("POST", webhook_url, body=json.loads(payload_str), headers={"Stripe-Signature": stale_sig}) - check("Webhook stale timestamp → 400", s, r, 400); time.sleep(delay) + check("Webhook stale timestamp → 400", s, r, 400) + time.sleep(delay) # ----------------------------------------------------------------------- section("7. Overage endpoint — plan restrictions") @@ -286,31 +296,37 @@ def run(base: str, existing_key: str = ""): s, r = _request("POST", f"{base}/v1/keys/overage", body={"enabled": True, "cap_eur": 20.0}, headers={"X-Api-Key": free_key}) - check("Free key cannot enable overage → 403", s, r, 403); time.sleep(delay) + check("Free key cannot enable overage → 403", s, r, 403) + time.sleep(delay) s, r = _request("POST", f"{base}/v1/keys/overage", body={"enabled": True, "cap_eur": 1.0}, headers={"X-Api-Key": free_key}) - check("Free key overage cap too low → 403", s, r, 403); time.sleep(delay) + check("Free key overage cap too low → 403", s, r, 403) + time.sleep(delay) s, r = _request("GET", f"{base}/v1/keys/overage", headers={"X-Api-Key": free_key}) - check("Free key GET overage → 200", s, r, 200); time.sleep(delay) + check("Free key GET overage → 200", s, r, 200) + time.sleep(delay) # ----------------------------------------------------------------------- section("8. Information disclosure") - s, r = _request("GET", f"{base}/v1/health"); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/health") + time.sleep(delay) check("Health endpoint → 200", s, r, 200) check("Health no secrets", s, r, 200, must_not_contain=["password", "secret", "fernet", "STRIPE_"]) - s, r = _request("GET", f"{base}/v1/pubkey"); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/pubkey") + time.sleep(delay) check("Pubkey → 200", s, r, 200) check("Pubkey no private key leak", s, r, 200, must_not_contain=["PRIVATE KEY", "private_key"]) - s, r = _request("GET", f"{base}/v1/pricing"); time.sleep(delay) + s, r = _request("GET", f"{base}/v1/pricing") + time.sleep(delay) check("Pricing → 200", s, r, 200) # ----------------------------------------------------------------------- diff --git a/tests/conftest.py b/tests/conftest.py index 039d751..7b725af 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -158,3 +158,40 @@ def client(): """FastAPI test client.""" from trust_layer.app import app return TestClient(app) + + +@pytest.fixture +def mailbox(monkeypatch): + """Capture every mail handed to _send_email as {"to", "subject", "body"}.""" + import trust_layer.email_notify as email_mod + sent: list[dict] = [] + monkeypatch.setattr( + email_mod, "_send_email", + lambda to, subject, body: sent.append({"to": to, "subject": subject, "body": body}), + ) + return sent + + +@pytest.fixture +def signup_key(mailbox): + """Return a callable that registers an address, confirms it from the mail, and returns the key. + + Needs TL_METRICS_SALT set and a Redis (the autouse fixture provides a fake one). + """ + import re + + def _signup(client, email, path="/v1/keys/free-signup", headers=None, **extra): + before = len(mailbox) + r = client.post(path, json={"email": email, **extra}, headers=headers or {}) + assert r.status_code == 202, r.text + mails = mailbox[before:] + assert len(mails) == 1 + token = re.search(r"#token=([A-Za-z0-9_\-]+)", mails[0]["body"]).group(1) + before = len(mailbox) + c = client.post("/v1/register/confirm", json={"token": token}, headers=headers or {}) + assert c.status_code == 200, c.text + key_mail = mailbox[before:] + assert len(key_mail) == 1 + return re.search(r"Your API key: (\S+)", key_mail[0]["body"]).group(1) + + return _signup diff --git a/tests/test_free_guard.py b/tests/test_free_guard.py index 7864770..e182eb6 100644 --- a/tests/test_free_guard.py +++ b/tests/test_free_guard.py @@ -114,17 +114,13 @@ def test_flag_false_pricing_exposes_only_free_and_no_upgrade_cta(client, monkeyp assert "upgrade_cta" not in json.dumps(body) -def test_flag_false_free_signup_response_has_no_upgrade_cta(client, monkeypatch): - monkeypatch.setenv("TL_PAID_PLANS_ENABLED", "false") +@pytest.mark.parametrize("flag", ["false", "true"]) +def test_free_signup_pending_response_has_no_upgrade_cta_whatever_the_flag(client, monkeypatch, flag): + # TLREG: the 202 is identical for every address and carries no offer. + monkeypatch.setenv("TL_PAID_PLANS_ENABLED", flag) r = client.post("/v1/keys/free-signup", json={"email": "nocta@arkforge-test.dev"}) - assert r.status_code == 200 - assert "upgrade_cta" not in r.json() - - -def test_flag_true_free_signup_response_keeps_upgrade_cta(client): - r = client.post("/v1/keys/free-signup", json={"email": "cta@arkforge-test.dev"}) - assert r.status_code == 200 - assert "upgrade_cta" in r.json() + assert r.status_code == 202 + assert "upgrade_cta" not in r.json() and "upgrade_url" not in r.json() def test_flag_false_stripe_webhook_still_processes_events(client, monkeypatch): @@ -337,25 +333,22 @@ async def test_email_not_sent_when_redis_cannot_decide(monkeypatch): # --- 5. Signup limit shared through Redis --- def test_signup_limit_is_shared_between_nodes(client, guard_redis): - import trust_layer.app as app_mod + # No per-process window any more: the count lives in Redis only, so every node sees it. statuses = [] for i in range(6): - # Each request lands on a "fresh node": the per-process memory is empty. - app_mod._FREE_SIGNUP_RATE.clear() statuses.append(client.post("/v1/keys/free-signup", json={"email": f"node{i}@arkforge-test.dev"}).status_code) - assert statuses == [200] * 5 + [429] + assert statuses == [202] * 5 + [429] -def test_refused_signup_creates_no_key(client, guard_redis): - import trust_layer.app as app_mod +def test_refused_signup_creates_no_key_and_sends_no_mail(client, guard_redis, mailbox): from trust_layer.keys import load_api_keys for i in range(5): client.post("/v1/keys/free-signup", json={"email": f"ok{i}@arkforge-test.dev"}) - app_mod._FREE_SIGNUP_RATE.clear() - before = len(load_api_keys()) + before, sent = len(load_api_keys()), len(mailbox) r = client.post("/v1/keys/free-signup", json={"email": "refused@arkforge-test.dev"}) assert r.status_code == 429 assert len(load_api_keys()) == before + assert len(mailbox) == sent # --- 6. Aggregate measurement --- @@ -370,8 +363,8 @@ def _today_row(response): return response.json()["days"][-1] -def test_signup_and_proof_increment_the_aggregates(client, monkeypatch): - key = client.post("/v1/keys/free-signup", json={"email": "agg@arkforge-test.dev"}).json()["api_key"] +def test_signup_and_proof_increment_the_aggregates(client, monkeypatch, signup_key): + key = signup_key(client, "agg@arkforge-test.dev") assert _prove(client, key).status_code == 200 row = _today_row(_metrics(client, monkeypatch)) assert row["free_keys_created"] == 1 @@ -413,10 +406,10 @@ def test_internal_key_proof_is_not_counted(client, monkeypatch): assert row["proofs"] == 0 and row["active_keys"] == 0 -def test_serialized_aggregate_holds_no_ip_email_or_key(client, free_key, monkeypatch, guard_redis): +def test_serialized_aggregate_holds_no_ip_email_or_key(client, free_key, monkeypatch, guard_redis, signup_key): email = "leak-check@arkforge-test.dev" ip = "203.0.113.77" - key = client.post("/v1/keys/free-signup", json={"email": email}, headers={"x-real-ip": ip}).json()["api_key"] + key = signup_key(client, email, headers={"x-real-ip": ip}) proof_id = _prove(client, key, headers={"x-real-ip": ip}).json()["proof"]["proof_id"] client.get(f"/v1/proof/{proof_id}", headers={"x-real-ip": ip}) text = _metrics(client, monkeypatch).text @@ -594,15 +587,12 @@ def test_410_carries_cors_headers(client, monkeypatch): assert "access-control-allow-origin" in r.headers -def test_register_for_existing_email_never_returns_the_key(client, monkeypatch): - from unittest.mock import patch - with patch("trust_layer.app.send_welcome_email") as mail: - first = client.post("/api/register", json={"email": "owner@arkforge-test.dev"}, headers={"x-real-ip": "198.51.100.9"}) - assert "api_key" in first.json() - key = first.json()["api_key"] - again = client.post("/api/register", json={"email": "owner@arkforge-test.dev"}, headers={"x-real-ip": "198.51.100.10"}) - body = again.json() - assert again.status_code == 200 and body["already_existed"] is True +def test_register_for_existing_email_never_returns_the_key(client, monkeypatch, signup_key, mailbox): + key = signup_key(client, "owner@arkforge-test.dev", path="/api/register", headers={"x-real-ip": "198.51.100.9"}) + sent = len(mailbox) + again = client.post("/api/register", json={"email": "owner@arkforge-test.dev"}, headers={"x-real-ip": "198.51.100.10"}) + assert again.status_code == 202 assert key not in again.text - assert "api_key" not in body - assert mail.call_args.args == ("owner@arkforge-test.dev", key) + assert "api_key" not in again.json() + # Only the confirmation link leaves before the confirm step: no key in any mail yet. + assert len(mailbox) == sent + 1 and key not in mailbox[-1]["body"] diff --git a/tests/test_funnel_metrics.py b/tests/test_funnel_metrics.py index 16063a4..b16c911 100644 --- a/tests/test_funnel_metrics.py +++ b/tests/test_funnel_metrics.py @@ -6,6 +6,12 @@ from fastapi.testclient import TestClient +@pytest.fixture(autouse=True) +def _salt(monkeypatch): + # Registration fails closed without the salt (the fake Redis comes from conftest). + monkeypatch.setenv("TL_METRICS_SALT", "test-salt-not-from-the-repo") + + @pytest.fixture def client(): from trust_layer.app import app @@ -71,14 +77,12 @@ def test_register_get_without_scan_id(self, client, tmp_path): class TestRegisterCompletion: - def test_register_post_logs_completion(self, client, tmp_path): - resp = client.post( - "/api/register", - json={"email": "newuser@example.com", "source": "web_register", "scan_id": "asr_test_123"}, + def test_register_post_logs_completion(self, client, tmp_path, signup_key): + key = signup_key( + client, "newuser@example.com", path="/api/register", + source="web_register", scan_id="asr_test_123", ) - assert resp.status_code == 200 - data = resp.json() - assert "api_key" in data + assert key.startswith("mcp_free_") events = _read_funnel_events(tmp_path) completion_events = [e for e in events if e["event"] == "register_completion"] @@ -86,12 +90,11 @@ def test_register_post_logs_completion(self, client, tmp_path): assert completion_events[0]["source"] == "web_register" assert completion_events[0]["scan_id"] == "asr_test_123" - def test_existing_key_no_completion_event(self, client, tmp_path): - client.post("/api/register", json={"email": "dup@example.com", "source": "web_register"}) + def test_existing_key_no_completion_event(self, client, tmp_path, signup_key): + signup_key(client, "dup@example.com", path="/api/register", source="web_register") resp = client.post("/api/register", json={"email": "dup@example.com", "source": "web_register"}) - assert resp.status_code == 200 - assert resp.json().get("already_existed") is True + assert resp.status_code == 202 assert "api_key" not in resp.json() events_after = _read_funnel_events(tmp_path) @@ -104,14 +107,14 @@ def test_requires_internal_key(self, client, free_key): resp = client.get("/v1/funnel-metrics", headers={"X-Api-Key": free_key}) assert resp.status_code == 403 - def test_returns_aggregated_counts(self, client, internal_key, free_key, tmp_path): + def test_returns_aggregated_counts(self, client, internal_key, free_key, tmp_path, signup_key): client.post( "/v1/assess", json={"server_id": "s1", "manifest": {"tools": [{"name": "t1"}]}}, headers={"X-Api-Key": free_key}, ) client.get("/register?scan_id=asr_test") - client.post("/api/register", json={"email": "agg@example.com", "source": "web_register"}) + signup_key(client, "agg@example.com", path="/api/register", source="web_register") resp = client.get("/v1/funnel-metrics", headers={"X-Api-Key": internal_key}) assert resp.status_code == 200 diff --git a/tests/test_receipt.py b/tests/test_receipt.py index 6b6ba30..20ffd9e 100644 --- a/tests/test_receipt.py +++ b/tests/test_receipt.py @@ -1,33 +1,31 @@ """Tests for receipt fetching, parsing, and chain hash integration.""" import hashlib -from unittest.mock import AsyncMock, patch, MagicMock +from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest +from trust_layer.proofs import ( + SPEC_VERSION, + generate_proof, + get_public_proof, + sha256_hex, + verify_proof_integrity, +) from trust_layer.receipt import ( - ReceiptResult, + _PARSER_REGISTRY, ReceiptParser, + ReceiptResult, StripeReceiptParser, + _detect_receipt_type, + _validate_receipt_url, fetch_receipt, - register_parser, get_parser, get_registered_domains, - _validate_receipt_url, - _detect_receipt_type, - _PARSER_REGISTRY, -) -from trust_layer.proofs import ( - generate_proof, - verify_proof_integrity, - get_public_proof, - sha256_hex, - SPEC_VERSION, - SPEC_VERSION_RECEIPT, + register_parser, ) - # ═══════════════════════════════════════════════════════════ # URL Validation # ═══════════════════════════════════════════════════════════ @@ -489,11 +487,18 @@ def test_public_proof_without_provider_payment(self): class TestProxyIntegration: """Integration tests using FastAPI TestClient.""" + @pytest.fixture(autouse=True) + def _salt(self, monkeypatch): + # Registration fails closed without the salt (the fake Redis comes from conftest). + monkeypatch.setenv("TL_METRICS_SALT", "test-salt-not-from-the-repo") + + @pytest.fixture(autouse=True) + def _signup(self, signup_key): + self._signup_key = signup_key + def _setup_free_key(self, client): - """Create a free API key and return it.""" - resp = client.post("/v1/keys/free-signup", json={"email": "receipt-test@arkforge-test.dev"}) - assert resp.status_code == 200 - return resp.json()["api_key"] + """Register a free address, confirm it from the mail, and return the key.""" + return self._signup_key(client, "receipt-test@arkforge-test.dev") def test_proxy_with_provider_payment(self, client): api_key = self._setup_free_key(client) diff --git a/tests/test_registration.py b/tests/test_registration.py new file mode 100644 index 0000000..392f944 --- /dev/null +++ b/tests/test_registration.py @@ -0,0 +1,599 @@ +"""TLREG: free API key delivered by email only, after the address is confirmed. + +Every guard has a refusal test that checks the absent effect (no mail sent, no key +stored, no pending record kept), not only the status code. +""" + +import json +import logging +import re +import smtplib +import threading +import time +from email import message_from_string + +import fakeredis +import pytest +from fastapi.testclient import TestClient + +from trust_layer.email_notify import _send_email as _real_send_email + +SALT = "test-salt-not-from-the-repo" +SIGNUP = "/v1/keys/free-signup" +REGISTER = "/api/register" +BOTH = [SIGNUP, REGISTER] +CONFIRM = "/v1/register/confirm" +TOKEN_RE = re.compile(r"#token=([A-Za-z0-9_\-]+)") + + +@pytest.fixture +def reg_redis(monkeypatch): + client = fakeredis.FakeRedis(server=fakeredis.FakeServer(), decode_responses=True) + import trust_layer.free_tier_guard as guard_mod + import trust_layer.usage_metrics as metrics_mod + monkeypatch.setattr(guard_mod, "get_redis", lambda: client) + monkeypatch.setattr(metrics_mod, "get_redis", lambda: client) + return client + + +@pytest.fixture(autouse=True) +def _env(monkeypatch, reg_redis): + for name in ("TL_REG_MAIL_DAILY_MAX", "TL_PAID_PLANS_ENABLED", "TL_WRITES_PAUSED"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("TL_METRICS_SALT", SALT) + + +@pytest.fixture +def client(): + from trust_layer.app import app + return TestClient(app) + + +def _post(client, path, email, ip=None, **extra): + headers = {"x-real-ip": ip} if ip else {} + return client.post(path, json={"email": email, **extra}, headers=headers) + + +def _token(mail): + return TOKEN_RE.search(mail["body"]).group(1) + + +def _keys(): + from trust_layer.keys import load_api_keys + return load_api_keys() + + +def _free_keys_of(email): + return [k for k, v in _keys().items() if v.get("email") == email and v.get("plan") == "free"] + + +def _pending(r): + return r.keys("reg_pending:*") + + +def _events(tmp_path, name): + path = tmp_path / "data" / name + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text().splitlines()] + + +# --- 1. Response never carries a key, same shape for new and known addresses --- + +@pytest.mark.parametrize("path", BOTH) +def test_request_answers_202_pending_without_api_key_for_new_and_known_address(client, mailbox, path): + from trust_layer.keys import create_api_key + create_api_key("", "known", "known@arkforge-test.dev", test_mode=False, plan="free") + new = _post(client, path, "brand-new@arkforge-test.dev") + known = _post(client, path, "known@arkforge-test.dev") + assert new.status_code == known.status_code == 202 + assert new.json() == known.json() + assert new.json()["status"] == "pending_confirmation" + for r in (new, known): + assert "api_key" not in r.text + assert "arkforge-test.dev" not in r.text + assert len(mailbox) == 2 + + +@pytest.mark.parametrize("path", BOTH) +def test_honeypot_signup_gets_the_same_202_and_nothing_is_sent_or_stored(client, mailbox, reg_redis, path): + r = _post(client, path, "bot@arkforge-test.dev", website="http://spam.invalid") + assert r.status_code == 202 + assert r.json()["status"] == "pending_confirmation" + assert mailbox == [] + assert _pending(reg_redis) == [] + + +# --- 2. No key before confirm, exactly one after --- + +@pytest.mark.parametrize("path", BOTH) +def test_no_key_exists_before_confirm_and_exactly_one_after(client, mailbox, path): + email = "once@arkforge-test.dev" + _post(client, path, email) + assert _free_keys_of(email) == [] + assert all("Your API key" not in m["body"] for m in mailbox) + r = client.post(CONFIRM, json={"token": _token(mailbox[0])}) + assert r.status_code == 200 + assert r.json() == {"status": "confirmed"} + assert len(_free_keys_of(email)) == 1 + assert len(mailbox) == 2 and "Your API key" in mailbox[1]["body"] + assert mailbox[1]["to"] == email + + +def test_confirm_for_a_known_address_resends_the_key_and_creates_no_second_key(client, mailbox): + from trust_layer.keys import create_api_key + key = create_api_key("", "known", "known@arkforge-test.dev", test_mode=False, plan="free") + _post(client, SIGNUP, "known@arkforge-test.dev") + r = client.post(CONFIRM, json={"token": _token(mailbox[0])}) + assert r.status_code == 200 and "api_key" not in r.text and key not in r.text + assert _free_keys_of("known@arkforge-test.dev") == [key] + assert key in mailbox[1]["body"] + + +# --- 3. Token: single use, 24h, no oracle; GET does not consume, POST does --- + +def test_token_is_single_use(client, mailbox): + _post(client, SIGNUP, "single@arkforge-test.dev") + token = _token(mailbox[0]) + assert client.post(CONFIRM, json={"token": token}).status_code == 200 + second = client.post(CONFIRM, json={"token": token}) + assert second.status_code == 400 + assert len(_free_keys_of("single@arkforge-test.dev")) == 1 + assert len(mailbox) == 2 + + +def test_token_expires_after_24_hours_and_no_key_is_created(client, mailbox, monkeypatch): + import trust_layer.registration as registration + _post(client, SIGNUP, "late@arkforge-test.dev") + token = _token(mailbox[0]) + real = time.time() + monkeypatch.setattr(registration, "_now", lambda: real + 24 * 3600 + 5) + r = client.post(CONFIRM, json={"token": token}) + assert r.status_code == 400 + assert _free_keys_of("late@arkforge-test.dev") == [] + assert len(mailbox) == 1 + + +def test_token_is_still_valid_just_before_24_hours(client, mailbox, monkeypatch): + import trust_layer.registration as registration + _post(client, SIGNUP, "justin@arkforge-test.dev") + real = time.time() + monkeypatch.setattr(registration, "_now", lambda: real + 24 * 3600 - 60) + assert client.post(CONFIRM, json={"token": _token(mailbox[0])}).status_code == 200 + + +def test_pending_record_has_a_24h_ttl_and_no_token_in_clear(client, mailbox, reg_redis): + _post(client, SIGNUP, "ttl@arkforge-test.dev") + (name,) = _pending(reg_redis) + assert 0 < reg_redis.ttl(name) <= 24 * 3600 + assert _token(mailbox[0]) not in name + assert _token(mailbox[0]) not in reg_redis.get(name) + + +@pytest.mark.parametrize("bad", ["", "x", "A" * 43, "A" * 5000, "../etc/passwd", None, 12]) +def test_wrong_token_is_400_with_one_identical_body_and_creates_nothing(client, mailbox, bad): + _post(client, SIGNUP, "victim@arkforge-test.dev") + used = _token(mailbox[0]) + client.post(CONFIRM, json={"token": used}) + keys_before = _keys() + answers = {client.post(CONFIRM, json={"token": bad}).text, client.post(CONFIRM, json={"token": used}).text} + assert len(answers) == 1 + assert client.post(CONFIRM, json={"token": bad}).status_code == 400 + assert _keys() == keys_before + + +def test_confirm_with_a_non_json_body_is_400(client): + assert client.post(CONFIRM, content=b"not json").status_code == 400 + + +def test_get_confirm_does_not_consume_the_token_and_post_does(client, mailbox, reg_redis): + _post(client, SIGNUP, "scanner@arkforge-test.dev") + token = _token(mailbox[0]) + for url in (CONFIRM, f"{CONFIRM}?token={token}"): + r = client.get(url) + assert r.status_code == 200 + assert token not in r.text + assert len(_pending(reg_redis)) == 1 + assert _free_keys_of("scanner@arkforge-test.dev") == [] + assert client.post(CONFIRM, json={"token": token}).status_code == 200 + assert _pending(reg_redis) == [] + + +# --- 4. Two tokens of one address confirmed in parallel: one key --- + +def test_two_tokens_of_one_address_confirmed_in_parallel_create_one_key(client, mailbox, monkeypatch): + import trust_layer.keys as keys_mod + email = "race@arkforge-test.dev" + _post(client, SIGNUP, email) + _post(client, REGISTER, email) + tokens = [_token(m) for m in mailbox] + assert len(set(tokens)) == 2 + + real_load = keys_mod.load_api_keys + + def slow_load(): + data = real_load() + time.sleep(0.05) # widen the window between the read and the write + return data + + monkeypatch.setattr(keys_mod, "load_api_keys", slow_load) + from trust_layer.app import app + statuses = [] + + def confirm(tok): + statuses.append(TestClient(app).post(CONFIRM, json={"token": tok}).status_code) + + threads = [threading.Thread(target=confirm, args=(t,)) for t in tokens] + for t in threads: + t.start() + for t in threads: + t.join() + monkeypatch.setattr(keys_mod, "load_api_keys", real_load) + assert statuses == [200, 200] + assert len(_free_keys_of(email)) == 1 + + +def test_get_or_create_free_key_returns_the_existing_key(client): + from trust_layer.keys import get_or_create_free_key + key, created = get_or_create_free_key("goc@arkforge-test.dev", "ref") + again, created_again = get_or_create_free_key("GOC@arkforge-test.dev", "ref") + assert created is True and created_again is False and again == key + + +# --- 5. Per-address cap, per-IP cap, daily mail cap --- + +@pytest.mark.parametrize("path", BOTH) +def test_fourth_request_for_one_address_gets_the_same_202_and_sends_no_mail(client, mailbox, reg_redis, path): + import trust_layer.registration as registration + n = registration.ADDRESS_MAX_PER_DAY + answers = [] + for _ in range(n + 2): + r = _post(client, path, "spammed@arkforge-test.dev") + answers.append((r.status_code, r.text)) + assert len(set(answers)) == 1 and answers[0][0] == 202 + assert len(mailbox) == n + assert len(_pending(reg_redis)) == n + + +def test_address_cap_counts_the_two_endpoints_together_and_ignores_case(client, mailbox): + for path, email in [(SIGNUP, "Mix@arkforge-test.dev"), (REGISTER, "mix@arkforge-test.dev"), + (SIGNUP, "MIX@arkforge-test.dev"), (REGISTER, "mix@arkforge-test.dev")]: + assert _post(client, path, email).status_code == 202 + assert len(mailbox) == 3 + + +def test_address_cap_does_not_block_another_address(client, mailbox): + for i in range(5): + _post(client, SIGNUP, "noisy@arkforge-test.dev", ip=f"198.51.100.{i}") + before = len(mailbox) + assert _post(client, SIGNUP, "quiet@arkforge-test.dev").status_code == 202 + assert len(mailbox) == before + 1 + + +def test_address_counter_is_salted_and_holds_no_address(client, mailbox, reg_redis): + _post(client, SIGNUP, "hidden@arkforge-test.dev") + names = reg_redis.keys("tl:reg_addr:*") + assert len(names) == 1 and "hidden" not in names[0] and "arkforge-test" not in names[0] + assert reg_redis.ttl(names[0]) > 0 + + +def test_address_window_is_not_extended_by_blocked_requests(client, mailbox, reg_redis): + for _ in range(3): + _post(client, SIGNUP, "fixed@arkforge-test.dev") + (name,) = reg_redis.keys("tl:reg_addr:*") + reg_redis.expire(name, 100) + _post(client, SIGNUP, "fixed@arkforge-test.dev") + assert reg_redis.ttl(name) <= 100 + + +def test_ip_limit_is_shared_refuses_with_429_and_sends_nothing(client, mailbox, reg_redis): + import trust_layer.registration as registration + n = registration.REQUEST_MAX_PER_IP_PER_HOUR + ip = "203.0.113.9" + for i in range(n): + assert _post(client, SIGNUP if i % 2 else REGISTER, f"u{i}@arkforge-test.dev", ip=ip).status_code == 202 + sent, pending = len(mailbox), len(_pending(reg_redis)) + r = _post(client, SIGNUP, "one-more@arkforge-test.dev", ip=ip) + assert r.status_code == 429 + assert len(mailbox) == sent and len(_pending(reg_redis)) == pending + assert _post(client, SIGNUP, "other-ip@arkforge-test.dev", ip="203.0.113.10").status_code == 202 + + +def test_ip_counter_lives_in_redis_under_a_salted_key(client, mailbox, reg_redis): + ip = "203.0.113.11" + _post(client, SIGNUP, "iphash@arkforge-test.dev", ip=ip) + names = [k for k in reg_redis.keys("*") if ip in k] + assert names == [] + assert reg_redis.keys("tl:signup_ip:*") + + +def test_daily_mail_cap_refuses_with_503_and_sends_nothing_more(client, mailbox, reg_redis, monkeypatch): + monkeypatch.setenv("TL_REG_MAIL_DAILY_MAX", "2") + assert _post(client, SIGNUP, "cap1@arkforge-test.dev").status_code == 202 + assert _post(client, REGISTER, "cap2@arkforge-test.dev").status_code == 202 + r = _post(client, SIGNUP, "cap3@arkforge-test.dev") + assert r.status_code == 503 + assert len(mailbox) == 2 and len(_pending(reg_redis)) == 2 + + +def test_unparseable_daily_mail_cap_refuses_with_503(client, mailbox, reg_redis, monkeypatch): + monkeypatch.setenv("TL_REG_MAIL_DAILY_MAX", "lots") + assert _post(client, SIGNUP, "badcap@arkforge-test.dev").status_code == 503 + assert mailbox == [] and _pending(reg_redis) == [] + + +def test_address_over_its_cap_does_not_consume_the_daily_mail_cap(client, mailbox, monkeypatch): + monkeypatch.setenv("TL_REG_MAIL_DAILY_MAX", "4") + for i in range(6): + _post(client, SIGNUP, "same@arkforge-test.dev", ip=f"198.51.100.{i}") + assert len(mailbox) == 3 + assert _post(client, SIGNUP, "fresh@arkforge-test.dev").status_code == 202 + + +def test_confirm_post_is_rate_limited_per_ip_and_keeps_the_token(client, mailbox, reg_redis): + import trust_layer.registration as registration + _post(client, SIGNUP, "brute@arkforge-test.dev") + token = _token(mailbox[0]) + ip = {"x-real-ip": "203.0.113.20"} + for i in range(registration.CONFIRM_MAX_PER_IP_PER_HOUR): + assert client.post(CONFIRM, json={"token": f"wrong{i}"}, headers=ip).status_code == 400 + r = client.post(CONFIRM, json={"token": token}, headers=ip) + assert r.status_code == 429 + assert _free_keys_of("brute@arkforge-test.dev") == [] + assert len(mailbox) == 1 + assert len(_pending(reg_redis)) == 1 + assert client.post(CONFIRM, json={"token": token}, headers={"x-real-ip": "203.0.113.21"}).status_code == 200 + + +# --- 6. Fail closed --- + +@pytest.mark.parametrize("path", BOTH) +def test_no_redis_is_503_with_no_mail_and_no_key(client, mailbox, monkeypatch, path): + import trust_layer.free_tier_guard as guard_mod + monkeypatch.setattr(guard_mod, "get_redis", lambda: None) + r = _post(client, path, "noredis@arkforge-test.dev") + assert r.status_code == 503 + assert mailbox == [] + assert _free_keys_of("noredis@arkforge-test.dev") == [] + + +@pytest.mark.parametrize("path", BOTH) +def test_no_salt_is_503_with_no_mail_no_key_and_nothing_in_redis(client, mailbox, reg_redis, monkeypatch, path): + monkeypatch.delenv("TL_METRICS_SALT") + r = _post(client, path, "nosalt@arkforge-test.dev") + assert r.status_code == 503 + assert mailbox == [] + assert _free_keys_of("nosalt@arkforge-test.dev") == [] + assert reg_redis.keys("*") == [] + + +def test_erroring_redis_is_503_with_no_mail_and_no_key(client, mailbox, monkeypatch): + import trust_layer.free_tier_guard as guard_mod + + class Broken: + def __getattr__(self, name): + def boom(*a, **k): + raise ConnectionError("redis down") + return boom + + monkeypatch.setattr(guard_mod, "get_redis", lambda: Broken()) + r = _post(client, SIGNUP, "broken@arkforge-test.dev") + assert r.status_code == 503 + assert mailbox == [] and _free_keys_of("broken@arkforge-test.dev") == [] + + +def test_confirm_without_redis_is_503_and_creates_no_key(client, mailbox, monkeypatch): + import trust_layer.free_tier_guard as guard_mod + _post(client, SIGNUP, "later@arkforge-test.dev") + token = _token(mailbox[0]) + real = guard_mod.get_redis + monkeypatch.setattr(guard_mod, "get_redis", lambda: None) + assert client.post(CONFIRM, json={"token": token}).status_code == 503 + assert _free_keys_of("later@arkforge-test.dev") == [] and len(mailbox) == 1 + monkeypatch.setattr(guard_mod, "get_redis", real) + assert client.post(CONFIRM, json={"token": token}).status_code == 200 + + +def test_confirm_without_salt_is_503_and_creates_no_key(client, mailbox, monkeypatch): + _post(client, SIGNUP, "nosaltc@arkforge-test.dev") + token = _token(mailbox[0]) + monkeypatch.delenv("TL_METRICS_SALT") + assert client.post(CONFIRM, json={"token": token}).status_code == 503 + assert _free_keys_of("nosaltc@arkforge-test.dev") == [] and len(mailbox) == 1 + + +def test_confirm_blocked_in_failover_keeps_the_token(client, mailbox, monkeypatch): + import trust_layer.app as app_mod + _post(client, SIGNUP, "failover@arkforge-test.dev") + token = _token(mailbox[0]) + monkeypatch.setattr(app_mod, "_writes_blocked", lambda: True) + assert client.post(CONFIRM, json={"token": token}).status_code == 503 + assert _free_keys_of("failover@arkforge-test.dev") == [] + monkeypatch.setattr(app_mod, "_writes_blocked", lambda: False) + assert client.post(CONFIRM, json={"token": token}).status_code == 200 + + +def test_key_creation_failure_at_confirm_gives_the_token_back(client, mailbox, monkeypatch): + import trust_layer.registration as registration + _post(client, SIGNUP, "boom@arkforge-test.dev") + token = _token(mailbox[0]) + + def boom(*a, **k): + raise OSError("disk full") + + real = registration.get_or_create_free_key + monkeypatch.setattr(registration, "get_or_create_free_key", boom) + assert client.post(CONFIRM, json={"token": token}).status_code == 503 + assert _free_keys_of("boom@arkforge-test.dev") == [] + monkeypatch.setattr(registration, "get_or_create_free_key", real) + assert client.post(CONFIRM, json={"token": token}).status_code == 200 + assert len(_free_keys_of("boom@arkforge-test.dev")) == 1 + + +# --- validation stays in front --- + +@pytest.mark.parametrize("path", BOTH) +def test_invalid_address_is_400_and_nothing_is_stored_or_sent(client, mailbox, reg_redis, path): + assert _post(client, path, "not-an-email").status_code == 400 + assert client.post(path, content=b"nope").status_code == 400 + assert mailbox == [] and _pending(reg_redis) == [] + + +def test_blocked_disposable_domain_is_refused_by_free_signup_and_sends_nothing(client, mailbox, reg_redis): + assert _post(client, SIGNUP, "x@mailinator.com").status_code == 422 + assert mailbox == [] and _pending(reg_redis) == [] + + +# --- 7. No clear address or token in logs --- + +class _FakeSMTP: + """Stand-in for smtplib.SMTP_SSL: context manager with login() and sendmail().""" + + sent: list = [] + refuse = False + + def __init__(self, *a, **k): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def login(self, *a): + pass + + def sendmail(self, sender, to, message): + if _FakeSMTP.refuse: + raise smtplib.SMTPRecipientsRefused({to: (550, b"mailbox unavailable")}) + _FakeSMTP.sent.append((to, message)) + + +@pytest.fixture +def real_smtp(monkeypatch): + import trust_layer.email_notify as email_mod + _FakeSMTP.sent = [] + _FakeSMTP.refuse = False + monkeypatch.setattr(email_mod, "_send_email", _real_send_email) + monkeypatch.setattr(email_mod, "SMTP_PASSWORD", "not-a-real-password") + monkeypatch.setattr(email_mod.smtplib, "SMTP_SSL", _FakeSMTP) + return _FakeSMTP + + +def _assert_no_leak(text, *needles): + for needle in needles: + assert needle not in text + + +@pytest.mark.parametrize("path", BOTH) +def test_full_flow_logs_no_address_and_no_token(client, real_smtp, caplog, path): + email = "private.person@arkforge-test.dev" + with caplog.at_level(logging.DEBUG): + _post(client, path, email, ip="203.0.113.30") + (to, message), = real_smtp.sent + assert to == email + body = message_from_string(message).get_payload(0).get_payload(decode=True).decode() + token = TOKEN_RE.search(body).group(1) + client.post(CONFIRM, json={"token": "wrong-token-value"}) + assert client.post(CONFIRM, json={"token": token}).status_code == 200 + for _ in range(4): + _post(client, path, email, ip="203.0.113.30") + _assert_no_leak(caplog.text, email, "private.person", "arkforge-test.dev", token, "wrong-token-value") + + +def test_smtp_refusal_logs_no_address(client, real_smtp, caplog): + real_smtp.refuse = True + email = "refused.person@arkforge-test.dev" + with caplog.at_level(logging.DEBUG): + r = _post(client, SIGNUP, email) + assert r.status_code == 202 + assert any(rec.levelno >= logging.ERROR for rec in caplog.records) + _assert_no_leak(caplog.text, email, "refused.person", "arkforge-test.dev") + + +def test_skipped_test_address_logs_neither_address_nor_local_part(client, real_smtp, caplog): + email = "smoke_leaky@arkforge.tech" + with caplog.at_level(logging.DEBUG): + _post(client, REGISTER, email) + assert real_smtp.sent == [] + assert "skipped" in caplog.text.lower() + _assert_no_leak(caplog.text, email, "smoke_leaky", "arkforge.tech") + + +def test_no_address_in_the_pending_record_key_or_in_funnel_logs(client, mailbox, reg_redis, tmp_path): + email = "funnel.person@arkforge-test.dev" + _post(client, SIGNUP, email) + client.post(CONFIRM, json={"token": _token(mailbox[0])}) + for name in ("funnel_events.jsonl", "conversion_events.jsonl"): + path = tmp_path / "data" / name + text = path.read_text() if path.exists() else "" + _assert_no_leak(text, email, "funnel.person") + assert all(email not in k for k in reg_redis.keys("*")) + + +# --- 8. Token in the fragment only --- + +def test_mail_carries_the_token_in_the_fragment_never_in_a_query_string(client, mailbox): + _post(client, SIGNUP, "frag@arkforge-test.dev") + body = mailbox[0]["body"] + assert "/v1/register/confirm#token=" in body + assert "?token=" not in body and "&token=" not in body + assert "https://test.arkforge.fr/v1/register/confirm#token=" in body + + +def test_confirmation_page_reads_the_fragment_and_posts_the_token(client): + html = client.get(CONFIRM).text + assert "location.hash" in html + assert "location.search" not in html + assert "fetch(" in html and "POST" in html + assert "history.replaceState" in html + + +def test_confirmation_page_does_not_leak_the_referrer(client): + r = client.get(CONFIRM) + assert "no-referrer" in r.text or r.headers.get("referrer-policy") == "no-referrer" + assert "no-store" in r.headers.get("cache-control", "") + + +# --- 9. Funnel events move to the confirm step --- + +def test_funnel_requested_at_request_completion_and_attribution_only_at_confirm(client, mailbox, tmp_path): + email = "events@arkforge-test.dev" + _post(client, REGISTER, email, source="web_register", scan_id="asr_1") + funnel = [e["event"] for e in _events(tmp_path, "funnel_events.jsonl")] + assert funnel == ["register_requested"] + assert _events(tmp_path, "conversion_events.jsonl") == [] + client.post(CONFIRM, json={"token": _token(mailbox[0])}) + funnel = _events(tmp_path, "funnel_events.jsonl") + assert [e["event"] for e in funnel] == ["register_requested", "register_completion"] + assert funnel[1]["source"] == "web_register" and funnel[1]["scan_id"] == "asr_1" + conversions = _events(tmp_path, "conversion_events.jsonl") + assert [e["event"] for e in conversions] == ["signup_attributed"] + assert conversions[0]["source"] == "web_register" + + +def test_known_address_confirm_emits_no_completion_and_counts_no_new_key(client, mailbox, tmp_path): + from trust_layer.keys import create_api_key + create_api_key("", "known", "known@arkforge-test.dev", test_mode=False, plan="free") + _post(client, REGISTER, "known@arkforge-test.dev") + client.post(CONFIRM, json={"token": _token(mailbox[0])}) + assert "register_completion" not in [e["event"] for e in _events(tmp_path, "funnel_events.jsonl")] + assert _events(tmp_path, "conversion_events.jsonl") == [] + + +def test_free_key_metric_counts_at_confirm_not_at_request(client, mailbox, reg_redis): + from datetime import UTC, datetime + name = f"tl:m:{datetime.now(UTC).strftime('%Y-%m-%d')}:free_keys_created" + _post(client, SIGNUP, "metric@arkforge-test.dev") + assert reg_redis.get(name) is None + client.post(CONFIRM, json={"token": _token(mailbox[0])}) + assert reg_redis.get(name) == "1" + + +# --- web form --- + +def test_register_page_no_longer_expects_a_key_in_the_response(client): + html = client.get("/register").text + assert "d.api_key" not in html + assert "confirm" in html.lower() diff --git a/trust_layer/app.py b/trust_layer/app.py index 42c7768..810de31 100644 --- a/trust_layer/app.py +++ b/trust_layer/app.py @@ -9,7 +9,7 @@ from datetime import UTC, datetime, timedelta import stripe -from fastapi import FastAPI, Header, HTTPException, Request +from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response from starlette.middleware.base import BaseHTTPMiddleware @@ -85,6 +85,7 @@ def _node_role() -> str: "/v1/keys/portal", "/v1/keys/free-signup", "/api/register", + "/v1/register/confirm", "/v1/keys/overage", "/v1/keys/bind-did", "/v1/keys/bind-did/confirm", @@ -250,6 +251,7 @@ async def dispatch(self, request: Request, call_next): _is_test_email, send_admin_alert, send_checkout_abandoned_email, + send_confirmation_email, send_demo_request_email, send_subscription_reactivated_email, send_subscription_suspended_email, @@ -259,7 +261,7 @@ async def dispatch(self, request: Request, call_next): send_welcome_email, send_welcome_email_pro, ) -from .free_tier_guard import hash_identifier, paid_plans_enabled, signup_count, writes_paused # noqa: E402 +from .free_tier_guard import hash_identifier, paid_plans_enabled, writes_paused # noqa: E402 from .keys import ( # noqa: E402 create_api_key, create_trial_key, @@ -726,9 +728,13 @@ async def lifespan(app): from .routers.verdict import router as _verdict_router # noqa: E402 app.include_router(_verdict_router) +from . import registration # noqa: E402 from .routers.admin import router as _admin_router # noqa: E402 app.include_router(_admin_router) +from .routers.registration import router as _registration_router # noqa: E402 + +app.include_router(_registration_router) # --- Helpers --- @@ -1780,9 +1786,6 @@ def _looks_like_gibberish(local_part: str) -> bool: # Valid proof ID format: prf_YYYYMMDD_HHMMSS_<6hex> _PROOF_ID_RE = _re.compile(r"^prf_\d{8}_\d{6}_[0-9a-f]{6}$") -_FREE_SIGNUP_RATE: dict[str, list[float]] = {} # IP -> timestamps (sliding 1h) -_FREE_SIGNUP_MAX_PER_HOUR = 5 - _BLOCKED_EMAIL_DOMAINS = frozenset({ "example.com", "example.org", "example.net", "test.com", "test.org", @@ -1908,18 +1911,48 @@ def _log_funnel_event(event: str, client_ip: str, referer: str, user_agent: str, pass -@app.post("/v1/keys/free-signup") -async def free_signup(request: Request): - """Create a free-tier API key with email only — no credit card required.""" - import time +_PENDING_RESPONSE = { + "status": "pending_confirmation", + "message": "If this address can receive mail, a confirmation link is on its way. " + "It is valid for 24 hours. The API key is sent to that address once confirmed.", +} + + +def _send_confirmation_mail(email: str, token: str) -> None: + try: + send_confirmation_email(email, token) + except Exception as e: + logger.warning("Confirmation mail not sent: %s", type(e).__name__) + + +async def _start_registration(request: Request, background: BackgroundTasks, email: str, meta: dict): + """Shared tail of /v1/keys/free-signup and /api/register: same 202 whether the address is new or known.""" + client_ip = ( + request.headers.get("x-real-ip") + or (request.client.host if request.client else "unknown") + ) + try: + job = registration.request_registration(email, client_ip, meta) + except registration.RegistrationError as e: + return _error_response(e.code, e.message, e.status) + if job is not None: + background.add_task(_send_confirmation_mail, *job) + registration.log_funnel("register_requested", client_ip, email, meta) + return JSONResponse(status_code=202, content=_PENDING_RESPONSE) + +@app.post("/v1/keys/free-signup") +async def free_signup(request: Request, background: BackgroundTasks): + """Ask for a free-tier API key by email only. The key is mailed once the address is confirmed.""" try: body = await request.json() except Exception: return _error_response("invalid_request", "Invalid JSON body", 400) + if not isinstance(body, dict): + return _error_response("invalid_request", "Invalid JSON body", 400) if body.get("website"): - return {"api_key": "", "limit": "500 proofs/month", "email": "", "message": "OK"} + return JSONResponse(status_code=202, content=_PENDING_RESPONSE) email = (body.get("email") or "").strip().lower() if not email or not _EMAIL_RE.match(email): @@ -1937,105 +1970,18 @@ async def free_signup(request: Request): if not _verify_mx(domain): return _error_response("invalid_request", "This email domain cannot receive mail. Please use a real email address.", 422) - # Rate limit: max 5 signups per IP per hour. - # X-Real-IP is set by nginx from $remote_addr and cannot be forged by clients. - # Fall back to direct connection IP if the header is absent. - client_ip = ( - request.headers.get("x-real-ip") - or (request.client.host if request.client else "unknown") - ) - # Shared between nodes through Redis; the per-node memory window is the fallback - # only when Redis cannot answer (free proofs are refused in that case anyway). - # No salt, no Redis key: an unsalted IP digest is reversible, so the node-local window serves. - ip_id = _ip_id(client_ip) - shared = signup_count(ip_id) if ip_id else None - if shared is not None: - if shared > _FREE_SIGNUP_MAX_PER_HOUR: - return _error_response("rate_limited", "Too many signups. Try again later.", 429) - else: - now = time.time() - timestamps = _FREE_SIGNUP_RATE.get(client_ip, []) - timestamps = [t for t in timestamps if t > now - 3600] - if len(timestamps) >= _FREE_SIGNUP_MAX_PER_HOUR: - return _error_response("rate_limited", "Too many signups. Try again later.", 429) - timestamps.append(now) - _FREE_SIGNUP_RATE[client_ip] = timestamps - - # Check if email already has a free key - from .keys import load_api_keys - existing_keys = load_api_keys() - for _key, info in existing_keys.items(): - if info.get("email", "").lower() == email and info.get("plan") == "free" and info.get("active"): - return _error_response("already_exists", "A free API key already exists for this email. Check your inbox or contact support.", 409) - - # Create free-tier key (no Stripe customer needed) - api_key = create_api_key( - stripe_customer_id="", - ref_id=f"free_signup_{email}", - email=email, - test_mode=False, - plan="free", - ) - logger.info("Free API key created for %s", email) - if client_ip not in _INTERNAL_IPS: - usage_metrics.record_free_signup() - - try: - send_welcome_email(email, api_key) - except (OSError, RuntimeError) as e: - logger.warning("Welcome email failed for free signup %s: %s", email, e) - - # Attribution event: capture referrer + UTM for funnel tracking + # Attribution: kept in the pending record, logged at the confirm step. referrer = request.headers.get("referer", "") - utm_source = body.get("utm_source", "") - utm_medium = body.get("utm_medium", "") - utm_campaign = body.get("utm_campaign", "") + utm_source = str(body.get("utm_source") or "") attribution_source = utm_source or _classify_referrer_source(referrer) - try: - with open(CONVERSION_EVENTS_LOG, "a") as _cel: - _cel.write(json.dumps({ - "ts": datetime.now(UTC).isoformat(), - "event": "signup_attributed", - "plan": "free", - "email_hash": _email_hash(email), - "source": attribution_source, - "utm_source": utm_source, - "utm_medium": utm_medium, - "utm_campaign": utm_campaign, - "referrer": referrer, - "client_ip_hash": hashlib.sha256(client_ip.encode()).hexdigest()[:12], - }) + "\n") - except OSError: - pass - - - # Funnel event: register_completion from web form (/en/signup.html → /v1/keys/free-signup). - # Mirrors the emission in /api/register (MCP phone-home) so funnel metrics aggregate - # both surfaces uniformly. Without this, web signups bypass the funnel_events stream. - try: - with open(FUNNEL_EVENTS_LOG, "a") as _f: - _f.write(json.dumps({ - "ts": datetime.now(UTC).isoformat(), - "event": "register_completion", - "scan_id": "", - "source": f"web_{attribution_source}" if attribution_source else "web_direct", - "client_ip_hash": hashlib.sha256(client_ip.encode()).hexdigest()[:12], - "email_hash": _email_hash(email), - }) + "\n") - except Exception: - pass - - response = { - "api_key": api_key, - "plan": "free", - "limit": f"{FREE_TIER_MONTHLY_LIMIT} proofs/month", - "email": email, - "message": "Your free API key is ready. It has also been sent to your email.", + meta = { + "source": f"web_{attribution_source}" if attribution_source else "web_direct", + "utm_source": utm_source, + "utm_medium": str(body.get("utm_medium") or ""), + "utm_campaign": str(body.get("utm_campaign") or ""), + "referrer": referrer, } - if paid_plans_enabled(): - response["upgrade_url"] = "https://arkforge.tech/en/pro-signup.html?utm_source=free_signup_response" - response["upgrade_cta"] = "Need more? Try Pro free for 14 days — 5,000 proofs/month, no charge until day 15." - return response + return await _start_registration(request, background, email, meta) # --- GET /register (inline CTA from MCP scan results) --- @@ -2125,12 +2071,12 @@ async def register_form(request: Request, scan_id: str = ""): body:JSON.stringify({{email:email,source:'web_register',scan_id:scanId}}) }}); const d=await r.json(); -if(r.ok&&d.api_key){{ +if(r.status===202&&d.status==='pending_confirmation'){{ res.className='result ok'; -res.innerHTML='API key activated!
'+d.api_key+'

Also sent to '+email+'

'; -btn.textContent='Done'; +res.textContent='Check your mailbox and confirm your email: your API key is sent to it once confirmed.'; +btn.textContent='Check your mailbox'; }}else{{ -throw new Error(d.detail||d.error||'Registration failed'); +throw new Error((d.error&&d.error.message)||d.detail||'Registration failed'); }} }}catch(err){{ res.className='result err'; @@ -2147,22 +2093,22 @@ async def register_form(request: Request, scan_id: str = ""): # --- POST /api/register (MCP phone-home) --- -_MCP_REGISTER_RATE: dict = {} -_MCP_REGISTER_MAX_PER_HOUR = 10 - @app.post("/api/register") -async def mcp_register(request: Request): - """Register a free API key from MCP stdio clients (phone-home). +async def mcp_register(request: Request, background: BackgroundTasks): + """Ask for a free API key from MCP stdio clients (phone-home). - Lightweight endpoint for MCP servers running in stdio mode to register - users server-side instead of writing keys locally (where they have no value). + Same flow as /v1/keys/free-signup: the response never carries the key, which is + mailed to the address once it is confirmed. """ - import time as _time - try: body = await request.json() except Exception: return _error_response("invalid_request", "Invalid JSON body", 400) + if not isinstance(body, dict): + return _error_response("invalid_request", "Invalid JSON body", 400) + + if body.get("website"): + return JSONResponse(status_code=202, content=_PENDING_RESPONSE) email = (body.get("email") or "").strip().lower() if not email or not _EMAIL_RE.match(email): @@ -2171,93 +2117,8 @@ async def mcp_register(request: Request): if len(email) > 320 or len(local_part) > 64: return _error_response("invalid_request", "Email address exceeds maximum allowed length", 400) - client_ip = ( - request.headers.get("x-real-ip") - or (request.client.host if request.client else "unknown") - ) - now = _time.time() - timestamps = _MCP_REGISTER_RATE.get(client_ip, []) - timestamps = [t for t in timestamps if t > now - 3600] - if len(timestamps) >= _MCP_REGISTER_MAX_PER_HOUR: - return _error_response("rate_limited", "Too many registrations. Try again later.", 429) - timestamps.append(now) - _MCP_REGISTER_RATE[client_ip] = timestamps - - from .keys import load_api_keys - existing_keys = load_api_keys() - for key, info in existing_keys.items(): - if info.get("email", "").lower() == email and info.get("plan") == "free" and info.get("active"): - # The key goes to the mailbox only: whoever typed the address must not get it. - try: - send_welcome_email(email, key) - except (OSError, RuntimeError) as e: - logger.warning("Key resend failed for MCP register %s: %s", email, e) - return JSONResponse(content={ - "plan": "free", - "email": email, - "already_existed": True, - "message": "A free API key already exists for this email. It has been sent to that address.", - }) - - api_key = create_api_key( - stripe_customer_id="", - ref_id=f"mcp_phonehome_{email}", - email=email, - test_mode=False, - plan="free", - ) - logger.info("MCP phone-home registration for %s", email) - - try: - send_welcome_email(email, api_key) - except (OSError, RuntimeError) as e: - logger.warning("Welcome email failed for MCP register %s: %s", email, e) - - # --- Funnel event: register completion --- - source = body.get("source", "mcp_phonehome") - scan_id = body.get("scan_id", "") - try: - with open(FUNNEL_EVENTS_LOG, "a") as _f: - _f.write(json.dumps({ - "ts": datetime.now(UTC).isoformat(), - "event": "register_completion", - "scan_id": scan_id[:32] if scan_id else "", - "source": source, - "client_ip_hash": hashlib.sha256(client_ip.encode()).hexdigest()[:12], - "email_hash": _email_hash(email), - }) + "\n") - except Exception: - pass - - try: - with open(CONVERSION_EVENTS_LOG, "a") as _cel: - _cel.write(json.dumps({ - "ts": datetime.now(UTC).isoformat(), - "event": "signup_attributed", - "plan": "free", - "email_hash": _email_hash(email), - "source": source, - "scan_id": scan_id[:32] if scan_id else "", - "client_ip_hash": hashlib.sha256(client_ip.encode()).hexdigest()[:12], - }) + "\n") - except OSError: - pass - - - if client_ip not in _INTERNAL_IPS: - usage_metrics.record_free_signup() - - response = { - "api_key": api_key, - "plan": "free", - "limit": f"{FREE_TIER_MONTHLY_LIMIT} proofs/month", - "email": email, - "message": "Your free API key is ready. It has also been sent to your email.", - } - if paid_plans_enabled(): - response["upgrade_url"] = "https://arkforge.tech/en/pro-signup.html?utm_source=mcp_register_response" - response["upgrade_cta"] = "Need more? Try Pro free for 14 days — 5,000 proofs/month, no charge until day 15." - return response + meta = {"source": str(body.get("source") or "mcp_phonehome"), "scan_id": str(body.get("scan_id") or "")} + return await _start_registration(request, background, email, meta) # --- POST /api/mcp-scan-ping --- @@ -3478,11 +3339,11 @@ async def get_agent_json(): }, { "name": "free_signup", - "description": "Create a free-tier API key (500 proofs/month, no credit card required)", + "description": "Request a free-tier API key (500 proofs/month, no credit card required). The key is emailed after address confirmation; it is not returned in the response", "endpoint": f"{base}/v1/keys/free-signup", "method": "POST", "parameters": {}, - "returns": {"type": "object", "description": "API key and usage quota"}, + "returns": {"type": "object", "description": "Pending confirmation status; the API key is sent by email"}, }, ], "pricing": { diff --git a/trust_layer/email_notify.py b/trust_layer/email_notify.py index 98431ab..d07dfb6 100644 --- a/trust_layer/email_notify.py +++ b/trust_layer/email_notify.py @@ -4,12 +4,14 @@ import smtplib import ssl import time -from datetime import datetime, timezone -from email.mime.text import MIMEText +from datetime import UTC, datetime from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText from email.utils import formatdate, make_msgid -from .config import SMTP_HOST, SMTP_PORT, SMTP_LOGIN, SMTP_USER, SMTP_CONTACT, SMTP_PASSWORD +from . import config +from .config import SMTP_CONTACT, SMTP_HOST, SMTP_LOGIN, SMTP_PASSWORD, SMTP_PORT, SMTP_USER +from .free_tier_guard import hash_identifier logger = logging.getLogger("trust_layer.email") @@ -55,6 +57,11 @@ def _is_test_email(to: str) -> tuple[bool, str]: return False, "" +def _who(to: str) -> str: + """Log identifier for a recipient: a short salted hash, never the address.""" + return hash_identifier((to or "").strip().lower())[:12] or "unhashed" + + def _send_email(to: str, subject: str, body: str): """Send a plain-text email via SMTP SSL. Best effort.""" if not to or not SMTP_PASSWORD: @@ -64,7 +71,7 @@ def _send_email(to: str, subject: str, body: str): # Block test/reserved/fake addresses — never deliver, never consume quota _blocked, _reason = _is_test_email(to) if _blocked: - logger.warning("Email skipped (%s): %s", _reason, to) + logger.warning("Email skipped (%s): to=%s", _reason.split(":", 1)[0], _who(to)) return msg = MIMEMultipart("alternative") @@ -85,11 +92,11 @@ def _send_email(to: str, subject: str, body: str): server.sendmail(SMTP_USER, to, msg.as_string()) _email_success_count += 1 _email_failure_count = 0 - logger.info("Email sent to %s: %s", to, subject) + logger.info("Email sent to %s: %s", _who(to), subject) except smtplib.SMTPRecipientsRefused as e: _email_failure_count += 1 _last_failure_time = time.time() - logger.error("SMTP recipient refused (count=%d): to=%s err=%s", _email_failure_count, to, e) + logger.error("SMTP recipient refused (count=%d): to=%s err=%s", _email_failure_count, _who(to), type(e).__name__) except smtplib.SMTPSenderRefused as e: _email_failure_count += 1 _last_failure_time = time.time() @@ -97,11 +104,33 @@ def _send_email(to: str, subject: str, body: str): except (smtplib.SMTPException, OSError) as e: _email_failure_count += 1 _last_failure_time = time.time() - logger.error("SMTP delivery failed (count=%d): to=%s err=%s", _email_failure_count, to, e) + logger.error("SMTP delivery failed (count=%d): to=%s err=%s", _email_failure_count, _who(to), + type(e).__name__) if _email_failure_count >= _FAILURE_ALERT_THRESHOLD: logger.critical("EMAIL_DELIVERY_ALERT: %d consecutive failures — last at %s. Check SMTP config (host=%s, from=%s)", _email_failure_count, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(_last_failure_time)), SMTP_HOST, SMTP_USER) +def send_confirmation_email(email: str, token: str): + """Send the address-confirmation link; the token travels in the URL fragment only.""" + link = f"{config.TRUST_LAYER_BASE_URL}/v1/register/confirm#token={token}" + subject = "Confirm your email for ArkForge Trust Layer" + body = f"""Someone asked for a free ArkForge Trust Layer API key for this address. + +To get the key, open this link and press the confirm button (valid for 24 hours, single use): + + {link} + +The key is then sent to this address. If you did not ask for it, ignore this message: +nothing is created unless the link is confirmed. + +Support: contact@arkforge.tech +""" + try: + _send_email(email, subject, body) + except Exception as e: + logger.warning("Confirmation email failed: %s", type(e).__name__) + + def send_welcome_email(email: str, api_key: str): """Send welcome email with API key after free signup.""" subject = "Your ArkForge Trust Layer API Key" @@ -766,7 +795,7 @@ def send_admin_alert(alert_type: str, details: str): {'=' * 50} Type: {alert_type} -Time: {datetime.now(timezone.utc).isoformat()} +Time: {datetime.now(UTC).isoformat()} {details} diff --git a/trust_layer/keys.py b/trust_layer/keys.py index f768a55..50a6bae 100644 --- a/trust_layer/keys.py +++ b/trust_layer/keys.py @@ -1,15 +1,20 @@ """API key lifecycle — generate, validate, deactivate.""" import json +import logging import os import secrets import threading -import logging -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from pathlib import Path -from typing import Optional -from .config import API_KEYS_FILE, OVERAGE_CAP_DEFAULT, OVERAGE_CAP_MIN, OVERAGE_CAP_MAX, OVERAGE_PRICES, PLATFORM_MONTHLY_LIMIT +from .config import ( + API_KEYS_FILE, + OVERAGE_CAP_DEFAULT, + OVERAGE_CAP_MAX, + OVERAGE_CAP_MIN, + OVERAGE_PRICES, +) from .persistence import load_json, save_json logger = logging.getLogger("trust_layer.keys") @@ -63,7 +68,6 @@ def load_api_keys() -> dict: if not raw: return {} try: - from cryptography.fernet import InvalidToken decrypted = fernet.decrypt(raw) return json.loads(decrypted) except Exception: @@ -110,7 +114,7 @@ def generate_api_key(test_mode: bool = False, plan: str = "pro") -> str: return f"{prefix}{secrets.token_hex(24)}" -def validate_api_key(key: str) -> Optional[dict]: +def validate_api_key(key: str) -> dict | None: """Return key info if valid and active, else None. Lazily expires trial keys.""" keys = load_api_keys() info = keys.get(key) @@ -118,12 +122,12 @@ def validate_api_key(key: str) -> Optional[dict]: return None if info.get("plan") == "trial": trial_ends = info.get("trial_ends", "") - if trial_ends and datetime.now(timezone.utc).isoformat() > trial_ends: + if trial_ends and datetime.now(UTC).isoformat() > trial_ends: with _KEYS_LOCK: keys2 = load_api_keys() if keys2.get(key, {}).get("active"): keys2[key]["active"] = False - keys2[key]["deactivated_at"] = datetime.now(timezone.utc).isoformat() + keys2[key]["deactivated_at"] = datetime.now(UTC).isoformat() keys2[key]["deactivation_reason"] = "trial_expired" save_api_keys(keys2) logger.info("Trial key lazily expired: %s***", key[:16]) @@ -131,41 +135,64 @@ def validate_api_key(key: str) -> Optional[dict]: return info +def _new_key_record(stripe_customer_id: str, ref_id: str, email: str, plan: str) -> dict: + return { + "active": True, + "plan": plan, + "created_at": datetime.now(UTC).isoformat(), + "stripe_customer_id": stripe_customer_id, + "stripe_ref_id": ref_id, + "email": email, + "transactions_total": 0, + "credit_balance": 0.0, + "total_credits_purchased": 0.0, + "overage_enabled": False, + "overage_cap_eur": OVERAGE_CAP_DEFAULT, + "overage_consent_at": None, + "overage_consent_rate": None, + "overage_disabled_at": None, + } + + def create_api_key(stripe_customer_id: str, ref_id: str, email: str = "", test_mode: bool = False, plan: str = "pro") -> str: """Create and persist a new API key.""" key = generate_api_key(test_mode=test_mode, plan=plan) with _KEYS_LOCK: keys = load_api_keys() - keys[key] = { - "active": True, - "plan": plan, - "created_at": datetime.now(timezone.utc).isoformat(), - "stripe_customer_id": stripe_customer_id, - "stripe_ref_id": ref_id, - "email": email, - "transactions_total": 0, - "credit_balance": 0.0, - "total_credits_purchased": 0.0, - "overage_enabled": False, - "overage_cap_eur": OVERAGE_CAP_DEFAULT, - "overage_consent_at": None, - "overage_consent_rate": None, - "overage_disabled_at": None, - } + keys[key] = _new_key_record(stripe_customer_id, ref_id, email, plan) save_api_keys(keys) logger.info("API key created for customer %s (plan=%s)", stripe_customer_id, plan) return key +def get_or_create_free_key(email: str, ref_id: str) -> tuple[str, bool]: + """Return (key, created) for the active free key of this address, creating it if none exists. + + The lookup and the creation run under one hold of _KEYS_LOCK, so two + confirmations of the same address cannot both create a key. + """ + email = (email or "").strip().lower() + with _KEYS_LOCK: + keys = load_api_keys() + for key, info in keys.items(): + if info.get("email", "").lower() == email and info.get("plan") == "free" and info.get("active"): + return key, False + key = generate_api_key(test_mode=False, plan="free") + keys[key] = _new_key_record("", ref_id, email, "free") + save_api_keys(keys) + logger.info("Free API key created") + return key, True + + def deactivate_key_by_ref(ref_id: str): """Deactivate all keys matching a Stripe ref (subscription/payment intent).""" with _KEYS_LOCK: keys = load_api_keys() - for key, info in keys.items(): + for info in keys.values(): if info.get("stripe_ref_id") == ref_id: info["active"] = False - info["deactivated_at"] = datetime.now(timezone.utc).isoformat() + info["deactivated_at"] = datetime.now(UTC).isoformat() logger.info("API key deactivated for ref %s", ref_id) save_api_keys(keys) @@ -174,7 +201,7 @@ def reactivate_key_by_ref(ref_id: str): """Reactivate keys matching a Stripe ref (e.g., after invoice.paid following past_due).""" with _KEYS_LOCK: keys = load_api_keys() - for key, info in keys.items(): + for info in keys.values(): if info.get("stripe_ref_id") == ref_id and not info.get("active"): info["active"] = True info.pop("deactivated_at", None) @@ -182,7 +209,7 @@ def reactivate_key_by_ref(ref_id: str): save_api_keys(keys) -def find_key_by_ref(ref_id: str) -> Optional[str]: +def find_key_by_ref(ref_id: str) -> str | None: """Find an active key by Stripe ref.""" keys = load_api_keys() for key, info in keys.items(): @@ -191,7 +218,7 @@ def find_key_by_ref(ref_id: str) -> Optional[str]: return None -def find_key_info_by_ref(ref_id: str) -> Optional[dict]: +def find_key_info_by_ref(ref_id: str) -> dict | None: """Find key record (active or not) by Stripe ref. Returns dict with '_key' injected.""" keys = load_api_keys() for key, info in keys.items(): @@ -203,13 +230,13 @@ def find_key_info_by_ref(ref_id: str) -> Optional[dict]: def create_trial_key(email: str, trial_days: int = 14, test_mode: bool = False) -> str: """Create an immediate card-free trial API key (no Stripe required).""" key = generate_api_key(test_mode=test_mode, plan="trial") - trial_ends = (datetime.now(timezone.utc) + timedelta(days=trial_days)).isoformat() + trial_ends = (datetime.now(UTC) + timedelta(days=trial_days)).isoformat() with _KEYS_LOCK: keys = load_api_keys() keys[key] = { "active": True, "plan": "trial", - "created_at": datetime.now(timezone.utc).isoformat(), + "created_at": datetime.now(UTC).isoformat(), "trial_ends": trial_ends, "stripe_customer_id": "", "stripe_ref_id": "", @@ -228,7 +255,7 @@ def create_trial_key(email: str, trial_days: int = 14, test_mode: bool = False) return key -def find_active_trial_by_email(email: str) -> Optional[dict]: +def find_active_trial_by_email(email: str) -> dict | None: """Return active trial key info for an email, or None.""" keys = load_api_keys() for key, info in keys.items(): @@ -240,7 +267,7 @@ def find_active_trial_by_email(email: str) -> Optional[dict]: def find_expiring_trial_keys(within_hours: int = 24) -> list: """Return active trial keys expiring within the given window.""" - now = datetime.now(timezone.utc) + now = datetime.now(UTC) cutoff = (now + timedelta(hours=within_hours)).isoformat() now_iso = now.isoformat() keys = load_api_keys() @@ -254,7 +281,7 @@ def find_expiring_trial_keys(within_hours: int = 24) -> list: def find_expired_trial_keys() -> list: """Return active trial keys whose trial_ends has passed.""" - now_iso = datetime.now(timezone.utc).isoformat() + now_iso = datetime.now(UTC).isoformat() keys = load_api_keys() return [ {**info, "_key": key} @@ -270,7 +297,7 @@ def deactivate_trial_key(key: str, reason: str = "trial_expired"): keys = load_api_keys() if keys.get(key) and keys[key].get("active"): keys[key]["active"] = False - keys[key]["deactivated_at"] = datetime.now(timezone.utc).isoformat() + keys[key]["deactivated_at"] = datetime.now(UTC).isoformat() keys[key]["deactivation_reason"] = reason save_api_keys(keys) logger.info("Trial key deactivated (%s): %s***", reason, key[:16]) @@ -280,7 +307,7 @@ def deactivate_trial_keys_for_email(email: str, reason: str = "upgraded_to_paid" """Deactivate all active trial keys for an email. Returns count deactivated.""" if not email: return 0 - now = datetime.now(timezone.utc).isoformat() + now = datetime.now(UTC).isoformat() count = 0 with _KEYS_LOCK: keys = load_api_keys() @@ -370,7 +397,7 @@ def update_overage_settings(api_key: str, enabled: bool, cap_eur: float, overage f"cap_eur must be between {OVERAGE_CAP_MIN} and {OVERAGE_CAP_MAX}, got {cap_eur}" ) - now = datetime.now(timezone.utc).isoformat() + now = datetime.now(UTC).isoformat() with _KEYS_LOCK: keys = load_api_keys() diff --git a/trust_layer/registration.py b/trust_layer/registration.py new file mode 100644 index 0000000..a8280dd --- /dev/null +++ b/trust_layer/registration.py @@ -0,0 +1,232 @@ +"""Free API key registration with address confirmation (TLREG). + +No key exists before the mailbox owner confirms. The flow: + +1. request_registration(): validate nothing about the address (the endpoints do), + count the limits, store a pending record under reg_pending:{sha256(token)} with a + 24 h TTL, and return the token for the caller to mail. +2. confirm_registration(): consume the token atomically (GETDEL), then + get_or_create_free_key() under the keys lock. + +Everything fails closed: no Redis or no TL_METRICS_SALT means 503, before any mail +or key. Only a salted hash of the address and never the token reach the logs. +""" + +import hashlib +import json +import logging +import re +import secrets +import time +from datetime import UTC, datetime + +from . import free_tier_guard as guard +from .free_tier_guard import hash_identifier +from .keys import get_or_create_free_key + +logger = logging.getLogger("trust_layer.registration") + +REQUEST_MAX_PER_IP_PER_HOUR = 5 +CONFIRM_MAX_PER_IP_PER_HOUR = 20 +ADDRESS_MAX_PER_DAY = 3 +DEFAULT_MAIL_DAILY_MAX = 500 + +PENDING_TTL = 24 * 3600 +_ADDRESS_WINDOW = 24 * 3600 +_HOUR = 3600 +_DAY_TTL = 26 * 3600 + +_TOKEN_RE = re.compile(r"^[A-Za-z0-9_\-]{20,128}$") +_META_FIELDS = {"source": 64, "scan_id": 32, "utm_source": 64, "utm_medium": 64, "utm_campaign": 64, "referrer": 300} + + +class RegistrationError(Exception): + """A guard refused the request. Carries the HTTP status and a public code.""" + + def __init__(self, code: str, message: str, status: int): + super().__init__(message) + self.code = code + self.message = message + self.status = status + + +def _unavailable() -> RegistrationError: + return RegistrationError( + "service_degraded", "Registration is temporarily unavailable. Retry later.", 503 + ) + + +def _invalid_token() -> RegistrationError: + return RegistrationError("invalid_token", "This confirmation link is invalid or has expired.", 400) + + +def _now() -> float: + return time.time() + + +def _today() -> str: + return datetime.now(UTC).strftime("%Y-%m-%d") + + +def _ready(): + """Return the Redis client; raise 503 when Redis or the salt is missing.""" + r = guard.get_redis() + if r is None or not hash_identifier("probe"): + raise _unavailable() + return r + + +def _token_key(token: str) -> str: + return "reg_pending:" + hashlib.sha256(token.encode()).hexdigest() + + +def _hourly_count(r, prefix: str, ip_id: str) -> int: + name = f"{prefix}:{datetime.now(UTC).strftime('%Y%m%d%H')}:{ip_id}" + pipe = r.pipeline(transaction=True) + pipe.incr(name) + pipe.expire(name, _HOUR + 60) + return int(pipe.execute()[0]) + + +def _address_count(r, addr_hash: str) -> int: + """Count one request for this address in a 24 h window that blocked requests do not extend.""" + name = f"tl:reg_addr:{addr_hash}" + pipe = r.pipeline(transaction=True) + # SET NX EX creates the counter with its TTL in the same transaction as INCR: + # no window where the counter exists without expiry, and blocked requests do not extend it. + pipe.set(name, 0, ex=_ADDRESS_WINDOW, nx=True) + pipe.incr(name) + count = pipe.execute()[1] + return int(count) + + +def _release(r, name: str) -> None: + try: + r.decr(name) + except Exception as e: + logger.error("Registration counter release failed: %s", type(e).__name__) + + +def _clean_meta(meta: dict | None) -> dict: + meta = meta or {} + return {k: str(meta.get(k) or "")[:n] for k, n in _META_FIELDS.items()} + + +def request_registration(email: str, ip: str, meta: dict | None = None) -> tuple[str, str] | None: + """Store a pending record and return (email, token) to mail; None when no mail must go out. + + None is the silent refusal of the per-address cap: the caller still answers 202, so the + answer tells nothing about the address. Raises RegistrationError for 429 (IP) and 503. + """ + r = _ready() + email = email.strip().lower() + addr_hash = hash_identifier(email) + ip_id = hash_identifier(ip)[:32] + cap = guard._int_setting("TL_REG_MAIL_DAILY_MAX", DEFAULT_MAIL_DAILY_MAX) + if cap is None: + logger.error("TL_REG_MAIL_DAILY_MAX is not a non-negative integer: registration refused") + raise _unavailable() + addr_name = f"tl:reg_addr:{addr_hash}" + mail_name = f"tl:reg_mail:{_today()}" + took_addr = took_mail = False + try: + if _hourly_count(r, "tl:signup_ip", ip_id) > REQUEST_MAX_PER_IP_PER_HOUR: + raise RegistrationError("rate_limited", "Too many signups. Try again later.", 429) + if _address_count(r, addr_hash) > ADDRESS_MAX_PER_DAY: + logger.info("Registration over the per-address cap: addr=%s", addr_hash[:12]) + return None + took_addr = True + pipe = r.pipeline(transaction=True) + pipe.incr(mail_name) + pipe.expire(mail_name, _DAY_TTL) + took_mail = True + if int(pipe.execute()[0]) > cap: + logger.warning("Daily confirmation mail cap reached: registration refused") + raise _unavailable() + token = secrets.token_urlsafe(32) + record = {"email": email, "expires_at": _now() + PENDING_TTL, "meta": _clean_meta(meta)} + r.set(_token_key(token), json.dumps(record), ex=PENDING_TTL) + except RegistrationError: + if took_mail: + _release(r, mail_name) + if took_addr: + _release(r, addr_name) + raise + except Exception as e: + logger.error("Registration store failed: %s", type(e).__name__) + if took_mail: + _release(r, mail_name) + if took_addr: + _release(r, addr_name) + raise _unavailable() from e + logger.info("Registration pending: addr=%s", addr_hash[:12]) + return email, token + + +def confirm_registration(token, ip: str) -> dict: + """Consume the token and return {"email", "key", "created", "meta"}. + + Raises RegistrationError: 503 (Redis, salt, key store), 429 (IP limit, token untouched), + 400 (unknown, used, expired or malformed token, all the same answer). + """ + r = _ready() + ip_id = hash_identifier(ip)[:32] + try: + over = _hourly_count(r, "tl:reg_confirm_ip", ip_id) > CONFIRM_MAX_PER_IP_PER_HOUR + except Exception as e: + logger.error("Confirm counter failed: %s", type(e).__name__) + raise _unavailable() from e + if over: + raise RegistrationError("rate_limited", "Too many attempts. Try again later.", 429) + if not isinstance(token, str) or not _TOKEN_RE.match(token): + raise _invalid_token() + name = _token_key(token) + try: + raw = r.getdel(name) + except Exception as e: + logger.error("Pending record read failed: %s", type(e).__name__) + raise _unavailable() from e + if raw is None: + raise _invalid_token() + try: + record = json.loads(raw) + email = record["email"] + remaining = float(record["expires_at"]) - _now() + except (ValueError, KeyError, TypeError) as e: + logger.error("Malformed pending record dropped: %s", type(e).__name__) + raise _invalid_token() from e + if remaining <= 0: + raise _invalid_token() + try: + key, created = get_or_create_free_key(email, f"free_signup_{email}") + except Exception as e: + logger.error("Key creation failed at confirm: %s", type(e).__name__) + try: + r.set(name, raw, ex=max(1, int(remaining))) # give the token back: nothing was created + except Exception as e2: + logger.error("Pending record restore failed: %s", type(e2).__name__) + raise _unavailable() from e + return {"email": email, "key": key, "created": created, "meta": record.get("meta") or {}} + + +def log_funnel(event: str, ip: str, email: str, meta: dict, conversion: bool = False) -> None: + """Append a funnel (or conversion) event; hashes only. Best effort.""" + # Lazy import: app.py owns the log paths (tests move them) and imports this package. + from . import app as app_mod + path = app_mod.CONVERSION_EVENTS_LOG if conversion else app_mod.FUNNEL_EVENTS_LOG + record = { + "ts": datetime.now(UTC).isoformat(), + "event": event, + "scan_id": meta.get("scan_id", ""), + "source": meta.get("source", ""), + "client_ip_hash": hashlib.sha256(ip.encode()).hexdigest()[:12], + "email_hash": hash_identifier(email)[:32], + } + if conversion: + record["plan"] = "free" + record.update({k: meta.get(k, "") for k in ("utm_source", "utm_medium", "utm_campaign", "referrer")}) + try: + with open(path, "a") as f: + f.write(json.dumps(record) + "\n") + except OSError: + pass diff --git a/trust_layer/routers/registration.py b/trust_layer/routers/registration.py new file mode 100644 index 0000000..b6ef580 --- /dev/null +++ b/trust_layer/routers/registration.py @@ -0,0 +1,100 @@ +"""GET/POST /v1/register/confirm: address confirmation for free API keys (TLREG).""" + +import logging + +from fastapi import APIRouter, BackgroundTasks, Request +from fastapi.responses import HTMLResponse, JSONResponse + +from .. import registration +from ..email_notify import send_welcome_email + +logger = logging.getLogger("trust_layer.routers.registration") + +router = APIRouter() + +# The page reads the token from the URL fragment (never sent to the server, so never in +# an access log) and POSTs it on a click: a mail scanner that prefetches the link +# only fetches this page and consumes nothing. +_CONFIRM_PAGE = """ + + + + + +Confirm your email - ArkForge + + + +
+

Confirm your email

+

Press the button to confirm this address. Your free API key is then sent to it by email.

+ +
+
+ + +""" + +_PAGE_HEADERS = {"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"} + + +def _error(code: str, message: str, status: int) -> JSONResponse: + return JSONResponse( + status_code=status, + content={"error": {"code": code, "message": message, "status": status}}, + headers={"Cache-Control": "no-store"}, + ) + + +@router.get("/v1/register/confirm") +async def confirm_page(): + """Static page: touches no state, whatever the query string carries.""" + return HTMLResponse(content=_CONFIRM_PAGE, headers=_PAGE_HEADERS) + + +@router.post("/v1/register/confirm") +async def confirm(request: Request, background: BackgroundTasks): + from .. import app as app_mod # lazy: app.py imports this router + + try: + body = await request.json() + except Exception: + return _error("invalid_token", "This confirmation link is invalid or has expired.", 400) + token = body.get("token") if isinstance(body, dict) else None + ip = request.headers.get("x-real-ip") or (request.client.host if request.client else "unknown") + try: + result = registration.confirm_registration(token, ip) + except registration.RegistrationError as e: + return _error(e.code, e.message, e.status) + + background.add_task(send_welcome_email, result["email"], result["key"]) + if result["created"]: + meta = result["meta"] + registration.log_funnel("register_completion", ip, result["email"], meta) + registration.log_funnel("signup_attributed", ip, result["email"], meta, conversion=True) + if ip not in app_mod._INTERNAL_IPS: + app_mod.usage_metrics.record_free_signup() + return JSONResponse(content={"status": "confirmed"}, headers={"Cache-Control": "no-store"})