Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
64 changes: 64 additions & 0 deletions docs/design/TLREG.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion scripts/deploy_trust_layer_prod.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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" \
Expand Down
68 changes: 42 additions & 26 deletions scripts/security_smoke_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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 <api_key> to provide an existing key.{RESET}")
f"Set TRUST_LAYER_INTERNAL_SECRET or use --key <api_key>.{RESET}")
sys.exit(2)
print(f"\nTest key created: {free_key[:20]}...")

Expand All @@ -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)

# -----------------------------------------------------------------------
Expand Down Expand Up @@ -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})
Expand Down Expand Up @@ -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"})
Expand All @@ -278,39 +287,46 @@ 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")

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)

# -----------------------------------------------------------------------
Expand Down
37 changes: 37 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading