Resumable Evidence Video Upload and Custody Ledger

Medium · System Design · Software Engineer · Technical Screen

Prompt

Field recording units—such as wearable officer cameras and patrol-vehicle dash units—upload recorded video over cellular, Wi-Fi, and station dock links that frequently drop mid-transfer. Because these recordings may later be introduced in court, design a backend ingestion and evidence-stewardship platform that handles multi-gigabyte transfers, vets untrusted files before exposure, and maintains a cryptographically verifiable audit ledger.

Core requirements:

  1. Resumable multi-gigabyte uploads with server-side byte proof:
    • Individual video recordings span multiple gigabytes.
    • Clients transmit files in chunks and must be able to resume interrupted sessions across unreliable networks without re-sending verified chunks.
    • Do not treat the cloud object store's built-in multipart completion step as trustworthy proof on its own; your service must independently verify and prove on the server side what exact bytes were received and assembled.
  2. Untrusted-content quarantine and security inspection:
    • Treat every incoming upload as untrusted until vetted.
    • Validate container structure/file format and run malware checks inside an isolated boundary before making any recording visible to users or downstream services.
  3. Tamper-evident custody history:
    • Capture an immutable, auditable log of every lifecycle event on a recording—including upload receipt, verification and scan verdicts, storage promotions or tier transitions, playback/downloads/exports, retention or legal-hold updates, and authorized purging.
    • Provide mathematical evidence that stored footage has remained unaltered since ingestion and that no audit entries were edited or removed.

Illustrative upload-to-evidence flow:

Suppose camera bwc-309 (off-512) uploads clip clip-7042 (18 MiB split into 8 MiB, 8 MiB, and 2 MiB chunks) over spotty LTE: if chunk 1 drops or suffers a transit bit-flip, only chunk 1 is resent; the recording stays invisible inside quarantine until server-side assembly, full read-back digest verification, container validation, and malware scanning all pass, and promotion to evid-615 plus any subsequent investigator download appends a verifiable entry to its custody ledger.

Scope & Expectations

  • Define the upload-session, chunk-transfer, and evidence-access APIs together with the underlying metadata and audit tables.
  • Detail the storage isolation layout separating quarantined uploads from verified evidence, along with the background assembly, scanning, and promotion pipeline.
  • Explain your end-to-end cryptographic integrity checks (independent of cloud multipart finalization) and your tamper-evident custody log design.
  • Address multi-tenant access controls, key architectural trade-offs, and failure/recovery paths across network drops and worker crashes.

