Build an authorised, polite collector for your own organisation's public footprint: httpx with rate limits, backoff and Retry-After, robots.txt handling, WARC archiving with warcio, and an append-only Django evidence store with a hash-chained custody log.
When a security team documents its organisation's public exposure, the collection code matters as much as the findings. A collector that ignores robots.txt, hammers a server, or stores pages without proof of when and how they were fetched produces evidence nobody can rely on. This tutorial builds a small, polite and auditable collection pipeline in Python and Django: an authorisation gate, rate-limited HTTP with httpx, robots.txt handling, WARC archiving, and an append-only evidence store with a hash-chained custody log.
The pipeline serves one purpose: an organisation examining its own public footprint, such as the software versions its websites announce and what changed since last month. Every target host must be covered by a written authorisation from the asset owner. It is not a tool for collecting information about people. Do not point it at social networks, people-search sites or personal pages, and do not use it to profile, locate or identify individuals; under the GDPR (AVG in the Netherlands) that would need a lawful basis you almost certainly do not have, and it is outside what defensive OSINT is for. If a capture of your own site happens to contain personal data, such as a staff page, handle it as personal data: limit access and set a retention period.
Three checks happen before the first request, and the code enforces them rather than trusting a checklist:
The code targets Python 3.12 or newer and was run on Python 3.13 with httpx 0.29.0, warcio 1.8.2 and Django 5.2.20 (the 5.2 LTS line). The examples only contact www.example.com through a mocked transport and a local test server started inside the code.
pip install "Django>=5.2,<6.0" "httpx>=0.29,<1.0" "warcio>=1.8,<2.0"
django-admin startproject myproject .
python manage.py startapp evidence
httpx is still pre-1.0, so run the tests after every upgrade.
The pipeline has five parts, each with one job:
The principle: store raw evidence first and immutably, interpret later and repeatably.
The collector is synchronous on purpose: politeness is about requests per host over time, and a single loop per host guarantees it. The sections after the code explain each decision.
"""A polite, auditable HTTP collector for your own organisation's assets."""
import email.utils
import hashlib
import random
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from urllib.parse import urlsplit
from urllib.robotparser import RobotFileParser
import httpx
AGENT = "myproject-exposure-audit"
USER_AGENT = f"{AGENT}/1.0 (+https://www.example.com/security/osint-policy)"
RETRY_STATUSES = {429, 500, 502, 503, 504}
class OutOfScope(Exception):
pass
class Disallowed(Exception):
pass
@dataclass(frozen=True)
class Authorisation:
"""The gate: no host is collected without a recorded decision."""
host: str
owner: str # who owns the asset
approved_by: str # who signed off
reference: str # ticket or letter of authorisation
terms_reviewed: bool # ToS / acceptable-use checked for this source
expires: datetime
@dataclass
class Capture:
url: str
final_url: str
status: int
request_headers: dict
response_headers: list[tuple[str, str]]
body: bytes
fetched_at: str
elapsed_ms: int
attempts: int
sha256: str = field(init=False)
def __post_init__(self):
self.sha256 = hashlib.sha256(self.body).hexdigest()
def retry_after_seconds(value: str | None, now: float) -> float | None:
if not value:
return None
if value.strip().isdigit():
return float(value)
parsed = email.utils.parsedate_to_datetime(value) # HTTP-date form
return max(0.0, parsed.timestamp() - now)
class HostThrottle:
"""Minimum interval between requests to the same host."""
def __init__(self, interval: float, clock=time.monotonic, sleep=time.sleep):
self.interval, self.clock, self.sleep = interval, clock, sleep
self.next_slot: dict[str, float] = {}
def wait(self, host: str, interval: float | None = None) -> None:
now = self.clock()
slot = self.next_slot.get(host, now)
if slot > now:
self.sleep(slot - now)
self.next_slot[host] = max(slot, now) + max(self.interval, interval or 0)
class PoliteCollector:
def __init__(self, authorisations, *, transport=None, interval=2.0,
max_attempts=4, base_backoff=1.0, max_backoff=60.0,
sleep=time.sleep, clock=time.monotonic):
self.auth = {a.host: a for a in authorisations}
self.throttle = HostThrottle(interval, clock=clock, sleep=sleep)
self.sleep = sleep
self.max_attempts, self.base, self.cap = max_attempts, base_backoff, max_backoff
self.robots: dict[str, RobotFileParser] = {}
self.validators: dict[str, dict[str, str]] = {} # url -> ETag etc.
self.client = httpx.Client(
# identity: the stored body is byte-for-byte what was sent
headers={"User-Agent": USER_AGENT, "Accept-Encoding": "identity"},
timeout=httpx.Timeout(10.0, connect=5.0),
follow_redirects=False, # every hop is checked against scope
transport=transport,
)
# -- gates ---------------------------------------------------------
def check_scope(self, url: str) -> str:
host = urlsplit(url).hostname or ""
auth = self.auth.get(host)
if auth is None:
raise OutOfScope(f"{host} is not in the authorised scope")
if not auth.terms_reviewed:
raise OutOfScope(f"terms for {host} not reviewed")
if auth.expires <= datetime.now(timezone.utc):
raise OutOfScope(f"authorisation for {host} expired")
return host
def robots_for(self, url: str) -> RobotFileParser:
parts = urlsplit(url)
origin = f"{parts.scheme}://{parts.netloc}"
if origin not in self.robots:
rp = RobotFileParser(origin + "/robots.txt")
self.throttle.wait(parts.hostname)
resp = self.client.get(origin + "/robots.txt", follow_redirects=True)
if resp.status_code in (401, 403) or resp.status_code >= 500:
rp.disallow_all = True # conservative: unreachable means "no"
elif resp.status_code >= 400:
rp.allow_all = True # 404: no robots.txt, no restrictions
else:
rp.parse(resp.text.splitlines())
self.robots[origin] = rp
return self.robots[origin]
# -- fetching ------------------------------------------------------
def backoff(self, attempt: int) -> float:
# "full jitter": random point between 0 and the exponential cap
return random.uniform(0, min(self.cap, self.base * 2 ** attempt))
def fetch(self, url: str) -> Capture | None:
host = self.check_scope(url)
robots = self.robots_for(url)
if not robots.can_fetch(AGENT, url):
raise Disallowed(url)
delay = robots.crawl_delay(AGENT)
headers = dict(self.validators.get(url, {}))
started = datetime.now(timezone.utc)
for attempt in range(self.max_attempts):
self.throttle.wait(host, float(delay) if delay else None)
t0 = time.perf_counter()
try:
resp = self.client.get(url, headers=headers)
except httpx.TransportError:
if attempt + 1 == self.max_attempts:
raise
self.sleep(self.backoff(attempt))
continue
if resp.status_code in RETRY_STATUSES and attempt + 1 < self.max_attempts:
wait = retry_after_seconds(resp.headers.get("Retry-After"), time.time())
self.sleep(min(self.cap, wait) if wait is not None else self.backoff(attempt))
continue
break
if resp.status_code == 304:
return None # unchanged since the last capture: nothing new to store
self.remember_validators(url, resp)
return Capture(
url=url, final_url=str(resp.url), status=resp.status_code,
request_headers=dict(resp.request.headers),
response_headers=list(resp.headers.multi_items()),
body=resp.content,
fetched_at=started.isoformat(timespec="milliseconds"),
elapsed_ms=round((time.perf_counter() - t0) * 1000),
attempts=attempt + 1,
)
def remember_validators(self, url: str, resp: httpx.Response) -> None:
v = {}
if etag := resp.headers.get("ETag"):
v["If-None-Match"] = etag
if modified := resp.headers.get("Last-Modified"):
v["If-Modified-Since"] = modified
if v:
self.validators[url] = v
The User-Agent names the tool, its version and a URL where a site operator can read who is collecting and how to object. Never borrow a browser User-Agent: it hides you from the owner's logs. The robots token (myproject-exposure-audit) matches the product part of the header.
httpx applies a five-second default timeout, but stating it documents intent: ten seconds for reads, writes and pool waits, five to connect. Redirects are not followed automatically because a redirect can leave the authorised scope. A 301 is captured as evidence in its own right; to follow it, the pipeline enqueues the Location URL, which passes through the scope gate again. The robots.txt fetch is the exception: RFC 9309 asks crawlers to follow its redirects.
HostThrottle keeps the next free slot per host on a monotonic clock, so a system clock change cannot cause a burst. The interval defaults to two seconds; a longer Crawl-delay in robots.txt wins, a shorter one is ignored. Clock and sleep are injected for testing.
Only transport errors and the statuses 429, 500, 502, 503 and 504 are retried, at most four attempts in total. If the server sends Retry-After, either as seconds or as an HTTP date, the collector waits that long (capped at the maximum backoff). Otherwise it uses exponential backoff with full jitter: a random delay between zero and base * 2 ** attempt, capped. Jitter stops restarted collectors from retrying in lockstep. A 404 or 403 is an answer, not a failure.
After a successful fetch the collector remembers the ETag and Last-Modified values and sends them back as If-None-Match and If-Modified-Since. A 304 Not Modified costs the server almost nothing and tells you the page has not changed since your last capture, so fetch() returns None and nothing new is stored.
One more header is set on every request: Accept-Encoding: identity. httpx decodes compressed responses transparently; if the stored body is decoded but the stored headers still say Content-Encoding: gzip, the record no longer describes what was transmitted. Asking for an uncompressed response keeps body and headers consistent.
RobotFileParser.read() fetches with urllib, which would bypass your User-Agent, timeouts and rate limiter. The collector therefore fetches robots.txt itself and hands the lines to parse(). For 4xx it follows the standard library (401 and 403 disallow everything, other 4xx mean no restrictions); a 5xx is treated as "disallow all", as RFC 9309 recommends. Results are cached per origin; refresh them at least daily.
Two parser details are worth knowing. can_fetch() returns False until something has been parsed, so a forgotten fetch fails closed. And it matches a User-agent line when that token appears, case-insensitively, in the product part of your agent name, falling back to the * group.
| Field | Why |
|---|---|
| Raw body bytes and SHA-256 | Proves the content has not changed since capture |
| Requested and final URL, status | What was asked and what answered |
| Request headers as sent | Shows you identified yourself and what you asked for |
| Response headers, in order, duplicates kept | Banners such as Server are often the finding |
| UTC timestamp, attempts, elapsed time | Unambiguous time; context for errors |
| Authorisation reference, collector version | Links evidence to its legal basis and to the code that made it |
Timestamps are always timezone-aware UTC (datetime.now(timezone.utc)), never naive local time. Note that multi_items() preserves repeated headers; a dict would silently keep only one.
WARC (ISO 28500) is the standard container for web archives. Each capture becomes a response record holding the HTTP status line, headers and body, plus a request record linked by WARC-Concurrent-To.
"""Archive captures as WARC request/response pairs."""
from http import HTTPStatus
from io import BytesIO
from urllib.parse import urlsplit
from warcio.statusandheaders import StatusAndHeaders
from warcio.warcwriter import WARCWriter
from .collector import Capture
def write_capture(stream, capture: Capture) -> None:
writer = WARCWriter(stream, gzip=True)
parts = urlsplit(capture.final_url)
target = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
warc_date = capture.fetched_at[:19] + "Z" # WARC 1.0: second precision, UTC
request = writer.create_warc_record(
capture.final_url, "request",
http_headers=StatusAndHeaders(f"GET {target} HTTP/1.1",
list(capture.request_headers.items()),
is_http_request=True),
warc_headers_dict={"WARC-Date": warc_date})
response = writer.create_warc_record(
capture.final_url, "response",
payload=BytesIO(capture.body), length=len(capture.body),
http_headers=StatusAndHeaders(
f"{capture.status} {HTTPStatus(capture.status).phrase}",
capture.response_headers, protocol="HTTP/1.1"),
warc_headers_dict={
"WARC-Date": warc_date,
"WARC-Concurrent-To": request.rec_headers.get_header("WARC-Record-ID"),
"X-Body-SHA256": capture.sha256, # our digest next to warcio's sha1
})
writer.write_record(response)
writer.write_record(request)
warcio computes WARC-Payload-Digest and WARC-Block-Digest as base32 SHA-1, the convention most WARC tools expect. SHA-1 is no longer collision-resistant, so the SHA-256 of the body travels in an extra X-Body-SHA256 header and in the database. Writers must emit WARC-Date in UTC; WARC 1.0 uses second precision, which is why the millisecond timestamp is truncated there and kept in full in the database. The real response record from the run later in this tutorial looks like this:
WARC/1.0
WARC-Date: 2026-12-05T16:24:34Z
WARC-Concurrent-To: <urn:uuid:8db774d6-9a79-4020-a0d5-bd82b019838d>
X-Body-SHA256: 34fbf75e57e14f1282755a869c772697b13777f3f877d0dcb0b607bad25089c3
WARC-Type: response
WARC-Payload-Digest: sha1:YMKWBVXXTPGM4GCCYW7TQA5T766VT575
WARC-Block-Digest: sha1:SC6CL5RLCAYDVMADYRPBPBPS57HVBNKV
Content-Type: application/http; msgtype=response
HTTP/1.1 200 OK
server: BaseHTTP/0.6 Python/3.13.7
...
server: ExampleHTTPd/2.4.41
x-powered-by: PHP/7.4.3
Both server headers (one from the Python test server, one from the handler) are preserved.
import hashlib
import json
from django.core.exceptions import PermissionDenied
from django.db import models
class AppendOnlyQuerySet(models.QuerySet):
def update(self, **kwargs):
raise PermissionDenied("evidence is append-only")
def delete(self):
raise PermissionDenied("evidence is append-only")
class AppendOnlyModel(models.Model):
objects = AppendOnlyQuerySet.as_manager()
class Meta:
abstract = True
def save(self, *args, **kwargs):
if not self._state.adding:
raise PermissionDenied("evidence is append-only")
kwargs["force_insert"] = True
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
raise PermissionDenied("evidence is append-only")
class Blob(AppendOnlyModel):
"""Content-addressed body storage: identical bodies are stored once."""
sha256 = models.CharField(max_length=64, primary_key=True)
size = models.PositiveBigIntegerField()
data = models.BinaryField()
class Evidence(AppendOnlyModel):
url = models.URLField(max_length=2000)
final_url = models.URLField(max_length=2000)
status = models.PositiveSmallIntegerField()
fetched_at = models.DateTimeField() # UTC, from the collector
request_headers = models.JSONField()
response_headers = models.JSONField()
blob = models.ForeignKey(Blob, on_delete=models.PROTECT)
authorisation_ref = models.CharField(max_length=100)
collector_version = models.CharField(max_length=50)
warc_file = models.CharField(max_length=200, blank=True)
class Meta:
indexes = [models.Index(fields=["url", "fetched_at"])]
class CustodyEvent(AppendOnlyModel):
"""Hash-chained log: who did what to which evidence, and when."""
evidence = models.ForeignKey(Evidence, on_delete=models.PROTECT)
action = models.CharField(max_length=30) # captured, exported, viewed
actor = models.CharField(max_length=150)
at = models.DateTimeField()
note = models.TextField(blank=True)
prev_hash = models.CharField(max_length=64, unique=True) # no forks
record_hash = models.CharField(max_length=64, unique=True)
def compute_hash(self) -> str:
payload = json.dumps({
"evidence": self.evidence_id, "sha256": self.evidence.blob_id,
"action": self.action,
"actor": self.actor, "at": self.at.isoformat(), "note": self.note,
"prev": self.prev_hash,
}, sort_keys=True).encode()
return hashlib.sha256(payload).hexdigest()
Bodies are content-addressed: Blob uses the SHA-256 as primary key, so an unchanged page captured a hundred times is stored once, while each capture still gets its own Evidence row, because "we saw the same thing again on this date" is itself evidence. PROTECT foreign keys stop cascading deletes.
Overriding save(), delete() and the queryset methods blocks mistakes in application code, but not raw SQL or a different client. A migration adds database triggers, so the database itself refuses changes:
from django.db import migrations
TABLES = ["evidence_blob", "evidence_evidence", "evidence_custodyevent"]
def forwards(apps, schema_editor):
vendor = schema_editor.connection.vendor
if vendor == "sqlite":
for t in TABLES:
for op in ("UPDATE", "DELETE"):
schema_editor.execute(
f"CREATE TRIGGER {t}_no_{op.lower()} BEFORE {op} ON {t} "
f"BEGIN SELECT RAISE(ABORT, 'append-only'); END;")
elif vendor == "postgresql":
schema_editor.execute(
"CREATE FUNCTION evidence_append_only() RETURNS trigger "
"LANGUAGE plpgsql AS $$ BEGIN "
"RAISE EXCEPTION 'append-only'; END $$;")
for t in TABLES:
schema_editor.execute(
f"CREATE TRIGGER {t}_append_only BEFORE UPDATE OR DELETE "
f"ON {t} FOR EACH ROW EXECUTE FUNCTION evidence_append_only();")
class Migration(migrations.Migration):
dependencies = [("evidence", "0001_initial")]
operations = [migrations.RunPython(forwards, migrations.RunPython.noop)]
The SQLite branch is exercised by the tests below. On PostgreSQL, also run the application with a database role that has only SELECT and INSERT on these tables, and keep the migration role separate.
import hashlib
from datetime import datetime, timezone
from django.db import IntegrityError, transaction
from .collector import Capture
from .models import Blob, CustodyEvent, Evidence
GENESIS = "0" * 64
COLLECTOR_VERSION = "myproject-exposure-audit/1.0"
def append_custody(evidence: Evidence, action: str, actor: str, note: str = "",
attempts: int = 3) -> CustodyEvent:
for _ in range(attempts):
last = CustodyEvent.objects.order_by("-id").first()
event = CustodyEvent(evidence=evidence, action=action, actor=actor,
note=note, at=datetime.now(timezone.utc),
prev_hash=last.record_hash if last else GENESIS)
event.record_hash = event.compute_hash()
try:
with transaction.atomic():
event.save()
return event
except IntegrityError: # someone else appended first; re-read the head
continue
raise RuntimeError("could not append to custody chain")
@transaction.atomic
def record(capture: Capture, authorisation_ref: str, actor: str,
warc_file: str = "") -> Evidence:
blob, created = Blob.objects.get_or_create(
sha256=capture.sha256,
defaults={"size": len(capture.body), "data": capture.body})
evidence = Evidence.objects.create(
url=capture.url, final_url=capture.final_url, status=capture.status,
fetched_at=datetime.fromisoformat(capture.fetched_at),
request_headers=capture.request_headers,
response_headers=capture.response_headers,
blob=blob, authorisation_ref=authorisation_ref,
collector_version=COLLECTOR_VERSION, warc_file=warc_file)
append_custody(evidence, "captured", actor,
note="new body" if created else "body identical to earlier capture")
return evidence
def verify_chain() -> list[str]:
problems, expected_prev = [], GENESIS
for event in CustodyEvent.objects.select_related("evidence").order_by("id"):
if event.prev_hash != expected_prev:
problems.append(f"event {event.id}: broken link")
if event.compute_hash() != event.record_hash:
problems.append(f"event {event.id}: hash mismatch")
expected_prev = event.record_hash
for blob in Blob.objects.all():
if hashlib.sha256(bytes(blob.data)).hexdigest() != blob.sha256:
problems.append(f"blob {blob.sha256[:12]}: content altered")
return problems
Each custody event stores the hash of the previous event and a hash over its own fields, including the evidence's body hash. Editing any event, or deleting one from the middle, breaks the chain, and verify_chain() reports where. The unique constraint on prev_hash means two concurrent writers cannot both append after the same head; the loser gets an IntegrityError and retries on the new head. Someone with full database access could still rewrite the entire chain, so periodically copy the current head hash somewhere they cannot reach: a signed ticket comment, a separate log system, or an RFC 3161 timestamp.
"""Collector -> queue -> archiver/normaliser -> store."""
import queue
import re
import threading
from pathlib import Path
from .collector import Capture, Disallowed, PoliteCollector
from .services import record
from .warc import write_capture
GENERATOR = re.compile(rb'<meta\s+name="generator"\s+content="([^"]+)"', re.I)
EXPOSING_HEADERS = ("server", "x-powered-by", "x-aspnet-version", "via")
def normalise(capture: Capture) -> dict:
"""Turn a raw capture into findings an analyst can sort and filter."""
headers = {k.lower(): v for k, v in capture.response_headers}
findings = {h: headers[h] for h in EXPOSING_HEADERS if h in headers}
if m := GENERATOR.search(capture.body):
findings["generator"] = m.group(1).decode(errors="replace")
return {"url": capture.url, "status": capture.status,
"sha256": capture.sha256[:16], "findings": findings}
def run(urls, collector: PoliteCollector, warc_dir: Path, auth_ref: str, actor: str):
work: queue.Queue[Capture | None] = queue.Queue(maxsize=100)
results = []
def store_worker():
while (cap := work.get()) is not None:
warc_path = warc_dir / f"{cap.sha256[:16]}.warc.gz"
with open(warc_path, "wb") as fh:
write_capture(fh, cap)
ev = record(cap, auth_ref, actor, warc_file=warc_path.name)
results.append((ev.id, normalise(cap)))
worker = threading.Thread(target=store_worker)
worker.start()
try:
for url in urls: # the collector is single-threaded per host on purpose
try:
if (cap := collector.fetch(url)) is not None:
work.put(cap)
except Disallowed:
results.append((None, {"url": url, "skipped": "robots.txt"}))
finally:
work.put(None)
worker.join()
return results
A demo script starts a local ThreadingHTTPServer whose robots.txt disallows /admin/, authorises 127.0.0.1, and runs three URLs through run():
1 {'url': 'http://127.0.0.1:50106/', 'status': 200, 'sha256': '34fbf75e57e14f12', 'findings': {'server': 'ExampleHTTPd/2.4.41', 'x-powered-by': 'PHP/7.4.3', 'generator': 'CMSName 6.4.2'}}
None {'url': 'http://127.0.0.1:50106/admin/', 'skipped': 'robots.txt'}
2 {'url': 'http://127.0.0.1:50106/contact', 'status': 200, 'sha256': '87dd5902450d91dc', 'findings': {'server': 'ExampleHTTPd/2.4.41', 'x-powered-by': 'PHP/7.4.3'}}
chain problems: []
['34fbf75e57e14f12.warc.gz', '87dd5902450d91dc.warc.gz']
An exact server version, an end-of-life PHP version and a CMS generator tag: typical first findings, each now backed by a WARC record and a hash.
The Django admin works well as the analyst view if it cannot change anything. Register Evidence and CustodyEvent with a ModelAdmin whose has_add_permission, has_change_permission and has_delete_permission all return False: even a superuser then gets a view-only page, and a POST to the change URL returns 403 (one of the tests checks exactly that).
httpx.MockTransport takes a function from request to response, so robots.txt, rate limiting and retries can be tested without a network. The helper collector(handler, sleeps) builds a PoliteCollector for www.example.com with a mock transport and sleep=sleeps.append, so delays are recorded instead of waited for. Further tests cover the scope gate, a robots.txt disallow, jitter bounds and a 304 on the second fetch.
def test_retry_after_is_honoured(self):
calls = []
def handler(request):
if request.url.path == "/robots.txt":
return httpx.Response(404)
calls.append(request.headers["User-Agent"])
if len(calls) == 1:
return httpx.Response(429, headers={"Retry-After": "7"})
return httpx.Response(200, text="ok")
sleeps = []
cap = collector(handler, sleeps, interval=0).fetch("https://www.example.com/")
self.assertEqual((cap.status, cap.attempts), (200, 2))
self.assertIn(7.0, sleeps)
self.assertEqual(calls, [USER_AGENT, USER_AGENT])
One test uses a real socket. LocalSite is a minimal BaseHTTPRequestHandler that serves the same robots.txt and a small page with an ETag; port 0 lets the OS pick a free port. The capture is written to WARC and read back with warcio's ArchiveIterator; note that each record must be read while iterating, because the iterator moves on through the same stream.
class LocalServerWarcTests(SimpleTestCase):
def setUp(self):
self.server = ThreadingHTTPServer(("127.0.0.1", 0), LocalSite)
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.addCleanup(self.server.shutdown)
self.base = f"http://127.0.0.1:{self.server.server_port}"
def test_capture_round_trips_through_warc(self):
c = PoliteCollector([auth(host="127.0.0.1")], interval=0)
cap = c.fetch(self.base + "/status")
buf = io.BytesIO()
write_capture(buf, cap)
buf.seek(0)
seen = []
for rec in ArchiveIterator(buf): # read each record while iterating
seen.append(rec.rec_type)
if rec.rec_type == "response":
digest = rec.rec_headers.get_header("X-Body-SHA256")
body = rec.content_stream().read()
self.assertEqual(seen, ["response", "request"])
self.assertEqual((digest, body), (cap.sha256, b"<h1>Status</h1>"))
The store tests prove both layers of immutability, and that tampering which bypasses them is still detected:
def test_database_refuses_raw_update(self):
record(capture(), "SEC-2026-014", "analyst1")
with self.assertRaises(IntegrityError), connection.cursor() as cur:
cur.execute("UPDATE evidence_evidence SET status = 404")
def test_tampering_is_detected(self):
record(capture(), "SEC-2026-014", "analyst1")
with connection.cursor() as cur: # simulate an attacker with DB access
cur.execute("DROP TRIGGER evidence_custodyevent_no_update")
cur.execute("UPDATE evidence_custodyevent SET actor = 'someone-else'")
self.assertEqual(verify_chain(), [f"event {CustodyEvent.objects.get().id}: hash mismatch"])
$ python manage.py test evidence
Found 11 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...........
----------------------------------------------------------------------
Ran 11 tests in 1.234s
OK
Authorisation records in an append-only Django model and make the collector load its scope from there, refusing to start when no valid authorisation exists.not-modified custody event when a 304 comes back.Location target, run it through the scope gate, and link the two Evidence rows.normalise() to compare findings with the previous capture of the same URL and report only changes.Found a mistake in this tutorial? Let us know and we will fix it.