-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathflask_app.py
More file actions
2046 lines (1711 loc) · 64.6 KB
/
Copy pathflask_app.py
File metadata and controls
2046 lines (1711 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
import os
import sqlite3
import time
import json
import secrets
import logging
import hashlib
import hmac
import random
import re
import threading
import uuid
from urllib.parse import urlencode, parse_qsl, quote
from flask import Flask, request, jsonify, g, Response, render_template_string, has_request_context
try:
from werkzeug.middleware.proxy_fix import ProxyFix
except ImportError:
ProxyFix = None
# =========================================================
# APP CONFIGURATION
# =========================================================
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 8 * 1024 # Limit request body size to prevent DoS attacks via large uploads.
# --- Structured JSON Logging Setup ---
# Whitelists extra fields to prevent sensitive or unexpected data from being logged.
class JSONFormatter(logging.Formatter):
ALLOWED_EXTRA = {
"status_code", "duration_ms", "intent_id", "worker_id", "remote_addr",
"expired_open_deleted", "expired_claims_requeued", "expired_claims_dead",
"fulfilled_deleted", "dead_deleted", "dead_letters_deleted", "store_deleted",
"rate_limits_deleted", "idempotency_deleted", "nonces_deleted"
}
def format(self, record):
try:
log_record = {
"timestamp": time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(record.created)),
"level": record.levelname,
"message": record.getMessage(),
"module": record.module
}
if has_request_context():
log_record["endpoint"] = request.path
log_record["method"] = request.method
log_record["request_id"] = getattr(g, "request_id", "unknown")
log_record["remote_addr"] = get_real_ip()
if record.exc_info:
log_record["exception"] = self.formatException(record.exc_info)
for key in self.ALLOWED_EXTRA:
if key in record.__dict__:
log_record[key] = record.__dict__[key]
return json.dumps(log_record, default=str)
except Exception as e:
return json.dumps({
"timestamp": time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
"level": "ERROR",
"message": "Logging failure",
"logger_error": str(e)
})
app.logger.setLevel(logging.INFO)
app.logger.handlers.clear()
json_handler = logging.StreamHandler()
json_handler.setFormatter(JSONFormatter())
app.logger.addHandler(json_handler)
app.logger.propagate = False
# -------------------------------------
TRUST_PROXY = os.environ.get("BUS_TRUST_PROXY", "false").lower() == "true"
if TRUST_PROXY and ProxyFix is not None:
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
app.logger.info("ProxyFix enabled. Trusting upstream proxy headers.")
if sqlite3.sqlite_version_info < (3, 35, 0):
raise RuntimeError("SQLite 3.35.0+ required for RETURNING clauses.") # Required for atomic claiming logic.
API_KEY = os.environ.get("BUS_SECRET", "dev_secret")
if API_KEY == "dev_secret":
# Prevent accidental use of default, insecure API key in production.
raise RuntimeError(
"CRITICAL: Refusing to start. Running with default BUS_SECRET in production is unsafe.")
ADMIN_SECRET = os.environ.get("BUS_ADMIN_SECRET", "")
DASHBOARD_PASSWORD = os.environ.get("DASHBOARD_PASSWORD", "")
DB_PATH = os.environ.get("BUS_DB_PATH", os.path.join(
os.path.dirname(__file__), "infrastructure.db"))
MAINTENANCE_MODE = os.environ.get(
"BUS_MAINTENANCE_MODE", "false").lower() == "true"
METRICS_TOKEN = os.environ.get("BUS_METRICS_TOKEN", "")
REQUIRE_SIGNATURES = os.environ.get(
"BUS_REQUIRE_SIGNATURES", "false").lower() == "true"
ENFORCE_HTTPS = os.environ.get("BUS_ENFORCE_HTTPS", "false").lower() == "true"
try:
CLEANUP_INTERVAL_SECONDS = max(
300,
min(86400, int(os.environ.get("BUS_CLEANUP_INTERVAL_SECONDS", "21600")))
)
except ValueError:
CLEANUP_INTERVAL_SECONDS = 21600
# =========================================================
# SYSTEM LIMITS & CONSTANTS
# =========================================================
RATE_LIMIT_WINDOW = 60
RATE_LIMIT_MAX = 60
DEFAULT_CLAIM_TIMEOUT = 60
DEFAULT_MAX_ATTEMPTS = 3
DEFAULT_BACKOFF_BASE = 5.0
DEFAULT_PRIORITY = 100
MAX_PRIORITY = 1000
NONCE_WINDOW_SECONDS = 300 # Valid window for a nonce to prevent replay attacks.
NONCE_RETENTION_SECONDS = NONCE_WINDOW_SECONDS * 2 # Retention period for nonce tracking.
FULFILLED_RETENTION_SECONDS = 7 * 24 * 60 * 60 # Retention for completed intents.
DEAD_RETENTION_SECONDS = 7 * 24 * 60 * 60 # Retention for dead intents.
MAX_PAYLOAD = 7 * 1024 # Max size for 'payload' and 'result' fields.
MAX_TTL = 86400
MAX_OPEN_INTENTS_PER_KEY = 2000
CLEANUP_ERROR_COOLDOWN_SECONDS = 60
last_cleanup_time = time.time()
last_cleanup_error_time = 0
cleanup_lock = threading.Lock()
# =========================================================
# HELPERS
# =========================================================
def now():
return time.time()
def api_error(code, message, status_code=400):
return jsonify({"error": {"code": code, "message": message}}), status_code
def safe_int(value, default, min_val=None, max_val=None):
try:
v = int(value)
except (TypeError, ValueError):
return default
if min_val is not None:
v = max(min_val, v)
if max_val is not None:
v = min(max_val, v)
return v
def safe_float(value, default, min_val=None, max_val=None):
try:
v = float(value)
except (TypeError, ValueError):
return default
if min_val is not None:
v = max(min_val, v)
if max_val is not None:
v = min(max_val, v)
return v
def get_real_ip():
ip = request.remote_addr or "unknown"
if ip.startswith("::ffff:"):
ip = ip[7:]
return ip
def is_local():
ip = get_real_ip()
return ip in ("127.0.0.1", "::1", "localhost")
def is_busy_or_locked(exc):
return "locked" in str(exc).lower() or "busy" in str(exc).lower()
def is_json_safe(obj, max_depth=10, depth=0):
if depth > max_depth:
return False
if isinstance(obj, dict):
return all(is_json_safe(v, max_depth, depth + 1) for v in obj.values())
if isinstance(obj, list):
return all(is_json_safe(v, max_depth, depth + 1) for v in obj)
return True
# Prevent deeply nested JSON payloads to mitigate recursion-based DoS.
def valid_namespace(ns: str) -> bool:
return bool(re.match(r"^[a-zA-Z0-9_.-]{1,64}$", ns)) # Validate namespace format to prevent injection.
def valid_label(value: str) -> bool:
return bool(re.match(r"^[a-zA-Z0-9_.:-]{1,64}$", value)) # Validate label format for safe query usage.
def strict_quote(s, safe='', encoding=None, errors=None):
"""Enforces strict RFC 3986 percent-encoding for HMAC canonicalization."""
# Ensure consistent URL encoding to prevent signature mismatches.
return quote(s, safe='', encoding=encoding or 'utf-8', errors=errors or 'strict')
def admin_auth_ok():
# Constant-time comparison to prevent timing attacks.
token = request.headers.get("X-Admin-Token")
if token:
if ADMIN_SECRET:
return hmac.compare_digest(token, ADMIN_SECRET)
return False
auth = request.authorization
if auth and auth.username == "admin":
return bool(
DASHBOARD_PASSWORD and
hmac.compare_digest(auth.password or "", DASHBOARD_PASSWORD)
)
return False
def require_admin():
if admin_auth_ok():
return None
response = Response(
"Authentication required.",
401,
)
response.headers["WWW-Authenticate"] = 'Basic realm="IntentBus Admin"'
return response
def metrics_auth_ok():
auth_header = request.headers.get("Authorization", "").strip()
if auth_header.startswith("Bearer "):
token = auth_header[7:].strip()
if bool(METRICS_TOKEN) and hmac.compare_digest(token, METRICS_TOKEN):
return True
return admin_auth_ok()
def maybe_cleanup():
global last_cleanup_time, last_cleanup_error_time
if request.path == "/admin/cleanup":
return
t = now()
if t - last_cleanup_time < CLEANUP_INTERVAL_SECONDS:
return
if t - last_cleanup_error_time < CLEANUP_ERROR_COOLDOWN_SECONDS:
return
if not cleanup_lock.acquire(blocking=False):
return
try:
if now() - last_cleanup_time < CLEANUP_INTERVAL_SECONDS:
return
success, _ = run_cleanup_once()
if success:
last_cleanup_time = now()
last_cleanup_error_time = 0
else:
last_cleanup_error_time = now()
finally:
cleanup_lock.release()
# =========================================================
# DATABASE ENGINE
# =========================================================
def get_db():
if "db" not in g:
# WAL mode for concurrency, synchronous=NORMAL for performance,
# and isolation_level=None for explicit transaction control.
db = sqlite3.connect(DB_PATH, timeout=30, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA journal_mode=WAL;")
db.execute("PRAGMA synchronous=NORMAL;")
db.execute("PRAGMA busy_timeout=30000;")
db.execute("PRAGMA foreign_keys=ON;")
g.db = db
return g.db
@app.teardown_appcontext
def close_db(e):
db = g.pop("db", None)
if db:
try:
db.rollback()
except Exception:
pass
db.close()
def ensure_columns(db, table, columns):
allowed_tables = {
"store", "intents", "tester_keys", "rate_limits",
"idempotency_keys", "request_nonces", "dead_letters"
}
# Prevent SQL injection into the table name.
if table not in allowed_tables:
raise ValueError(f"Security Exception: Untrusted table name '{table}'")
existing = {row["name"] for row in db.execute(
f"PRAGMA table_info({table})").fetchall()}
for col_def in columns:
col_name = col_def.split()[0]
if col_name not in existing:
db.execute(f"ALTER TABLE {table} ADD COLUMN {col_def}")
def setup_schema(db):
db.execute("""
CREATE TABLE IF NOT EXISTS store (
key TEXT PRIMARY KEY,
value TEXT,
expires_at REAL
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS intents (
id TEXT PRIMARY KEY,
namespace TEXT DEFAULT 'default',
goal TEXT NOT NULL,
payload TEXT NOT NULL,
status TEXT NOT NULL,
priority INTEGER DEFAULT 100,
target_worker TEXT,
required_capability TEXT,
created_at REAL NOT NULL,
expires_at REAL NOT NULL,
run_at REAL NOT NULL,
claimed_at REAL,
claim_expires_at REAL,
claimed_by TEXT,
claim_token TEXT,
publisher TEXT NOT NULL,
claim_attempts INTEGER DEFAULT 0,
max_attempts INTEGER DEFAULT 3,
backoff_base REAL DEFAULT 5.0,
visibility TEXT DEFAULT 'private',
last_error TEXT,
failed_at REAL,
result TEXT,
result_type TEXT,
completed_at REAL
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS tester_keys (
api_key TEXT PRIMARY KEY,
owner TEXT,
total_requests INTEGER DEFAULT 0,
created_at REAL
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS rate_limits (
identifier TEXT PRIMARY KEY,
count INTEGER,
window REAL
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS idempotency_keys (
api_key TEXT,
key TEXT,
body_hash TEXT,
response TEXT,
status_code INTEGER,
created_at REAL,
PRIMARY KEY (api_key, key)
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS request_nonces (
api_key TEXT,
nonce TEXT,
created_at REAL,
PRIMARY KEY (api_key, nonce)
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS dead_letters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
intent_id TEXT UNIQUE,
namespace TEXT,
goal TEXT,
payload TEXT,
publisher TEXT,
visibility TEXT,
attempts INTEGER,
reason TEXT,
created_at REAL
)
""")
ensure_columns(db, "intents", [
"namespace TEXT DEFAULT 'default'",
"goal TEXT",
"payload TEXT",
"status TEXT",
"priority INTEGER DEFAULT 100",
"target_worker TEXT",
"required_capability TEXT",
"created_at REAL NOT NULL",
"expires_at REAL NOT NULL",
"run_at REAL DEFAULT 0",
"claimed_at REAL",
"claim_expires_at REAL",
"claimed_by TEXT",
"claim_token TEXT",
"publisher TEXT",
"claim_attempts INTEGER DEFAULT 0",
"max_attempts INTEGER DEFAULT 3",
"backoff_base REAL DEFAULT 5.0",
"visibility TEXT DEFAULT 'private'",
"last_error TEXT",
"failed_at REAL",
"result TEXT",
"result_type TEXT",
"completed_at REAL",
])
needs_migration = db.execute("""
SELECT 1
FROM intents
WHERE namespace IS NULL
OR run_at IS NULL
OR run_at = 0
OR priority IS NULL
OR max_attempts IS NULL
OR backoff_base IS NULL
LIMIT 1
""").fetchone()
if needs_migration:
db.execute(
"UPDATE intents SET namespace='default' WHERE namespace IS NULL")
db.execute(
"UPDATE intents SET run_at=created_at WHERE run_at IS NULL OR run_at=0")
db.execute("UPDATE intents SET priority=100 WHERE priority IS NULL")
db.execute("UPDATE intents SET max_attempts=3 WHERE max_attempts IS NULL")
db.execute(
"UPDATE intents SET backoff_base=5.0 WHERE backoff_base IS NULL")
db.execute("DROP INDEX IF EXISTS idx_intents_routing")
db.execute("DROP INDEX IF EXISTS idx_intents_routing_v2")
db.execute("DROP INDEX IF EXISTS idx_intents_routing_v3")
db.execute("DROP INDEX IF EXISTS idx_intents_routing_pub")
db.execute("DROP INDEX IF EXISTS idx_intents_routing_vis")
db.execute("DROP INDEX IF EXISTS idx_intents_claim")
db.execute("CREATE INDEX IF NOT EXISTS idx_intents_pub_claim ON intents(status, namespace, publisher, priority DESC, run_at, claim_attempts, created_at)")
db.execute("CREATE INDEX IF NOT EXISTS idx_intents_vis_claim ON intents(status, namespace, visibility, priority DESC, run_at, claim_attempts, created_at)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_intents_publisher ON intents(publisher, status)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_intents_cleanup ON intents(status, claim_expires_at)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_intents_failed ON intents(status, failed_at)")
db.execute("CREATE INDEX IF NOT EXISTS idx_store_expires ON store(expires_at)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_rate_limits_window ON rate_limits(window)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_idempotency_created ON idempotency_keys(created_at)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_request_nonces_created ON request_nonces(created_at)")
db.execute(
"CREATE INDEX IF NOT EXISTS idx_dead_letters_created ON dead_letters(created_at)")
def init_db():
with app.app_context():
setup_schema(get_db())
# =========================================================
# AUTH & SECURITY
# =========================================================
def get_role(key):
# Constant-time comparison to prevent timing attacks.
if not key:
return None
if hmac.compare_digest(key, API_KEY):
return "admin"
row = get_db().execute("SELECT 1 FROM tester_keys WHERE api_key=?", (key,)).fetchone()
return "tester" if row else None
def verify_signed_request(api_key):
sig = request.headers.get("X-Signature")
ts = request.headers.get("X-Timestamp")
nonce = request.headers.get("X-Nonce")
if not sig or not ts or not nonce:
return False, "Missing required signature headers."
try:
ts_int = int(ts)
except Exception:
return False, "Invalid timestamp"
if abs(now() - ts_int) > NONCE_WINDOW_SECONDS:
# Reject requests with timestamps outside the allowed window to prevent replay.
return False, "Stale timestamp"
raw_body = request.get_data(cache=True, as_text=False) or b""
parsed = parse_qsl(request.query_string.decode(
"utf-8"), keep_blank_values=True)
# Canonicalize query parameters for consistent signature verification.
canonical_query = urlencode(
sorted(parsed, key=lambda x: x[0]), doseq=True, quote_via=strict_quote)
canonical_path = request.path + \
("?" + canonical_query if canonical_query else "")
msg = b"\n".join([
request.method.upper().encode(),
canonical_path.encode(),
ts.encode(),
nonce.encode(),
raw_body, # Include raw body to prevent payload tampering.
])
expected = hmac.new(api_key.encode(), msg, hashlib.sha256).hexdigest()
# Constant-time comparison to mitigate timing attacks.
if not hmac.compare_digest(sig, expected):
return False, "Bad signature"
db = get_db()
try:
db.execute("BEGIN IMMEDIATE") # Atomic nonce insertion.
db.execute("INSERT INTO request_nonces VALUES (?, ?, ?)",
(api_key, nonce, now()))
db.commit()
return True, None
except sqlite3.IntegrityError:
# Nonce already exists; replay attack detected.
try:
db.rollback()
except Exception:
pass
return False, "Replay detected"
except sqlite3.OperationalError:
try:
db.rollback()
except Exception:
pass
return False, "Database busy, please retry"
except Exception:
try:
db.rollback()
except Exception:
pass
return False, "Internal error during signature validation"
# =========================================================
# CLEANUP
# =========================================================
def archive_dead_letter(db, row, reason):
db.execute("""
INSERT OR REPLACE INTO dead_letters (
intent_id, namespace, goal, payload, publisher, visibility,
attempts, reason, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
row["id"],
row["namespace"],
row["goal"],
row["payload"],
row["publisher"],
row["visibility"],
row["claim_attempts"],
reason,
now(),
))
def run_cleanup_once():
db = None
stats = {
"expired_open_deleted": 0,
"expired_claims_requeued": 0,
"expired_claims_dead": 0,
"fulfilled_deleted": 0,
"dead_deleted": 0,
"dead_letters_deleted": 0,
"store_deleted": 0,
"rate_limits_deleted": 0,
"idempotency_deleted": 0,
"nonces_deleted": 0,
}
try:
db = sqlite3.connect(DB_PATH, timeout=30, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA journal_mode=WAL;")
db.execute("PRAGMA synchronous=NORMAL;")
db.execute("PRAGMA busy_timeout=30000;")
db.execute("PRAGMA foreign_keys=ON;")
t = now()
db.execute("BEGIN IMMEDIATE")
cur = db.execute("DELETE FROM store WHERE expires_at < ?", (t,))
stats["store_deleted"] = cur.rowcount
cur = db.execute(
"DELETE FROM rate_limits WHERE window < ?", (t - 3600,))
stats["rate_limits_deleted"] = cur.rowcount
cur = db.execute(
"DELETE FROM idempotency_keys WHERE created_at < ?", (t - 3600,))
stats["idempotency_deleted"] = cur.rowcount
cur = db.execute(
"DELETE FROM request_nonces WHERE created_at < ?", (t - NONCE_RETENTION_SECONDS,))
stats["nonces_deleted"] = cur.rowcount
cur = db.execute(
"DELETE FROM intents WHERE status='open' AND expires_at < ?", (t,))
stats["expired_open_deleted"] = cur.rowcount
expired_claims = db.execute("""
SELECT id, namespace, goal, payload, publisher, visibility,
claim_attempts, max_attempts, backoff_base, last_error
FROM intents
WHERE status='claimed'
AND COALESCE(claim_expires_at, claimed_at + ?) < ?
ORDER BY COALESCE(claim_expires_at, claimed_at) ASC
""", (DEFAULT_CLAIM_TIMEOUT, t)).fetchall()
for r in expired_claims:
if r["claim_attempts"] >= r["max_attempts"]:
db.execute("""
UPDATE intents
SET status='dead',
failed_at=?,
last_error=COALESCE(last_error, 'Max retries exceeded'),
claimed_at=NULL,
claim_expires_at=NULL,
claim_token=NULL,
result=NULL,
result_type=NULL,
completed_at=NULL
WHERE id=?
""", (t, r["id"]))
archive_dead_letter(db, {
"id": r["id"],
"namespace": r["namespace"],
"goal": r["goal"],
"payload": r["payload"],
"publisher": r["publisher"],
"visibility": r["visibility"],
"claim_attempts": r["claim_attempts"],
}, r["last_error"] or "Max retries exceeded")
stats["expired_claims_dead"] += 1
else:
jitter = random.uniform(0, 2)
next_run = t + (r["backoff_base"] *
(2 ** r["claim_attempts"])) + jitter
db.execute("""
UPDATE intents
SET status='open',
run_at=?,
claimed_by=NULL,
claimed_at=NULL,
claim_expires_at=NULL,
claim_token=NULL,
last_error=COALESCE(last_error, 'Lease expired. Backing off.'),
result=NULL,
result_type=NULL,
completed_at=NULL
WHERE id=?
""", (next_run, r["id"]))
stats["expired_claims_requeued"] += 1
cur = db.execute("DELETE FROM intents WHERE status='fulfilled' AND completed_at < ?",
(t - FULFILLED_RETENTION_SECONDS,))
stats["fulfilled_deleted"] = cur.rowcount
cur = db.execute(
"DELETE FROM intents WHERE status='dead' AND failed_at < ?", (t - DEAD_RETENTION_SECONDS,))
stats["dead_deleted"] = cur.rowcount
cur = db.execute(
"DELETE FROM dead_letters WHERE created_at < ?", (t - DEAD_RETENTION_SECONDS,))
stats["dead_letters_deleted"] = cur.rowcount
db.commit()
app.logger.info("cleanup_complete", extra=stats)
return True, stats
except sqlite3.OperationalError as e:
if not is_busy_or_locked(e):
app.logger.error(f"Cleanup failed (OperationalError): {e}")
if db:
try:
db.rollback()
except Exception:
pass
return False, stats
except Exception as e:
app.logger.error(f"Cleanup failed: {e}")
if db:
try:
db.rollback()
except Exception:
pass
return False, stats
finally:
if db:
try:
db.close()
except Exception:
pass
# =========================================================
# REQUEST LIFECYCLE
# =========================================================
@app.before_request
def security():
# Sanitize X-Request-ID to prevent log injection.
if getattr(g, "request_id", None) is None:
req_id = request.headers.get("X-Request-ID", "")
if re.match(r"^[a-zA-Z0-9_.:-]{1,128}$", req_id):
g.request_id = req_id
else:
g.request_id = uuid.uuid4().hex
g.request_start = time.perf_counter()
if request.path in ("/", "/health"):
return
if ENFORCE_HTTPS and not is_local() and not request.is_secure:
# Enforce HTTPS to prevent MitM attacks.
return api_error("https_required", "HTTPS required.", 403)
if request.path != "/admin/cleanup":
maybe_cleanup()
if request.path == "/metrics":
if not metrics_auth_ok():
return api_error("unauthorized", "Metrics access denied.", 401)
return
admin_path = request.path.startswith("/admin/")
if MAINTENANCE_MODE and not admin_path:
return api_error("maintenance", "Server in maintenance mode.", 503)
if admin_path:
return
key = request.headers.get("X-API-KEY")
if not key:
return api_error("unauthorized", "Missing API key.", 401)
role = get_role(key)
if not role:
return api_error("unauthorized", "Invalid API key.", 401)
g.api_key = key
g.role = role
has_sig_headers = bool(request.headers.get("X-Signature"))
if REQUIRE_SIGNATURES or has_sig_headers:
ok, err = verify_signed_request(key)
if not ok:
return api_error("invalid_signature", err, 403)
if role == "tester":
db = get_db()
t = now()
try:
db.execute("BEGIN IMMEDIATE")
row = db.execute(
"SELECT count, window FROM rate_limits WHERE identifier=?", (key,)).fetchone()
if not row or t - row["window"] > RATE_LIMIT_WINDOW:
db.execute(
"REPLACE INTO rate_limits VALUES (?, 1, ?)", (key, t))
elif row["count"] >= RATE_LIMIT_MAX:
db.rollback()
return api_error("rate_limited", "Too many requests.", 429)
else:
db.execute(
"UPDATE rate_limits SET count=count+1 WHERE identifier=?", (key,))
db.execute(
"UPDATE tester_keys SET total_requests=total_requests+1 WHERE api_key=?", (key,))
db.commit()
except sqlite3.OperationalError:
try:
db.rollback()
except Exception:
pass
return api_error("database_busy", "Database busy, please retry.", 503)
except Exception:
try:
db.rollback()
except Exception:
pass
return api_error("internal_error", "An internal error occurred.", 500)
@app.after_request
def log_response(response):
start_time = getattr(g, "request_start", None)
duration_ms = round((time.perf_counter() - start_time)
* 1000, 2) if start_time else 0.0
app.logger.info(
"request_complete",
extra={
"status_code": response.status_code,
"duration_ms": duration_ms,
},
)
# Standard security headers to prevent clickjacking, sniffing, and caching.
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "no-referrer"
response.headers["Cache-Control"] = "no-store"
response.headers["X-Intent-Version"] = "2.1"
return response
# =========================================================
# ROOT / HEALTH
# =========================================================
@app.route("/")
def index():
return "Intent Bus V7.61", 200
@app.route("/health")
def health():
return jsonify({"ok": True, "ts": now(), "version": "7.61"}), 200
# =========================================================
# DASHBOARD
# =========================================================
DASHBOARD_HTML = """
{% autoescape true %} {# Prevent XSS in rendered templates. #}
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Intent Bus Dashboard</title>
<style>
body { font-family: system-ui, sans-serif; background:#0d1117; color:#c9d1d9; padding:20px; }
h1,h2 { margin: 0.2em 0; }
.grid { display:grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap:12px; margin: 16px 0; }
.card { background:#161b22; border:1px solid #30363d; border-radius:12px; padding:12px; }
table { width:100%; border-collapse: collapse; margin-top: 10px; }
th, td { border-bottom:1px solid #30363d; padding:8px; text-align:left; font-size: 14px; }
code { background:#161b22; padding:2px 4px; border-radius:4px; }
.muted { color:#8b949e; font-size: 13px; }
</style>
</head>
<body>
<h1>Intent Bus</h1>
<div class="muted">Version {{ version }}</div>
<div class="muted">Dead letters: {{ stats.dead_letters }}</div>
<div class="grid">
<div class="card"><h2>{{ stats.open }}</h2><div>Open</div></div>
<div class="card"><h2>{{ stats.claimed }}</h2><div>Claimed</div></div>
<div class="card"><h2>{{ stats.fulfilled }}</h2><div>Fulfilled</div></div>
<div class="card"><h2>{{ stats.dead }}</h2><div>Dead</div></div>
</div>
<div class="card">
<h2>Recent Intents</h2>
<table>
<thead>
<tr>
<th>ID</th><th>Namespace</th><th>Goal</th><th>Status</th>
<th>Priority</th><th>Worker</th><th>Capability</th><th>Attempts</th>
</tr>
</thead>
<tbody>
{% for i in intents %}
<tr>
<td><code>{{ i.id }}</code></td>
<td>{{ i.namespace }}</td>
<td>{{ i.goal }}</td>
<td>{{ i.status }}</td>
<td>{{ i.priority }}</td>
<td>{{ i.target_worker or "" }}</td>
<td>{{ i.required_capability or "" }}</td>
<td>{{ i.claim_attempts }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card">
<h2>Tester Keys</h2>
<table>
<thead><tr><th>Owner</th><th>Requests</th><th>Created</th></tr></thead>
<tbody>
{% for k in keys %}
<tr>
<td>{{ k.owner }}</td>
<td>{{ k.total_requests }}</td>
<td>{{ k.created_at|int }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card">
<h2>Dead Letters</h2>
<table>
<thead><tr><th>Intent</th><th>Namespace</th><th>Goal</th><th>Attempts</th><th>Reason</th></tr></thead>
<tbody>
{% for d in dead %}
<tr>
<td><code>{{ d.intent_id }}</code></td>
<td>{{ d.namespace }}</td>
<td>{{ d.goal }}</td>
<td>{{ d.attempts }}</td>
<td>{{ d.reason }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
{% endautoescape %}
"""
@app.route("/admin/dashboard")
def admin_dashboard():
denied = require_admin()
if denied:
return denied
db = get_db()
stat_rows = db.execute("""
SELECT status, COUNT(*) AS c
FROM intents
GROUP BY status
""").fetchall()
stats = {
"open": 0,