Step-by-step walkthrough

  1. Clarify requirements and pin down trust boundaries

    We are designing a video ingestion, threat-isolation, and evidentiary audit platform for wearable and vehicle-mounted cameras. Three distinct challenges intersect here: transferring multi-gigabyte files reliably across drop-prone mobile links, quarantining untrusted uploads so malformed or malicious files never touch production evidence or viewers, and proving years later in court that neither an external attacker, a storage-layer bug, nor a privileged administrator altered a single byte or erased an access record.

    Before designing components, we state our core assumptions and trust boundaries:

    • Clients and file sizes: Wearable and vehicle cameras store a unique private key inside a hardware secure element (a tamper-resistant chip that signs digests without exposing the raw key) and connect via mutual TLS over LTE, patrol-car Wi-Fi, or station docks. A typical 20-minute clip is ~0.9 GB; a 12-hour continuous shift recording reaches ~32 GB (hard cap: 64 GB per file). Witness or prosecutor web uploads pass through the same pipeline without hardware-key signatures.
    • Why provider multipart completion is not trusted: Cloud object stores such as Amazon S3 finalize multipart uploads internally and return an ETag that hashes part digests (MD5(md5_1 || md5_2 ...)-N) rather than computing a cryptographic hash across the assembled byte stream. If a storage bug or untrusted completion step drops trailing bytes, reorders parts, or serves stale metadata, relying on that ETag cannot prove what sits on disk. Every integrity claim in our design relies on SHA-256 cryptographic hashes (256-bit fingerprints where flipping one bit changes the entire digest) computed by our processes over bytes we received and we read back from disk.
    • Quarantine before exposure: Incoming bytes are treated as hostile until proven clean. No viewer, media player, or downstream workflow can list or fetch an item until byte verification, container-format validation, and malware scanning all pass.
    • Complete, tamper-evident custody: Every lifecycle event—session start, chunk receipt summary, assembly, scan verdicts, promotion, storage-tier moves, playback, original download, export, retention/legal-hold changes, and deletion—is recorded in a log whose integrity can be verified offline by an untrusting third party.
    • Multi-tenancy: Each law-enforcement agency is an isolated tenant with separate encryption keys and access policies.
  2. Back-of-the-envelope capacity planning

    Fleet assumption      10,000 active cameras x 3 h recorded/day = 30,000 video hours/day
    Video bitrate         1080p H.264 @ ~6 Mbit/s                  = 0.75 MB/s = 2.7 GB/hour
    File count            at 20 min average clip length (~0.9 GB)  = 90,000 recordings/day (~1.04/s)
    
    Daily ingest bytes    30,000 h x 2.7 GB/h                      = 81 TB/day
    Average ingress       81 TB / 86,400 s                         = 0.94 GB/s (~7.5 Gbit/s)
    Peak ingress (3x end-of-shift docking rush)                    = 2.8 GB/s  (~22.5 Gbit/s)
    
    Chunk sizing (8 MiB = 8,388,608 B):
      Chunks per day      81 TB / 8 MiB                            = ~9.7 M chunks/day
      Chunk PUT rate      ~112 chunks/s average, ~340 chunks/s at peak
      Slow cellular link  8 MiB over 2 Mbit/s (250 KB/s)           = ~34 s per chunk (max lost on drop)
    
    Metadata & audit rate ~112 chunk receipts/s + ~12 custody events/s (~1 M custody events/day)
    
    Annual storage        81 TB/day x 365 days                     = ~30 PB/year (originals)
                          1.5 Mbit/s streaming proxies (+25%)      = ~7.4 PB/year
    
    Verification I/O      assemble read (1x) + read-back & scan (1x) + evidence copy read-back (1x)
                          = 3 internal reads/byte                  = ~243 TB/day (~2.8 GB/s in-region)
    SHA-256 CPU cost      CPUs with SHA hardware instructions hash ~1.5-2.0 GB/s per core
                          -> 2.8 GB/s peak ingress needs only ~2-6 CPU cores across the gateway fleet
    

    What these numbers tell us:

    1. Metadata QPS is tiny (~125 writes/s), so a single primary-standby relational database (PostgreSQL) comfortably handles all upload sessions, chunk receipts, and custody events with strong ACID transactions.
    2. Network and disk throughput (22.5 Gbit/s peak ingress, 243 TB/day verification reads) dominate. Reading every byte back 3 times inside the cloud region is the explicit price of not trusting provider finalization—and in-region object-storage reads are free of internet egress fees.
    3. 8 MiB chunks hit the sweet spot: small enough that a dropped 2 Mbit/s cellular connection wastes at most 34 seconds of transfer, yet large enough to cap quarantine object count under 10 million/day.
    4. ~37 PB/year of cumulative video makes lifecycle tiering to cold storage and retention-driven purging essential for cost control.
  3. API design

    Devices authenticate via mutual TLS (mTLS) using their hardware certificate. Every mutating endpoint is idempotent (safe to retry on flaky networks without creating duplicate sessions or corrupting state).

    1. Device Upload APIs
    POST /v1/uploads
      Body:    { "recording_id": "clip-7042",
                 "manifest": { "device_id": "bwc-309", "officer_id": "off-512",
                               "start_ts": "...", "end_ts": "...",
                               "file_size": 943718400, "chunk_size": 8388608,
                               "chunk_sha256": ["b4e1...", "72a9...", ...],
                               "file_sha256": "9c74d108..." },
                 "manifest_signature": "30450221..." }      # Signed by camera's hardware key
      201:     { "upload_id": "sess-840", "chunk_count": 113, "received_chunks": [] }
               (Idempotent on (device_id, recording_id): retrying returns existing session & progress)
    
    PUT /v1/uploads/{upload_id}/chunks/{index}
      Headers: Content-Length: 8388608, X-Chunk-SHA256: 72a9...
      201:     { "index": 1, "sha256": "72a9...", "receipt_id": "rcpt-3190" }
      200:     Already stored with identical hash (safe network retry)
      422:     Computed SHA-256 did not match signed manifest -> discard & resend chunk
    
    GET /v1/uploads/{upload_id}
      200:     { "state": "OPEN", "missing_chunks": [37, 38, 112] }   # Enables parallel/out-of-order resume
    
    POST /v1/uploads/{upload_id}:complete
      202:     { "evidence_id": "evid-615", "state": "RECEIVED" }
      409:     { "missing_chunks": [112] }
    
    GET /v1/uploads/{upload_id}/receipt
      200:     { "state": "AVAILABLE", "verified_sha256": "9c74d108...", "safe_to_delete_local": true }
    
    2. Investigator & Prosecutor Evidence APIs (OIDC login + RBAC; every call writes a custody event)
    GET  /v1/evidence/{id}                        -> Metadata, hashes, scan verdicts, holds, retention
    POST /v1/evidence/{id}/playback-sessions      -> Short-lived URL to transcoded streaming proxy
    POST /v1/evidence/{id}/downloads              -> {reason, case_id} -> One-time token for original blob
    POST /v1/evidence/{id}/exports                -> {case_id, recipient} -> Self-verifying court bundle
    PUT  /v1/evidence/{id}/legal-hold             -> {enabled, case_id, reason}
    PUT  /v1/evidence/{id}/retention              -> {retain_until} (extend freely; never shorten lock)
    POST /v1/evidence/{id}/deletion-requests      -> {reason} (requires a second independent approver)
    GET  /v1/evidence/{id}/custody                -> Ordered custody events + verification status
    POST /v1/evidence/{id}/custody:verify         -> Recomputes hash chain, Merkle proofs & timestamps
    
    • Why safe_to_delete_local is separate from :complete: If a camera erased its local flash right when :complete returned 202, a storage failure before assembly would lose the evidence forever. safe_to_delete_local turns true only after the assembled object has been read back from disk and verified against file_sha256. (If a camera streams segments while still recording, it closes 20-minute segments with individual manifests—or supplies per-chunk X-Chunk-SHA256 on PUT and presents the signed manifest on :complete.)
  4. Data model and evidence state machine

    Core Relational Tables (PostgreSQL, primary + synchronous standby):
      devices          (device_id PK, tenant_id, cert_fingerprint, public_key, status)
      upload_sessions  (upload_id PK, tenant_id, device_id, recording_id UNIQUE(device_id, recording_id),
                        manifest_json, manifest_sig, chunk_size, chunk_count,
                        declared_size, declared_sha256, state, created_at, last_chunk_at)
      chunk_receipts   ((upload_id, chunk_idx) PK, byte_size, gateway_sha256,
                        quarantine_key, object_version, gateway_node, received_at)
      evidence_items   (evidence_id PK, tenant_id, upload_id, officer_id, device_id,
                        recorded_start, recorded_end, byte_size, verified_sha256, receipts_merkle_root,
                        quarantine_key, evidence_key, evidence_version, state,
                        retain_until, legal_hold, custody_head_seq, custody_head_hash)
      scan_results     ((evidence_id, check_type) PK, engine_name, engine_version, verdict, scanned_at)
      derived_assets   (asset_id PK, evidence_id, kind [proxy|thumbnail|redacted], sha256, object_key)
      custody_events   ((evidence_id, seq) PK, event_type, actor_id, auth_ctx, occurred_at,
                        details_json, prev_hash, event_hash)          -- INSERT-only for app role
      custody_anchors  (anchor_id PK, window_end, merkle_root, prev_anchor_hash,
                        hsm_signature, key_id, rfc3161_tsa_token, worm_leaf_list_key)
    

    Every state transition updates evidence_items and appends a custody_events row inside one atomic SQL transaction:

      OPEN ---(:complete)---> RECEIVED ---> ASSEMBLING ---> CHECKING ---> PROMOTING ---> AVAILABLE
        |                                       |              |    |                        |
        | (7d no chunks)                        v              |    +---> REJECTED           | (retention expired,
        v                                INTEGRITY_FAILED <----+          (security hold)    |  no legal hold,
     STALLED                             (retained for                    |                  |  2 approvals)
     (alert agency;                       investigation)                  +--> MANUAL_REVIEW v
      resumable, never                                                         (scanner err) DELETED
      auto-deleted)                                                                          (tombstone +
                                                                                              custody kept)
    
  5. High-level architecture and quarantine-vs-evidence storage layout

     Cameras / Station Docks (mTLS)                             Investigators / Prosecutors (OIDC)
              | 8 MiB chunk PUTs                                               |
              v                                                                v
     +--------------------+   write chunks   +-----------------------------+  +--------------------+
     | Upload Gateways    |----------------->| QUARANTINE CLOUD ACCOUNT    |  | Evidence API       |
     | - Hash stream live |                  | - chunks/{up}/{idx}/{sha}   |  | - RBAC + case auth |
     | - Match manifest   |                  | - assembled/{up}            |  | - Fail-closed log  |
     +---------+----------+                  | - rejected/  &  derived/    |  +----+----------+----+
               | receipts                    +------+--------------^-------+       |          |
               v                                    | read         | write         |          |
     +--------------------+   outbox jobs    +------v--------------+-------+       |          |
     | Metadata & Custody |----------------->| Pipeline Workers            |       |          |
     | DB (PostgreSQL)    |<-----------------| 1. Assembler                |       |          |
     | - Sessions & items |  atomic state +  | 2. Sandboxed Scanner/Prober |       |          |
     | - Custody chains   |  custody event   | 3. Promoter  4. Transcoder  |       |          |
     +---------+----------+                  +--------------+--------------+       |          |
               | 1-min batch anchor                         | copy, read-back,     v          v
               v                                            v & apply WORM lock   +----------------+
     +--------------------+                  +-----------------------------+      | Download Proxy |
     | WORM Anchor Store  |                  | EVIDENCE CLOUD ACCOUNT      |----->| & Short-Lived  |
     | - HSM-signed roots |                  | - Versioned + Object Lock   |      | Proxy CDN URLs |
     | - Leaf lists + TSA |                  | - Per-tenant KMS keys       |      +----------------+
     +--------------------+                  | - Cross-region replicated   |
                                             +-----------------------------+
    

    Why split Quarantine and Evidence into two separate cloud accounts: Video parsers, malware scanners, and transcoders must inspect untrusted bytes—historically one of the highest-risk attack surfaces for memory-corruption exploits. Placing Quarantine in its own cloud account ensures the scanner and transcoder hold zero IAM permissions to the Evidence account. Even if a crafted MP4 exploits a decoder inside its sandbox, it has no network route and no credentials to read, alter, or delete promoted evidence. Only the tiny Promoter service (which copies opaque bytes without parsing video) can write new objects into the Evidence account, and no service role has delete permission before retention expiry.

  6. Deep dive 1: Resumable chunked uploads and server-side byte proof

    Why chunks stream through our Upload Gateways: If clients uploaded directly to object storage via pre-signed URLs, we would have to trust the storage provider's reported checksum at upload time or re-read every chunk immediately. Streaming chunks through stateless Upload Gateways lets our code compute SHA-256 over the raw TCP bytes in flight. At 22.5 Gbit/s peak, 9 gateway VMs (3 per availability zone, 10 Gbit/s NICs at < 30% utilization) handle the entire fleet comfortably.

    Step-by-step lifecycle of a single chunk (PUT /v1/uploads/U/chunks/37):

    1. Gateway streams the 8 MiB request body to quarantine key chunks/U/37/{declared_sha}
       while feeding every byte through a streaming SHA-256 hasher in RAM.
    2. Stream ends -> compare gateway_sha256 against manifest.chunk_sha256[37]:
       - Mismatch (flipped bit on cellular link) -> delete quarantine object, return 422 Unprocessable.
       - Match -> INSERT INTO chunk_receipts (U, 37, size, gateway_sha256, key, version, now())
                  ON CONFLICT (upload_id, chunk_idx) DO NOTHING, then return 201 Created.
    
    • Resuming after flaky drops: Each 8 MiB PUT is atomic. If patrol-car Wi-Fi drops at 7 MiB, no receipt row is written; when connectivity returns, GET /v1/uploads/U returns missing_chunks as a set of integer indexes, so the camera resends chunk 37 (and can upload multiple missing chunks in parallel once docked on gigabit Ethernet). If a gateway crashes after writing the object to Quarantine but before committing the receipt row, the retry harmlessly overwrites the deterministic key chunks/U/37/{sha}, and a daily janitor deletes unreferenced quarantine objects older than 24 hours.

    Proving server-side assembly without trusting cloud multipart finalization: We record five independent SHA-256 checkpoints in the custody log and promote only when all of them agree bit-for-bit:

    1. device_signed_sha256  : Whole-file SHA-256 signed inside the camera's hardware key before upload
    2. receipts_merkle_root  : Merkle root over (chunk_idx, byte_size, gateway_sha256) of all N chunks
    3. assembled_sha256      : Whole-file SHA-256 computed by our Assembler while concatenating chunks
    4. readback_sha256       : Whole-file SHA-256 computed by reading the finalized Quarantine object back
    5. evidence_sha256       : Whole-file SHA-256 computed by reading the copied Evidence object back
    
    Promotion invariant:  device_signed == assembled == readback == evidence, AND all chunk hashes match!
    

    Even if the cloud provider's underlying CompleteMultipartUpload reordered parts, dropped trailing bytes, or fabricated an ETag, readback_sha256 and evidence_sha256 are computed by reading the finalized stored object back from byte 0 to EOF—catching any storage-layer defect immediately.

    To avoid storing millions of permanent chunk_receipts rows in PostgreSQL forever while still letting an auditor prove any chunk receipt belonged to the upload, we summarize all chunk receipts with a Merkle tree—a binary tree of hashes where each parent hashes its two children up to a single 32-byte root hash. Prefixing leaves with 0x00 and internal nodes with 0x01 (domain separation) prevents an attacker from passing off an internal pair of hashes as a fake leaf:

    import hashlib
    
    
    def merkle_root(leaves):
        """Compute a tamper-evident 32-byte Merkle root over an ordered list of byte strings."""
        if not leaves:
            return hashlib.sha256(b"").digest()
    
        # Hash every leaf with a 0x00 domain-separation prefix.
        current_level = []
        for leaf_bytes in leaves:
            leaf_digest = hashlib.sha256(b"\x00" + leaf_bytes).digest()
            current_level.append(leaf_digest)
    
        # Repeatedly pair adjacent nodes with a 0x01 internal-node prefix until 1 root remains.
        while len(current_level) > 1:
            next_level = []
            for idx in range(0, len(current_level) - 1, 2):
                left = current_level[idx]
                right = current_level[idx + 1]
                parent_digest = hashlib.sha256(b"\x01" + left + right).digest()
                next_level.append(parent_digest)
    
            # If this level has an odd number of nodes, promote the trailing node unchanged.
            if len(current_level) % 2 == 1:
                next_level.append(current_level[-1])
            current_level = next_level
    
        return current_level[0]
    
  7. Deep dive 2: Background assembly, sandboxed scanning, and promotion

    Every background stage is triggered via a transactional outbox (the PostgreSQL transaction that updates evidence_items.state also inserts a job row into an outbox table, which a relay publishes to workers—guaranteeing no state transition ever loses its background job). Every stage is idempotent on upload_id.

    Stage 1: Assemble (RECEIVED -> ASSEMBLING -> CHECKING). An Assembler worker streams chunks/U/0..N-1 in index order from Quarantine, re-computing each chunk's SHA-256 against chunk_receipts (catching silent corruption inside Quarantine), writes the contiguous stream to assembled/U (using multipart upload purely as an untrusted write transport), and verifies assembled_sha256 == manifest.file_sha256. On mismatch, the item enters INTEGRITY_FAILED and alerts engineering while preserving all chunks.

    Stage 2: Read-back verification & isolated security checks (CHECKING). A coordinator reads assembled/U back from Quarantine once from byte 0 to EOF and tees that byte stream into four checks:

    1. Independent read-back hash (readback_sha256): Confirms storage actually returns the exact assembled bytes. Only once this matches file_sha256 do we set safe_to_delete_local = true so the camera can free its flash storage.
    2. Magic-byte & container box-tree validation: Never trust filename extensions or Content-Type headers. A memory-safe parser verifies the file starts with a valid container header (such as an MP4 ftyp atom), checks codecs against an explicit allowlist (e.g., H.264/H.265 video + AAC/Opus audio), and verifies that top-level MP4 box lengths sum exactly to the file's byte size with zero trailing bytes. Rejecting trailing bytes blocks polyglot files—malicious files crafted to play as a valid MP4 while hiding a valid ZIP archive, script, or executable at the end of the file.
    3. Signature & heuristic malware scan: Runs updated AV engines over the stream and logs exact engine + signature-database versions.
    4. Sandboxed frame-decode probe: Samples keyframes inside an ephemeral microVM sandbox (such as AWS Firecracker or gVisor—a single-use virtualized jail with zero network access, strict CPU/RAM quotas, and automatic destruction after one file) to catch malformed bitstreams targeting decoder vulnerabilities.
    • Verdict routing: All pass -> PROMOTING. Malware or invalid structure -> REJECTED (moved to rejected/ under security hold—never auto-deleted, because a tampering attempt on a police camera is itself forensic evidence!). Scanner crash/timeout after 3 fresh-sandbox retries -> MANUAL_REVIEW (never fail-open into promotion).

    Stage 3: Verify-before-lock promotion (PROMOTING -> AVAILABLE). We use WORM (Write Once, Read Many) Object Lock in Compliance Mode—a storage-level lock where nobody, not even the cloud account's root administrator, can overwrite or delete that object version before retain_until. Because Compliance locks are irreversible, the exact order of operations is critical:

    Step A: Copy assembled/U -> evidence/{tenant}/{evidence_id}/original (encrypted with tenant KMS key;
            files > 5 GB use multipart server-side copy).
    Step B: Read the new Evidence object back byte-for-byte -> compute evidence_sha256.
            If evidence_sha256 != readback_sha256: DELETE the unlocked copy immediately and retry!
    Step C: ONLY AFTER Step B matches, apply Compliance-Mode Object Lock (retain_until = category minimum).
    Step D: Commit SQL transaction: state = AVAILABLE + append PROMOTED custody event.
    

    Stage 4: Sandboxed proxy transcoding. A sandboxed transcoder reads assembled/U inside Quarantine (never holding Evidence credentials!) to generate a 1.5 Mbit/s streaming proxy and thumbnails in derived/U/. The Promoter copies those derived assets into the Evidence account and logs a DERIVED custody event linking each proxy's SHA-256 back to the untouched original's SHA-256.

  8. Deep dive 3: Tamper-evident chain of custody

    Why isn't an INSERT-only PostgreSQL table enough for legal chain of custody? Because a compromised server admin or rogue DBA with superuser access can temporarily disable database triggers and rewrite rows. Even if we link rows in a per-item hash chain, a superuser could still: 1. Rewrite and re-hash an entire item's chain from event 1 to the end, OR 2. Truncate the tail—delete the most recent 2 events (say, an unauthorized DOWNLOADED event!) and rewind custody_head_hash, leaving a shorter chain whose math still verifies cleanly!

    We defeat both attacks with a two-layer custody architecture:

    Layer 1: Per-item cryptographic hash chain (inside PostgreSQL). Every action on evidence_id locks its evidence_items row, increments seq, and hashes the canonical JSON event together with prev_hash:

    genesis("evid-615") ---> Event 1 (UPLOAD_RECEIVED) ---> Event 2 (VERIFIED) ---> Event 3 (PROMOTED)
                             prev = genesis                 prev = H(Event 1)       prev = H(Event 2)
    
    import hashlib
    import json
    
    
    def genesis_hash(evidence_id):
        """Deterministic starting anchor for one evidence item's custody chain."""
        return hashlib.sha256(("genesis:" + evidence_id).encode("utf-8")).hexdigest()
    
    
    def compute_event_hash(fields, prev_hash):
        """Hash canonical sorted-key JSON of the event fields plus the previous event's hash."""
        payload = dict(fields)
        payload["prev_hash"] = prev_hash
        canonical_json = json.dumps(payload, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical_json.encode("utf-8")).hexdigest()
    
    
    def verify_item_chain(evidence_id, ordered_events):
        """Return True only if seq has no gaps and every prev_hash/event_hash link matches."""
        expected_prev = genesis_hash(evidence_id)
        expected_seq = 1
    
        for event in ordered_events:
            if event["seq"] != expected_seq or event["prev_hash"] != expected_prev:
                return False
            # Recompute hash from all fields except prev_hash and event_hash.
            core_fields = {}
            for key, value in event.items():
                if key not in ("prev_hash", "event_hash"):
                    core_fields[key] = value
            if compute_event_hash(core_fields, expected_prev) != event["event_hash"]:
                return False
            expected_prev = event["event_hash"]
            expected_seq += 1
    
        return True
    

    Layer 2: 1-minute HSM-signed Merkle anchors + external timestamps + WORM leaf lists. Every 60 seconds, an Anchor Worker collects all ~700 custody_events committed across all items during that minute: 1. Computes merkle_root over their (evidence_id, seq, event_hash) leaves. 2. Signs (window_end, merkle_root, prev_anchor_hash) using an asymmetric key stored inside an HSM (Hardware Security Module)—dedicated hardware that signs digests without ever letting any administrator export the private signing key. 3. Obtains an RFC 3161 cryptographic timestamp token from an independent external Time-Stamping Authority (TSA), proving to any court that this Merkle root existed no later than window_end. 4. Writes the signed anchor plus the compact list of (evidence_id, seq, event_hash) leaves (< 100 KB/min) into a separate WORM-locked bucket (and replicates it to an external archive). Because that WORM leaf list cannot be deleted, tail truncation is caught immediately: if someone deletes Event 9 from PostgreSQL, the WORM leaf list from that minute still proves Event 9 existed!

    Fail-closed access auditing: When a prosecutor requests an original video download, the Evidence API commits the DOWNLOADED custody event before returning the one-time download token. If the custody database is unreachable, the download fails closed (503)—guaranteeing no byte of evidence can ever be served off the record.

  9. Access control, scaling, and failure handling

    Defense-in-depth security & access control: - Tenant isolation via envelope encryption: Every evidence object is encrypted with a unique data key wrapped by that agency's dedicated KMS (Key Management Service) key, and every API request assumes a short-lived IAM role scoped solely to the caller's tenant_id key—so an application bug querying the wrong object key fails at KMS decryption. - Audited sharing & dual-control deletion: Routine viewers watch watermarked streaming proxies via 5-minute signed URLs; original downloads stream through our Download Proxy using single-use tokens. Deleting expired evidence requires now > retain_until, legal_hold == false, and two distinct authorized approvers; deletion removes the video blobs while retaining the metadata tombstone and full custody chain forever.

    Scaling & long-term durability: - Transcoding pool: 30,000 video hours/day at 5x real-time encode speed requires 30,000 / (24 × 5) = 250 worker instances (or ~40 GPU/ASIC-accelerated nodes), autoscaled on queue depth. - Quarantine cleanup & cold tiering: chunk_receipts rows and Quarantine chunks are deleted 30 days after promotion (after saving a signed receipt manifest beside the Evidence object). Originals transition to cold archive storage after 60–90 days (logging a MOVED custody event and re-verifying SHA-256 upon any cold restore). - Bit-rot scrubbing: A background scrubber continuously re-hashes hot Evidence objects (~1 GB/s read rate checks 30 PB/year) and logs INTEGRITY_CHECKED; if a disk bit flip ever occurs, it repairs from the verified cross-region replica.

    Failure modes: - Dropped chunk or rebooted camera: Resend only missing 8 MiB chunks via idempotent session lookup; camera keeps local copy until safe_to_delete_local == true. - Stalled upload (camera powered off in locker): Flagged STALLED after 7 idle days to alert agency supervisors; never auto-purged. - Worker, KMS, or DB outage: Outbox retries assembly/scanning safely; KMS/TSA delays only lag the 1-minute anchor batch without blocking uploads; custody DB downtime fails closed on reads/downloads while cameras continue buffering locally.

  10. Summary of design trade-offs

    • Streaming chunks through our Upload Gateways vs. pre-signed direct S3 uploads: Gives server-computed per-chunk SHA-256 receipts and instant rejection of corrupted chunks, at the cost of running ~9 gateway nodes to carry 22.5 Gbit/s peak ingress.
    • Full read-back verification (3 internal reads/byte) vs. trusting cloud ETags: Directly satisfies "cannot trust provider multipart finalization" by verifying what storage actually returns, at the cost of ~243 TB/day of in-region read I/O.
    • Separate Quarantine and Evidence cloud accounts vs. single bucket with tags: Eliminates any credential path from high-risk video/AV parsers to promoted evidence, adding one cross-account server-side copy and verification read.
    • Fixed 8 MiB chunk retries vs. byte-offset streaming resume: Enables simple parallel uploads and pre-signed per-chunk manifest hashes, wasting at most ~34 s on a 2 Mbit/s link when a connection drops mid-chunk.
    • Per-item hash chain + 1-minute HSM/TSA WORM anchors vs. plain append-only SQL table: Detects insider tampering, full-chain rewrites, and tail truncation with third-party mathematical proof, adding an HSM/TSA pipeline and a 60-second pre-anchor window.
    • Fail-closed audit logging & post-verification Compliance locks: Guarantees zero unlogged access and zero premature deletion even by root admins, requiring read-back verification before locking so a corrupted copy is never locked permanently.

