mirror of
https://github.com/block/buzz.git
synced 2026-11-28 20:22:39 +00:00
## Summary Adds a durable, operator-controlled V1 for deleting an entire Buzz community without deleting another tenant's data. The workflow is exposed through `buzz-admin deletions`: - `sweep` records independent fleet storage-taxonomy observations - `submit`, `list`, `inspect`, and `approve` manage a deletion request - `unblock` resumes a fail-closed request after an operator records remediation identity and reason - `run` and `drain` execute bounded work Requests advance through a PostgreSQL-backed state machine and stop at `retention_pending` after logical deletion has been independently verified across PostgreSQL, object storage, and Redis. This PR ships the engine and CLI, not a continuously running worker or Kubernetes packaging. For V1, a cluster/VM administrator invokes `/usr/local/bin/buzz-admin` from the existing relay image, for example with `kubectl exec` or an equivalent container/VM exec path. ## What whole-community V1 removes For the target community, V1 removes: - rows from the allowlisted community-scoped PostgreSQL catalog, including members, profiles, authored events and bodies, DMs, reactions, mentions, memberships, tokens, workflows, moderation, audit, feedback, and rate-limit state - media sidecars and upload-attribution records under `_meta/<community>/` and `_uploads/<community>/` - Git repository pointers under `repos/<community>/` - Redis keys under `buzz:<community>:*` The community row survives as a permanent tombstone, and deletion control-plane records remain as evidence of the request, approval, execution, and result. ## Safety model Deletion is not a broad `DELETE CASCADE` followed by optimistic cleanup. The destructive boundaries are durable and fail closed. ### 1. Inventory and approval - `submit` resolves the target and freezes the schema plus summary-only storage inventory. - Approval is bound to the exact request, community, and frozen inventory digest. - Unsupported manifest versions, malformed keys inside the target's owned prefixes, live scoped-table/write-fence coverage drift, frozen-inventory mismatch, and approval mismatch block execution rather than guessing. Migration and catalog revision numbers are not authorization gates; the executor validates the live safety shape instead. - Storage inventory is server-side prefix scoped to exactly: - `_meta/<community>/` - `_uploads/<community>/` - `repos/<community>/` - The deletion path never lists the whole shared bucket and has no arbitrary per-community object cap. Its listing work is proportional to the target community's bindings, not total fleet storage. - Fleet-wide taxonomy sweeps remain independent observability. They report unknown writer shapes but do not gate deletion submission, fencing, or destructive progress. Maintainers must add deletion taxonomy coverage whenever a new community-owned object-key class is introduced; writer-coverage tests bind the current media and Git writers to that contract. ### 2. Quiesce, fence, and destructive freeze - Writes continue through submission, inventory, and approval. They stop when execution moves the target into `quiescing` and then establishes the durable fence. - Already-admitted external effects finish under heartbeated serving-write leases; the exact admitted lease may renew while the community is quiescing, but new lease acquisition is rejected. The executor drains admitted leases before destructive work. - Invite minting after quiescing begins fails as typed `AccessDenied` (HTTP 503 at the relay boundary) before an invite can be persisted. - Database triggers enforce the community write fence across the complete catalog of community-scoped tables. Startup/readiness and destructive execution validate that catalog so a newly added but unfenced table cannot silently escape. - **Named isolation assumption — fresh write snapshot.** Every writer transaction that can reach a community-fenced relation must use PostgreSQL `READ COMMITTED`; each guarded write therefore observes a statement snapshot no older than acquisition of the community deletion lock. `REPEATABLE READ` and `SERIALIZABLE` can retain a pre-fence snapshot and are unsupported for writers. The writer pool refuses non-`READ COMMITTED` sessions at connection setup, and both SQL fence functions reject an explicit per-transaction isolation override with SQLSTATE `25000`. Configuration-delivered bad isolation can surface through SQLx as a pool-acquire timeout because every `after_connect` attempt is rejected; the precise `community writes require READ COMMITTED isolation` reason remains observable when the SQL guard is reached. Read-only replica transactions are outside this assumption. - Holding the shared advisory lock until the guarded write executes is a separate liveness condition: under `READ COMMITTED`, releasing it early does not permit resurrection because the trigger rechecks the fence, but it can turn a fleet sweep into a statement-wide SQLSTATE `55000` abort. - After the fence closes writers, storage is re-enumerated into chunked side-table rows. Per-prefix counts and digests bind those concrete keys to the destructive manifest. - Manifest chunk insertion, update, and deletion are protected after freeze. This closes the race where an unbound key could otherwise appear after the manifest was committed. ### 3. Checkpointed destruction - Target-owned object bindings are deleted from the frozen destructive manifest in bounded batches with durable progress. - The concrete key list lives in chunked side-table rows rather than one request-row JSON value. It supports large communities, resumable execution, and terminal cleanup. - Missing objects are accepted as idempotent crash-window outcomes; malformed ownership, changed evidence, and unexplained target-prefix drift fail closed. - PostgreSQL purging remains scoped by `community_id`, including the guarded NIP-RS hard-delete path discovered with real Desktop kind `30078` read-state data. - Redis cleanup explicitly scans and `UNLINK`s only `buzz:<community_id>:*`. Natural expiry is insufficient because some keys, including tunnel generation counters used as fencing state, are deliberately persistent. ### 4. Independent verification - PostgreSQL logical absence is checked after purge. - The three target-owned storage prefixes are freshly inventoried again and must be empty. - Redis requires two complete empty namespace scans. - Only after all three stores pass does the request advance through `logically_verified` to `retention_pending`. ## What V1 deliberately does not erase ### Shared content-addressed storage Per-community deletion removes bindings, metadata, attribution records, and Git pointers. It does **not** physically delete fleet-shared CAS bytes that another community may still reference: - media blobs and thumbnails - Git manifests, packs, and indexes (`manifests/`, `packs/`, and `idx/`) Safe reclamation requires a separate fleet-wide reachability and retention GC. Unknown keys elsewhere in the shared bucket do not block one community's deletion; malformed or unrecognized keys inside that community's three owned prefixes still fail closed. ### External retained copies The online logical-deletion proof does not erase object versions/replicas, database backups/WAL, CDN copies, provider retention copies, or observability exports. Those require their own retention and purge controls. ### Member-only erasure This PR erases a whole community. It does not implement the different operation "erase one npub while preserving the community." Removing membership or accepting NIP-09 is not member erasure. A member-only workflow would need to find and selectively remove or redact authored event content and pubkeys, profile data, DMs, reactions, mentions, memberships/roles, tokens, workflows/subscriptions, upload attribution, moderation/audit history, repository attribution, and identity embedded in tags or JSON. It would also need explicit rules for ownership transfer, surviving replies and thread metadata, audit-chain integrity, immutable Git history, and shared-CAS reachability. That requires a pubkey-level fence and selective graph rewrite; it is a separate deletion product, not a safe extension of this whole-tenant worker. ## In scope - migration `0029_community_deletion.sql`: requests, approvals, leases, manifest chunks, checkpoints, tombstones, and the universal write-fence catalog - durable executor leases, generations, heartbeats, retry/block state, and resumable stage transitions - operator-driven `sweep`, `submit`, `list`, `inspect`, `approve`, `unblock`, `run`, and `drain` commands - serving-path fences for database writes and external effects across event ingest, media, Git, workflow, push, invites, mesh/tunnel, and related paths - target-prefix-only storage inventory, summary manifests, post-fence destructive chunks, and bounded batch deletion - exact community Redis namespace purge and two-pass absence verification - cross-community isolation, crash/resume, manifest-integrity, writer-taxonomy, and schema/migration regressions - desired-state `schema/schema.sql` support without requiring a SQLx migration ledger ## Deferred / not covered - dedicated Helm/chart worker Deployment, service account, secrets, probes, resources, and network policy - autonomous `buzz-admin deletions worker` poll loop and worker-only health server - least-privilege separation among migration, relay-serving, and destructive execution roles - fleet-wide shared-CAS physical GC - backup/provider/CDN/observability retention completion - member-only erasure - provider-native conditional-delete improvements - a general force-continue escape hatch; permanent safety failures remain fail closed unless an operator remediates the cause and records an audited `unblock` The removed continuous-worker implementation remains deferred; no remote follow-up branch is claimed by this PR. ## Validation ### Current PR head and repository state Current pushed head: `359d8402ee15f049768f54156f67b953c7a7e2ed`, rebased onto `cc9a2f783375e51a6e8d1f2f9d01d5f7e22813d1` (`origin/main` at push time). The complete PR diff is now 47 files, 9,834 additions, and 517 deletions. The bespoke source-scanner stack was removed to keep this PR scoped to community deletion. Tyler/team requested the underlying fenced-write safety behavior, not `ast-grep`, `crates/buzz-db/tests/community_fenced_writes.rs`, its 27 fixtures, or the new `scripts/lints/community_*.yml` rules. Those scanner-specific files, dependencies, Hermit links, and runner wiring are absent from the current tree. The production database write fence, startup/destructive live-catalog validation, and deletion behavior remain. Source validation on this exact SHA passed: - `cargo fmt --all -- --check` - `bash -n scripts/run-tests.sh` - `cargo nextest run -p buzz-db --all-targets`: 102 passed, 173 skipped, 0 failed - `cargo nextest run -p buzz-deletion --all-targets`: 10 passed, 9 skipped, 0 failed - `cargo nextest run -p buzz-admin --all-targets`: 1 passed, 0 failed - affected-package/all-target Clippy with warnings denied - lockfile consistency - Helm 3.16.4 lint and all 44 chart unit tests - Helm region controls using that fixture: default `BUZZ_S3_REGION=us-east-1`, explicit `eu-west-2` override, and blank-region schema rejection The prior Kubernetes battery below was run against `928992237358a3294621ac0280830b77155abc04`. It remains useful evidence for the patch-equivalent production deletion implementation, but it is **not** claimed as exact-SHA evidence for current head `359d8402ee15f049768f54156f67b953c7a7e2ed`; the current cleanup removes only scanner/test/tooling infrastructure. CI restarted for the new head after the rebase and is pending. Human review remains `CHANGES_REQUESTED`. ### Prior-head live Kubernetes deletion and safety gates The full program used one immutable image, real PostgreSQL, Redis, MinIO, and a three-relay Kubernetes release: - source: `928992237358a3294621ac0280830b77155abc04` (**prior head**) - image: `buzz-e2e:sha-928992237358` - immutable image digest: `sha256:a1a204f4618ac22d9e210be5e5290645a15d79831ae30b0e44379357c8e4a895` - evidence root: `/tmp/buzz-e2e/20260807T033025Z-928992237358-full-gates/` - evidence-manifest digest: `82875c5bc9bea7370b796a7aef3457b3a1c8306c84c59e0f7388bbb5ad30e865` Passed gates at that prior head: - **Chart/operator region:** default `us-east-1`, explicit nondefault propagation, blank-region schema rejection, live in-pod environment, and an in-pod taxonomy sweep over 18 objects with zero unknown. - **Fenced writers and lifecycle:** open-write/fence ordering; 100-attempt anti-starvation; invite, push matcher, and exhausted-reaper bystander isolation; non-`READ-COMMITTED` rejection; manifest/tombstone contracts; eight-failure stage block and audited `unblock`. - **Destructive lifecycle:** submit → approve → run → `retention_pending`; PostgreSQL tombstone and Redis/S3 verification true; zero retries/errors; terminal reruns rejected with exit 5. - **Fresh 10,001-object crash boundary:** exactly two chunks (10,000 + 1). The executor deleted chunk 0 from MinIO while its PostgreSQL stamp was row-lock-blocked, was killed with `SIGKILL`, left one object and both stamps absent, then resumed the same request under generation 2 to zero objects and terminal state. - **Independent dead-owner recovery:** a dedicated executor claimed generation 1, blocked before effects, and was killed through containerd with `SIGKILL` (no TERM cleanup). The request remained owned and unreclaimable before lease expiry; a successor claimed generation 2 after 60 seconds and completed with two attempts and zero retries. - **Three-pod socket isolation:** ordinary NIP-42 and joined huddle-audio target witnesses on every replica received exact `1008 / community deleted`; healthy-tenant witnesses on those pods remained live; deleted-host reconnect returned HTTP 404. - **Health/provenance:** all replicas independently returned ready and retained the exact image digest before/after destructive runs and an audio-enabled rolling restart; PostgreSQL, Redis, and MinIO were healthy at close. Instrument corrections were retained as evidence rather than counted as product failures: a foreground PostgreSQL forward caused an initial `PoolTimedOut`; Kubernetes pod deletion exercised graceful TERM rather than dead-owner recovery; shell-background socket witnesses died with their parent; and the first image build hit the corporate TLS proxy. Detached forwarding/witnesses, containerd `SIGKILL`, and the configured internal CA/Artifactory mirror produced the discriminating runs without weakening product security. ### Prior-head cleanup For the prior-head Kubernetes run, the Helm release was removed, namespace absence was verified, run-owned Screen sessions were absent, and that source worktree remained clean. The evidence manifest was independently recomputed and every indexed artifact passed `shasum -a 256 -c`. The current `359d8402` source worktree is also clean after the scanner-only cleanup and push. --------- Signed-off-by: npub122y0pqkertljmedu303rl0aqrj3w8pvu43t6jxm6875lzg6f2pwqegc3xc <5288f082d91aff2de5bc8be23fbfa01ca2e3859cac57a91b7a3fa9f12349505c@buzz.block.builderlab.xyz> Signed-off-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz> Signed-off-by: Kalvin Chau <kalvin@block.xyz> Signed-off-by: am <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz> Signed-off-by: cid <d9f92a72922bf45c17379a47d64dae84b6020397c2d5a52b5317d512068cd9d3@buzz.block.builderlab.xyz> Co-authored-by: npub122y0pqkertljmedu303rl0aqrj3w8pvu43t6jxm6875lzg6f2pwqegc3xc <5288f082d91aff2de5bc8be23fbfa01ca2e3859cac57a91b7a3fa9f12349505c@buzz.block.builderlab.xyz> Co-authored-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz> Co-authored-by: cid <d9f92a72922bf45c17379a47d64dae84b6020397c2d5a52b5317d512068cd9d3@buzz.block.builderlab.xyz>
582 lines
22 KiB
Rust
582 lines
22 KiB
Rust
//! Manifest schema for git-on-object-storage.
|
|
//!
|
|
//! The manifest is the immutable, content-addressed snapshot of a repo's
|
|
//! published state at a single point in time (§System Model). A push commits
|
|
//! by CAS-installing a new pointer to a new manifest digest; readers resolve
|
|
//! pointer → manifest → packs to hydrate (§Read).
|
|
//!
|
|
//! ## Canonical serialization
|
|
//!
|
|
//! `Manifest::canonical_bytes()` produces a deterministic byte sequence so
|
|
//! that `key == sha256(bytes)` (A1 detectability):
|
|
//!
|
|
//! - `refs: BTreeMap` — sorted ref names at serialization.
|
|
//! - `packs: Vec<String>` — sorted by `canonical_bytes()` before writing.
|
|
//! - Struct field order: `version`, `head`, `refs`, `packs`, `parent`
|
|
//! (matches declaration; serde emits in this order).
|
|
//! - `serde_json::to_vec` — no whitespace.
|
|
//!
|
|
//! Round-trip + byte-stability are pinned in unit tests.
|
|
//!
|
|
//! ## Why HEAD is in the manifest
|
|
//!
|
|
//! HEAD is *published* ref state (§Implementation Correspondence), not a
|
|
//! read-time default. Deriving it ("default to main, fallback to first head")
|
|
//! would let a clone advertise a different default branch than the writer
|
|
//! intended — `Inv_RefEffectApplied` would not hold.
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
use buzz_core::tenant::CommunityId;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
/// Current manifest schema version. Bump on incompatible change.
|
|
pub const MANIFEST_VERSION: u32 = 1;
|
|
/// Maximum number of pack objects one manifest may reference.
|
|
///
|
|
/// Hydration indexes packs one at a time, but an unbounded pack list still
|
|
/// turns one request into unbounded object-store and git subprocess work.
|
|
pub const MAX_MANIFEST_PACKS: usize = 128;
|
|
/// Pack count that triggers proactive consolidation during the next accepted push.
|
|
///
|
|
/// Keeping one quarter of the manifest capacity in reserve prevents a hot
|
|
/// repository from reaching the hard limit while a prior compaction attempt
|
|
/// falls back to the normal delta-pack path.
|
|
pub const PACK_COMPACTION_THRESHOLD: usize = MAX_MANIFEST_PACKS * 3 / 4;
|
|
/// Maximum number of refs one manifest may advertise.
|
|
pub const MAX_MANIFEST_REFS: usize = 10_000;
|
|
|
|
/// A repository's published state.
|
|
///
|
|
/// Field order is significant for canonical JSON — do not reorder.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct Manifest {
|
|
/// Schema version. Must equal [`MANIFEST_VERSION`] on read.
|
|
pub version: u32,
|
|
/// Symbolic HEAD ref, unprefixed (e.g. `"refs/heads/main"`). No `"ref: "`
|
|
/// — that's a Git-protocol formatting concern, applied at hydrate time.
|
|
pub head: String,
|
|
/// All refs in the published state: refname → 40-char hex oid.
|
|
pub refs: BTreeMap<String, String>,
|
|
/// Store keys of every pack covering `refs`. Sorted ascending —
|
|
/// `canonical_bytes` enforces this on serialize.
|
|
pub packs: Vec<String>,
|
|
/// **Bare hex digest** of the manifest this one supersedes (64 chars,
|
|
/// SHA-256), or `None` for the first push to a fresh repo. Contrast with
|
|
/// `packs` which carries full store keys (`packs/<hex>`); `parent` is the
|
|
/// digest alone, matching the pointer-body shape so `Inv_RefDerivedFromParent`
|
|
/// reads literally as `parent = pointer.digest`. Writers must strip any
|
|
/// `manifests/` prefix before assigning. Enforced by `validate()`.
|
|
pub parent: Option<String>,
|
|
}
|
|
|
|
/// Errors from manifest (de)serialization or validation.
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum ManifestError {
|
|
/// `serde_json` failed to encode or decode.
|
|
#[error("manifest serde: {0}")]
|
|
Serde(#[from] serde_json::Error),
|
|
/// On-the-wire manifest carried a `version` we don't understand.
|
|
#[error("unsupported manifest version {got} (expected {expected})")]
|
|
UnsupportedVersion {
|
|
/// The version we read.
|
|
got: u32,
|
|
/// The version we support.
|
|
expected: u32,
|
|
},
|
|
/// A refname in `refs` (or `head`) violates `is_safe_refname` — must start
|
|
/// with `refs/`, no traversal, no control chars. Symmetric write-side check
|
|
/// for the reader-side validation in `api::git::hydrate`.
|
|
#[error("manifest contains unsafe ref name {0:?}")]
|
|
UnsafeRefName(String),
|
|
/// An object id in `refs` is not a valid hex SHA-1 (40) or SHA-256 (64).
|
|
#[error("manifest ref {refname:?} has malformed oid {oid:?}")]
|
|
MalformedOid {
|
|
/// The ref carrying the bad oid.
|
|
refname: String,
|
|
/// The oid that failed validation.
|
|
oid: String,
|
|
},
|
|
/// Manifest `head` is empty — pre-CAS validation must reject this so we
|
|
/// never commit an un-clone-able manifest (read side `is_safe_refname("")`
|
|
/// returns false).
|
|
#[error("manifest head is empty")]
|
|
EmptyHead,
|
|
/// `parent` is not a bare 64-char hex digest. Common mistake: storing the
|
|
/// full store key (`manifests/<hex>`) instead of stripping the prefix.
|
|
/// Breaks the "manifest.parent == pointer.digest" model invariant
|
|
/// (`Inv_RefDerivedFromParent`).
|
|
#[error("manifest parent is not a bare 64-char hex digest: {0:?}")]
|
|
MalformedParent(String),
|
|
/// Manifest names too many packs for one bounded hydration request.
|
|
#[error("manifest contains too many packs: {got} (max {max})")]
|
|
TooManyPacks {
|
|
/// Number of pack keys in the manifest.
|
|
got: usize,
|
|
/// Hard cap enforced by the relay.
|
|
max: usize,
|
|
},
|
|
/// Manifest names too many refs for one bounded advertisement request.
|
|
#[error("manifest contains too many refs: {got} (max {max})")]
|
|
TooManyRefs {
|
|
/// Number of refs in the manifest.
|
|
got: usize,
|
|
/// Hard cap enforced by the relay.
|
|
max: usize,
|
|
},
|
|
/// A pack key is not exactly `packs/<64 lowercase hex sha256>`.
|
|
#[error("manifest contains malformed pack key {0:?}")]
|
|
MalformedPackKey(String),
|
|
}
|
|
|
|
/// Conservative refname validation, used symmetrically on both the write side
|
|
/// (in `Manifest::validate`, before `put_manifest`) and the read side (in
|
|
/// `api::git::hydrate`, before writing the ref to disk).
|
|
///
|
|
/// Refuses traversal (`..`), null/newline/control chars, non-`refs/` prefixes,
|
|
/// and leading/trailing/double slashes. Allowed alphabet:
|
|
/// `[a-zA-Z0-9_./-]`.
|
|
///
|
|
/// Sharing one predicate is load-bearing: any divergence creates the
|
|
/// "valid CAS, un-clone-able output" hazard.
|
|
pub fn is_safe_refname(s: &str) -> bool {
|
|
if !s.starts_with("refs/") {
|
|
return false;
|
|
}
|
|
if s.contains("..") || s.contains("//") || s.starts_with('/') || s.ends_with('/') {
|
|
return false;
|
|
}
|
|
s.chars()
|
|
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '.' | '-'))
|
|
}
|
|
|
|
/// Hex-OID predicate. Accepts both SHA-1 (40 chars) and SHA-256 (64 chars) —
|
|
/// buzz pins SHA-1 today but the predicate is forward-looking. Used
|
|
/// symmetrically by write-side validation and read-side hydration.
|
|
pub fn is_hex_oid(s: &str) -> bool {
|
|
(s.len() == 40 || s.len() == 64) && s.chars().all(|c| c.is_ascii_hexdigit())
|
|
}
|
|
|
|
/// Bare manifest-digest predicate (64-char hex SHA-256).
|
|
///
|
|
/// Distinct from `is_hex_oid` (which also accepts 40-char SHA-1 for ref OIDs):
|
|
/// manifest digests are *always* SHA-256, so this is the tighter predicate
|
|
/// for the `Manifest::parent` field.
|
|
fn is_manifest_digest(s: &str) -> bool {
|
|
s.len() == 64 && s.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f'))
|
|
}
|
|
|
|
/// Content-addressed pack-key predicate.
|
|
pub fn is_pack_key(s: &str) -> bool {
|
|
s.strip_prefix("packs/").is_some_and(is_manifest_digest)
|
|
}
|
|
|
|
/// The canonical pointer key for a repo: `repos/<community>/<owner>/<repo>/pointer`.
|
|
///
|
|
/// Single source of truth shared by `cas_publish` (write side) and `hydrate`
|
|
/// (read side). Strips a trailing `.git` if the caller passed it. The
|
|
/// `repos/<community>/<owner>/<repo>/` namespace keeps the existing repo-local
|
|
/// subtree intact under the server-resolved community boundary, while shared
|
|
/// pack/manifest CAS objects remain outside that scoped pointer namespace.
|
|
pub fn pointer_key(community: CommunityId, owner: &str, repo: &str) -> String {
|
|
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
|
format!("repos/{community}/{owner}/{repo}/pointer")
|
|
}
|
|
|
|
impl Manifest {
|
|
/// Validate pre-commit invariants.
|
|
///
|
|
/// **Writers must call this before `canonical_bytes` → `put_manifest`.**
|
|
/// A manifest that hydrators reject (unsafe refname, malformed oid, empty
|
|
/// HEAD) MUST NOT be written: it would CAS successfully and then 5xx every
|
|
/// subsequent clone — "valid CAS, un-clone-able output". Pre-CAS rejection
|
|
/// turns those into push-time 4xx, which is the right surface for the bug.
|
|
///
|
|
/// Checks:
|
|
/// - `head` is non-empty and passes `is_safe_refname`.
|
|
/// - Every key in `refs` passes `is_safe_refname`.
|
|
/// - Every value in `refs` is a hex OID per `is_hex_oid`.
|
|
/// - Pack/ref cardinality stays within bounded hydration limits.
|
|
/// - Every pack key is a canonical content-addressed key.
|
|
/// - `parent`, if `Some`, is a bare 64-char hex digest (not a store key).
|
|
///
|
|
/// Read-side `hydrate` runs the same predicates as defense-in-depth.
|
|
pub fn validate(&self) -> Result<(), ManifestError> {
|
|
if self.packs.len() > MAX_MANIFEST_PACKS {
|
|
return Err(ManifestError::TooManyPacks {
|
|
got: self.packs.len(),
|
|
max: MAX_MANIFEST_PACKS,
|
|
});
|
|
}
|
|
if self.refs.len() > MAX_MANIFEST_REFS {
|
|
return Err(ManifestError::TooManyRefs {
|
|
got: self.refs.len(),
|
|
max: MAX_MANIFEST_REFS,
|
|
});
|
|
}
|
|
if self.head.is_empty() {
|
|
return Err(ManifestError::EmptyHead);
|
|
}
|
|
if !is_safe_refname(&self.head) {
|
|
return Err(ManifestError::UnsafeRefName(self.head.clone()));
|
|
}
|
|
for (refname, oid) in &self.refs {
|
|
if !is_safe_refname(refname) {
|
|
return Err(ManifestError::UnsafeRefName(refname.clone()));
|
|
}
|
|
if !is_hex_oid(oid) {
|
|
return Err(ManifestError::MalformedOid {
|
|
refname: refname.clone(),
|
|
oid: oid.clone(),
|
|
});
|
|
}
|
|
}
|
|
for pack in &self.packs {
|
|
if !is_pack_key(pack) {
|
|
return Err(ManifestError::MalformedPackKey(pack.clone()));
|
|
}
|
|
}
|
|
if let Some(p) = &self.parent {
|
|
if !is_manifest_digest(p) {
|
|
return Err(ManifestError::MalformedParent(p.clone()));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Serialize to canonical bytes suitable for `put_manifest`.
|
|
///
|
|
/// Sorts `packs` defensively (writer is responsible for keeping them
|
|
/// sorted, but a misuse should not silently break content-addressing).
|
|
///
|
|
/// Does NOT call `validate()` — callers must invoke it explicitly so a
|
|
/// validation failure is visible at the write seam, not buried inside
|
|
/// serialization.
|
|
pub fn canonical_bytes(&self) -> Result<Vec<u8>, ManifestError> {
|
|
let mut owned = self.clone();
|
|
owned.packs.sort();
|
|
owned.packs.dedup();
|
|
Ok(serde_json::to_vec(&owned)?)
|
|
}
|
|
|
|
/// Parse from bytes; reject unknown schema versions.
|
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self, ManifestError> {
|
|
let m: Manifest = serde_json::from_slice(bytes)?;
|
|
if m.version != MANIFEST_VERSION {
|
|
return Err(ManifestError::UnsupportedVersion {
|
|
got: m.version,
|
|
expected: MANIFEST_VERSION,
|
|
});
|
|
}
|
|
Ok(m)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn pack_key(ch: char) -> String {
|
|
format!("packs/{}", ch.to_string().repeat(64))
|
|
}
|
|
|
|
fn sample() -> Manifest {
|
|
let mut refs = BTreeMap::new();
|
|
refs.insert(
|
|
"refs/heads/main".into(),
|
|
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
|
|
);
|
|
refs.insert(
|
|
"refs/heads/feature".into(),
|
|
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".into(),
|
|
);
|
|
Manifest {
|
|
version: MANIFEST_VERSION,
|
|
head: "refs/heads/main".into(),
|
|
refs,
|
|
packs: vec![pack_key('c'), pack_key('d')],
|
|
parent: Some("ee".repeat(32)),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn canonical_bytes_round_trip() {
|
|
let m = sample();
|
|
let bytes = m.canonical_bytes().unwrap();
|
|
let back = Manifest::from_bytes(&bytes).unwrap();
|
|
assert_eq!(m, back);
|
|
}
|
|
|
|
#[test]
|
|
fn canonical_bytes_byte_stable_across_ref_insertion_order() {
|
|
// Insert refs in opposite orders; canonical bytes must match because
|
|
// BTreeMap iterates sorted.
|
|
let mut a = sample();
|
|
a.refs.clear();
|
|
a.refs.insert("refs/heads/zzz".into(), "11".repeat(20));
|
|
a.refs.insert("refs/heads/aaa".into(), "22".repeat(20));
|
|
let mut b = sample();
|
|
b.refs.clear();
|
|
b.refs.insert("refs/heads/aaa".into(), "22".repeat(20));
|
|
b.refs.insert("refs/heads/zzz".into(), "11".repeat(20));
|
|
assert_eq!(a.canonical_bytes().unwrap(), b.canonical_bytes().unwrap());
|
|
}
|
|
|
|
#[test]
|
|
fn canonical_bytes_sorts_and_dedups_packs() {
|
|
let mut m = sample();
|
|
m.packs = vec![pack_key('d'), pack_key('c'), pack_key('d')];
|
|
let bytes = m.canonical_bytes().unwrap();
|
|
let back = Manifest::from_bytes(&bytes).unwrap();
|
|
assert_eq!(back.packs, vec![pack_key('c'), pack_key('d')]);
|
|
}
|
|
|
|
#[test]
|
|
fn safe_refnames_predicate() {
|
|
assert!(is_safe_refname("refs/heads/main"));
|
|
assert!(is_safe_refname("refs/tags/v1.0.0"));
|
|
assert!(is_safe_refname("refs/heads/feat/cas-publish"));
|
|
assert!(!is_safe_refname("refs/heads/../escape"));
|
|
assert!(!is_safe_refname("HEAD"));
|
|
assert!(!is_safe_refname(""));
|
|
assert!(!is_safe_refname("refs/heads/"));
|
|
assert!(!is_safe_refname("/refs/heads/main"));
|
|
assert!(!is_safe_refname("refs/heads/main\nrefs/heads/evil"));
|
|
assert!(!is_safe_refname("refs/heads/main\0"));
|
|
}
|
|
|
|
#[test]
|
|
fn hex_oid_predicate() {
|
|
assert!(is_hex_oid(&"a".repeat(40)));
|
|
assert!(is_hex_oid(&"a".repeat(64)));
|
|
assert!(!is_hex_oid(&"a".repeat(39)));
|
|
assert!(!is_hex_oid(&"g".repeat(40)));
|
|
assert!(!is_hex_oid(""));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_happy_path() {
|
|
sample().validate().expect("sample manifest must validate");
|
|
}
|
|
|
|
/// The empty manifest is the announce-time seed (`side_effects.rs::
|
|
/// seed_manifest_pointer`). It must validate — otherwise repo announce
|
|
/// would fail before the pointer can be seeded, and the read path would
|
|
/// 404 every freshly-announced repo. This pins that contract.
|
|
#[test]
|
|
fn empty_manifest_validates() {
|
|
let m = Manifest {
|
|
version: MANIFEST_VERSION,
|
|
head: "refs/heads/main".into(),
|
|
refs: BTreeMap::new(),
|
|
packs: Vec::new(),
|
|
parent: None,
|
|
};
|
|
m.validate().expect("empty manifest is the announce-seed");
|
|
// Canonical bytes must be deterministic + stable so all empty manifests
|
|
// share one digest (idempotent put_manifest, one shared S3 object).
|
|
let bytes = m.canonical_bytes().expect("serialize");
|
|
let s = std::str::from_utf8(&bytes).expect("utf8");
|
|
assert_eq!(
|
|
s,
|
|
r#"{"version":1,"head":"refs/heads/main","refs":{},"packs":[],"parent":null}"#
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_empty_head() {
|
|
let mut m = sample();
|
|
m.head = String::new();
|
|
assert!(matches!(m.validate(), Err(ManifestError::EmptyHead)));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_unsafe_head() {
|
|
let mut m = sample();
|
|
m.head = "refs/heads/..".into();
|
|
assert!(matches!(m.validate(), Err(ManifestError::UnsafeRefName(_))));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_non_refs_head() {
|
|
let mut m = sample();
|
|
m.head = "HEAD".into();
|
|
assert!(matches!(m.validate(), Err(ManifestError::UnsafeRefName(_))));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_unsafe_ref_name() {
|
|
let mut m = sample();
|
|
m.refs.insert("refs/heads/bad\nname".into(), "a".repeat(40));
|
|
assert!(matches!(m.validate(), Err(ManifestError::UnsafeRefName(_))));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_malformed_oid() {
|
|
let mut m = sample();
|
|
m.refs
|
|
.insert("refs/heads/ok".into(), "not-a-hex-oid".into());
|
|
assert!(matches!(
|
|
m.validate(),
|
|
Err(ManifestError::MalformedOid { .. })
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_parent_with_store_prefix() {
|
|
// The common bug Perci named: storing the full key in `parent` instead
|
|
// of the bare digest. `Inv_RefDerivedFromParent` reads `parent =
|
|
// pointer.digest`; carrying the prefix breaks the model literal.
|
|
let mut m = sample();
|
|
m.parent = Some(format!("manifests/{}", "a".repeat(64)));
|
|
assert!(matches!(
|
|
m.validate(),
|
|
Err(ManifestError::MalformedParent(_))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_short_parent() {
|
|
let mut m = sample();
|
|
m.parent = Some("abc".into());
|
|
assert!(matches!(
|
|
m.validate(),
|
|
Err(ManifestError::MalformedParent(_))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_malformed_pack_key() {
|
|
let mut m = sample();
|
|
m.packs = vec!["packs/not-a-digest".into()];
|
|
assert!(matches!(
|
|
m.validate(),
|
|
Err(ManifestError::MalformedPackKey(_))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_rejects_too_many_packs() {
|
|
let mut m = sample();
|
|
m.packs = (0..=MAX_MANIFEST_PACKS)
|
|
.map(|i| format!("packs/{i:064x}"))
|
|
.collect();
|
|
assert!(matches!(
|
|
m.validate(),
|
|
Err(ManifestError::TooManyPacks { .. })
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn validate_accepts_no_parent() {
|
|
let mut m = sample();
|
|
m.parent = None;
|
|
m.validate().expect("no parent is fine (first push)");
|
|
}
|
|
|
|
#[test]
|
|
fn pointer_writer_is_covered_by_deletion_taxonomy() {
|
|
let community = CommunityId::from_uuid(uuid::Uuid::from_u128(1));
|
|
let owner = "a".repeat(64);
|
|
let key = pointer_key(community, &owner, "repo");
|
|
let prefixes = buzz_media::tenant_prefixes(*community.as_uuid());
|
|
|
|
assert!(prefixes.iter().any(|prefix| key.starts_with(prefix)));
|
|
assert!(buzz_media::is_tenant_owned_key(*community.as_uuid(), &key));
|
|
}
|
|
|
|
#[test]
|
|
fn pointer_key_strips_dot_git() {
|
|
let c = CommunityId::from_uuid(uuid::Uuid::from_u128(1));
|
|
assert_eq!(
|
|
pointer_key(c, "alice", "myrepo"),
|
|
format!("repos/{c}/alice/myrepo/pointer")
|
|
);
|
|
assert_eq!(
|
|
pointer_key(c, "alice", "myrepo.git"),
|
|
format!("repos/{c}/alice/myrepo/pointer")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn pointer_key_is_community_scoped() {
|
|
let a = CommunityId::from_uuid(uuid::Uuid::from_u128(1));
|
|
let b = CommunityId::from_uuid(uuid::Uuid::from_u128(2));
|
|
|
|
assert_ne!(
|
|
pointer_key(a, "alice", "repo"),
|
|
pointer_key(b, "alice", "repo")
|
|
);
|
|
assert_eq!(
|
|
pointer_key(a, "alice", "repo"),
|
|
format!("repos/{a}/alice/repo/pointer")
|
|
);
|
|
assert_ne!(pointer_key(a, "alice", "repo"), "repos/alice/repo/pointer");
|
|
}
|
|
|
|
/// Mutate-bite shape for git hosting: same owner/repo string in two
|
|
/// communities must resolve to different pointer cells. If the community
|
|
/// segment is dropped from `pointer_key`, B overwrites A and A observes B's
|
|
/// manifest pointer (wrong answer, not absence).
|
|
#[test]
|
|
fn same_owner_repo_pointers_do_not_bleed_between_communities() {
|
|
use std::collections::HashMap;
|
|
|
|
let a = CommunityId::from_uuid(uuid::Uuid::from_u128(1));
|
|
let b = CommunityId::from_uuid(uuid::Uuid::from_u128(2));
|
|
let mut pointers = HashMap::new();
|
|
|
|
pointers.insert(pointer_key(a, "alice", "repo"), "manifest-a");
|
|
pointers.insert(pointer_key(b, "alice", "repo"), "manifest-b");
|
|
|
|
assert_eq!(pointers[&pointer_key(a, "alice", "repo")], "manifest-a");
|
|
assert_eq!(pointers[&pointer_key(b, "alice", "repo")], "manifest-b");
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_unknown_version() {
|
|
let mut m = sample();
|
|
m.version = 999;
|
|
let bytes = serde_json::to_vec(&m).unwrap();
|
|
let err = Manifest::from_bytes(&bytes).unwrap_err();
|
|
assert!(matches!(
|
|
err,
|
|
ManifestError::UnsupportedVersion { got: 999, .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn first_push_has_no_parent() {
|
|
let mut m = sample();
|
|
m.parent = None;
|
|
let bytes = m.canonical_bytes().unwrap();
|
|
let back = Manifest::from_bytes(&bytes).unwrap();
|
|
assert!(back.parent.is_none());
|
|
}
|
|
|
|
/// Pin the exact byte shape so any unintended change to serialization
|
|
/// (field order, whitespace, key ordering) triggers a failure rather than
|
|
/// silently shifting the manifest digest.
|
|
#[test]
|
|
fn canonical_bytes_pinned() {
|
|
let mut refs = BTreeMap::new();
|
|
refs.insert("refs/heads/main".into(), "a".repeat(40));
|
|
let m = Manifest {
|
|
version: 1,
|
|
head: "refs/heads/main".into(),
|
|
refs,
|
|
packs: vec![pack_key('1')],
|
|
parent: None,
|
|
};
|
|
let bytes = m.canonical_bytes().unwrap();
|
|
let s = std::str::from_utf8(&bytes).unwrap();
|
|
assert_eq!(
|
|
s,
|
|
format!(
|
|
r#"{{"version":1,"head":"refs/heads/main","refs":{{"refs/heads/main":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}},"packs":["{}"],"parent":null}}"#,
|
|
pack_key('1')
|
|
)
|
|
);
|
|
}
|
|
}
|