From c3eae7910e0624eaada79c3d12d1bff653c120f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 06:42:01 +0000 Subject: [PATCH] id: gallery admission: public removals, review posture, transparency list Removals, refusals and reinstatements from the hosted gallery are written to an append-only transparency list (record identity, time, reason class) and served at /api/gallery/transparency. A removal hides the record from this endpoint only and keeps its bundle, so a reinstatement reverses it. Posture (open or reviewed) and per-class response hours are configuration in operator/admission.json, and 'id gallery' administers removals, appeals, review, posture and the operator's tags offline. Closes #10005 Co-Authored-By: Claude Opus 5.5 --- pkgs/id/crates/id-cli/src/cli/gallery.rs | 93 ++ pkgs/id/crates/id-cli/src/cli/mod.rs | 14 +- pkgs/id/crates/id-cli/src/cli/tests.rs | 51 ++ pkgs/id/crates/id-cli/src/commands/gallery.rs | 195 +++++ pkgs/id/crates/id-cli/src/commands/mod.rs | 2 + pkgs/id/crates/id-cli/src/commands/serve.rs | 7 +- pkgs/id/crates/id-web/src/gallery.rs | 153 +++- pkgs/id/crates/id-worlds/src/lib.rs | 1 + .../crates/id-worlds/src/program_gallery.rs | 291 ++++++- .../src/program_gallery_admission.rs | 822 ++++++++++++++++++ .../crates/id-worlds/src/program_registry.rs | 21 + pkgs/id/src/main.rs | 1 + 12 files changed, 1627 insertions(+), 24 deletions(-) create mode 100644 pkgs/id/crates/id-cli/src/cli/gallery.rs create mode 100644 pkgs/id/crates/id-cli/src/commands/gallery.rs create mode 100644 pkgs/id/crates/id-worlds/src/program_gallery_admission.rs diff --git a/pkgs/id/crates/id-cli/src/cli/gallery.rs b/pkgs/id/crates/id-cli/src/cli/gallery.rs new file mode 100644 index 0000000000..7d2a30fc2d --- /dev/null +++ b/pkgs/id/crates/id-cli/src/cli/gallery.rs @@ -0,0 +1,93 @@ +//! `id gallery`: administer the gallery directory that +//! `id serve --web --gallery-dir` serves (#10005; v3 design G2, G6). + +use std::path::PathBuf; + +use clap::{Args, Subcommand}; +use id_worlds::program_gallery_admission::{AdmissionPosture, ReasonClass}; + +/// Arguments for `id gallery`. +#[derive(Args, Debug)] +pub struct GalleryArgs { + /// The gallery directory: the one `id serve --gallery-dir` serves. A + /// running server reads it when it starts, so restart it to serve a + /// change. + #[arg(long, env = "ID_GALLERY_DIR")] + pub dir: PathBuf, + /// What to do. + #[command(subcommand)] + pub command: GalleryCommand, +} + +/// Subcommands for `id gallery`. +#[derive(Subcommand, Debug)] +pub enum GalleryCommand { + /// Stop listing a record here and write the removal to the public + /// transparency list. The bundle file is kept, and the record stays + /// valid on other hosts. + Remove { + /// The record's content hash. + content_hash: String, + /// Reason class: `illegal_content`, `malware`, `spam` or `policy`. + #[arg(long)] + reason: ReasonClass, + /// A short public note for the transparency list. + #[arg(long)] + note: Option, + }, + /// Refuse a record waiting for review, publicly. + Refuse { + /// The record's content hash. + content_hash: String, + /// Reason class: `illegal_content`, `malware`, `spam` or `policy`. + #[arg(long)] + reason: ReasonClass, + /// A short public note for the transparency list. + #[arg(long)] + note: Option, + }, + /// Reverse a removal or refusal (an appeal upheld) and list the record + /// again; the reinstatement goes on the transparency list. + Reinstate { + /// The record's content hash. + content_hash: String, + /// A short public note for the transparency list. + #[arg(long)] + note: Option, + }, + /// List a record waiting for review. + Approve { + /// The record's content hash. + content_hash: String, + }, + /// Show the records waiting for review. + Pending, + /// Show the transparency list. + Transparency, + /// Set the admission posture: `open` lists every verified record until + /// it is removed, `reviewed` lists a record once it is approved. + Posture { + /// open or reviewed. + posture: AdmissionPosture, + }, + /// State, or with no hours withdraw, the response time published for + /// one reason class. + ResponseHours { + /// Reason class: `illegal_content`, `malware`, `spam` or `policy`. + reason: ReasonClass, + /// Hours; leave out to withdraw the statement. + hours: Option, + }, + /// Set the operator's own tags for a program or an author (none clears + /// them). Tags are operator speech, served apart from signed records. + Tag { + /// A program's content hash. + #[arg(long, required_unless_present = "author", conflicts_with = "author")] + program: Option, + /// An author's public key. + #[arg(long)] + author: Option, + /// The tags, in the portable form (lower-case letters, digits, `-`). + tags: Vec, + }, +} diff --git a/pkgs/id/crates/id-cli/src/cli/mod.rs b/pkgs/id/crates/id-cli/src/cli/mod.rs index 1ccc5fe7c9..7f5fc44732 100644 --- a/pkgs/id/crates/id-cli/src/cli/mod.rs +++ b/pkgs/id/crates/id-cli/src/cli/mod.rs @@ -104,6 +104,7 @@ use clap::{Args, CommandFactory, Parser, Subcommand}; pub mod claim; pub mod doc; +pub mod gallery; pub mod groups; #[cfg(feature = "sandbox")] pub mod match_audit; @@ -113,6 +114,7 @@ pub mod writer_sets; pub use claim::{ClaimCommand, ClaimScope}; pub use doc::DocCommand; +pub use gallery::{GalleryArgs, GalleryCommand}; pub use groups::{DelegateArgs, GroupCommand, GroupRemoveMode, GroupTemplate, RevokeArgs}; #[cfg(feature = "sandbox")] pub use match_audit::MatchAuditCommand; @@ -474,10 +476,11 @@ pub struct ServeArgs { /// /// The web interface answers `/api/gallery/records`, /// `/api/gallery/bundles/`, `/api/gallery/search`, - /// `/api/gallery/authors/` and `/api/gallery/collections` from the - /// verified bundle files (`.idpb`) in the directory and - /// the operator's collections and tags under `operator/`. Every file is - /// verified when the server starts. + /// `/api/gallery/authors/`, `/api/gallery/collections` and + /// `/api/gallery/transparency` from the verified bundle files + /// (`.idpb`) in the directory and the operator's + /// collections, tags and admission decisions under `operator/` (managed + /// with `id gallery`). Every file is verified when the server starts. #[arg(long, env = "ID_GALLERY_DIR", requires = "web")] pub gallery_dir: Option, /// Host a multiplayer world over Iroh (and `/ws/world` with `--web`). @@ -1374,6 +1377,9 @@ pub enum Command { /// ``` #[command(subcommand)] World(Box), + /// Administer a program gallery directory: removals, appeals, review, + /// posture and operator tags, all on the public transparency list. + Gallery(GalleryArgs), /// Export and verify signed match-audit v0 logs. #[cfg(feature = "sandbox")] #[command(subcommand)] diff --git a/pkgs/id/crates/id-cli/src/cli/tests.rs b/pkgs/id/crates/id-cli/src/cli/tests.rs index b6d307edff..fb3230641d 100644 --- a/pkgs/id/crates/id-cli/src/cli/tests.rs +++ b/pkgs/id/crates/id-cli/src/cli/tests.rs @@ -3049,3 +3049,54 @@ fn test_every_verb_is_documented_and_dispatchable() { .join() .unwrap(); } + +#[test] +fn test_cli_parse_gallery_admin() { + use id_worlds::program_gallery_admission::{AdmissionPosture, ReasonClass}; + + let hash = "a".repeat(64); + match Cli::parse_from([ + "id", + "gallery", + "--dir", + "/srv/gallery", + "remove", + &hash, + "--reason", + "malware", + "--note", + "reported", + ]) + .command + { + Some(Command::Gallery(GalleryArgs { + dir, + command: + GalleryCommand::Remove { + content_hash, + reason, + note, + }, + })) => { + assert_eq!(dir, std::path::Path::new("/srv/gallery")); + assert_eq!(content_hash, hash); + assert_eq!(reason, ReasonClass::Malware); + assert_eq!(note.as_deref(), Some("reported")); + } + _ => panic!("Expected gallery remove"), + } + match Cli::parse_from(["id", "gallery", "--dir", "/g", "posture", "reviewed"]).command { + Some(Command::Gallery(GalleryArgs { + command: GalleryCommand::Posture { posture }, + .. + })) => assert_eq!(posture, AdmissionPosture::Reviewed), + _ => panic!("Expected gallery posture"), + } + assert!( + Cli::try_parse_from([ + "id", "gallery", "--dir", "/g", "remove", &hash, "--reason", "rude" + ]) + .is_err() + ); + assert!(Cli::try_parse_from(["id", "gallery", "--dir", "/g", "tag", "board"]).is_err()); +} diff --git a/pkgs/id/crates/id-cli/src/commands/gallery.rs b/pkgs/id/crates/id-cli/src/commands/gallery.rs new file mode 100644 index 0000000000..0a73432532 --- /dev/null +++ b/pkgs/id/crates/id-cli/src/commands/gallery.rs @@ -0,0 +1,195 @@ +//! `id gallery`: offline administration of a gallery directory (#10005). + +use anyhow::{Context as _, bail}; +use serde::Serialize; + +use id_worlds::program_gallery::Gallery; +use id_worlds::program_gallery_admission::AdmissionConfig; +use id_worlds::program_registry::AdmitAll; + +use crate::cli::{GalleryArgs, GalleryCommand}; + +/// Run a gallery administration command. +/// +/// # Errors +/// +/// The directory is missing or does not load, or the gallery refuses the +/// step. +pub fn cmd_gallery(args: GalleryArgs) -> anyhow::Result<()> { + if !args.dir.is_dir() { + bail!("{} is not a gallery directory", args.dir.display()); + } + let mut gallery = Gallery::open_dir(&args.dir, AdmitAll) + .with_context(|| format!("opening the gallery in {}", args.dir.display()))?; + match args.command { + GalleryCommand::Remove { + content_hash, + reason, + note, + } => print(&gallery.remove(&content_hash, reason, now(), note)?), + GalleryCommand::Refuse { + content_hash, + reason, + note, + } => print(&gallery.refuse(&content_hash, reason, now(), note)?), + GalleryCommand::Reinstate { content_hash, note } => { + print(&gallery.reinstate(&content_hash, now(), note)?) + } + GalleryCommand::Approve { content_hash } => print(&gallery.approve(&content_hash)?), + GalleryCommand::Pending => print(&gallery.pending()), + GalleryCommand::Transparency => print(gallery.admission().list().entries()), + GalleryCommand::Posture { posture } => { + let config = AdmissionConfig { + posture, + ..gallery.admission().config().clone() + }; + gallery.set_admission_config(config)?; + print(gallery.admission().config()) + } + GalleryCommand::ResponseHours { reason, hours } => { + let mut config = gallery.admission().config().clone(); + match hours { + Some(hours) => config.response_hours.insert(reason, hours), + None => config.response_hours.remove(&reason), + }; + gallery.set_admission_config(config)?; + print(gallery.admission().config()) + } + GalleryCommand::Tag { + program, + author, + tags, + } => { + let mut overlay = gallery.overlay().clone(); + let (map, key) = match (program, author) { + (Some(program), _) => (&mut overlay.programs, program), + (None, Some(author)) => (&mut overlay.authors, author), + (None, None) => bail!("name a --program or an --author"), + }; + if tags.is_empty() { + map.remove(&key); + } else { + map.insert(key, tags); + } + gallery.set_overlay(overlay)?; + print(gallery.overlay()) + } + } +} + +fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()) +} + +fn print(value: &(impl Serialize + ?Sized)) -> anyhow::Result<()> { + println!("{}", serde_json::to_string_pretty(value)?); + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use id_worlds::program_bundle::{ProgramSpec, export}; + use id_worlds::program_gallery_admission::{AdmissionPosture, ReasonClass}; + use id_worlds::program_registry::ListQuery; + + use super::*; + + fn run(dir: &std::path::Path, command: GalleryCommand) -> anyhow::Result<()> { + cmd_gallery(GalleryArgs { + dir: dir.to_path_buf(), + command, + }) + } + + #[test] + fn removal_review_and_tags_are_stored_for_the_server() { + let dir = tempfile::tempdir().unwrap(); + let chess = export( + b"chess".to_vec(), + ProgramSpec { + name: "chess", + version: 1, + licence: None, + description: Some("Board game."), + categories: &["board"], + }, + &ed25519_dalek::SigningKey::from_bytes(&[3; 32]), + ) + .unwrap(); + let hash = chess.manifest().content_hash.clone(); + Gallery::open_dir(dir.path(), AdmitAll) + .unwrap() + .publish(&chess.to_bytes()) + .unwrap(); + + run( + dir.path(), + GalleryCommand::Remove { + content_hash: hash.clone(), + reason: ReasonClass::Spam, + note: None, + }, + ) + .unwrap(); + let served = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + assert!(served.list(&ListQuery::default()).is_empty()); + assert_eq!(served.admission().list().len(), 1); + + run( + dir.path(), + GalleryCommand::Reinstate { + content_hash: hash.clone(), + note: Some("mistake".to_owned()), + }, + ) + .unwrap(); + run( + dir.path(), + GalleryCommand::Posture { + posture: AdmissionPosture::Reviewed, + }, + ) + .unwrap(); + run( + dir.path(), + GalleryCommand::ResponseHours { + reason: ReasonClass::Malware, + hours: Some(4), + }, + ) + .unwrap(); + run( + dir.path(), + GalleryCommand::Tag { + program: Some(hash.clone()), + author: None, + tags: vec!["classic".to_owned()], + }, + ) + .unwrap(); + + let served = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + assert_eq!( + served.list(&ListQuery::default()), + vec![chess.record()], + "reinstated records stay listed under review" + ); + assert_eq!( + served.admission().config().posture, + AdmissionPosture::Reviewed + ); + assert_eq!( + served.admission().config().response_hours[&ReasonClass::Malware], + 4 + ); + assert_eq!(served.overlay().programs[&hash], vec!["classic".to_owned()]); + assert!( + run(dir.path(), GalleryCommand::Approve { content_hash: hash }).is_err(), + "it is not pending" + ); + assert!(run(&dir.path().join("missing"), GalleryCommand::Transparency).is_err()); + } +} diff --git a/pkgs/id/crates/id-cli/src/commands/mod.rs b/pkgs/id/crates/id-cli/src/commands/mod.rs index a1b285921e..adec5d462e 100644 --- a/pkgs/id/crates/id-cli/src/commands/mod.rs +++ b/pkgs/id/crates/id-cli/src/commands/mod.rs @@ -59,6 +59,7 @@ pub mod claim; pub mod client; pub mod doc; pub mod find; +pub mod gallery; pub mod get; pub mod group; pub mod id; @@ -86,6 +87,7 @@ pub use doc::cmd_doc; pub use find::{ PeekOptions, SearchOptions, cmd_find, cmd_find_matches, cmd_peek, cmd_search, cmd_show, }; +pub use gallery::cmd_gallery; pub use get::{cmd_get_local, cmd_get_multi, cmd_get_one, cmd_get_one_remote, cmd_gethash}; pub use group::{cmd_delegate, cmd_group, cmd_revoke}; pub use id::cmd_id; diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index eed926afd1..c9e044b3d8 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -2001,9 +2001,14 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { anyhow::anyhow!("open the gallery in {}: {error:#}", dir.display()) })?; status!( - "gallery: {} program bundles and {} featured collections from {}", + "gallery: {} program bundles ({} listed, {} admission), {} featured collections and {} transparency entries from {}", gallery.registry().len(), + gallery + .list(&id_worlds::program_registry::ListQuery::default()) + .len(), + gallery.admission().config().posture.as_str(), gallery.collections().count(), + gallery.admission().list().len(), dir.display() ); Some(std::sync::Arc::new(std::sync::RwLock::new(gallery))) diff --git a/pkgs/id/crates/id-web/src/gallery.rs b/pkgs/id/crates/id-web/src/gallery.rs index eea74bfa09..58cc88f112 100644 --- a/pkgs/id/crates/id-web/src/gallery.rs +++ b/pkgs/id/crates/id-web/src/gallery.rs @@ -14,6 +14,14 @@ //! - `GET /api/gallery/collections` and //! `GET /api/gallery/collections/{operator}/{name}`: featured collections, //! each signed by and attributed to its operator (G4). +//! - `GET /api/gallery/transparency?after=&limit=`: the public list of +//! removals, refusals and reinstatements, with the admission posture and +//! any stated response times (G6, #10005). +//! +//! The listing routes show only records the operator's admission lists. A +//! fetch of a record removed or refused here answers 410 Gone with the +//! transparency entry that explains it, so the decision is never silent; +//! the bundle stays valid and may be listed by other hosts. //! //! Operator speech (collections and the operator's tags, G2) is always //! under a field that names the operator, never mixed into a record, so a @@ -38,6 +46,9 @@ use serde::{Deserialize, Serialize}; use id_worlds::program_bundle::BundleRecord; use id_worlds::program_gallery::{Gallery, SearchQuery}; +use id_worlds::program_gallery_admission::{ + AdmissionPosture, MAX_TRANSPARENCY_PAGE, ReasonClass, TransparencyEntry, +}; use id_worlds::program_gallery_operator::SignedCollection; use id_worlds::program_registry::ListQuery; @@ -66,6 +77,7 @@ pub fn gallery_routes() -> Router> { "/api/gallery/collections/{operator}/{name}", get(collection_handler), ) + .route("/api/gallery/transparency", get(transparency_handler)) } /// A list or search answer. @@ -110,6 +122,35 @@ pub struct CollectionsAnswer { pub collections: Vec, } +/// A page of the transparency list (G6). +#[derive(Debug, Serialize, Deserialize)] +pub struct TransparencyAnswer { + /// Whether records are listed before review. + pub posture: AdmissionPosture, + /// The operator's stated response time per reason class, in hours. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub response_hours: BTreeMap, + /// The entries after the requested sequence, in order. + pub entries: Vec, + /// Pass as `after` for the next page, when there is one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_after: Option, +} + +/// The answer to a fetch of a record this gallery stopped listing. +#[derive(Debug, Serialize, Deserialize)] +pub struct UnlistedAnswer { + /// The removal or refusal, as it stands on the transparency list. + pub unlisted_by: TransparencyEntry, +} + +#[derive(Debug, Deserialize)] +struct TransparencyParams { + #[serde(default)] + after: u64, + limit: Option, +} + #[derive(Debug, Deserialize)] struct ListParams { author: Option, @@ -167,12 +208,22 @@ async fn bundle_handler( ) .into_response(); } - let bytes = match gallery.read() { - Ok(gallery) => gallery.fetch(&content_hash), + let (bytes, unlisted_by) = match gallery.read() { + Ok(gallery) => ( + gallery.fetch(&content_hash), + gallery.unlisted_by(&content_hash).cloned(), + ), Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), }; let Some(bytes) = bytes else { - return StatusCode::NOT_FOUND.into_response(); + return unlisted_by.map_or_else( + || StatusCode::NOT_FOUND.into_response(), + |unlisted_by| { + let mut response = listing(&UnlistedAnswer { unlisted_by }); + *response.status_mut() = StatusCode::GONE; + response + }, + ); }; let mut response = bytes.into_response(); let headers = response.headers_mut(); @@ -265,6 +316,36 @@ async fn collection_handler( ) } +async fn transparency_handler( + State(gallery): State>, + Query(params): Query, +) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let answer = match gallery.read() { + Ok(gallery) => { + let admission = gallery.admission(); + let list = admission.list(); + let entries = list + .page(params.after, params.limit.unwrap_or(MAX_TRANSPARENCY_PAGE)) + .to_vec(); + let next_after = entries + .last() + .map(|last| last.sequence) + .filter(|&last| usize::try_from(last).is_ok_and(|last| last < list.len())); + TransparencyAnswer { + posture: admission.config().posture, + response_hours: admission.config().response_hours.clone(), + entries, + next_after, + } + } + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + listing(&answer) +} + /// A stored collection with the attribution its own signature proves. fn featured(signed: &SignedCollection) -> Option { let collection = signed.verify().ok()?; @@ -428,6 +509,7 @@ mod tests { "/api/gallery/records", "/api/gallery/search?q=chess", &format!("/api/gallery/bundles/{}", "0".repeat(64)), + "/api/gallery/transparency", ] { assert_eq!(get(&app, uri).await.0, StatusCode::NOT_FOUND, "{uri}"); } @@ -505,4 +587,69 @@ mod tests { .await; assert_eq!(status, StatusCode::NOT_FOUND, "attribution is by signer"); } + + #[tokio::test] + async fn a_removal_is_public_and_a_fetch_of_it_says_why() { + use id_worlds::program_gallery_admission::{AdmissionAction, ReasonClass}; + + let registry = Registry::open_dir(tempfile::tempdir().unwrap().keep(), AdmitAll).unwrap(); + let gallery = Arc::new(RwLock::new(Gallery::new(registry))); + let (chess, go) = ( + bundle("chess", 1, "Board game.", &["board"]), + bundle("go", 1, "Stones.", &["board"]), + ); + let hash = chess.manifest().content_hash.clone(); + { + let mut gallery = gallery.write().unwrap(); + gallery.publish(&chess.to_bytes()).unwrap(); + gallery.publish(&go.to_bytes()).unwrap(); + gallery + .remove( + &hash, + ReasonClass::Malware, + 100, + Some("reported".to_owned()), + ) + .unwrap(); + } + let app = app(Some(Arc::clone(&gallery))); + + let (status, headers, body) = get(&app, &format!("/api/gallery/bundles/{hash}")).await; + assert_eq!(status, StatusCode::GONE); + assert_ne!(headers[header::CACHE_CONTROL], BUNDLE_CACHE); + let gone: UnlistedAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(gone.unlisted_by.record, chess.identity()); + assert_eq!(gone.unlisted_by.reason, ReasonClass::Malware); + + let (_, _, body) = get(&app, "/api/gallery/records").await; + let records: RecordsAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(records.records, vec![go.record()]); + let (_, _, body) = get(&app, "/api/gallery/search?q=board").await; + let found: RecordsAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(found.records, vec![go.record()]); + + gallery + .write() + .unwrap() + .reinstate(&hash, 200, None) + .unwrap(); + assert_eq!( + get(&app, &format!("/api/gallery/bundles/{hash}")).await.0, + StatusCode::OK + ); + + let (status, _, body) = get(&app, "/api/gallery/transparency?limit=1").await; + assert_eq!(status, StatusCode::OK); + let page: TransparencyAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(page.posture, AdmissionPosture::Open); + assert_eq!(page.entries.len(), 1); + assert_eq!(page.entries[0].action, AdmissionAction::Removed); + assert_eq!(page.next_after, Some(1)); + let (_, _, body) = get(&app, "/api/gallery/transparency?after=1").await; + let page: TransparencyAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(page.entries.len(), 1); + assert_eq!(page.entries[0].action, AdmissionAction::Reinstated); + assert_eq!(page.entries[0].reverses, Some(1)); + assert_eq!(page.next_after, None); + } } diff --git a/pkgs/id/crates/id-worlds/src/lib.rs b/pkgs/id/crates/id-worlds/src/lib.rs index 1a1456a48a..b71fdc4ea7 100644 --- a/pkgs/id/crates/id-worlds/src/lib.rs +++ b/pkgs/id/crates/id-worlds/src/lib.rs @@ -48,6 +48,7 @@ pub mod blob_gate; pub mod groups; pub mod program_bundle; pub mod program_gallery; +pub mod program_gallery_admission; pub mod program_gallery_operator; pub mod program_registry; #[cfg(feature = "sandbox")] diff --git a/pkgs/id/crates/id-worlds/src/program_gallery.rs b/pkgs/id/crates/id-worlds/src/program_gallery.rs index e63af9483c..2642cc3ce6 100644 --- a/pkgs/id/crates/id-worlds/src/program_gallery.rs +++ b/pkgs/id/crates/id-worlds/src/program_gallery.rs @@ -13,12 +13,22 @@ //! query word, then everything else; within each group the most recent //! version comes first, then name, author and content hash break ties. //! There is no engagement ranking. +//! +//! What the gallery lists is its operator's admission (G6, +//! [`crate::program_gallery_admission`]): list, fetch, search and author +//! pages show only records the admission state lists, and every removal, +//! refusal and reinstatement goes on the public transparency list. A +//! removed record keeps its bundle file here and keeps verifying elsewhere. use std::collections::BTreeMap; use crate::program_bundle::{BundleManifest, BundleRecord}; +use crate::program_gallery_admission::{ + Admission, AdmissionConfig, AdmissionError, ReasonClass, TransparencyEntry, +}; use crate::program_gallery_operator::{ - AuthorPage, OperatorData, OperatorError, OperatorOverlay, SignedCollection, check_author_key, + AuthorPage, OPERATOR_DIR, OperatorData, OperatorError, OperatorOverlay, SignedCollection, + check_author_key, }; use crate::program_registry::{AdmissionPolicy, ListQuery, Registry, RegistryError}; @@ -204,6 +214,7 @@ pub struct Gallery { registry: Registry, index: SearchIndex, operator: OperatorData, + admission: Admission, dir: Option, } @@ -217,13 +228,15 @@ impl Gallery { registry, index, operator: OperatorData::default(), + admission: Admission::default(), dir: None, } } /// Open the gallery stored in `dir`: its bundles (verified as - /// [`Registry::open_dir`] does) and its operator data (verified as - /// [`OperatorData::load`] does). + /// [`Registry::open_dir`] does), its operator data (verified as + /// [`OperatorData::load`] does) and its admission state (checked as + /// [`Admission::load`] does). /// /// # Errors /// @@ -235,12 +248,25 @@ impl Gallery { let dir = dir.into(); let registry = Registry::open_dir(&dir, policy)?; let operator = OperatorData::load(&dir)?; + let admission = Admission::load(&dir.join(OPERATOR_DIR))?; let mut gallery = Self::new(registry); gallery.operator = operator; + gallery.admission = admission; gallery.dir = Some(dir); + gallery.rebuild_index(); Ok(gallery) } + /// Serve `registry` under this admission state, with no operator data + /// and nothing kept on disk beyond what the registry keeps. + #[must_use] + pub fn with_admission(registry: Registry, admission: Admission) -> Self { + let mut gallery = Self::new(registry); + gallery.admission = admission; + gallery.rebuild_index(); + gallery + } + /// Every record `author` published here, addressed by the key alone /// (G5), with the operator's tags for that author kept apart. /// @@ -251,7 +277,7 @@ impl Gallery { check_author_key(author)?; Ok(AuthorPage { author: author.to_owned(), - records: self.registry.list(&ListQuery { + records: self.list(&ListQuery { author: Some(author.to_owned()), name: None, }), @@ -325,19 +351,26 @@ impl Gallery { &self.index } - /// Throw the index away and rebuild it from the registry's records. + /// Throw the index away and rebuild it from the listed records. pub fn rebuild_index(&mut self) { - self.index = SearchIndex::rebuild(self.registry.list(&ListQuery::default())); + self.index = SearchIndex::rebuild(self.list(&ListQuery::default())); } - /// Publish through the registry and index the new record. + /// Publish through the registry, and index the new record if the + /// admission state lists it (under the reviewed posture it waits for + /// [`Self::approve`]). /// /// # Errors /// /// Whatever [`Registry::publish`] refuses. pub fn publish(&mut self, bytes: &[u8]) -> Result { let record = self.registry.publish(bytes)?; - self.index.insert(record.clone()); + if record + .verify() + .is_ok_and(|manifest| self.admission.lists(&manifest.content_hash)) + { + self.index.insert(record.clone()); + } Ok(record) } @@ -356,29 +389,155 @@ impl Gallery { Ok(record) } - /// Delist on the operator's authority and drop it from the index. + /// Stop listing a record here, on the operator's authority, and write + /// the removal to the transparency list (G6). The bundle file stays, + /// so [`Self::reinstate`] can reverse it. /// /// # Errors /// - /// Whatever [`Registry::remove`] refuses. - pub fn remove(&mut self, content_hash: &str) -> Result { - let record = self.registry.remove(content_hash)?; + /// No such bundle is held or listed, the note is too long, or the list + /// cannot be stored. + pub fn remove( + &mut self, + content_hash: &str, + reason: ReasonClass, + at: u64, + note: Option, + ) -> Result { + let (_, identity) = self.held(content_hash)?; + let operator_dir = self.operator_dir(); + let entry = self + .admission + .remove(identity, reason, at, note, operator_dir.as_deref())?; self.index.remove(content_hash); + Ok(entry) + } + + /// Refuse a record that waits for review, and write the refusal to the + /// transparency list. + /// + /// # Errors + /// + /// No such bundle is held or pending, the note is too long, or the list + /// cannot be stored. + pub fn refuse( + &mut self, + content_hash: &str, + reason: ReasonClass, + at: u64, + note: Option, + ) -> Result { + let (_, identity) = self.held(content_hash)?; + let operator_dir = self.operator_dir(); + self.admission + .refuse(identity, reason, at, note, operator_dir.as_deref()) + } + + /// Reverse a removal or refusal (an appeal upheld, or a mistake), write + /// that to the transparency list, and list the record again. + /// + /// # Errors + /// + /// The record is not removed or refused, the note is too long, or the + /// list cannot be stored. + pub fn reinstate( + &mut self, + content_hash: &str, + at: u64, + note: Option, + ) -> Result { + let operator_dir = self.operator_dir(); + let entry = self + .admission + .reinstate(content_hash, at, note, operator_dir.as_deref())?; + if let Some((record, _)) = self.registry.get(content_hash) { + self.index.insert(record); + } + Ok(entry) + } + + /// List a record that waits for review. + /// + /// # Errors + /// + /// No such bundle is held or pending, or the approval cannot be stored. + pub fn approve(&mut self, content_hash: &str) -> Result { + let (record, _) = self.held(content_hash)?; + let operator_dir = self.operator_dir(); + self.admission + .approve(content_hash, operator_dir.as_deref())?; + self.index.insert(record.clone()); Ok(record) } - /// The registry's list operation, unchanged. + /// The records waiting for review, in list order. + #[must_use] + pub fn pending(&self) -> Vec { + self.registry.list_where(&ListQuery::default(), |manifest| { + self.admission.is_pending(&manifest.content_hash) + }) + } + + /// The admission state: configuration, approvals and the public list. + #[must_use] + pub const fn admission(&self) -> &Admission { + &self.admission + } + + /// Change the admission configuration (posture and stated response + /// times), storing it when the gallery has a directory. What is listed + /// changes at once. + /// + /// # Errors + /// + /// The configuration cannot be stored. + pub fn set_admission_config(&mut self, config: AdmissionConfig) -> Result<(), AdmissionError> { + let operator_dir = self.operator_dir(); + self.admission.set_config(config, operator_dir.as_deref())?; + self.rebuild_index(); + Ok(()) + } + + /// The removal or refusal that keeps this record unlisted here, if any. + #[must_use] + pub fn unlisted_by(&self, content_hash: &str) -> Option<&TransparencyEntry> { + self.admission + .list() + .latest(content_hash) + .filter(|entry| entry.hides()) + } + + /// The listed records matching `query`: the registry's list operation, + /// narrowed to what the admission state lists. #[must_use] pub fn list(&self, query: &ListQuery) -> Vec { - self.registry.list(query) + self.registry.list_where(query, |manifest| { + self.admission.lists(&manifest.content_hash) + }) } - /// The registry's fetch operation, unchanged. + /// The registry's fetch operation, for listed records only. #[must_use] pub fn fetch(&self, content_hash: &str) -> Option> { + if !self.admission.lists(content_hash) { + return None; + } self.registry.fetch(content_hash) } + fn held( + &self, + content_hash: &str, + ) -> Result<(BundleRecord, crate::program_bundle::ProgramIdentity), AdmissionError> { + self.registry + .get(content_hash) + .ok_or_else(|| AdmissionError::NotFound(content_hash.to_owned())) + } + + fn operator_dir(&self) -> Option { + self.dir.as_ref().map(|dir| dir.join(OPERATOR_DIR)) + } + /// Search the index. /// /// # Errors @@ -605,7 +764,7 @@ mod tests { .verify() .unwrap() .content_hash; - gallery.remove(&racer).unwrap(); + gallery.remove(&racer, ReasonClass::Spam, 0, None).unwrap(); assert!(search(&gallery, "arcade").is_empty()); assert_eq!(gallery.index().len(), 4); } @@ -700,4 +859,104 @@ mod tests { )]) ); } + + #[test] + fn a_removal_hides_the_record_here_only_and_reinstatement_restores_it() { + use crate::program_gallery_admission::{AdmissionAction, AdmissionError}; + + let dir = tempfile::tempdir().unwrap(); + let chess = program(&alice(), "chess", 1, "Board game.", &["board"]); + let hash = chess.manifest().content_hash.clone(); + let key = crate::world_session::encode_hex(&alice().verifying_key().to_bytes()); + { + let mut gallery = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + gallery.publish(&chess.to_bytes()).unwrap(); + let removed = gallery + .remove(&hash, ReasonClass::Malware, 100, None) + .unwrap(); + assert_eq!(removed.action, AdmissionAction::Removed); + assert_eq!(removed.record, chess.identity()); + assert!(gallery.list(&ListQuery::default()).is_empty()); + assert!(gallery.fetch(&hash).is_none()); + assert!(search(&gallery, "board").is_empty()); + assert!(gallery.author_page(&key).unwrap().records.is_empty()); + assert_eq!(gallery.unlisted_by(&hash), Some(&removed)); + assert_eq!( + gallery.registry().fetch(&hash), + Some(chess.to_bytes()), + "removal binds this endpoint only; the bundle is kept" + ); + gallery.publish(&chess.to_bytes()).unwrap(); + assert!( + gallery.list(&ListQuery::default()).is_empty(), + "republishing does not undo it" + ); + } + let mut gallery = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + assert!( + gallery.fetch(&hash).is_none(), + "the removal survives a restart" + ); + assert_eq!(gallery.admission().list().len(), 1); + let back = gallery + .reinstate(&hash, 200, Some("appeal upheld".to_owned())) + .unwrap(); + assert_eq!(back.reverses, Some(1)); + assert_eq!(gallery.list(&ListQuery::default()), vec![chess.record()]); + assert_eq!(search(&gallery, "board"), vec![("chess".to_owned(), 1)]); + assert!(gallery.unlisted_by(&hash).is_none()); + assert_eq!( + gallery.remove(&"0".repeat(64), ReasonClass::Spam, 0, None), + Err(AdmissionError::NotFound("0".repeat(64))) + ); + } + + #[test] + fn under_review_a_record_waits_and_the_posture_switches_by_configuration() { + use crate::program_gallery_admission::{AdmissionConfig, AdmissionPosture}; + + let dir = tempfile::tempdir().unwrap(); + let chess = program(&alice(), "chess", 1, "Board game.", &["board"]); + let spam = program(&bob(), "free-coins", 1, "Click.", &[]); + let (chess_hash, spam_hash) = ( + chess.manifest().content_hash.clone(), + spam.manifest().content_hash.clone(), + ); + { + let mut gallery = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + gallery + .set_admission_config(AdmissionConfig { + posture: AdmissionPosture::Reviewed, + ..AdmissionConfig::default() + }) + .unwrap(); + gallery.publish(&chess.to_bytes()).unwrap(); + gallery.publish(&spam.to_bytes()).unwrap(); + assert!(gallery.list(&ListQuery::default()).is_empty()); + assert_eq!(gallery.pending().len(), 2); + gallery.approve(&chess_hash).unwrap(); + gallery + .refuse(&spam_hash, ReasonClass::Spam, 1, None) + .unwrap(); + assert!(gallery.pending().is_empty()); + assert_eq!(gallery.list(&ListQuery::default()), vec![chess.record()]); + assert_eq!(search(&gallery, "board").len(), 1); + } + let mut gallery = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + assert_eq!(gallery.list(&ListQuery::default()), vec![chess.record()]); + let later = program(&alice(), "go", 1, "Stones.", &[]); + gallery.publish(&later.to_bytes()).unwrap(); + assert!( + search(&gallery, "stones").is_empty(), + "pending is not searchable" + ); + gallery + .set_admission_config(AdmissionConfig::default()) + .unwrap(); + assert_eq!(search(&gallery, "stones").len(), 1, "open lists it at once"); + assert!( + gallery.fetch(&spam_hash).is_none(), + "a refusal holds under any posture" + ); + } } diff --git a/pkgs/id/crates/id-worlds/src/program_gallery_admission.rs b/pkgs/id/crates/id-worlds/src/program_gallery_admission.rs new file mode 100644 index 0000000000..39d5c068f3 --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/program_gallery_admission.rs @@ -0,0 +1,822 @@ +//! Gallery admission and its public transparency list (#10005; v3 design +//! `doc/2026-11-14T13-33-00Z_design_id_program_ecosystem_v3/`, G6). +//! +//! Validity is protocol, admission is policy (D6). Whether a verified record +//! is listed by *this* gallery is the operator's decision, and it binds only +//! this endpoint: a removed record keeps verifying, keeps its bundle file +//! here, and stays listed on any other host. What this module adds is that +//! the decision is never silent. Every removal, every refusal and every +//! reinstatement is appended to a [`TransparencyList`] that the gallery +//! serves publicly: the record's identity, when, and one of four reason +//! classes ([`ReasonClass`]). +//! +//! The default posture and the abuse response times are operator rulings, +//! so both are configuration ([`AdmissionConfig`], stored as +//! `operator/admission.json`), never constants: +//! +//! - [`AdmissionPosture::Open`]: every verified record is listed until it is +//! removed. +//! - [`AdmissionPosture::Reviewed`]: a record is listed once the operator +//! approves it; until then it is pending, and the operator may refuse it +//! (which is public, like a removal). +//! +//! Switching posture changes what is listed at once, because a record's +//! visibility is computed from the posture, the approvals and the list. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +use crate::program_bundle::{ProgramIdentity, check_identity}; + +/// Longest public note on one transparency entry, in bytes. +pub const MAX_NOTE_BYTES: usize = 500; + +/// Most transparency entries one page of the list returns. +pub const MAX_TRANSPARENCY_PAGE: usize = 500; + +/// File, under the operator directory, holding the admission configuration. +pub const ADMISSION_FILE: &str = "admission.json"; + +/// File, under the operator directory, holding the transparency list as one +/// JSON entry per line, appended in sequence order. +pub const TRANSPARENCY_FILE: &str = "transparency.jsonl"; + +/// File, under the operator directory, holding the approved content hashes. +pub const APPROVED_FILE: &str = "approved.json"; + +/// Why the operator stopped listing a record (G6). The classes are coarse +/// on purpose: the list is auditable without publishing the details of an +/// abuse report. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReasonClass { + /// The content is unlawful where the operator runs the endpoint. + IllegalContent, + /// The program is malicious. + Malware, + /// The record is spam. + Spam, + /// The record breaks the operator's published policy. + Policy, +} + +impl ReasonClass { + /// Every class, in the documented order. + pub const ALL: [Self; 4] = [ + Self::IllegalContent, + Self::Malware, + Self::Spam, + Self::Policy, + ]; + + /// The class's wire name. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::IllegalContent => "illegal_content", + Self::Malware => "malware", + Self::Spam => "spam", + Self::Policy => "policy", + } + } +} + +impl std::fmt::Display for ReasonClass { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +impl FromStr for ReasonClass { + type Err = String; + + fn from_str(text: &str) -> Result { + Self::ALL + .into_iter() + .find(|class| class.as_str() == text.replace('-', "_")) + .ok_or_else(|| { + format!( + "reason class is one of illegal_content, malware, spam or policy, not {text:?}" + ) + }) + } +} + +/// Which records the gallery lists before the operator has looked at them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AdmissionPosture { + /// Every verified record is listed until it is removed. + #[default] + Open, + /// A record is listed once the operator approves it. + Reviewed, +} + +impl AdmissionPosture { + /// The posture's wire name. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Open => "open", + Self::Reviewed => "reviewed", + } + } +} + +impl FromStr for AdmissionPosture { + type Err = String; + + fn from_str(text: &str) -> Result { + match text { + "open" => Ok(Self::Open), + "reviewed" => Ok(Self::Reviewed), + _ => Err(format!("posture is open or reviewed, not {text:?}")), + } + } +} + +/// The operator's admission configuration, published with the list. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AdmissionConfig { + /// Whether records are listed before review. + #[serde(default)] + pub posture: AdmissionPosture, + /// The operator's stated response time for each reason class, in hours. + /// A class without an entry has no stated commitment. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub response_hours: BTreeMap, +} + +/// What an operator did to a record's listing. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AdmissionAction { + /// A listed record stopped being listed. + Removed, + /// A pending record was refused (reviewed posture). + Refused, + /// A removal or refusal was reversed, on appeal or otherwise. + Reinstated, +} + +/// One public admission decision. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TransparencyEntry { + /// Position in the list, counting from 1 with no gaps. + pub sequence: u64, + /// When the operator recorded it, in Unix seconds by the operator's + /// clock. + pub at: u64, + /// What was done. + pub action: AdmissionAction, + /// The record it was done to, exactly as signed. + pub record: ProgramIdentity, + /// The reason class. A reinstatement carries the class of the decision + /// it reverses. + pub reason: ReasonClass, + /// For a reinstatement, the sequence of the removal or refusal it + /// reverses. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reverses: Option, + /// The operator's public note, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +impl TransparencyEntry { + /// Whether this entry, as a record's latest, keeps it unlisted. + #[must_use] + pub const fn hides(&self) -> bool { + matches!( + self.action, + AdmissionAction::Removed | AdmissionAction::Refused + ) + } +} + +/// Why an admission step or admission data was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum AdmissionError { + /// No bundle with this content hash is held here. + #[error("no bundle {0} is held here")] + NotFound(String), + /// The record is not listed, so there is nothing to remove. + #[error("{0} is not listed")] + NotListed(String), + /// The record is not waiting for review. + #[error("{0} is not pending review")] + NotPending(String), + /// The record is not removed or refused, so there is nothing to reverse. + #[error("{0} is not removed or refused")] + NotHidden(String), + /// The note is longer than [`MAX_NOTE_BYTES`]. + #[error("a note is at most {MAX_NOTE_BYTES} bytes")] + Note, + /// The stored configuration, list or approvals are malformed. + #[error("admission data: {0}")] + Data(String), + /// Reading or writing admission data failed. + #[error("admission storage: {0}")] + Storage(String), +} + +/// The append-only public record of admission decisions. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TransparencyList { + entries: Vec, + latest: BTreeMap, +} + +impl TransparencyList { + /// Rebuild a list from its entries, checking that it is well formed: + /// sequences count from 1 with no gaps, every identity is canonical, + /// a removal follows a listing, a refusal follows nothing, and a + /// reinstatement reverses its record's latest decision with that + /// decision's reason class. + /// + /// # Errors + /// + /// The entries do not form such a list. + pub fn from_entries( + entries: impl IntoIterator, + ) -> Result { + let mut list = Self::default(); + for entry in entries { + list.check_next(&entry)?; + list.push(entry); + } + Ok(list) + } + + /// Every entry, in sequence order. + #[must_use] + pub fn entries(&self) -> &[TransparencyEntry] { + &self.entries + } + + /// The entries after `sequence`, at most `limit` of them (and never + /// more than [`MAX_TRANSPARENCY_PAGE`]). + #[must_use] + pub fn page(&self, after: u64, limit: usize) -> &[TransparencyEntry] { + let start = usize::try_from(after) + .unwrap_or(usize::MAX) + .min(self.entries.len()); + let end = start + .saturating_add(limit.min(MAX_TRANSPARENCY_PAGE)) + .min(self.entries.len()); + &self.entries[start..end] + } + + /// The latest decision about the record with `content_hash`. + #[must_use] + pub fn latest(&self, content_hash: &str) -> Option<&TransparencyEntry> { + self.latest + .get(content_hash) + .and_then(|&at| self.entries.get(at)) + } + + /// Whether the latest decision about this record keeps it unlisted. + #[must_use] + pub fn hides(&self, content_hash: &str) -> bool { + self.latest(content_hash) + .is_some_and(TransparencyEntry::hides) + } + + /// How many entries the list holds. + #[must_use] + pub const fn len(&self) -> usize { + self.entries.len() + } + + /// Whether the list is empty. + #[must_use] + pub const fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + fn next_sequence(&self) -> u64 { + u64::try_from(self.entries.len()).map_or(u64::MAX, |n| n.saturating_add(1)) + } + + fn check_next(&self, entry: &TransparencyEntry) -> Result<(), AdmissionError> { + let data = |why: &str| AdmissionError::Data(format!("entry {}: {why}", entry.sequence)); + if entry.sequence != self.next_sequence() { + return Err(data("is out of sequence")); + } + check_identity(&entry.record).map_err(|e| data(&e))?; + if entry + .note + .as_ref() + .is_some_and(|n| n.len() > MAX_NOTE_BYTES) + { + return Err(data("note is too long")); + } + let latest = self.latest(&entry.record.content_hash); + match entry.action { + AdmissionAction::Removed | AdmissionAction::Refused => { + if entry.reverses.is_some() { + return Err(data("only a reinstatement reverses an entry")); + } + if latest.is_some_and(TransparencyEntry::hides) { + return Err(data("the record is already unlisted")); + } + } + AdmissionAction::Reinstated => { + let Some(latest) = latest.filter(|latest| latest.hides()) else { + return Err(data("nothing to reinstate")); + }; + if entry.reverses != Some(latest.sequence) || entry.reason != latest.reason { + return Err(data( + "a reinstatement must reverse the record's latest decision", + )); + } + if entry.record != latest.record { + return Err(data("a reinstatement names the record it reverses")); + } + } + } + Ok(()) + } + + fn push(&mut self, entry: TransparencyEntry) { + self.latest + .insert(entry.record.content_hash.clone(), self.entries.len()); + self.entries.push(entry); + } +} + +/// A gallery's admission state: its configuration, its approvals and its +/// transparency list, kept under the operator directory when it has one. +#[derive(Clone, Debug, Default)] +pub struct Admission { + config: AdmissionConfig, + approved: BTreeSet, + list: TransparencyList, +} + +impl Admission { + /// Admission in memory with this configuration and no decisions. + #[must_use] + pub fn with_config(config: AdmissionConfig) -> Self { + Self { + config, + ..Self::default() + } + } + + /// Load the admission data under `operator_dir`; a missing file means + /// the default (open posture, nothing approved, an empty list). + /// + /// # Errors + /// + /// A file cannot be read or is malformed. + pub fn load(operator_dir: &Path) -> Result { + let mut admission = Self::default(); + let config = operator_dir.join(ADMISSION_FILE); + if config.is_file() { + let bytes = std::fs::read(&config).map_err(|e| storage(&config, &e))?; + admission.config = id_core::json_unique::from_slice_without_duplicate_keys(&bytes) + .map_err(|e| AdmissionError::Data(format!("{}: {e}", config.display())))?; + } + let approved = operator_dir.join(APPROVED_FILE); + if approved.is_file() { + let bytes = std::fs::read(&approved).map_err(|e| storage(&approved, &e))?; + let hashes: Vec = + id_core::json_unique::from_slice_without_duplicate_keys(&bytes) + .map_err(|e| AdmissionError::Data(format!("{}: {e}", approved.display())))?; + admission.approved = hashes.into_iter().collect(); + } + let list = operator_dir.join(TRANSPARENCY_FILE); + if list.is_file() { + let text = std::fs::read_to_string(&list).map_err(|e| storage(&list, &e))?; + let entries = text + .lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| { + id_core::json_unique::from_slice_without_duplicate_keys(line.as_bytes()) + .map_err(|e| AdmissionError::Data(format!("{}: {e}", list.display()))) + }) + .collect::, _>>()?; + admission.list = TransparencyList::from_entries(entries)?; + } + Ok(admission) + } + + /// The configuration in force. + #[must_use] + pub const fn config(&self) -> &AdmissionConfig { + &self.config + } + + /// The public transparency list. + #[must_use] + pub const fn list(&self) -> &TransparencyList { + &self.list + } + + /// Whether the record with `content_hash` is listed by this gallery, + /// given that it holds the bundle. + #[must_use] + pub fn lists(&self, content_hash: &str) -> bool { + !self.list.hides(content_hash) + && (self.config.posture == AdmissionPosture::Open + || self.approved.contains(content_hash)) + } + + /// Whether the record is waiting for the operator (reviewed posture). + #[must_use] + pub fn is_pending(&self, content_hash: &str) -> bool { + self.config.posture == AdmissionPosture::Reviewed + && !self.approved.contains(content_hash) + && !self.list.hides(content_hash) + } + + /// Change the configuration, storing it under `operator_dir` if given. + /// + /// # Errors + /// + /// The file cannot be written. + pub fn set_config( + &mut self, + config: AdmissionConfig, + operator_dir: Option<&Path>, + ) -> Result<(), AdmissionError> { + if let Some(dir) = operator_dir { + write_json(&dir.join(ADMISSION_FILE), &config)?; + } + self.config = config; + Ok(()) + } + + /// Approve a pending record so it is listed. Approval is not a public + /// decision: listing is what the gallery does by default. + /// + /// # Errors + /// + /// The record is not pending, or the approvals cannot be stored. + pub fn approve( + &mut self, + content_hash: &str, + operator_dir: Option<&Path>, + ) -> Result<(), AdmissionError> { + if !self.is_pending(content_hash) { + return Err(AdmissionError::NotPending(content_hash.to_owned())); + } + self.approve_unchecked(content_hash, operator_dir) + } + + /// Record that a listed record is removed from this gallery. + /// + /// # Errors + /// + /// The record is not listed, the note is too long, or the list cannot + /// be stored. + pub fn remove( + &mut self, + record: ProgramIdentity, + reason: ReasonClass, + at: u64, + note: Option, + operator_dir: Option<&Path>, + ) -> Result { + if !self.lists(&record.content_hash) { + return Err(AdmissionError::NotListed(record.content_hash)); + } + self.decide( + AdmissionAction::Removed, + record, + reason, + at, + note, + operator_dir, + ) + } + + /// Record that a pending record is refused. + /// + /// # Errors + /// + /// The record is not pending, the note is too long, or the list cannot + /// be stored. + pub fn refuse( + &mut self, + record: ProgramIdentity, + reason: ReasonClass, + at: u64, + note: Option, + operator_dir: Option<&Path>, + ) -> Result { + if !self.is_pending(&record.content_hash) { + return Err(AdmissionError::NotPending(record.content_hash)); + } + self.decide( + AdmissionAction::Refused, + record, + reason, + at, + note, + operator_dir, + ) + } + + /// Reverse the record's removal or refusal, and approve it so it is + /// listed under either posture. + /// + /// # Errors + /// + /// The record is not removed or refused, the note is too long, or the + /// list cannot be stored. + pub fn reinstate( + &mut self, + content_hash: &str, + at: u64, + note: Option, + operator_dir: Option<&Path>, + ) -> Result { + let Some(latest) = self.list.latest(content_hash).filter(|e| e.hides()) else { + return Err(AdmissionError::NotHidden(content_hash.to_owned())); + }; + let (record, reason, reverses) = (latest.record.clone(), latest.reason, latest.sequence); + let entry = self.append( + TransparencyEntry { + sequence: self.list.next_sequence(), + at, + action: AdmissionAction::Reinstated, + record, + reason, + reverses: Some(reverses), + note, + }, + operator_dir, + )?; + self.approve_unchecked(content_hash, operator_dir)?; + Ok(entry) + } + + fn decide( + &mut self, + action: AdmissionAction, + record: ProgramIdentity, + reason: ReasonClass, + at: u64, + note: Option, + operator_dir: Option<&Path>, + ) -> Result { + self.append( + TransparencyEntry { + sequence: self.list.next_sequence(), + at, + action, + record, + reason, + reverses: None, + note, + }, + operator_dir, + ) + } + + fn append( + &mut self, + entry: TransparencyEntry, + operator_dir: Option<&Path>, + ) -> Result { + if entry + .note + .as_ref() + .is_some_and(|n| n.len() > MAX_NOTE_BYTES) + { + return Err(AdmissionError::Note); + } + self.list.check_next(&entry)?; + if let Some(dir) = operator_dir { + append_line(&dir.join(TRANSPARENCY_FILE), &entry)?; + } + self.list.push(entry.clone()); + Ok(entry) + } + + fn approve_unchecked( + &mut self, + content_hash: &str, + operator_dir: Option<&Path>, + ) -> Result<(), AdmissionError> { + let mut approved = self.approved.clone(); + if !approved.insert(content_hash.to_owned()) { + return Ok(()); + } + if let Some(dir) = operator_dir { + write_json(&dir.join(APPROVED_FILE), &approved)?; + } + self.approved = approved; + Ok(()) + } +} + +fn write_json(path: &Path, value: &impl Serialize) -> Result<(), AdmissionError> { + let dir = path + .parent() + .ok_or_else(|| AdmissionError::Storage(format!("{} has no parent", path.display())))?; + std::fs::create_dir_all(dir).map_err(|e| storage(dir, &e))?; + let bytes = + serde_json::to_vec_pretty(value).map_err(|e| AdmissionError::Storage(e.to_string()))?; + let mut staged = tempfile::NamedTempFile::new_in(dir).map_err(|e| storage(dir, &e))?; + std::io::Write::write_all(&mut staged, &bytes).map_err(|e| storage(path, &e))?; + staged.as_file().sync_all().map_err(|e| storage(path, &e))?; + staged.persist(path).map_err(|e| storage(path, &e.error))?; + Ok(()) +} + +fn append_line(path: &Path, entry: &TransparencyEntry) -> Result<(), AdmissionError> { + let dir = path + .parent() + .ok_or_else(|| AdmissionError::Storage(format!("{} has no parent", path.display())))?; + std::fs::create_dir_all(dir).map_err(|e| storage(dir, &e))?; + let mut line = serde_json::to_vec(entry).map_err(|e| AdmissionError::Storage(e.to_string()))?; + line.push(b'\n'); + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map_err(|e| storage(path, &e))?; + std::io::Write::write_all(&mut file, &line).map_err(|e| storage(path, &e))?; + file.sync_all().map_err(|e| storage(path, &e)) +} + +fn storage(path: &Path, error: &std::io::Error) -> AdmissionError { + AdmissionError::Storage(format!("{}: {error}", path.display())) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + + fn identity(hash_byte: char) -> ProgramIdentity { + ProgramIdentity { + author: crate::world_session::encode_hex( + ed25519_dalek::SigningKey::from_bytes(&[1; 32]) + .verifying_key() + .as_bytes(), + ), + name: "chess".to_owned(), + version: 1, + content_hash: hash_byte.to_string().repeat(64), + } + } + + #[test] + fn removal_and_reinstatement_are_public_and_reverse_each_other() { + let root = tempfile::tempdir().unwrap(); + let dir = Some(root.path()); + let mut admission = Admission::default(); + let record = identity('a'); + let hash = record.content_hash.clone(); + assert!(admission.lists(&hash)); + + let removed = admission + .remove(record.clone(), ReasonClass::Malware, 10, None, dir) + .unwrap(); + assert_eq!( + (removed.sequence, removed.action), + (1, AdmissionAction::Removed) + ); + assert!(!admission.lists(&hash)); + assert_eq!( + admission.remove(record, ReasonClass::Spam, 11, None, dir), + Err(AdmissionError::NotListed(hash.clone())) + ); + + let back = admission + .reinstate(&hash, 20, Some("appeal upheld".to_owned()), dir) + .unwrap(); + assert_eq!(back.reverses, Some(1)); + assert_eq!(back.reason, ReasonClass::Malware); + assert!(admission.lists(&hash)); + assert_eq!( + admission.reinstate(&hash, 21, None, dir), + Err(AdmissionError::NotHidden(hash.clone())) + ); + + let reloaded = Admission::load(root.path()).unwrap(); + assert_eq!(reloaded.list(), admission.list()); + assert!(reloaded.lists(&hash)); + } + + #[test] + fn reviewed_posture_lists_only_approved_records_and_switches_at_once() { + let root = tempfile::tempdir().unwrap(); + let dir = Some(root.path()); + let mut admission = Admission::with_config(AdmissionConfig { + posture: AdmissionPosture::Reviewed, + response_hours: BTreeMap::from([(ReasonClass::Malware, 4)]), + }); + let (a, b) = (identity('a'), identity('b')); + assert!(admission.is_pending(&a.content_hash)); + assert!(!admission.lists(&a.content_hash)); + + admission.approve(&a.content_hash, dir).unwrap(); + assert!(admission.lists(&a.content_hash)); + assert_eq!( + admission.approve(&a.content_hash, dir), + Err(AdmissionError::NotPending(a.content_hash.clone())) + ); + let refused = admission + .refuse(b.clone(), ReasonClass::Spam, 5, None, dir) + .unwrap(); + assert_eq!(refused.action, AdmissionAction::Refused); + assert!(!admission.is_pending(&b.content_hash)); + + let open = AdmissionConfig { + posture: AdmissionPosture::Open, + ..admission.config().clone() + }; + admission.set_config(open, dir).unwrap(); + assert!(admission.lists(&identity('c').content_hash)); + assert!(!admission.lists(&b.content_hash), "a refusal still holds"); + + let reloaded = Admission::load(root.path()).unwrap(); + assert_eq!(reloaded.config().posture, AdmissionPosture::Open); + assert_eq!(reloaded.config().response_hours[&ReasonClass::Malware], 4); + assert!(reloaded.lists(&a.content_hash)); + assert!(!reloaded.lists(&b.content_hash)); + } + + #[test] + fn a_tampered_list_is_refused_on_load() { + let mut admission = Admission::default(); + admission + .remove(identity('a'), ReasonClass::Policy, 1, None, None) + .unwrap(); + let mut entries = admission.list().entries().to_vec(); + + let mut gap = entries.clone(); + gap[0].sequence = 2; + assert!(TransparencyList::from_entries(gap).is_err()); + + entries.push(TransparencyEntry { + sequence: 2, + at: 2, + action: AdmissionAction::Reinstated, + record: identity('a'), + reason: ReasonClass::Spam, + reverses: Some(1), + note: None, + }); + assert!( + TransparencyList::from_entries(entries.clone()).is_err(), + "a reinstatement keeps the reversed class" + ); + entries[1].reason = ReasonClass::Policy; + assert!(TransparencyList::from_entries(entries).is_ok()); + } + + #[test] + fn notes_are_bounded_and_classes_parse() { + let mut admission = Admission::default(); + assert_eq!( + admission.remove( + identity('a'), + ReasonClass::Spam, + 1, + Some("x".repeat(MAX_NOTE_BYTES + 1)), + None + ), + Err(AdmissionError::Note) + ); + assert!(admission.list().is_empty()); + assert_eq!("illegal-content".parse(), Ok(ReasonClass::IllegalContent)); + assert!("other".parse::().is_err()); + assert_eq!("reviewed".parse(), Ok(AdmissionPosture::Reviewed)); + let json = serde_json::to_string(&AdmissionConfig { + posture: AdmissionPosture::Reviewed, + response_hours: BTreeMap::from([(ReasonClass::IllegalContent, 24)]), + }) + .unwrap(); + assert_eq!( + json, + r#"{"posture":"reviewed","response_hours":{"illegal_content":24}}"# + ); + } + + #[test] + fn pages_follow_the_sequence() { + let mut admission = Admission::default(); + for (i, byte) in ['a', 'b', 'c'].into_iter().enumerate() { + admission + .remove(identity(byte), ReasonClass::Spam, i as u64, None, None) + .unwrap(); + } + let page = admission.list().page(1, 1); + assert_eq!(page.len(), 1); + assert_eq!(page[0].sequence, 2); + assert!(admission.list().page(3, 10).is_empty()); + assert!(admission.list().page(u64::MAX, 10).is_empty()); + } +} diff --git a/pkgs/id/crates/id-worlds/src/program_registry.rs b/pkgs/id/crates/id-worlds/src/program_registry.rs index d6702cc89b..92ce5f6aa0 100644 --- a/pkgs/id/crates/id-worlds/src/program_registry.rs +++ b/pkgs/id/crates/id-worlds/src/program_registry.rs @@ -267,6 +267,17 @@ impl Registry { /// The records matching `query`, ordered by author, name and version. #[must_use] pub fn list(&self, query: &ListQuery) -> Vec { + self.list_where(query, |_| true) + } + + /// The records matching `query` whose manifest `keep` accepts, in the + /// same order as [`Self::list`]. + #[must_use] + pub fn list_where( + &self, + query: &ListQuery, + keep: impl Fn(&BundleManifest) -> bool, + ) -> Vec { self.versions .iter() .filter(|((author, name, _), _)| { @@ -274,10 +285,20 @@ impl Registry { && query.name.as_ref().is_none_or(|wanted| wanted == name) }) .filter_map(|(_, hash)| self.bundles.get(hash)) + .filter(|bundle| keep(bundle.manifest())) .map(ProgramBundle::record) .collect() } + /// The record and identity of the bundle with this content hash, if + /// held. + #[must_use] + pub fn get(&self, content_hash: &str) -> Option<(BundleRecord, ProgramIdentity)> { + self.bundles + .get(content_hash) + .map(|bundle| (bundle.record(), bundle.identity())) + } + /// The bundle file with this content hash, if listed. #[must_use] pub fn fetch(&self, content_hash: &str) -> Option> { diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index 83b1af3823..13f7dc9494 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -457,6 +457,7 @@ async fn main() -> Result<()> { id::commands::cmd_unpublish(listen.as_deref(), path.as_deref()).await } Some(Command::Publications) => id::commands::cmd_publications().await, + Some(Command::Gallery(args)) => id::commands::cmd_gallery(args), #[cfg(feature = "sandbox")] Some(Command::MatchAudit(command)) => id::commands::cmd_match_audit(command), #[cfg(feature = "world")]