Intuition & how it works

Think of this system like a courthouse evidence vault guarded by an air-gapped X-ray mailroom and a notarized ledger. When an officer's body camera finishes recording, it seals a signed packing slip (manifest) listing the exact cryptographic fingerprint (SHA-256 hash, a 256-bit digest that changes completely if even one bit flips) of every 8 MiB slice and of the complete video. Over shaky cellular service, the camera mails those 8 MiB slices in any order to our Quarantine mailroom (a completely separate cloud account): a clerk weighs and hashes each arriving slice on the spot, crosses it off the checklist, and only tells the camera "safe to erase your memory card" after gluing all slices together, reading the entire assembled movie back from storage, and confirming its fingerprint matches the camera's signed slip. Next, isolated robots inside disposable microVM sandboxes (single-use virtual machines with no network cable and zero keys to the main vault) inspect the file's container structure and scan for malware before a courier copies the clean video into the Evidence vault under a WORM (Write Once, Read Many) Compliance lock that not even a system administrator can delete early. Every single touch—from upload to courtroom export—adds a numbered link to a hash chain (where each log entry embeds the fingerprint of the previous entry) that is stamped every 60 seconds by an external Time-Stamping Authority (TSA) so nobody can silently edit, rewrite, or rip pages out of the ledger.

Why do simpler cloud-upload patterns fall short here? Using standard pre-signed multipart uploads and trusting the cloud provider's CompleteMultipartUpload ETag fails the core requirement: multipart ETags only hash per-part checksums (MD5(part1 || part2...)-N) reported by the vendor, offering zero server-side proof if storage finalization reorders parts or drops bytes. Scanning files inside the same bucket where evidence lives means a single video-decoder exploit could let an attacker read or corrupt other cases' footage. Finally, storing custody logs in a plain INSERT-only SQL table—or even an unanchored hash chain—lets a rogue database administrator rewrite hashes from start to finish or delete the newest rows (tail truncation) without leaving a trace.

