-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
4646 lines (4077 loc) · 175 KB
/
api.py
File metadata and controls
4646 lines (4077 loc) · 175 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
"""
Haldir API Server — REST endpoints for Gate, Vault, Watch.
Minimal Flask app. No frontend. Just API.
Routes:
POST /v1/sessions — Create agent session
GET /v1/sessions/:id — Get session info
DELETE /v1/sessions/:id — Revoke session
POST /v1/sessions/:id/check — Check permission
POST /v1/secrets — Store a secret
GET /v1/secrets/:name — Retrieve a secret
DELETE /v1/secrets/:name — Delete a secret
GET /v1/secrets — List secret names
POST /v1/payments/authorize — Authorize a payment
POST /v1/audit — Log an action
GET /v1/audit — Query audit trail
GET /v1/audit/spend — Get spend summary
POST /v1/keys — Create API key (bootstrap)
GET /healthz — Health check
"""
import os
import json
import time
import uuid
import secrets
import hashlib
from functools import wraps
from flask import Flask, request, jsonify, abort, redirect, g, send_from_directory
from flask_cors import CORS
from haldir_db import init_db, get_db
from haldir_gate.gate import Gate
from haldir_vault.vault import Vault
from haldir_watch.watch import Watch
import haldir_idempotency
from haldir_logging import configure_logging, get_logger
from haldir_metrics import registry as prom_metrics
from haldir_validation import validate_body
from haldir_openapi import generate_openapi
from haldir_status import build_status
from haldir_scopes import require_scope
configure_logging()
log = get_logger("haldir.api")
# Platform metrics — declared once at module load, incremented in the
# before/after request hooks.
_M_REQUESTS = prom_metrics.counter(
"haldir_http_requests_total",
"Total HTTP requests the API has handled.",
label_names=("method", "path", "status"),
)
_M_DURATION = prom_metrics.histogram(
"haldir_http_request_duration_seconds",
"HTTP request duration (seconds) per route.",
label_names=("method", "path"),
)
_M_RL_HITS = prom_metrics.counter(
"haldir_rate_limit_exceeded_total",
"Requests rejected with 429 by the rate limiter.",
label_names=("tier",),
)
_M_IDEM_HITS = prom_metrics.counter(
"haldir_idempotency_hits_total",
"POSTs short-circuited by a prior Idempotency-Key match.",
label_names=("endpoint",),
)
_M_IDEM_MISMATCH = prom_metrics.counter(
"haldir_idempotency_mismatches_total",
"Idempotency-Key reused against a different body (422).",
label_names=("endpoint",),
)
# ── App setup ──
DB_PATH = os.environ.get("HALDIR_DB_PATH", "/data/haldir.db" if os.path.isdir("/data") else "haldir.db")
ENCRYPTION_KEY = os.environ.get("HALDIR_ENCRYPTION_KEY", "").encode() or None
app = Flask(__name__)
# Reject bodies larger than 1 MiB. Every Haldir POST body is a small
# JSON document — sessions, secrets, policy rules — so there's no
# legitimate reason to accept more. Oversize bodies are cheap DoS fodder
# (memory-amplification, slow JSON parse). Flask returns 413 automatically
# when this is exceeded; our error handler converts it to JSON.
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
CORS(app, resources={r"/v1/*": {"origins": "*"}, r"/mcp": {"origins": "*"}})
# Init DB on startup. init_db() creates tables via the legacy
# CREATE TABLE IF NOT EXISTS path, which is safe to keep as a belt-
# and-suspenders — the migrations runner becomes canonical going
# forward, but init_db() remains a no-op safety net for any table
# that doesn't yet have a migration covering it.
init_db(DB_PATH)
# Schema migrations. Under HALDIR_AUTO_MIGRATE=1 we apply every
# pending migration at import time so each gunicorn cold start
# converges to the declared schema. Under the default (off) the
# operator runs `python -m haldir_migrate up` explicitly — useful
# when deploys want migrations in a dedicated job before traffic
# reaches the workers.
if os.environ.get("HALDIR_AUTO_MIGRATE") == "1":
import haldir_migrate
_mig_summary = haldir_migrate.apply_pending(DB_PATH)
if _mig_summary["applied"] or _mig_summary["bootstrapped"]:
log.info("schema migrations run at boot", extra={
"applied": _mig_summary["applied"],
"bootstrapped": _mig_summary["bootstrapped"],
})
if _mig_summary["drift"]:
log.warning("schema migration drift detected", extra={
"drifted_versions": _mig_summary["drift"],
})
# Idempotency schema — retry-safe POST handling for /v1/audit and
# /v1/payments/authorize. See haldir_idempotency.py.
_idem_conn = get_db(DB_PATH)
try:
haldir_idempotency.init_schema(_idem_conn)
_idem_conn.commit()
finally:
_idem_conn.close()
# Init components
gate = Gate(db_path=DB_PATH)
vault = Vault(encryption_key=ENCRYPTION_KEY, db_path=DB_PATH)
watch = Watch(db_path=DB_PATH)
# Require encryption key in production
if not ENCRYPTION_KEY:
log.warning(
"no HALDIR_ENCRYPTION_KEY set — generated ephemeral key; secrets will be lost on restart",
)
# ── Idempotency helpers ────────────────────────────────────────────────
#
# Every mutating POST endpoint accepts an optional `Idempotency-Key`
# header. When present, the two helpers below gate handler execution so
# a second POST with the same (tenant, key, endpoint, body) returns the
# original response rather than re-processing. See haldir_idempotency.py.
#
# Usage inside an endpoint:
#
# @app.route("/v1/sessions", methods=["POST"])
# def create_session():
# data = request.json or {}
# tenant = getattr(request, "tenant_id", "")
# cached = _idempotency_lookup("/v1/sessions", data, tenant)
# if cached is not None:
# return cached
# ...do the work...
# _idempotency_store("/v1/sessions", data, tenant, response, status)
# return jsonify(response), status
def _idempotency_lookup(endpoint: str, body: dict, tenant: str):
"""Return (jsonify_response, status) to short-circuit the handler, or
None to proceed. Returns a 422 response if the caller reused a key
with a different body."""
idem_key = request.headers.get("Idempotency-Key")
if not idem_key:
return None
conn = get_db(DB_PATH)
try:
try:
hit = haldir_idempotency.lookup(
conn, tenant, idem_key, endpoint, body,
)
if hit is not None:
_M_IDEM_HITS.inc(endpoint=endpoint)
return jsonify(hit.body), hit.status
except haldir_idempotency.IdempotencyMismatch as e:
_M_IDEM_MISMATCH.inc(endpoint=endpoint)
return jsonify({"error": str(e)}), 422
finally:
conn.close()
return None
def _idempotency_store(endpoint: str, body: dict, tenant: str,
response: dict, status: int) -> None:
"""Cache a response for future retries with the same Idempotency-Key.
No-op when the header is absent."""
idem_key = request.headers.get("Idempotency-Key")
if not idem_key:
return
conn = get_db(DB_PATH)
try:
haldir_idempotency.store(
conn, tenant, idem_key, endpoint, body, response, status,
)
conn.commit()
finally:
conn.close()
# ── Platform middleware ────────────────────────────────────────────────
#
# Three cross-cutting concerns applied to every HTTP request:
#
# 1. Request-ID propagation — every request gets a UUID (or echoes the
# caller's X-Request-ID header). Returned on every response so users
# can correlate client logs to server logs, and embedded in JSON
# error bodies so bug reports always carry a traceable identifier.
#
# 2. Security headers — HSTS, X-Content-Type-Options, Referrer-Policy,
# X-Frame-Options. Cheap, standards-based defenses that browsers
# enforce on the client side. Applied to all responses.
#
# 3. Rate-limit headers — Stripe/GitHub-style X-RateLimit-Limit,
# X-RateLimit-Remaining, X-RateLimit-Reset so clients can budget
# their traffic before hitting a 429.
#
# JSON error handlers below replace Flask's default HTML error pages so
# API clients always receive a parseable body.
SECURITY_HEADERS = {
# HSTS: force HTTPS for a year + subdomains. Tell browsers never to
# downgrade to plaintext for haldir.xyz.
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
# Stop MIME-type sniffing; browsers must honor our Content-Type.
"X-Content-Type-Options": "nosniff",
# Deny framing — nothing on Haldir should be embedded in an iframe.
"X-Frame-Options": "DENY",
# Don't leak the full URL (which may carry session IDs) to off-site
# resources. Stripe uses the same policy.
"Referrer-Policy": "strict-origin-when-cross-origin",
# Disable unused browser features for API responses (defense in depth).
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
}
@app.before_request
def _platform_before() -> None:
"""Attach per-request state: request_id + start timestamp."""
# Honor an inbound X-Request-ID from load balancers / gateways so a
# single ID flows across the whole stack. Cap length defensively to
# avoid header-injection tricks.
incoming = (request.headers.get("X-Request-ID") or "").strip()[:64]
g.request_id = incoming or uuid.uuid4().hex
g.request_start = time.time()
@app.after_request
def _platform_after(response): # type: ignore[no-untyped-def]
"""Emit request-ID, security, and rate-limit headers, then access log."""
response.headers["X-Request-ID"] = getattr(g, "request_id", "")
for k, v in SECURITY_HEADERS.items():
response.headers.setdefault(k, v)
# Rate-limit headers. Two bucket dimensions, each with its own full
# surface so a client hitting the 429 can tell which limit fired and
# when to retry:
#
# X-RateLimit-* — the short (hourly) window
# X-RateLimit-Monthly-* — the subscription-tier quota
# X-RateLimit-Resource — which bucket this response
# pertains to ("hourly" | "monthly")
# Retry-After — RFC 7231 seconds-until-retry,
# set only on 429 responses
#
# Populated by the rate_limit before_request hook below when the
# request was authenticated. Missing on unauthenticated requests
# (health checks, bootstrap) — clients don't need them there.
rl = getattr(g, "rate_limit", None)
if rl:
response.headers["X-RateLimit-Limit"] = str(rl["limit"])
response.headers["X-RateLimit-Remaining"] = str(max(0, rl["remaining"]))
response.headers["X-RateLimit-Used"] = str(rl["used"])
response.headers["X-RateLimit-Reset"] = str(rl["reset"])
response.headers["X-RateLimit-Reset-After"] = str(max(0, rl["reset_after"]))
response.headers["X-RateLimit-Resource"] = rl.get("resource", "hourly")
rlm = getattr(g, "rate_limit_monthly", None)
if rlm:
response.headers["X-RateLimit-Monthly-Limit"] = str(rlm["limit"])
response.headers["X-RateLimit-Monthly-Remaining"] = str(max(0, rlm["remaining"]))
response.headers["X-RateLimit-Monthly-Used"] = str(rlm["used"])
response.headers["X-RateLimit-Monthly-Reset"] = str(rlm["reset"])
response.headers["X-RateLimit-Monthly-Reset-After"] = str(max(0, rlm["reset_after"]))
retry_after = getattr(g, "retry_after", None)
if retry_after is not None and response.status_code == 429:
response.headers["Retry-After"] = str(max(1, int(retry_after)))
# Metrics + structured access log.
start = getattr(g, "request_start", None)
duration_s = (time.time() - start) if start else None
# Use the matched URL rule (e.g. `/v1/sessions/<id>/check`) rather
# than the raw path so metric cardinality stays bounded — otherwise
# every UUID in a URL produces a new time series.
rule = getattr(request.url_rule, "rule", None)
metric_path = rule or "unmatched"
_M_REQUESTS.inc(
method=request.method,
path=metric_path,
status=str(response.status_code),
)
if duration_s is not None:
_M_DURATION.observe(duration_s, method=request.method, path=metric_path)
# Skip /healthz access logs by default (noisy, uninteresting) —
# flip HALDIR_LOG_HEALTHZ=1 to include them.
if request.path != "/healthz" or os.environ.get("HALDIR_LOG_HEALTHZ") == "1":
log.info(
"request",
extra={
"method": request.method,
"path": request.path,
"status": response.status_code,
"duration_ms": int(duration_s * 1000) if duration_s is not None else None,
"remote_addr": request.remote_addr,
"user_agent": request.headers.get("User-Agent", "")[:120],
},
)
return response
def _json_error(code: str, message: str, status: int, **extra): # type: ignore[no-untyped-def]
"""Uniform error envelope: machine-readable `code` + human `error` +
request_id so support requests are always traceable."""
payload = {
"error": message,
"code": code,
"request_id": getattr(g, "request_id", ""),
}
payload.update(extra)
return jsonify(payload), status
@app.errorhandler(404)
def _err_404(_e): # type: ignore[no-untyped-def]
return _json_error("not_found", "Endpoint not found", 404)
@app.errorhandler(405)
def _err_405(_e): # type: ignore[no-untyped-def]
return _json_error("method_not_allowed", "Method not allowed for this endpoint", 405)
@app.errorhandler(413)
def _err_413(_e): # type: ignore[no-untyped-def]
return _json_error(
"payload_too_large",
"Request body exceeds 1 MiB limit",
413,
max_bytes=app.config["MAX_CONTENT_LENGTH"],
)
@app.errorhandler(500)
def _err_500(e): # type: ignore[no-untyped-def]
# Log the stack server-side with full context; never leak it to clients.
log.exception(
"unhandled exception",
extra={"method": request.method, "path": request.path},
)
return _json_error("internal_error", "Internal server error", 500)
# ── Billing tier limits ──
TIER_LIMITS = {
"free": {"agents": 1, "actions_per_month": 1_000},
"pro": {"agents": 10, "actions_per_month": 50_000},
"enterprise": {"agents": 999_999, "actions_per_month": 999_999_999},
}
STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "")
STRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET", "")
STRIPE_PRICE_PRO = os.environ.get("STRIPE_PRICE_PRO", "")
STRIPE_PRICE_ENTERPRISE = os.environ.get("STRIPE_PRICE_ENTERPRISE", "")
# ── API Key auth ──
def _hash_key(key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()
def require_api_key(f):
@wraps(f)
def decorated(*args, **kwargs):
key = request.headers.get("Authorization", "").replace("Bearer ", "")
if not key:
key = request.headers.get("X-API-Key", "")
if not key:
return jsonify({"error": "Missing API key. Pass via Authorization: Bearer <key> or X-API-Key header."}), 401
key_hash = _hash_key(key)
conn = get_db(DB_PATH)
row = conn.execute("SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0", (key_hash,)).fetchone()
if row:
conn.execute("UPDATE api_keys SET last_used = ? WHERE key_hash = ?", (time.time(), key_hash))
conn.commit()
conn.close()
if not row:
return jsonify({"error": "Invalid or revoked API key."}), 401
request.api_key_tier = row["tier"]
request.api_key_name = row["name"]
try:
request.tenant_id = row["tenant_id"] or key_hash[:16]
except (IndexError, KeyError):
request.tenant_id = key_hash[:16]
# Scopes — defaults to wildcard for legacy rows that pre-date
# migration 003. The decorator @require_scope reads this list
# off `request.api_key_scopes` when gating individual endpoints.
import haldir_scopes
try:
request.api_key_scopes = haldir_scopes.parse(row["scopes"])
except (IndexError, KeyError):
request.api_key_scopes = [haldir_scopes.WILDCARD]
return f(*args, **kwargs)
return decorated
def _get_tenant_tier(tenant_id):
"""Get the effective billing tier for a tenant from subscriptions table."""
conn = get_db(DB_PATH)
row = conn.execute(
"SELECT tier, status FROM subscriptions WHERE tenant_id = ?",
(tenant_id,)
).fetchone()
conn.close()
if row and row["status"] == "active":
return row["tier"]
return "free"
def _get_tenant_agent_count(tenant_id):
"""Count distinct agents with active sessions for a tenant."""
conn = get_db(DB_PATH)
count = conn.execute(
"SELECT COUNT(DISTINCT agent_id) FROM sessions WHERE tenant_id = ? AND revoked = 0 AND (expires_at = 0 OR expires_at > ?)",
(tenant_id, time.time())
).fetchone()[0]
conn.close()
return count
def _get_tenant_monthly_actions(tenant_id):
"""Get action count for current month."""
month = time.strftime("%Y-%m")
conn = get_db(DB_PATH)
row = conn.execute(
"SELECT action_count FROM usage WHERE tenant_id = ? AND month = ?",
(tenant_id, month)
).fetchone()
conn.close()
return row["action_count"] if row else 0
# ── Bootstrap: create first API key ──
@app.route("/v1/keys", methods=["POST"])
def create_api_key():
"""Create an API key. First key requires HALDIR_BOOTSTRAP_TOKEN env var."""
conn = get_db(DB_PATH)
key_count = conn.execute("SELECT COUNT(*) FROM api_keys WHERE revoked = 0").fetchone()[0]
conn.close()
# First key is free; subsequent keys need auth. When authed,
# the new key inherits the caller's tenant_id so a tenant admin
# can mint sub-keys (read-only SIEM key, CI deploy key, etc.)
# under their existing tenant — that's the multi-key, single-
# tenant pattern every Stripe-shaped API ships.
inherited_tenant: str | None = None
if key_count > 0:
key = request.headers.get("Authorization", "").replace("Bearer ", "") or request.headers.get("X-API-Key", "")
bootstrap = os.environ.get("HALDIR_BOOTSTRAP_TOKEN", "")
if key:
key_hash = _hash_key(key)
conn = get_db(DB_PATH)
row = conn.execute("SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0", (key_hash,)).fetchone()
conn.close()
if not row:
return jsonify({"error": "Invalid API key"}), 401
inherited_tenant = row["tenant_id"] or None
elif bootstrap and request.json and request.json.get("bootstrap_token") == bootstrap:
pass
else:
return jsonify({"error": "Authentication required to create additional keys"}), 401
data = request.json or {}
# Pre-auth endpoint (bootstrap) so there's no tenant yet — cache under
# the empty tenant string; Idempotency-Keys are UUIDv4 so collision
# risk across callers is negligible.
cached = _idempotency_lookup("/v1/keys", data, "")
if cached is not None:
return cached
name = data.get("name", "default")
tier = "free" # Always free on creation — only Stripe webhooks can upgrade
# Per-key scopes. Default to wildcard for back-compat with every
# existing client that doesn't pass `scopes`. Validate aggressively
# so a typo like "aduit:read" fails fast with a 400 rather than
# silently locking the holder out.
import haldir_scopes
try:
requested_scopes = haldir_scopes.parse(data.get("scopes"))
validated_scopes = haldir_scopes.validate(requested_scopes)
except haldir_scopes.ScopeValidationError as e:
return jsonify({"error": str(e), "code": "invalid_scope"}), 400
full_key = f"hld_{secrets.token_urlsafe(32)}"
key_hash = _hash_key(full_key)
# Inherit caller's tenant so sub-keys live under the same tenant;
# only the very first / bootstrap key starts a fresh one.
tenant_id = inherited_tenant or key_hash[:16]
conn = get_db(DB_PATH)
conn.execute(
"INSERT INTO api_keys (key_hash, key_prefix, tenant_id, name, tier, "
"scopes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(key_hash, full_key[:12], tenant_id, name, tier,
haldir_scopes.serialize(validated_scopes), time.time()),
)
conn.commit()
conn.close()
response = {
"key": full_key,
"prefix": full_key[:12],
"name": name,
"tier": tier,
"scopes": validated_scopes,
"message": "Save this key — it won't be shown again.",
}
_idempotency_store("/v1/keys", data, "", response, 201)
return jsonify(response), 201
# ── Key admin lifecycle (list + revoke) ─────────────────────────────
@app.route("/v1/keys", methods=["GET"])
@require_api_key
@require_scope("admin:read")
def list_api_keys():
"""List every API key registered against the authed tenant.
Returns prefix (the first 12 chars — safe to display, can't be
used to authenticate), name, tier, scopes, created_at, last_used,
revoked. The full key is never returned — once minted, it lives
only on the holder's machine.
This is the operational surface every security review asks for:
'who can hit our API right now?' answered without a DB shell."""
tenant = getattr(request, "tenant_id", "")
conn = get_db(DB_PATH)
rows = conn.execute(
"SELECT key_prefix, name, tier, scopes, created_at, "
"last_used, revoked FROM api_keys WHERE tenant_id = ? "
"ORDER BY created_at DESC",
(tenant,),
).fetchall()
conn.close()
keys = []
for r in rows:
try:
scopes = json.loads(r["scopes"]) if "scopes" in r.keys() else ["*"]
except (TypeError, json.JSONDecodeError):
scopes = ["*"]
keys.append({
"prefix": r["key_prefix"],
"name": r["name"],
"tier": r["tier"],
"scopes": scopes,
"created_at": r["created_at"],
"last_used": r["last_used"],
"revoked": bool(r["revoked"]),
})
return jsonify({"keys": keys, "count": len(keys)})
@app.route("/v1/keys/<prefix>", methods=["DELETE"])
@require_api_key
@require_scope("admin:write")
def revoke_api_key(prefix: str):
"""Revoke a key by its 12-char prefix.
Tenant-scoped: a tenant can only revoke their own keys. Returns
404 if the prefix doesn't exist within the authed tenant.
The currently-authed key can revoke itself — useful for the "I
just found this in a public commit, kill it now" flow without
needing to mint another key first.
"""
if not prefix or len(prefix) > 64:
return _json_error("invalid_prefix",
"prefix must be 1-64 chars", 400)
tenant = getattr(request, "tenant_id", "")
conn = get_db(DB_PATH)
row = conn.execute(
"SELECT key_hash FROM api_keys WHERE key_prefix = ? "
"AND tenant_id = ? AND revoked = 0",
(prefix, tenant),
).fetchone()
if not row:
conn.close()
return _json_error("not_found",
"no active key with that prefix in this tenant",
404)
conn.execute(
"UPDATE api_keys SET revoked = 1 WHERE key_hash = ?",
(row["key_hash"],),
)
conn.commit()
conn.close()
return jsonify({"revoked": True, "prefix": prefix}), 200
@app.route("/v1/demo/key", methods=["POST"])
def create_demo_key():
"""Create a temporary demo API key for the landing page. No auth required."""
try:
full_key = f"hld_{secrets.token_urlsafe(32)}"
key_hash = _hash_key(full_key)
tenant_id = f"demo_{key_hash[:12]}"
conn = get_db(DB_PATH)
conn.execute(
"INSERT INTO api_keys (key_hash, key_prefix, tenant_id, name, tier, created_at) VALUES (?, ?, ?, ?, ?, ?)",
(key_hash, full_key[:12], tenant_id, "landing-demo", "free", time.time())
)
conn.commit()
conn.close()
return jsonify({
"key": full_key,
"prefix": full_key[:12],
"name": "landing-demo",
"tier": "free",
}), 201
except Exception:
log.exception("demo key creation failed")
return jsonify({"error": "Demo temporarily unavailable. Try again in a moment."}), 503
# ── Gate: Sessions ──
@app.route("/v1/sessions", methods=["POST"])
@require_api_key
@validate_body({
"agent_id": {"type": str, "required": True, "maxlen": 128},
"scopes": {"type": list, "default": ["read", "browse"]},
"ttl": {"type": int, "default": 3600, "min": 0, "max": 86400 * 30},
"spend_limit": {"type": float, "default": None, "min": 0},
})
def create_session():
data = request.validated
agent_id = data["agent_id"]
scopes = data["scopes"]
ttl = data["ttl"]
spend_limit = data["spend_limit"]
tenant = getattr(request, "tenant_id", "")
cached = _idempotency_lookup("/v1/sessions", data, tenant)
if cached is not None:
return cached
# Enforce agent limit per billing tier
tier = _get_tenant_tier(tenant)
limits = TIER_LIMITS.get(tier, TIER_LIMITS["free"])
current_agents = _get_tenant_agent_count(tenant)
# Only count as new agent if this agent_id doesn't already have an active session
conn = get_db(DB_PATH)
existing = conn.execute(
"SELECT COUNT(*) FROM sessions WHERE tenant_id = ? AND agent_id = ? AND revoked = 0 AND (expires_at = 0 OR expires_at > ?)",
(tenant, agent_id, time.time())
).fetchone()[0]
conn.close()
if existing == 0 and current_agents >= limits["agents"]:
return jsonify({
"error": "Agent limit reached for your tier",
"tier": tier,
"limit": limits["agents"],
"current": current_agents,
"upgrade": "https://haldir.xyz/pricing",
}), 403
gate.register_agent(agent_id, default_scopes=scopes, tenant_id=tenant)
session = gate.create_session(agent_id, scopes=scopes, ttl=ttl, spend_limit=spend_limit, tenant_id=tenant)
response = {
"session_id": session.session_id,
"agent_id": session.agent_id,
"scopes": session.scopes,
"spend_limit": session.spend_limit,
"expires_at": session.expires_at,
"ttl": ttl,
}
_idempotency_store("/v1/sessions", data, tenant, response, 201)
return jsonify(response), 201
@app.route("/v1/sessions/<session_id>", methods=["GET"])
@require_api_key
@require_scope("sessions:read")
def get_session(session_id):
tenant = getattr(request, "tenant_id", "")
session = gate.get_session(session_id, tenant_id=tenant)
if not session:
return jsonify({"error": "Session not found or expired"}), 404
return jsonify({
"session_id": session.session_id,
"agent_id": session.agent_id,
"scopes": session.scopes,
"spend_limit": session.spend_limit,
"spent": session.spent,
"remaining_budget": session.remaining_budget,
"is_valid": session.is_valid,
"created_at": session.created_at,
"expires_at": session.expires_at,
})
@app.route("/v1/sessions/<session_id>", methods=["DELETE"])
@require_api_key
@require_scope("sessions:write")
def revoke_session(session_id):
tenant = getattr(request, "tenant_id", "")
revoked = gate.revoke_session(session_id, tenant_id=tenant)
if not revoked:
return jsonify({"error": "Session not found"}), 404
return jsonify({"revoked": True, "session_id": session_id})
@app.route("/v1/sessions/<session_id>/check", methods=["POST"])
@require_api_key
@require_scope("sessions:read")
def check_permission(session_id):
data = request.json or {}
scope = data.get("scope")
if not scope:
return jsonify({"error": "scope is required"}), 400
tenant = getattr(request, "tenant_id", "")
allowed = gate.check_permission(session_id, scope, tenant_id=tenant)
return jsonify({"allowed": allowed, "session_id": session_id, "scope": scope})
# ── Vault: Secrets ──
@app.route("/v1/secrets", methods=["POST"])
@require_api_key
@require_scope("vault:write")
def store_secret():
data = request.json or {}
name = data.get("name")
value = data.get("value")
if not name or not value:
return jsonify({"error": "name and value are required"}), 400
tenant = getattr(request, "tenant_id", "")
cached = _idempotency_lookup("/v1/secrets", data, tenant)
if cached is not None:
return cached
scope_required = data.get("scope_required", "read")
vault.store_secret(name, value, scope_required=scope_required, tenant_id=tenant)
response = {"stored": True, "name": name}
_idempotency_store("/v1/secrets", data, tenant, response, 201)
return jsonify(response), 201
@app.route("/v1/secrets/<name>", methods=["GET"])
@require_api_key
@require_scope("vault:read")
def get_secret(name):
tenant = getattr(request, "tenant_id", "")
session_id = request.headers.get("X-Session-ID") or request.args.get("session_id")
if not session_id:
return jsonify({"error": "X-Session-ID header or session_id param required to access secrets"}), 400
session = gate.get_session(session_id, tenant_id=tenant)
if not session:
return jsonify({"error": "Invalid or expired session"}), 401
try:
value = vault.get_secret(name, session=session, tenant_id=tenant)
except PermissionError as e:
return jsonify({"error": str(e)}), 403
if value is None:
return jsonify({"error": f"Secret '{name}' not found"}), 404
return jsonify({"name": name, "value": value})
@app.route("/v1/secrets/<name>", methods=["DELETE"])
@require_api_key
@require_scope("vault:write")
def delete_secret(name):
tenant = getattr(request, "tenant_id", "")
deleted = vault.delete_secret(name, tenant_id=tenant)
if not deleted:
return jsonify({"error": f"Secret '{name}' not found"}), 404
return jsonify({"deleted": True, "name": name})
@app.route("/v1/secrets", methods=["GET"])
@require_api_key
@require_scope("vault:read")
def list_secrets():
tenant = getattr(request, "tenant_id", "")
names = vault.list_secrets(tenant_id=tenant)
return jsonify({"secrets": names, "count": len(names)})
# ── Vault: Payments ──
@app.route("/v1/payments/authorize", methods=["POST"])
@require_api_key
@validate_body({
"session_id": {"type": str, "required": True, "maxlen": 128},
# Minimum 1 cent, maximum $1M per single authorization — guards
# against fat-finger disasters and still leaves headroom for
# enterprise purchases.
"amount": {"type": float, "required": True, "min": 0.01, "max": 1_000_000},
"currency": {"type": str, "default": "USD", "maxlen": 8},
"description": {"type": str, "default": "", "maxlen": 500},
})
def authorize_payment():
data = request.validated
session_id = data["session_id"]
amount = data["amount"]
tenant = getattr(request, "tenant_id", "")
cached = _idempotency_lookup("/v1/payments/authorize", data, tenant)
if cached is not None:
return cached
session = gate.get_session(session_id, tenant_id=tenant)
if not session:
return jsonify({"error": "Invalid or expired session"}), 401
result = vault.authorize_payment(
session, amount,
currency=data["currency"],
description=data["description"],
)
status = 200 if result["authorized"] else 403
_idempotency_store("/v1/payments/authorize", data, tenant, result, status)
return jsonify(result), status
# ── Watch: Audit ──
@app.route("/v1/audit", methods=["POST"])
@require_api_key
@require_scope("audit:write")
def log_action():
data = request.json or {}
session_id = data.get("session_id")
tool = data.get("tool", "")
action = data.get("action", "")
if not session_id or not action:
return jsonify({"error": "session_id and action are required"}), 400
cost_usd = data.get("cost_usd", 0)
try:
cost_usd = float(cost_usd)
except (TypeError, ValueError):
return jsonify({"error": "cost_usd must be a number"}), 400
if cost_usd < 0:
return jsonify({"error": "cost_usd must be non-negative"}), 400
tenant = getattr(request, "tenant_id", "")
cached = _idempotency_lookup("/v1/audit", data, tenant)
if cached is not None:
return cached
session = gate.get_session(session_id, tenant_id=tenant)
if not session:
return jsonify({"error": "Invalid or expired session"}), 401
entry = watch.log_action(
session, tool=tool, action=action,
details=data.get("details"),
cost_usd=cost_usd,
tenant_id=tenant,
)
response = {
"logged": True,
"entry_id": entry.entry_id,
"flagged": entry.flagged,
"flag_reason": entry.flag_reason,
}
_idempotency_store("/v1/audit", data, tenant, response, 201)
return jsonify(response), 201
@app.route("/v1/audit", methods=["GET"])
@require_api_key
@require_scope("audit:read")
def get_audit_trail():
tenant = getattr(request, "tenant_id", "")
entries = watch.get_audit_trail(
session_id=request.args.get("session_id"),
agent_id=request.args.get("agent_id"),
tool=request.args.get("tool"),
flagged_only=request.args.get("flagged") == "true",
limit=int(request.args.get("limit", 100)),
tenant_id=tenant,
)
return jsonify({
"count": len(entries),
"entries": [
{
"entry_id": e.entry_id,
"session_id": e.session_id,
"agent_id": e.agent_id,
"tool": e.tool,
"action": e.action,
"cost_usd": e.cost_usd,
"flagged": e.flagged,
"flag_reason": e.flag_reason,
"timestamp": e.timestamp,
"details": e.details,
"prev_hash": e.prev_hash,
"entry_hash": e.entry_hash,
}
for e in entries
],
})
@app.route("/v1/audit/spend", methods=["GET"])
@require_api_key
@require_scope("audit:read")
def get_spend():
tenant = getattr(request, "tenant_id", "")
return jsonify(watch.get_spend(
session_id=request.args.get("session_id"),
agent_id=request.args.get("agent_id"),
tenant_id=tenant,
))
@app.route("/v1/audit/verify", methods=["GET"])
@require_api_key
@require_scope("audit:read")
def verify_audit_chain():
"""Verify the cryptographic integrity of the audit log hash chain."""
tenant = getattr(request, "tenant_id", "")
result = watch.verify_chain(tenant_id=tenant)
return jsonify(result)
# ── Audit export (compliance / SIEM / archival) ─────────────────────────
#
# Two endpoints. The first streams the trail in CSV or JSONL; the second
# returns the same integrity manifest without the body, for consumers
# who verify out-of-band. Both share an ExportFilters object so the
# OpenAPI contract stays in lock-step.
def _parse_export_filters() -> "haldir_export.ExportFilters":
from haldir_export import ExportFilters
def _f(k: str) -> float | None:
v = request.args.get(k)
if not v:
return None
try:
# Accept both unix seconds and ISO 8601.
return float(v)
except ValueError:
try:
from datetime import datetime
return datetime.fromisoformat(v.replace("Z", "+00:00")).timestamp()
except ValueError:
return None
return ExportFilters(
session_id=request.args.get("session_id"),
agent_id=request.args.get("agent_id"),
tool=request.args.get("tool"),
since=_f("since"),
until=_f("until"),
flagged_only=request.args.get("flagged") == "true",