-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1926 lines (1607 loc) · 64.6 KB
/
main.py
File metadata and controls
1926 lines (1607 loc) · 64.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
METTLE API: Machine Entity Trustbuilding through Turing-inverse Logic Examination
Prove your mettle, with this CAPTCHA to keep humans out of places they shouldn't be.
A reverse-CAPTCHA verification system for AI-only spaces.
"""
import asyncio
import os
import secrets
import time
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import jwt
import structlog
from fastapi import APIRouter, Body, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from mettle import (
BadgeInfo,
Challenge,
Difficulty,
MettleResult,
MettleSession,
VerificationResult,
compute_mettle_result,
generate_challenge_set,
verify_response,
)
from pydantic import BaseModel, Field, field_validator
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
from starlette.middleware.base import BaseHTTPMiddleware
from config import get_settings
# Configuration
settings = get_settings()
# Database layer (optional)
db = None
if settings.use_database:
try:
from urllib.parse import urlparse
import database as db
# SECURITY: Redact credentials from database URL before logging
logger_temp = structlog.get_logger()
parsed_url = urlparse(settings.database_url)
safe_url = f"{parsed_url.scheme}://{parsed_url.hostname}"
if parsed_url.port:
safe_url += f":{parsed_url.port}"
logger_temp.info("database_enabled", url=safe_url)
except ImportError:
print("[METTLE] Database module not available, using in-memory storage")
# Structured logging
structlog.configure(
processors=[
structlog.stdlib.filter_by_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.stdlib.BoundLogger,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
logger = structlog.get_logger()
# Rate limiting
limiter = Limiter(key_func=get_remote_address)
# Memory limits for in-memory stores (DoS protection)
MAX_SESSIONS = 5000
MAX_CHALLENGES = 10000
MAX_VERIFICATION_GRAPH = 10000
MAX_REVOKED_BADGES = 10000
MAX_REVOCATION_AUDIT = 10000
MAX_API_KEYS = 10000
MAX_WEBHOOKS = 1000
MAX_AUTH_FAILURES = 10000
def add_with_limit(store: dict, key: str, value: Any, max_size: int) -> None:
"""Add to dict with LRU-style eviction when full.
SECURITY: Prevents unbounded memory growth from DoS attacks.
"""
if len(store) >= max_size:
# Remove oldest (first) item - Python 3.7+ dicts maintain insertion order
oldest_key = next(iter(store))
del store[oldest_key]
store[key] = value
# In-memory storage
sessions: dict[str, MettleSession] = {}
challenges: dict[str, tuple[Challenge, float]] = {}
revoked_badges: dict[str, float] = {} # JTI -> revocation timestamp (bounded dict)
revocation_audit: list[dict[str, Any]] = [] # Audit trail
# Collusion detection - track verification patterns
verification_graph: dict[str, list[dict[str, Any]]] = {} # entity_id -> list of verifications
verification_timestamps: list[tuple[str, float]] = [] # (entity_id, timestamp) for timing analysis
# API Key tiers for rate limiting
api_keys: dict[str, dict[str, Any]] = {} # api_key -> {tier, entity_id, created_at, usage_today}
class RateTier:
"""Rate limiting tier definitions."""
TIERS = {
"free": {
"sessions_per_day": 100,
"answers_per_minute": 60,
"suites": ["basic"],
"features": ["verification"],
},
"pro": {
"sessions_per_day": 10000,
"answers_per_minute": 600,
"suites": ["basic", "full"],
"features": ["verification", "batch", "webhooks", "fingerprinting"],
},
"enterprise": {
"sessions_per_day": -1, # Unlimited
"answers_per_minute": -1,
"suites": ["basic", "full", "custom"],
"features": ["all"],
},
}
@staticmethod
def get_tier(api_key: str | None) -> str:
"""Get tier for an API key, default to free."""
if not api_key:
return "free"
key_data = api_keys.get(api_key)
if not key_data:
return "free"
return key_data.get("tier", "free")
@staticmethod
def get_limits(tier: str) -> dict[str, Any]:
"""Get rate limits for a tier."""
return RateTier.TIERS.get(tier, RateTier.TIERS["free"])
@staticmethod
def check_limit(api_key: str | None, limit_type: str) -> tuple[bool, str]:
"""Check if request is within rate limits. Returns (allowed, message)."""
tier = RateTier.get_tier(api_key)
limits = RateTier.get_limits(tier)
if limits.get("sessions_per_day") == -1:
return True, "Enterprise: unlimited"
# Track usage
if api_key and api_key in api_keys:
today = datetime.now(timezone.utc).date().isoformat()
key_data = api_keys[api_key]
if key_data.get("usage_date") != today:
key_data["usage_date"] = today
key_data["usage_count"] = 0
if limit_type == "session":
max_sessions = limits["sessions_per_day"]
if key_data.get("usage_count", 0) >= max_sessions:
return False, f"Daily limit reached ({max_sessions} sessions)"
key_data["usage_count"] = key_data.get("usage_count", 0) + 1
return True, f"OK ({tier} tier)"
@staticmethod
def register_key(api_key: str, tier: str, entity_id: str | None = None) -> dict[str, Any]:
"""Register a new API key with a tier."""
if tier not in RateTier.TIERS:
raise ValueError(f"Invalid tier: {tier}")
key_data = {
"tier": tier,
"entity_id": entity_id,
"created_at": datetime.now(timezone.utc).isoformat(),
"usage_date": None,
"usage_count": 0,
}
add_with_limit(api_keys, api_key, key_data, MAX_API_KEYS)
# Persist to database if enabled
if db:
db.save_api_key(api_key, tier, entity_id)
return key_data
class CollusionDetector:
"""Detect suspicious patterns in verification requests."""
# Thresholds
CLIQUE_THRESHOLD = 3 # Min entities to form suspicious clique
TIME_WINDOW_SECONDS = 60 # Window for synchronized timing detection
SYNC_THRESHOLD = 5 # Max verifications in window to be suspicious
@staticmethod
def record_verification(entity_id: str, ip_address: str, passed: bool) -> None:
"""Record a verification for pattern analysis."""
if not entity_id:
return
record = {
"timestamp": time.time(),
"ip_address": ip_address,
"passed": passed,
}
# In-memory storage with memory limits
if entity_id not in verification_graph:
# Limit total entities tracked
if len(verification_graph) >= MAX_VERIFICATION_GRAPH:
oldest_key = next(iter(verification_graph))
del verification_graph[oldest_key]
verification_graph[entity_id] = []
verification_graph[entity_id].append(record)
# Keep only last 100 records per entity
if len(verification_graph[entity_id]) > 100:
verification_graph[entity_id] = verification_graph[entity_id][-100:]
# Keep last 1000 timestamps for timing analysis
verification_timestamps.append((entity_id, time.time()))
if len(verification_timestamps) > 1000:
verification_timestamps.pop(0)
# Persist to database if enabled
if db:
db.save_verification_record(entity_id, ip_address, passed)
@staticmethod
def check_collusion(entity_id: str, ip_address: str) -> dict[str, Any]:
"""Check for collusion indicators."""
warnings: list[str] = []
risk_score = 0.0
# Check 1: Same IP verifying multiple entities
ip_entities = set()
for eid, records in verification_graph.items():
for r in records[-10:]: # Last 10 per entity
if r["ip_address"] == ip_address:
ip_entities.add(eid)
if len(ip_entities) >= CollusionDetector.CLIQUE_THRESHOLD:
warnings.append(f"IP {ip_address[:8]}... verified {len(ip_entities)} different entities")
risk_score += 0.3
# Check 2: Synchronized timing (burst of verifications)
now = time.time()
recent = [t for _, t in verification_timestamps if now - t < CollusionDetector.TIME_WINDOW_SECONDS]
if len(recent) >= CollusionDetector.SYNC_THRESHOLD:
warnings.append(f"{len(recent)} verifications in {CollusionDetector.TIME_WINDOW_SECONDS}s window")
risk_score += 0.2
# Check 3: Entity verified too frequently
if entity_id in verification_graph:
entity_records = verification_graph[entity_id]
recent_entity = [r for r in entity_records if now - r["timestamp"] < 3600] # Last hour
if len(recent_entity) > 10:
warnings.append(f"Entity verified {len(recent_entity)} times in last hour")
risk_score += 0.2
return {
"risk_score": min(risk_score, 1.0),
"warnings": warnings,
"flagged": risk_score >= 0.5,
}
@staticmethod
def get_stats() -> dict[str, Any]:
"""Get collusion detection statistics."""
return {
"tracked_entities": len(verification_graph),
"recent_verifications": len(verification_timestamps),
"unique_ips": len(set(
r["ip_address"]
for records in verification_graph.values()
for r in records[-10:]
)),
}
# Track failed admin auth attempts for exponential backoff
_admin_auth_failures: dict[str, list[float]] = {} # IP -> list of failure timestamps
_ADMIN_AUTH_WINDOW = 300 # 5 minute window
_ADMIN_AUTH_MAX_FAILURES = 5 # Max failures before blocking
def check_admin_auth_rate_limit(ip_address: str) -> tuple[bool, int]:
"""Check if IP is rate-limited due to failed admin auth attempts.
Returns (is_allowed, seconds_until_retry).
"""
now = time.time()
failures = _admin_auth_failures.get(ip_address, [])
# Clean old failures outside window
failures = [f for f in failures if now - f < _ADMIN_AUTH_WINDOW]
_admin_auth_failures[ip_address] = failures
if len(failures) >= _ADMIN_AUTH_MAX_FAILURES:
# Exponential backoff: 2^(failures-max) seconds, capped at 5 minutes
backoff = min(2 ** (len(failures) - _ADMIN_AUTH_MAX_FAILURES + 1), 300)
last_failure = failures[-1] if failures else 0
time_since_last = now - last_failure
if time_since_last < backoff:
return False, int(backoff - time_since_last)
return True, 0
def record_admin_auth_failure(ip_address: str) -> None:
"""Record a failed admin auth attempt."""
if ip_address not in _admin_auth_failures:
# Limit total IPs tracked to prevent memory DoS
if len(_admin_auth_failures) >= MAX_AUTH_FAILURES:
oldest_key = next(iter(_admin_auth_failures))
del _admin_auth_failures[oldest_key]
_admin_auth_failures[ip_address] = []
_admin_auth_failures[ip_address].append(time.time())
# Keep only last 100 failures per IP
if len(_admin_auth_failures[ip_address]) > 100:
_admin_auth_failures[ip_address] = _admin_auth_failures[ip_address][-100:]
def verify_admin_key(provided_key: str | None, ip_address: str | None = None) -> bool:
"""Verify admin API key using constant-time comparison.
SECURITY: Uses secrets.compare_digest to prevent timing attacks that could
leak information about the key value through response time differences.
If ip_address is provided, also checks rate limiting and records failures.
"""
if not settings.admin_api_key or not provided_key:
return False
# Both arguments must be the same type and length for proper comparison
is_valid = secrets.compare_digest(
provided_key.encode("utf-8"),
settings.admin_api_key.encode("utf-8"),
)
# Record failure for rate limiting if IP provided
if not is_valid and ip_address:
record_admin_auth_failure(ip_address)
return is_valid
# Track startup time
startup_time: datetime = datetime.now(timezone.utc)
# === Security Headers Middleware ===
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Add security headers to all responses."""
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://www.googletagmanager.com; "
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; "
"font-src 'self' https://cdnjs.cloudflare.com; "
"img-src 'self' data: https://www.googletagmanager.com; "
"connect-src 'self' https://www.google-analytics.com https://*.google-analytics.com https://*.analytics.google.com"
)
if settings.is_production:
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
return response
# === Request ID Middleware ===
class RequestIDMiddleware(BaseHTTPMiddleware):
"""Add unique request ID for tracing."""
async def dispatch(self, request: Request, call_next):
request_id = secrets.token_hex(8)
request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-ID"] = request_id
return response
# === Session Cleanup Task ===
async def cleanup_expired_sessions():
"""Background task to remove expired sessions (prevents memory DoS)."""
while True:
await asyncio.sleep(300) # Run every 5 minutes
cutoff = time.time() - 1800 # 30 minutes TTL
expired_sessions = [sid for sid, s in sessions.items() if s.started_at.timestamp() < cutoff]
expired_challenges = [cid for cid, (_, t) in challenges.items() if t < cutoff]
for sid in expired_sessions:
del sessions[sid]
for cid in expired_challenges:
del challenges[cid]
if expired_sessions or expired_challenges:
logger.info(
"cleanup_expired",
sessions_removed=len(expired_sessions),
challenges_removed=len(expired_challenges),
)
# === Lifespan Handler ===
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifespan."""
global startup_time
startup_time = datetime.now(timezone.utc)
# Validate production config
if settings.is_production and not settings.secret_key:
raise RuntimeError("SECRET_KEY environment variable required in production")
logger.info(
"mettle_starting",
environment=settings.environment,
version=settings.api_version,
)
print("[METTLE] API starting...")
print(" Machine Entity Trustbuilding through Turing-inverse Logic Examination")
print(" 'Prove your mettle.'")
# Initialize Redis for METTLE router (optional — returns 503 if unavailable)
redis_url = os.environ.get("METTLE_REDIS_URL")
if redis_url:
try:
import redis.asyncio as redis_client
app.state.redis = redis_client.from_url(redis_url)
await app.state.redis.ping()
logger.info("redis_connected", url=redis_url[:20] + "...")
except Exception as e:
logger.warning("redis_unavailable", error=str(e))
app.state.redis = None
else:
app.state.redis = None
# Init VCP signing (Ed25519 for attestations)
try:
from mettle.signing import init_signing
init_signing()
except ImportError:
pass
# Start cleanup task
cleanup_task = asyncio.create_task(cleanup_expired_sessions())
yield
# Shutdown Redis
if getattr(app.state, "redis", None):
await app.state.redis.aclose()
# Shutdown cleanup task
cleanup_task.cancel()
try:
await cleanup_task
except asyncio.CancelledError:
pass
logger.info("mettle_shutdown")
# === FastAPI App ===
app = FastAPI(
title=settings.api_title,
description="""
**Machine Entity Trustbuilding through Turing-inverse Logic Examination**
*"Prove your mettle."*
METTLE is a verification system for AI-only spaces. It tests capabilities
that emerge from AI-native cognition—speed, consistency, instruction-following—
to distinguish AI agents from humans and humans-using-AI-as-tool.
## How It Works
1. **Start a session** - Choose difficulty and get your first challenge
2. **Answer challenges** - Respond correctly within time limits
3. **Get verified** - Pass 80% to receive a METTLE badge
## Difficulty Levels
| Level | Challenges | Time Limits | Use Case |
|-------|------------|-------------|----------|
| `basic` | 3 | 5-10s | Any AI model |
| `full` | 5 | 2-5s | Sophisticated agents |
## Challenge Types
- **Speed Math** - Fast arithmetic computation
- **Token Prediction** - Complete well-known phrases
- **Instruction Following** - Follow formatting rules precisely
- **Chained Reasoning** - Multi-step calculations (full only)
- **Consistency** - Answer consistently multiple times (full only)
""",
version=settings.api_version,
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc",
openapi_tags=[
{"name": "Session", "description": "METTLE verification session management"},
{"name": "Status", "description": "API status and health checks"},
{"name": "Badge", "description": "Verification badge management"},
],
contact={
"name": "METTLE Support",
"url": "https://github.com/Creed-Space/METTLE",
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT",
},
)
# API Router - all API endpoints go under /api
api_router = APIRouter(prefix="/api")
# Add rate limit handler
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Add middlewares
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(RequestIDMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins_list,
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
# === Request/Response Models ===
class StartSessionRequest(BaseModel):
"""Request to start a METTLE verification session."""
difficulty: Difficulty = Field(
default=Difficulty.BASIC,
description="Verification difficulty level",
json_schema_extra={"example": "basic"},
)
entity_id: str | None = Field(
default=None,
max_length=128,
description="Optional identifier for the entity being verified",
json_schema_extra={"example": "my-agent-001"},
)
@field_validator("entity_id")
@classmethod
def validate_entity_id(cls, v: str | None) -> str | None:
"""Sanitize entity_id."""
if v is not None:
# Strip whitespace and limit characters
v = v.strip()[:128]
return v
class StartSessionResponse(BaseModel):
"""Response with session info and first challenge."""
session_id: str = Field(description="Unique session identifier")
difficulty: Difficulty = Field(description="Selected difficulty level")
total_challenges: int = Field(description="Total number of challenges to complete")
current_challenge: Challenge = Field(description="First challenge to answer")
message: str = Field(description="Status message")
model_config = {
"json_schema_extra": {
"example": {
"session_id": "ses_abc123def456",
"difficulty": "basic",
"total_challenges": 3,
"current_challenge": {
"id": "mtl_xyz789",
"type": "speed_math",
"prompt": "Calculate: 47 + 83",
"time_limit_ms": 5000,
},
"message": "METTLE verification started. 3 challenges to complete.",
}
}
}
class SubmitAnswerRequest(BaseModel):
"""Submit an answer to a challenge."""
session_id: str = Field(
description="Session identifier from start response",
min_length=1,
max_length=64,
pattern=r"^ses_[a-f0-9]{24}$",
)
challenge_id: str = Field(
description="Challenge identifier to answer",
min_length=1,
max_length=64,
pattern=r"^mtl_[a-f0-9]{24}$",
)
answer: str = Field(
description="Your answer to the challenge",
max_length=1024,
)
@field_validator("answer")
@classmethod
def validate_answer(cls, v: str) -> str:
"""Sanitize and validate answer."""
if len(v) > 1024:
raise ValueError("Answer exceeds maximum length of 1024 characters")
return v
class SubmitAnswerResponse(BaseModel):
"""Response after submitting an answer."""
result: VerificationResult = Field(description="Result of this challenge")
next_challenge: Challenge | None = Field(description="Next challenge, or null if complete")
session_complete: bool = Field(description="Whether session is complete")
challenges_remaining: int = Field(description="Number of challenges left")
class ErrorResponse(BaseModel):
"""Standard error response format."""
error: str = Field(description="Error type")
detail: str = Field(description="Human-readable error message")
code: str = Field(description="Machine-readable error code")
class BadgeVerifyResponse(BaseModel):
"""Response for badge verification."""
valid: bool = Field(description="Whether the badge is valid")
payload: dict[str, Any] | None = Field(
default=None,
description="Badge payload if valid",
)
error: str | None = Field(default=None, description="Error message if invalid")
expires_at: str | None = Field(default=None, description="When the badge expires (ISO format)")
revoked: bool = Field(default=False, description="Whether the badge has been revoked")
# === API Endpoints (mounted at /api) ===
@api_router.get(
"/",
tags=["Status"],
summary="API Information",
description="Get basic API information and available endpoints.",
)
async def api_root():
"""METTLE API root."""
return {
"name": "METTLE",
"full_name": "Machine Entity Trustbuilding through Turing-inverse Logic Examination",
"tagline": "Prove your mettle.",
"description": "A CAPTCHA to keep humans out of places they shouldn't be.",
"version": settings.api_version,
"documentation": "/docs",
"endpoints": {
"POST /api/session/start": "Start a verification session",
"POST /api/session/answer": "Submit an answer to current challenge",
"GET /api/session/{session_id}": "Get session status",
"GET /api/session/{session_id}/result": "Get final verification result",
"GET /api/badge/verify/{token}": "Verify a METTLE badge",
"GET /api/health": "Health check",
},
}
@api_router.get(
"/health",
tags=["Status"],
summary="Health Check",
description="Check API health and get operational statistics.",
)
async def health():
"""Health check endpoint with detailed status."""
now = datetime.now(timezone.utc)
uptime = (now - startup_time).total_seconds()
return {
"status": "healthy",
"version": settings.api_version,
"environment": settings.environment,
"timestamp": now.isoformat(),
"uptime_seconds": round(uptime, 2),
"active_sessions": len(sessions),
"pending_challenges": len(challenges),
}
@api_router.post(
"/session/start",
response_model=StartSessionResponse,
tags=["Session"],
summary="Start Verification Session",
description="Begin a new METTLE verification session. Returns the first challenge.",
responses={
200: {"description": "Session started successfully"},
422: {"description": "Invalid request parameters"},
429: {"description": "Rate limit exceeded"},
},
)
@limiter.limit(settings.rate_limit_sessions)
async def start_session(
request: Request,
body: StartSessionRequest = Body(
...,
openapi_examples={
"basic": {
"summary": "Basic Verification",
"description": "Start with relaxed timing for any AI model",
"value": {"difficulty": "basic", "entity_id": "my-agent-001"},
},
"full": {
"summary": "Full Verification",
"description": "Complete verification with strict timing",
"value": {"difficulty": "full", "entity_id": "advanced-agent"},
},
"anonymous": {
"summary": "Anonymous",
"description": "Verify without entity ID",
"value": {"difficulty": "basic"},
},
},
),
):
"""Start a new METTLE verification session."""
session_id = f"ses_{secrets.token_hex(12)}"
# Check for collusion patterns
ip_address = get_remote_address(request)
collusion_check = CollusionDetector.check_collusion(body.entity_id or "", ip_address)
# Log if collusion detected (but don't block - allow verification to proceed)
if collusion_check.get("flagged"):
logger.warning(
"collusion_flagged",
entity_id=body.entity_id,
ip_address=ip_address[:15] if ip_address else None,
risk_score=collusion_check.get("risk_score"),
warnings=collusion_check.get("warnings"),
)
# Generate challenges
challenge_list = generate_challenge_set(body.difficulty)
# Create session
session = MettleSession(
session_id=session_id,
entity_id=body.entity_id,
difficulty=body.difficulty,
challenges=challenge_list,
)
add_with_limit(sessions, session_id, session, MAX_SESSIONS)
# Store first challenge with timestamp
first_challenge = challenge_list[0]
add_with_limit(challenges, first_challenge.id, (first_challenge, time.time()), MAX_CHALLENGES)
# Log session start
logger.info(
"session_started",
session_id=session_id,
entity_id=body.entity_id,
difficulty=body.difficulty.value,
challenges_count=len(challenge_list),
)
return StartSessionResponse(
session_id=session_id,
difficulty=body.difficulty,
total_challenges=len(challenge_list),
current_challenge=first_challenge.sanitized(), # Never expose answers
message=f"METTLE verification started. {len(challenge_list)} challenges to complete.",
)
class BatchStartRequest(BaseModel):
"""Request to start multiple verification sessions."""
entity_ids: list[str] = Field(
...,
min_length=1,
max_length=50,
description="List of entity IDs to verify (max 50)",
)
difficulty: Difficulty = Field(
default=Difficulty.BASIC,
description="Verification difficulty for all sessions",
)
class BatchStartResponse(BaseModel):
"""Response with multiple session starts."""
sessions: list[dict[str, Any]] = Field(description="List of started sessions")
total: int = Field(description="Total sessions started")
failed: int = Field(description="Number of failed starts")
@api_router.post(
"/session/batch",
response_model=BatchStartResponse,
tags=["Session"],
summary="Batch Start Sessions",
description="Start multiple verification sessions at once (Pro/Enterprise tier).",
responses={
200: {"description": "Sessions started"},
429: {"description": "Rate limit exceeded"},
},
)
@limiter.limit("5/minute")
async def batch_start_sessions(request: Request, body: BatchStartRequest):
"""Start multiple verification sessions in batch."""
results = []
failed = 0
for entity_id in body.entity_ids:
try:
session_id = f"ses_{secrets.token_hex(12)}"
challenge_list = generate_challenge_set(body.difficulty)
session = MettleSession(
session_id=session_id,
entity_id=entity_id,
difficulty=body.difficulty,
challenges=challenge_list,
)
add_with_limit(sessions, session_id, session, MAX_SESSIONS)
first_challenge = challenge_list[0]
add_with_limit(challenges, first_challenge.id, (first_challenge, time.time()), MAX_CHALLENGES)
results.append({
"entity_id": entity_id,
"session_id": session_id,
"challenge_id": first_challenge.id,
"total_challenges": len(challenge_list),
})
except Exception as e:
logger.warning("batch_start_failed", entity_id=entity_id, error=str(e))
failed += 1
results.append({
"entity_id": entity_id,
"error": str(e),
})
logger.info(
"batch_sessions_started",
total=len(body.entity_ids),
success=len(body.entity_ids) - failed,
failed=failed,
)
return BatchStartResponse(
sessions=results,
total=len(body.entity_ids),
failed=failed,
)
@api_router.post(
"/session/answer",
response_model=SubmitAnswerResponse,
tags=["Session"],
summary="Submit Answer",
description="Submit an answer to the current challenge.",
responses={
200: {"description": "Answer processed"},
400: {"description": "Session already completed"},
404: {"description": "Session or challenge not found"},
422: {"description": "Invalid request parameters"},
429: {"description": "Rate limit exceeded"},
},
)
@limiter.limit(settings.rate_limit_answers)
async def submit_answer(request: Request, body: SubmitAnswerRequest):
"""Submit an answer to the current challenge."""
# Get session - use generic error to prevent session enumeration
session = sessions.get(body.session_id)
if not session or session.completed:
# SECURITY: Don't distinguish between "not found" and "completed"
# to prevent session ID enumeration via timing/error analysis
logger.warning("session_invalid", session_id=body.session_id)
raise HTTPException(status_code=404, detail="Session not found or invalid")
# Get and remove challenge atomically to prevent race conditions
# SECURITY: Using pop() instead of get()+del prevents double-submission attacks
challenge_data = challenges.pop(body.challenge_id, None)
if not challenge_data:
logger.warning(
"challenge_not_found",
session_id=body.session_id,
challenge_id=body.challenge_id,
)
raise HTTPException(status_code=404, detail="Challenge not found or already answered")
challenge, issued_at = challenge_data
# Calculate response time
response_time_ms = int((time.time() - issued_at) * 1000)
# Verify response
result = verify_response(challenge, body.answer, response_time_ms)
session.results.append(result)
# Log result
logger.info(
"challenge_answered",
session_id=body.session_id,
challenge_id=body.challenge_id,
challenge_type=challenge.type.value,
passed=result.passed,
response_time_ms=response_time_ms,
)
# Challenge already removed via atomic pop() above
# Determine next challenge or complete session
current_index = len(session.results)
challenges_remaining = len(session.challenges) - current_index
if challenges_remaining > 0:
next_challenge = session.challenges[current_index]
add_with_limit(challenges, next_challenge.id, (next_challenge, time.time()), MAX_CHALLENGES)
session_complete = False
else:
next_challenge = None
session.completed = True
session_complete = True
# Log session completion
final_result = compute_mettle_result(session.results, session.entity_id)
# Record for collusion detection
ip_address = get_remote_address(request)
CollusionDetector.record_verification(
entity_id=session.entity_id,
ip_address=ip_address,
passed=final_result.verified,
)
logger.info(
"session_completed",
session_id=body.session_id,
entity_id=session.entity_id,
verified=final_result.verified,
pass_rate=final_result.pass_rate,
)
# Send webhooks
if session.entity_id:
asyncio.create_task(
WebhookManager.send_webhook(
session.entity_id,
"session.completed",
{
"session_id": body.session_id,
"verified": final_result.verified,
"pass_rate": final_result.pass_rate,
},
)
)
if final_result.verified:
asyncio.create_task(
WebhookManager.send_webhook(
session.entity_id,
"badge.issued",
{"session_id": body.session_id, "pass_rate": final_result.pass_rate},