Let us trace an 18 MiB wearable-camera clip (clip-7042, split into three chunks of 8 MiB, 8 MiB, and 2 MiB) from field unit bwc-309 (off-512) to courtroom verification:

1. Camera prepares signed manifest before upload:
   chunk_sha256 = [H0, H1, H2],  file_sha256 = HF,  signed by bwc-309's hardware key.

2. Flaky cellular upload into QUARANTINE account (session sess-840):
   - PUT chunk 0 -> Gateway hashes bytes = H0 (matches!) -> stores receipt 0 (201)
   - PUT chunk 1 -> Cellular bit-flip! Gateway hashes = BAD != H1 -> deletes blob, returns 422
   - PUT chunk 1 (retry) -> Gateway hashes = H1 (matches!) -> stores receipt 1 (201)
   - PUT chunk 2 -> Gateway hashes = H2 (matches!) -> stores receipt 2 (201)
   - POST :complete -> item evid-615 state = RECEIVED, Event #1 (UPLOAD_RECEIVED, receipts_merkle_root)

3. Server-side assembly, read-back proof, scan & promotion:
   - Assembler re-hashes chunks 0..2, writes assembled/sess-840 -> assembled_sha256 == HF
   - Verifier reads assembled/sess-840 back from disk -> readback_sha256 == HF
     (Camera now sees safe_to_delete_local = true!)
   - Sandboxed MP4 box parser + AV + frame decode all pass -> Event #2/#3 (VERIFIED, SCAN_RESULT)
   - Promoter copies to EVIDENCE account -> reads copy back -> evidence_sha256 == HF ->
     applies Compliance WORM Lock -> state = AVAILABLE, Event #4 (PROMOTED)

