-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1965 lines (1788 loc) · 73.9 KB
/
api.py
File metadata and controls
1965 lines (1788 loc) · 73.9 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
"""
api.py — PeerGlass REST API
============================
A thin FastAPI wrapper around the same rir_client.py logic that powers
the MCP server. This makes every tool available as a plain HTTP endpoint,
compatible with any LLM (OpenAI function calling, Gemini tool use, etc.),
any HTTP client, or any browser.
Architecture:
┌─────────────────────────────────────┐
│ Your Code / LLM │
│ (Claude, OpenAI, Gemini, curl, ...) │
└──────────────┬──────────────────────┘
│ HTTP REST
▼
┌─────────────────────────────────────┐
│ api.py (FastAPI) │
│ /v1/ip /v1/asn /v1/health ... │
└──────────────┬──────────────────────┘
│ Python call (same code)
▼
┌─────────────────────────────────────┐
│ rir_client.py (shared logic) │
│ RDAP · RPKI · BGP · PeeringDB · ... │
└─────────────────────────────────────┘
Running locally:
uvicorn api:app --host 0.0.0.0 --port 8000 --reload
Interactive docs (auto-generated by FastAPI):
http://localhost:8000/docs ← Swagger UI
http://localhost:8000/redoc ← ReDoc
All endpoints accept ?format=markdown (default) or ?format=json
"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from fastapi import FastAPI, Query, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, PlainTextResponse
from pydantic import BaseModel, Field
from typing import Optional
import asyncio
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
def _real_ip(request: Request) -> str:
"""
Extract the real client IP, respecting X-Forwarded-For and X-Real-IP
headers set by reverse proxies (Render, nginx, Cloudflare, etc.).
Falls back to direct connection address if no proxy headers are present.
"""
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
return forwarded_for.split(",")[0].strip()
real_ip = request.headers.get("X-Real-IP")
if real_ip:
return real_ip.strip()
return get_remote_address(request)
limiter = Limiter(key_func=_real_ip)
import rir_client
import cache as cache_module
from formatters import (
format_ip_results_md,
format_asn_results_md,
format_abuse_contact_md,
format_rpki_result_md,
format_bgp_status_md,
format_org_audit_md,
format_prefix_history_md,
format_transfer_detect_md,
format_ipv4_stats_md,
format_prefix_overview_md,
format_peering_info_md,
format_ixp_lookup_md,
format_network_health_md,
format_change_monitor_md,
format_dns_resolve_md,
format_dns_enumerate_md,
format_dns_dnssec_md,
format_dns_dnsbl_md,
format_email_security_md,
format_dns_propagation_md,
format_tls_inspect_md,
format_ct_logs_md,
format_threat_intel_md,
format_passive_dns_md,
format_irr_result_md,
format_route_leak_md,
format_looking_glass_md,
format_route_stability_md,
format_shutdown_detect_md,
format_monitor_register_md,
format_shutdown_timeline_md,
format_censorship_probe_md,
format_satellite_connectivity_md,
format_chokepoints_md,
format_ooni_report_md,
format_country_health_md,
format_as_relationships_md,
format_geo_lookup_md,
format_atlas_trace_md,
to_json,
)
from normalizer import normalize_ip_response, normalize_asn_response
from models import (
AbuseContact, OrgAuditResult,
ResponseFormat,
DNSResolveInput, DNSEnumerateInput, DNSSECInput,
DNSBLInput, EmailSecurityInput, DNSPropagationInput,
TLSInspectInput, CTLogInput, ThreatIntelInput, PassiveDNSInput,
MonitorRegisterInput,
)
# ──────────────────────────────────────────────────────────────
# App setup
# ──────────────────────────────────────────────────────────────
app = FastAPI(
title="PeerGlass API",
description=(
"Universal REST API for internet resource intelligence. "
"Query all 5 RIRs (AFRINIC, APNIC, ARIN, LACNIC, RIPE), "
"validate RPKI routes, check BGP status, look up PeeringDB, "
"trace allocation history, and monitor resources for changes.\n\n"
"Compatible with any HTTP client, LLM function-calling interface "
"(OpenAI, Gemini, Claude), or browser.\n\n"
"Source: https://github.com/peerglass/peerglass "
"| License: MIT"
),
version="1.0.0",
contact={
"name": "PeerGlass",
"url": "https://peerglass.io",
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT",
},
)
# B1 — Rate limiting: protects upstream RIRs from being hammered by abusive clients.
# Default: 60 req/min per IP. Heavy endpoints (org audit, health) use 10/min.
# Override with PEERGLASS_RATE_LIMIT env var (e.g. "120/minute").
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
_DEFAULT_RATE = os.environ.get("PEERGLASS_RATE_LIMIT", "60/minute")
_HEAVY_RATE = os.environ.get("PEERGLASS_RATE_LIMIT_HEAVY", "10/minute")
# B2 — CORS: restrict allowed origins in production via env var.
# Set PEERGLASS_ALLOWED_ORIGINS="https://yourdomain.com,https://other.com"
# Defaults to "*" (open) when env var is absent — suitable for local/demo use.
_cors_env = os.environ.get("PEERGLASS_ALLOWED_ORIGINS", "")
_cors_origins = [o.strip() for o in _cors_env.split(",") if o.strip()] if _cors_env else ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
# ──────────────────────────────────────────────────────────────
# Helpers
# ──────────────────────────────────────────────────────────────
FORMAT_QUERY = Query(
default="markdown",
description="Response format: 'markdown' for human-readable, 'json' for machine-readable",
pattern="^(markdown|json)$",
)
def _resp(md: str, jsn: str, fmt: str):
"""Return markdown as plain text or json as JSON based on format param."""
if fmt == "json":
import json
try:
return JSONResponse(content=json.loads(jsn))
except Exception:
return JSONResponse(content={"raw": jsn})
return PlainTextResponse(content=md, media_type="text/markdown")
# ──────────────────────────────────────────────────────────────
# Root + Health
# ──────────────────────────────────────────────────────────────
@app.get("/", tags=["Meta"], summary="API root — links to docs")
async def root():
return {
"name": "PeerGlass API",
"version": "1.0.0",
"description": "Internet resource intelligence: RIR + BGP + RPKI + PeeringDB",
"docs": "/docs",
"redoc": "/redoc",
"tools": 42,
"endpoints": {
"ip": "/v1/ip/{ip}",
"asn": "/v1/asn/{asn}",
"abuse": "/v1/abuse/{ip}",
"rpki": "/v1/rpki?prefix=...&asn=...",
"bgp": "/v1/bgp/{resource}",
"announced": "/v1/announced/{asn}",
"org": "/v1/org?name=...",
"history": "/v1/history/{resource}",
"transfers": "/v1/transfers/{resource}",
"ipv4stats": "/v1/stats/ipv4",
"overview": "/v1/overview/{prefix}",
"peering": "/v1/peering/{asn}",
"ixp": "/v1/ixp?query=...",
"health": "/v1/health/{resource}",
"monitor": "/v1/monitor/{resource}",
"dns_resolve": "/v1/dns/resolve/{target}",
"dns_enumerate": "/v1/dns/enumerate/{domain}",
"dns_dnssec": "/v1/dns/dnssec/{domain}",
"dns_dnsbl": "/v1/dns/dnsbl/{ip}",
"dns_email": "/v1/dns/email/{domain}",
"dns_propagation": "/v1/dns/propagation/{domain}",
"tls": "/v1/tls/{hostname}",
"ct_logs": "/v1/ct/{domain}",
"threat_intel": "/v1/threat/{ip}",
"passive_dns": "/v1/pdns/{resource}",
"irr": "/v1/irr?prefix=...&asn=...",
"route_leak": "/v1/route-leak/{prefix}",
"looking_glass": "/v1/looking-glass/{prefix}",
"route_stability": "/v1/stability/{prefix}",
"shutdown": "/v1/shutdown/{country_code}",
"shutdown_monitor":"/v1/shutdown/monitor",
"shutdown_timeline":"/v1/shutdown/timeline/{resource}",
"dns_censorship": "/v1/censorship/{domain}",
"satellite": "/v1/satellite/{country_code}",
"chokepoints": "/v1/chokepoints/{country_code}",
"ooni": "/v1/ooni/{country_code}",
"country_health": "/v1/health/country/{country_code}",
"as_relationships": "/v1/as-relationships/{asn}",
"geo": "/v1/geo/{ip}",
"atlas": "/v1/atlas/{target}",
"bulk": "/v1/bulk (POST)",
"cache_stats": "/v1/meta/cache",
"server_status": "/v1/meta/status",
},
}
@app.get("/v1/meta/cache", tags=["Meta"], summary="Cache statistics")
@limiter.limit(_DEFAULT_RATE)
async def meta_cache(request: Request):
"""Returns the current in-memory cache health: total entries, alive, expired."""
return cache_module.stats()
@app.get("/v1/meta/status", tags=["Meta"], summary="RIR server reachability")
@limiter.limit(_DEFAULT_RATE)
async def meta_status(request: Request):
"""Pings all 5 RIR RDAP servers and returns their status."""
statuses = await rir_client.get_rir_server_status()
return statuses
# ──────────────────────────────────────────────────────────────
# Phase 1 — RDAP Lookups
# ──────────────────────────────────────────────────────────────
@app.get(
"/v1/ip/{ip}",
tags=["RDAP"],
summary="Who owns this IP address?",
response_description="Registration info from the authoritative RIR",
)
@limiter.limit(_DEFAULT_RATE)
async def query_ip(
request: Request,
ip: str,
format: str = FORMAT_QUERY,
):
"""
Query all 5 RIRs and return the authoritative RDAP registration
for an IPv4 or IPv6 address.
Returns: holder, org, RIR, country, allocation dates, abuse contact.
**Examples:** `1.1.1.1`, `8.8.8.8`, `2001:4860:4860::8888`
"""
cache_key = cache_module.make_ip_key(ip)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
results = await rir_client.query_ip_all_rirs(ip)
normalized = []
for r in results:
if r.status == "ok" and r.data:
try:
normalized.append(normalize_ip_response(r.rir.value, r.data))
except Exception:
pass
if not normalized:
# J3: RDAP returned nothing — try raw WHOIS port-43 fallback
whois_result = await rir_client.get_whois_fallback(ip, "ip")
if whois_result and whois_result.data:
try:
normalized.append(normalize_ip_response(whois_result.rir.value, whois_result.data))
results.append(whois_result)
except Exception:
pass
if not normalized:
errors = [r.error for r in results if r.error]
err_detail = "; ".join(errors) if errors else "all RIRs returned no data"
md = f"## IP Lookup: `{ip}`\n\n> ⚠️ No RDAP record found. {err_detail}\n\n"
md += "_This IP may be unallocated, reserved, or all RIR RDAP servers are unreachable._\n"
jsn = to_json({"ip": ip, "error": f"No RDAP record found for {ip}", "details": errors})
return _resp(md, jsn, format)
md = format_ip_results_md(ip, normalized, results)
jsn = to_json({"ip": ip, "results": [r.model_dump(exclude={"data"}) for r in results],
"normalized": [n.model_dump(exclude={"raw"}) for n in normalized]})
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_IP)
return _resp(md, jsn, format)
@app.get(
"/v1/asn/{asn}",
tags=["RDAP"],
summary="Who owns this Autonomous System Number?",
)
@limiter.limit(_DEFAULT_RATE)
async def query_asn(
request: Request,
asn: str,
format: str = FORMAT_QUERY,
):
"""
Query all 5 RIRs for the RDAP registration of an ASN.
Returns: org name, RIR, country, allocation date, contact info.
**Examples:** `AS13335`, `AS15169`, `13335`
"""
cache_key = cache_module.make_asn_key(asn)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
results = await rir_client.query_asn_all_rirs(asn)
normalized = []
for r in results:
if r.status == "ok" and r.data:
try:
normalized.append(normalize_asn_response(r.rir.value, r.data))
except Exception:
pass
if not normalized:
# J3: RDAP returned nothing — try raw WHOIS port-43 fallback
whois_result = await rir_client.get_whois_fallback(asn, "asn")
if whois_result and whois_result.data:
try:
normalized.append(normalize_asn_response(whois_result.rir.value, whois_result.data))
results.append(whois_result)
except Exception:
pass
if not normalized:
errors = [r.error for r in results if r.error]
err_detail = "; ".join(errors) if errors else "all RIRs returned no data"
md = f"## ASN Lookup: `{asn}`\n\n> ⚠️ No RDAP record found. {err_detail}\n\n"
md += "_This ASN may be unallocated or all RIR RDAP servers are unreachable._\n"
jsn = to_json({"asn": asn, "error": f"No RDAP record found for {asn}", "details": errors})
return _resp(md, jsn, format)
md = format_asn_results_md(asn, normalized, results)
jsn = to_json({"asn": asn, "results": [r.model_dump(exclude={"data"}) for r in results],
"normalized": [n.model_dump(exclude={"raw"}) for n in normalized]})
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_ASN)
return _resp(md, jsn, format)
@app.get(
"/v1/abuse/{ip}",
tags=["RDAP"],
summary="Who do I report abuse to for this IP?",
)
@limiter.limit(_DEFAULT_RATE)
async def get_abuse_contact(
request: Request,
ip: str,
format: str = FORMAT_QUERY,
):
"""
Find the abuse contact email for an IP address.
Use this to report spam, DDoS, or other abuse from that IP.
**Examples:** `185.220.101.45`, `1.1.1.1`
"""
cache_key = cache_module.make_abuse_key(ip)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
contact = await rir_client.get_abuse_contact(ip)
md = format_abuse_contact_md(contact)
jsn = to_json(contact)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_ABUSE)
return _resp(md, jsn, format)
# ──────────────────────────────────────────────────────────────
# Phase 2 — RPKI + BGP
# ──────────────────────────────────────────────────────────────
@app.get(
"/v1/rpki",
tags=["Routing Security"],
summary="Is this BGP route RPKI valid?",
)
@limiter.limit(_DEFAULT_RATE)
async def check_rpki(
request: Request,
prefix: str = Query(..., description="IP prefix in CIDR notation, e.g. '1.1.1.0/24'"),
asn: str = Query(..., description="Origin ASN, e.g. 'AS13335' or '13335'"),
format: str = FORMAT_QUERY,
):
"""
Validate a BGP route using RPKI (Resource Public Key Infrastructure).
RPKI uses cryptographic certificates (ROAs) to prove which ASN is
authorized to announce a given prefix. An **invalid** result means
the announcement is NOT authorized — potential BGP hijack.
Results: `valid` | `invalid` | `not-found` | `unknown`
"""
asn_num = asn.upper().lstrip("AS")
cache_key = cache_module.make_rpki_key(prefix, asn_num)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.check_rpki(prefix, asn_num)
md = format_rpki_result_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_RPKI)
return _resp(md, jsn, format)
@app.get(
"/v1/bgp/{resource:path}",
tags=["Routing Security"],
summary="Is this prefix/ASN visible in global BGP?",
)
@limiter.limit(_DEFAULT_RATE)
async def check_bgp(
request: Request,
resource: str,
format: str = FORMAT_QUERY,
):
"""
Check if a prefix or ASN is currently announced in the global BGP routing table.
Returns: announcement status, originating ASN(s), visibility percentage
(% of BGP route collectors that see this route).
**Examples:** `1.1.1.0/24`, `AS13335`, `8.8.8.0/24`
"""
cache_key = cache_module.make_bgp_key(resource)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_bgp_status(resource)
md = format_bgp_status_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_BGP)
return _resp(md, jsn, format)
@app.get(
"/v1/announced/{asn}",
tags=["Routing Security"],
summary="What prefixes is this ASN announcing?",
)
@limiter.limit(_DEFAULT_RATE)
async def get_announced(
request: Request,
asn: str,
format: str = FORMAT_QUERY,
):
"""
List all IP prefixes currently announced by an ASN in the global BGP table.
**Examples:** `AS13335`, `AS15169`
"""
asn_num = asn.upper().lstrip("AS")
cache_key = cache_module.make_bgp_key(f"announced-{asn_num}")
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_announced_prefixes(asn_num)
from formatters import format_announced_prefixes_md
md = format_announced_prefixes_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_BGP)
return _resp(md, jsn, format)
@app.get(
"/v1/org",
tags=["RDAP"],
summary="Find all internet resources for an organization",
)
@limiter.limit(_HEAVY_RATE)
async def audit_org(
request: Request,
name: str = Query(..., description="Organization name or handle, e.g. 'Cloudflare' or 'GOOGL-ARIN'"),
format: str = FORMAT_QUERY,
):
"""
Search all 5 RIRs for every IP block and ASN registered to an organization.
Useful for M&A due diligence, security research, or footprint mapping.
**Examples:** `Cloudflare`, `GOOGL-ARIN`, `Amazon`
"""
cache_key = cache_module.make_org_key(name)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
resources, errors = await rir_client.search_org_all_rirs(name)
ip_blocks = [r for r in resources if r.resource_type in ("ip", "entity")]
asns = [r for r in resources if r.resource_type == "asn"]
audit = OrgAuditResult(
org_query = name,
total_resources = len(resources),
ip_blocks = ip_blocks,
asns = asns,
rirs_found_in = list({r.rir for r in resources}),
errors = errors,
)
md = format_org_audit_md(audit)
jsn = to_json(audit)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_ORG)
return _resp(md, jsn, format)
# ──────────────────────────────────────────────────────────────
# Phase 3 — History + Stats
# ──────────────────────────────────────────────────────────────
@app.get(
"/v1/history/{resource:path}",
tags=["History"],
summary="Full registration history for a prefix or ASN",
)
@limiter.limit(_DEFAULT_RATE)
async def prefix_history(
request: Request,
resource: str,
format: str = FORMAT_QUERY,
):
"""
Chronological timeline of every ownership and status change ever recorded
for an IP prefix or ASN. Best coverage for RIPE NCC resources.
**Examples:** `8.8.8.0/24`, `AS15169`, `1.1.1.0/24`
"""
cache_key = cache_module.make_history_key(resource)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_prefix_history(resource)
md = format_prefix_history_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_HISTORY)
return _resp(md, jsn, format)
@app.get(
"/v1/transfers/{resource:path}",
tags=["History"],
summary="Detect cross-org or cross-RIR resource transfers",
)
@limiter.limit(_DEFAULT_RATE)
async def detect_transfers(
request: Request,
resource: str,
format: str = FORMAT_QUERY,
):
"""
Detect past ownership or cross-RIR transfers for an IP prefix or ASN.
Transfer types: org change 🏢, inter-RIR 🌍→🌎, intra-RIR 🔄
**Examples:** `8.8.8.0/24`, `AS15169`
"""
cache_key = cache_module.make_transfer_key(resource)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.detect_transfers(resource)
md = format_transfer_detect_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_TRANSFER)
return _resp(md, jsn, format)
@app.get(
"/v1/stats/ipv4",
tags=["Statistics"],
summary="Global IPv4 / IPv6 / ASN exhaustion dashboard",
)
@limiter.limit(_DEFAULT_RATE)
async def ipv4_stats(
request: Request,
rir: Optional[str] = Query(
default=None,
description="Filter to one RIR: AFRINIC, APNIC, ARIN, LACNIC, or RIPE. Leave empty for all 5.",
),
include_blocks: bool = Query(
default=False,
description="Include raw delegated IPv4 block rows. Requires rir to be set.",
),
status: Optional[str] = Query(
default=None,
description="Optional status filter for block rows: allocated, assigned, available (free is normalized).",
),
country: Optional[str] = Query(
default=None,
description="Optional 2-letter country filter for block rows (e.g. GH, ZA).",
),
limit: int = Query(
default=100,
ge=1,
le=5000,
description="Maximum block rows to return when include_blocks=true.",
),
offset: int = Query(
default=0,
ge=0,
le=1_000_000,
description="Pagination offset for block rows when include_blocks=true.",
),
format: str = FORMAT_QUERY,
):
"""
Real-time global IPv4, IPv6, and ASN allocation statistics from all 5 RIRs.
Sourced from NRO Extended Delegation Stats files (published daily).
Use this to track IPv4 exhaustion, IPv6 adoption, and ASN growth.
"""
rir_filter = (rir or "").upper().strip() or "all"
cache_key = cache_module.make_ipv4stat_key(
rir_filter=rir_filter,
include_blocks=include_blocks,
status_filter=status,
country_filter=country,
limit=limit,
offset=offset,
)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_global_ipv4_stats(
rir_filter=rir or None,
include_blocks=include_blocks,
status_filter=status,
country_filter=country,
limit=limit,
offset=offset,
)
md = format_ipv4_stats_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_IPV4STAT)
return _resp(md, jsn, format)
@app.get(
"/v1/overview/{prefix:path}",
tags=["History"],
summary="Prefix hierarchy: parent blocks, children, and BGP status",
)
@limiter.limit(_DEFAULT_RATE)
async def prefix_overview(
request: Request,
prefix: str,
format: str = FORMAT_QUERY,
):
"""
Rich hierarchical view of an IP prefix: who owns it, parent blocks
(less-specifics), child assignments (more-specifics), and BGP status.
**Examples:** `1.1.1.0/24`, `8.8.8.0/24`
"""
cache_key = cache_module.make_overview_key(prefix)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_prefix_overview(prefix)
md = format_prefix_overview_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_OVERVIEW)
return _resp(md, jsn, format)
# ──────────────────────────────────────────────────────────────
# Phase 4 — PeeringDB + Health + Monitor
# ──────────────────────────────────────────────────────────────
@app.get(
"/v1/peering/{asn}",
tags=["PeeringDB"],
summary="PeeringDB: peering policy, IXP presence, NOC contacts",
)
@limiter.limit(_DEFAULT_RATE)
async def peering_info(
request: Request,
asn: str,
format: str = FORMAT_QUERY,
):
"""
Fetch peering policy, IXP presence, NOC/abuse contacts, and BGP
neighbours for an ASN from PeeringDB + RIPE Stat.
**Examples:** `AS13335`, `AS15169`, `AS1299`
"""
asn_num = asn.upper().lstrip("AS")
cache_key = cache_module.make_peering_key(asn_num)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_peering_info(asn_num)
md = format_peering_info_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_PEERING)
return _resp(md, jsn, format)
@app.get(
"/v1/ixp",
tags=["PeeringDB"],
summary="Find Internet Exchange Points by country or name",
)
@limiter.limit(_DEFAULT_RATE)
async def ixp_lookup(
request: Request,
query: str = Query(..., description="2-letter country code (e.g. 'MU') or IXP name fragment (e.g. 'AMS-IX')"),
format: str = FORMAT_QUERY,
):
"""
Search PeeringDB for Internet Exchange Points by country code or name.
**Examples:** `MU` (Mauritius), `ZA` (South Africa), `AMS-IX`, `LINX`, `Frankfurt`
"""
cache_key = cache_module.make_ixp_key(query)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.lookup_ixps(query)
md = format_ixp_lookup_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_IXP)
return _resp(md, jsn, format)
@app.get(
"/v1/health/{resource}",
tags=["Health"],
summary="One-shot health check: RDAP + BGP + RPKI + PeeringDB",
)
@limiter.limit(_HEAVY_RATE)
async def network_health(
request: Request,
resource: str,
format: str = FORMAT_QUERY,
):
"""
Comprehensive parallel health check: fires RDAP + BGP + RPKI + PeeringDB
simultaneously and returns a unified health signal dashboard.
🚨 Critical: RPKI invalid, multiple origin ASNs (possible hijack)
⚠️ Warning: not announced, no ROA, missing abuse contact
✅ Healthy: registered, announced, RPKI valid
**Examples:** `1.1.1.1`, `1.1.1.0/24`, `AS13335`
"""
cache_key = cache_module.make_health_key(resource)
cached = cache_module.get(cache_key)
if cached:
return _resp(cached["markdown"], cached["json"], format)
result = await rir_client.get_network_health(resource)
md = format_network_health_md(result)
jsn = to_json(result)
cache_module.set(cache_key, {"markdown": md, "json": jsn}, cache_module.TTL_HEALTH)
return _resp(md, jsn, format)
@app.get(
"/v1/monitor/{resource:path}",
tags=["Monitor"],
summary="Monitor registration + BGP changes between calls",
)
@limiter.limit(_DEFAULT_RATE)
async def change_monitor(
request: Request,
resource: str,
reset: bool = Query(
default=False,
description="Set to true to discard the stored baseline and start fresh",
),
):
"""
Stateful change monitor for a prefix or ASN.
- **First call:** captures a baseline snapshot (RDAP + BGP state).
- **Later calls:** diffs current state vs baseline and reports changes.
- **reset=true:** discards baseline, captures fresh snapshot.
Tracked: holder, RIR, country, allocation status, abuse email,
BGP announced, origin ASN(s), BGP visibility %.
⚠️ Baselines live in server memory — lost on server restart.
**Examples:** `8.8.8.0/24`, `AS15169`
"""
result = await rir_client.run_change_monitor(
resource=resource,
reset_baseline=reset,
)
md = format_change_monitor_md(result)
jsn = to_json(result)
# Always return JSON for monitor (structured diff is more useful)
import json
try:
return JSONResponse(content=json.loads(jsn))
except Exception:
return PlainTextResponse(content=md)
# ──────────────────────────────────────────────────────────────
# DNS endpoints (Sprint 2 — E1–E5, E7)
# ──────────────────────────────────────────────────────────────
_RTYPE_HELP = "DNS record type (A, AAAA, MX, TXT, NS, CNAME …). Default: auto"
@app.get(
"/v1/dns/resolve/{target}",
tags=["DNS"],
summary="Forward/reverse DNS resolution with RDAP correlation",
)
@limiter.limit(_DEFAULT_RATE)
async def dns_resolve(
request: Request,
target: str,
record_type: str = Query(default="A", description=_RTYPE_HELP),
format: ResponseFormat = Query(default=ResponseFormat.MARKDOWN),
):
"""
Resolve a hostname (A/AAAA/PTR/etc.) and correlate resolved IPs with
RDAP registration data (holder, country, RIR, covering prefix).
**Examples:** `8.8.8.8`, `cloudflare.com`, `google.com`
"""
inp = DNSResolveInput(target=target)
result = await rir_client.dns_resolve(inp)
md = format_dns_resolve_md(result)
jsn = to_json(result)
return _resp(md, jsn, format)
@app.get(
"/v1/dns/enumerate/{domain}",
tags=["DNS"],
summary="Full DNS record enumeration for a domain",
)
@limiter.limit(_DEFAULT_RATE)
async def dns_enumerate(
request: Request,
domain: str,
format: ResponseFormat = Query(default=ResponseFormat.MARKDOWN),
):
"""
Query all common DNS record types (A, AAAA, MX, NS, TXT, SOA, CNAME, CAA,
SRV, PTR) for a domain and extract SPF/DMARC inline.
**Example:** `cloudflare.com`
"""
inp = DNSEnumerateInput(domain=domain)
result = await rir_client.dns_enumerate(inp)
md = format_dns_enumerate_md(result)
jsn = to_json(result)
return _resp(md, jsn, format)
@app.get(
"/v1/dns/dnssec/{domain}",
tags=["DNS"],
summary="DNSSEC chain validation",
)
@limiter.limit(_DEFAULT_RATE)
async def dns_dnssec(
request: Request,
domain: str,
format: ResponseFormat = Query(default=ResponseFormat.MARKDOWN),
):
"""
Check DNSSEC deployment: validates chain-of-trust (DNSKEY → DS → RRSIG),
returns SECURE / INSECURE / BOGUS / INDETERMINATE with algorithm details.
**Example:** `cloudflare.com`
"""
inp = DNSSECInput(domain=domain)
result = await rir_client.dns_dnssec(inp)
md = format_dns_dnssec_md(result)
jsn = to_json(result)
return _resp(md, jsn, format)
@app.get(
"/v1/dns/dnsbl/{ip}",
tags=["DNS"],
summary="DNS blocklist (DNSBL/RBL) check across 30 lists",
)
@limiter.limit(_DEFAULT_RATE)
async def dns_dnsbl(
request: Request,
ip: str,
format: ResponseFormat = Query(default=ResponseFormat.MARKDOWN),
):
"""
Check an IP against 30 DNS blocklists in parallel (Spamhaus ZEN,
Barracuda, SORBS, URIBL, and more). Returns per-list listed/clean status.
**Example:** `1.2.3.4`
"""
inp = DNSBLInput(ip=ip)
result = await rir_client.dns_dnsbl(inp)
md = format_dns_dnsbl_md(result)
jsn = to_json(result)
return _resp(md, jsn, format)
@app.get(
"/v1/dns/email/{domain}",
tags=["DNS"],
summary="Email security posture (SPF + DMARC + DKIM + BIMI)",
)
@limiter.limit(_DEFAULT_RATE)
async def dns_email(
request: Request,
domain: str,
format: ResponseFormat = Query(default=ResponseFormat.MARKDOWN),
):
"""
Comprehensive email security audit: SPF record validity, DMARC policy
strength, DKIM selector probing, MX records, BIMI presence, and a
risk score (LOW / MEDIUM / HIGH / CRITICAL).
**Example:** `example.com`
"""
inp = EmailSecurityInput(domain=domain)
result = await rir_client.dns_email_security(inp)
md = format_email_security_md(result)
jsn = to_json(result)
return _resp(md, jsn, format)
@app.get(
"/v1/dns/propagation/{domain}",
tags=["DNS"],
summary="DNS propagation check across 10 global resolvers",
)
@limiter.limit(_DEFAULT_RATE)
async def dns_propagation(
request: Request,
domain: str,
record_type: str = Query(default="A", description=_RTYPE_HELP),
format: ResponseFormat = Query(default=ResponseFormat.MARKDOWN),
):
"""
Query 10 geographically distributed resolvers (Cloudflare, Google,
Quad9, OpenDNS, Comodo, Verisign, etc.) and compare answers to the
majority — useful for verifying recent DNS changes have propagated.
**Example:** `cloudflare.com`
"""
inp = DNSPropagationInput(domain=domain, record_type=record_type)