4. Tamper-evident custody check when Prosecutor downloads original:
   - Event #5 (DOWNLOADED) committed BEFORE token is issued; anchored at 09:15:00Z in WORM + TSA.
   - If a rogue DBA later deletes Event #5 from Postgres, custody:verify checks the 09:15:00Z
     WORM leaf list, sees (evid-615, seq=5) missing from Postgres, and flags TAMPERING DETECTED!

Key trade-offs

  • Proxying uploads through our gateways vs. direct pre-signed object-storage URLs. Routing chunks through stateless Upload Gateways lets our code compute SHA-256 on incoming bytes, reject corrupted chunks immediately with 422, and issue receipts without trusting provider-reported checksums. The trade-off is running ~9 gateway nodes to carry 22.5 Gbit/s peak ingress instead of offloading ingress bandwidth directly to S3.
  • Full byte read-back verification (3 internal reads/byte) vs. trusting provider multipart completion. Reading chunks during assembly (1x), reading the finalized quarantine blob back (1x), and reading the promoted evidence blob back (1x) generates ~243 TB/day of internal reads for 81 TB/day of uploads. That I/O cost buys mathematical proof over the exact bytes storage returns rather than trusting cloud finalization metadata.
  • Hardware-signed device manifests vs. server-only hashing. Signing (chunk_sha256[], file_sha256) inside the camera's hardware secure element proves provenance from the moment of recording and catches transit corruption on every chunk PUT. It requires device PKI certificate lifecycle management and revocation lists, whereas third-party web uploads can only anchor provenance starting at server receipt time.
  • Two separate cloud accounts (Quarantine vs. Evidence) vs. one bucket with object tags. Isolating Quarantine in its own account guarantees that high-risk video decoders, malware scanners, and transcoders never hold IAM credentials to Evidence storage. The cost is one cross-account server-side copy and verification pass per video.
  • Fixed 8 MiB chunk retries vs. byte-offset streaming resume. Retrying whole 8 MiB chunks keeps PUT operations atomic, enables parallel multi-chunk uploads on station docks, and aligns cleanly with manifest chunk hashes, trading away at most ~34 seconds of wasted upload on a 2 Mbit/s link when a connection drops mid-chunk.
  • Per-item hash chain + 1-minute HSM/TSA WORM anchors vs. append-only database permissions. Combining per-item hash links with 1-minute Merkle tree roots (binary hash trees summarizing a batch of events) signed by an HSM (Hardware Security Module), stamped by an external RFC 3161 TSA, and paired with WORM-locked leaf lists catches edits, full-chain rewrites, and tail truncation even by database superusers. The cost is maintaining signing/TSA infrastructure and accepting a 60-second exposure window before a new minute's events are externally anchored.
  • Fail-closed custody logging and Compliance-mode WORM locks vs. operational flexibility. Refusing downloads when the custody database is down guarantees 100% of accesses are logged at the expense of read availability during DB outages. Similarly, Compliance-mode WORM locks prevent even a compromised root admin from deleting evidence, which means we must read back and verify the Evidence object before applying the lock and lock only for the minimum statutory period (extending later via legal holds).

Common mistakes

  • Trusting the cloud provider's multipart ETag or 200 OK completion response as proof of assembled file integrity, violating the prompt's explicit constraint and missing silent truncation or part-ordering bugs.
  • Allowing the camera to delete its local recording as soon as the final chunk PUT or :complete succeeds, before the server has assembled the file and verified readback_sha256 from disk.
  • Exposing uploaded videos before scanning finishes, or running ffmpeg/AV parsers outside a networkless sandbox while holding read/write credentials to the production Evidence bucket.
  • Validating file type only by .mp4 extension or first few magic bytes instead of walking the full MP4 container box tree to reject polyglot files (valid video headers followed by appended archives or scripts).
  • Relying on an INSERT-only SQL table or an unanchored hash chain for chain of custody, overlooking that a privileged insider can recompute an unanchored chain from genesis or truncate the newest events off the tail without breaking earlier links.
  • Applying Compliance-mode Object Lock before reading back and verifying the copied Evidence object, which permanently locks a corrupted blob so nobody can clean it up.
  • Writing audit logs asynchronously after serving a video download, allowing crashes or queue drops to serve evidence with no custody record, or overwriting the original video during transcoding/redaction instead of storing derived assets linked by hash.

Follow-up questions

  • How can an independent defense expert verify offline that neither the video bytes nor the custody history were tampered with, without trusting your live servers? We export a self-contained verification package containing the original video file, the camera's hardware-signed manifest and device certificate chain, the ordered custody_events JSON entries, each entry's Merkle inclusion proof up to its 1-minute custody_anchor, the HSM signatures, and the independent RFC 3161 TSA tokens. An open-source offline verifier recomputes the video's SHA-256, confirms it matches both the hardware signature and the PROMOTED entry, checks every hash link from genesis_hash, and validates each Merkle proof against the external TSA timestamp—with zero network calls back to our servers. To additionally verify that no recent entries were omitted from the end of the ledger, a court-appointed auditor inspects the immutable WORM leaf lists (mirrored to an independent archive) to confirm every anchored (evidence_id, seq) pair appears in the export.
  • When an agency releases a clip publicly with blurred faces, license plates, or muted audio, how do you produce and store the redacted copy without breaking chain of custody on the original? The locked original Evidence object is never altered or unlocked. Instead, the redaction pipeline copies the verified original into the Quarantine account, checks its SHA-256, and runs blurring and audio muting inside a networkless sandboxed worker that holds zero Evidence-account credentials. The Promoter then copies the newly rendered MP4 into evidence/{tenant}/{evidence_id}/derived/{asset_id}, verifies its read-back digest, and appends a DERIVED custody entry recording the original's SHA-256, the redacted asset's SHA-256, the redaction model/tool version, the exact timecode and mask coordinates, and the approving official—preserving a cryptographic link between the public release and the untouched court original.
  • Suppose a high-priority incident occurs in a rural area with only a shaky 500 kbit/s cellular link and supervisors need rapid situational video. How would you adapt ingestion without weakening evidentiary guarantees? Transferring a 20-minute 1080p recording (~0.9 GB) over 500 kbit/s (62.5 KB/s) takes ~4 hours, whereas a 2-minute 360p preview encoded at 250 kbit/s (~3.8 MB) finishes in ~60 seconds. We run dual-track priority ingestion: pressing an incident button causes the camera to first upload a low-bitrate preview explicitly labeled NON_EVIDENTIARY_PREVIEW (still vetted in Quarantine before playback) using smaller 1 MiB chunks (~16 seconds per chunk at 500 kbit/s so connection drops lose minimal progress), while simultaneously prioritizing the 5-minute full-resolution segment straddling the incident marker ahead of routine patrol segments. Supervisors gain visibility within two minutes, and the hardware-signed full-resolution segments finish uploading over cellular or station Wi-Fi to become the WORM-locked evidentiary record.

Follow-up questions

Similar questions

More Axon interview questions

All 17 Axon questions →