From d38e46e9939cc1d69509993f5e2651457b443896 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 06:27:30 +0000 Subject: [PATCH] id: gallery operator layer: author pages, featured collections, category overlay Author pages are addressed by signing key, featured collections are signed by the operator and kept by revision, and operator tags stay apart from the author's own categories. A directory gallery keeps collections and the overlay under operator/ across restarts. Closes #10004 Co-Authored-By: Claude Opus 5.5 --- pkgs/id/crates/id-cli/src/cli/mod.rs | 8 +- pkgs/id/crates/id-cli/src/commands/serve.rs | 20 +- pkgs/id/crates/id-web/src/gallery.rs | 207 ++++++- pkgs/id/crates/id-worlds/src/lib.rs | 1 + .../id/crates/id-worlds/src/program_bundle.rs | 23 +- .../crates/id-worlds/src/program_gallery.rs | 179 +++++- .../id-worlds/src/program_gallery_operator.rs | 520 ++++++++++++++++++ 7 files changed, 923 insertions(+), 35 deletions(-) create mode 100644 pkgs/id/crates/id-worlds/src/program_gallery_operator.rs diff --git a/pkgs/id/crates/id-cli/src/cli/mod.rs b/pkgs/id/crates/id-cli/src/cli/mod.rs index f9f06fae66..1ccc5fe7c9 100644 --- a/pkgs/id/crates/id-cli/src/cli/mod.rs +++ b/pkgs/id/crates/id-cli/src/cli/mod.rs @@ -473,9 +473,11 @@ pub struct ServeArgs { /// Serve the program gallery stored in this directory (#10003). /// /// The web interface answers `/api/gallery/records`, - /// `/api/gallery/bundles/` and `/api/gallery/search` from the - /// verified bundle files (`.idpb`) in the directory. - /// Every file is verified when the server starts. + /// `/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. #[arg(long, env = "ID_GALLERY_DIR", requires = "web")] pub gallery_dir: Option, /// Host a multiplayer world over Iroh (and `/ws/world` with `--web`). diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 1d6d8885f7..eed926afd1 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1987,26 +1987,26 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { }); minter }; - // #10003: the program gallery's read surface, from verified - // bundle files in --gallery-dir. A file that no longer verifies - // stops the start rather than being served or skipped. + // #10003/#10004: the program gallery's read surface, from + // verified bundle files and operator data in --gallery-dir. A + // file that no longer verifies stops the start rather than + // being served or skipped. let gallery = match &gallery_dir { Some(dir) => { - let registry = id_worlds::program_registry::Registry::open_dir( + let gallery = id_worlds::program_gallery::Gallery::open_dir( dir, id_worlds::program_registry::AdmitAll, ) .map_err(|error| { - anyhow::anyhow!("open the gallery in {}: {error}", dir.display()) + anyhow::anyhow!("open the gallery in {}: {error:#}", dir.display()) })?; status!( - "gallery: {} program bundles from {}", - registry.len(), + "gallery: {} program bundles and {} featured collections from {}", + gallery.registry().len(), + gallery.collections().count(), dir.display() ); - Some(std::sync::Arc::new(std::sync::RwLock::new( - id_worlds::program_gallery::Gallery::new(registry), - ))) + Some(std::sync::Arc::new(std::sync::RwLock::new(gallery))) } None => None, }; diff --git a/pkgs/id/crates/id-web/src/gallery.rs b/pkgs/id/crates/id-web/src/gallery.rs index d2421d2e16..eea74bfa09 100644 --- a/pkgs/id/crates/id-web/src/gallery.rs +++ b/pkgs/id/crates/id-web/src/gallery.rs @@ -9,12 +9,22 @@ //! - `GET /api/gallery/search?q=&category=&limit=`: search over the //! rebuildable index, in its documented order (exact name, then //! category, then most recent version). +//! - `GET /api/gallery/authors/{key}`: an author page addressed by key +//! alone (G5, #10004). +//! - `GET /api/gallery/collections` and +//! `GET /api/gallery/collections/{operator}/{name}`: featured collections, +//! each signed by and attributed to its operator (G4). +//! +//! 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 +//! surface cannot present it as the author's. //! //! Records are signed and bundles are content-addressed, so every answer //! is cacheable at any tier without trust implications (G7): a cache cannot //! forge a record that verifies. A fetched bundle never changes, so it is //! marked immutable. With no gallery wired in, every route answers 404. +use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use axum::{ @@ -28,6 +38,7 @@ use serde::{Deserialize, Serialize}; use id_worlds::program_bundle::BundleRecord; use id_worlds::program_gallery::{Gallery, SearchQuery}; +use id_worlds::program_gallery_operator::SignedCollection; use id_worlds::program_registry::ListQuery; /// A gallery shared between the web routes and whatever publishes to it. @@ -49,6 +60,12 @@ pub fn gallery_routes() -> Router> { .route("/api/gallery/records", get(records_handler)) .route("/api/gallery/bundles/{content_hash}", get(bundle_handler)) .route("/api/gallery/search", get(search_handler)) + .route("/api/gallery/authors/{author}", get(author_handler)) + .route("/api/gallery/collections", get(collections_handler)) + .route( + "/api/gallery/collections/{operator}/{name}", + get(collection_handler), + ) } /// A list or search answer. @@ -59,6 +76,38 @@ pub struct RecordsAnswer { /// For a search, the documented result order. #[serde(default, skip_serializing_if = "Option::is_none")] pub order: Option, + /// The operator's own tags for these records, by content hash: operator + /// speech, never part of a signed record (G2). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub operator_tags: BTreeMap>, +} + +/// An author page. +#[derive(Debug, Serialize, Deserialize)] +pub struct AuthorAnswer { + /// The author's key: the page's address. + pub author: String, + /// Every record that key published here. + pub records: Vec, + /// The operator's own tags for this author (G2): operator speech. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub operator_tags: Vec, +} + +/// A featured collection with its attribution. +#[derive(Debug, Serialize, Deserialize)] +pub struct FeaturedAnswer { + /// The key of the operator who signed and features the collection. + pub featured_by: String, + /// The collection exactly as the operator signed it. + pub collection: SignedCollection, +} + +/// Every featured collection. +#[derive(Debug, Serialize, Deserialize)] +pub struct CollectionsAnswer { + /// The collections, ordered by operator key then name. + pub collections: Vec, } #[derive(Debug, Deserialize)] @@ -86,14 +135,18 @@ async fn records_handler( author: params.author, name: params.name, }; - let records = match gallery.read() { - Ok(gallery) => gallery.list(&query), + let answer = match gallery.read() { + Ok(gallery) => { + let records = gallery.list(&query); + RecordsAnswer { + operator_tags: gallery.overlay().tags_for(&records), + records, + order: None, + } + } Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), }; - listing(RecordsAnswer { - records, - order: None, - }) + listing(&answer) } async fn bundle_handler( @@ -150,19 +203,78 @@ async fn search_handler( limit: params.limit, }; let found = match gallery.read() { - Ok(gallery) => gallery.search(&query), + Ok(gallery) => gallery.search(&query).map(|records| RecordsAnswer { + operator_tags: gallery.overlay().tags_for(&records), + records, + order: Some(SEARCH_ORDER.to_owned()), + }), Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), }; match found { - Ok(records) => listing(RecordsAnswer { - records, - order: Some(SEARCH_ORDER.to_owned()), + Ok(answer) => listing(&answer), + Err(error) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(), + } +} + +async fn author_handler( + State(gallery): State>, + Path(author): Path, +) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let page = match gallery.read() { + Ok(gallery) => gallery.author_page(&author), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + match page { + Ok(page) => listing(&AuthorAnswer { + author: page.author, + records: page.records, + operator_tags: page.operator_tags, }), Err(error) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(), } } -fn listing(answer: RecordsAnswer) -> Response { +async fn collections_handler(State(gallery): State>) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let collections = match gallery.read() { + Ok(gallery) => gallery.collections().filter_map(featured).collect(), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + listing(&CollectionsAnswer { collections }) +} + +async fn collection_handler( + State(gallery): State>, + Path((operator, name)): Path<(String, String)>, +) -> Response { + let Some(gallery) = gallery else { + return StatusCode::NOT_FOUND.into_response(); + }; + let found = match gallery.read() { + Ok(gallery) => gallery.collection(&operator, &name).and_then(featured), + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + found.map_or_else( + || StatusCode::NOT_FOUND.into_response(), + |answer| listing(&answer), + ) +} + +/// A stored collection with the attribution its own signature proves. +fn featured(signed: &SignedCollection) -> Option { + let collection = signed.verify().ok()?; + Some(FeaturedAnswer { + featured_by: collection.operator, + collection: signed.clone(), + }) +} + +fn listing(answer: &impl Serialize) -> Response { let mut response = Json(answer).into_response(); response.headers_mut().insert( header::CACHE_CONTROL, @@ -320,4 +432,77 @@ mod tests { assert_eq!(get(&app, uri).await.0, StatusCode::NOT_FOUND, "{uri}"); } } + + #[tokio::test] + async fn author_pages_collections_and_operator_tags_are_served_apart() { + let author = SigningKey::from_bytes(&[7; 32]); + let author_key = id_worlds::world_session::encode_hex(&author.verifying_key().to_bytes()); + let operator = SigningKey::from_bytes(&[9; 32]); + let operator_key = + id_worlds::world_session::encode_hex(&operator.verifying_key().to_bytes()); + let mut gallery = Gallery::new(Registry::in_memory(AdmitAll)); + let chess = bundle("chess", 1, "The classic board game.", &["board"]); + gallery.publish(&chess.to_bytes()).unwrap(); + let picks = SignedCollection::sign( + "staff-picks", + "Staff picks", + 1, + vec![chess.identity()], + &operator, + ) + .unwrap(); + gallery.feature(&picks).unwrap(); + let mut overlay = id_worlds::program_gallery_operator::OperatorOverlay::default(); + overlay.programs.insert( + chess.manifest().content_hash.clone(), + vec!["miscategorised".to_owned()], + ); + overlay + .authors + .insert(author_key.clone(), vec!["verified".to_owned()]); + gallery.set_overlay(overlay).unwrap(); + let app = app(Some(Arc::new(RwLock::new(gallery)))); + + let (status, _, body) = get(&app, &format!("/api/gallery/authors/{author_key}")).await; + assert_eq!(status, StatusCode::OK); + let page: AuthorAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(page.author, author_key); + assert_eq!(page.records, vec![chess.record()]); + assert_eq!(page.operator_tags, ["verified"]); + let (status, _, _) = get(&app, "/api/gallery/authors/not-a-key").await; + assert_eq!(status, StatusCode::BAD_REQUEST); + + let (_, _, body) = get(&app, "/api/gallery/records").await; + let answer: RecordsAnswer = serde_json::from_slice(&body).unwrap(); + let hash = &chess.manifest().content_hash; + assert_eq!(answer.operator_tags[hash], ["miscategorised"]); + assert_eq!( + answer.records[0].verify().unwrap().categories, + ["board"], + "the signed categories are untouched by the overlay" + ); + + let (_, _, body) = get(&app, "/api/gallery/collections").await; + let all: CollectionsAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!(all.collections.len(), 1); + assert_eq!(all.collections[0].featured_by, operator_key); + assert_eq!(all.collections[0].collection, picks); + let (status, _, body) = get( + &app, + &format!("/api/gallery/collections/{operator_key}/staff-picks"), + ) + .await; + assert_eq!(status, StatusCode::OK); + let one: FeaturedAnswer = serde_json::from_slice(&body).unwrap(); + assert_eq!( + one.collection.verify().unwrap().items, + vec![chess.identity()] + ); + let (status, _, _) = get( + &app, + &format!("/api/gallery/collections/{author_key}/staff-picks"), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "attribution is by signer"); + } } diff --git a/pkgs/id/crates/id-worlds/src/lib.rs b/pkgs/id/crates/id-worlds/src/lib.rs index f535d49a68..1a1456a48a 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_operator; pub mod program_registry; #[cfg(feature = "sandbox")] pub mod sandbox; diff --git a/pkgs/id/crates/id-worlds/src/program_bundle.rs b/pkgs/id/crates/id-worlds/src/program_bundle.rs index 1fec7fe362..c13863200d 100644 --- a/pkgs/id/crates/id-worlds/src/program_bundle.rs +++ b/pkgs/id/crates/id-worlds/src/program_bundle.rs @@ -575,7 +575,7 @@ fn push_segment(out: &mut Vec, segment: &[u8]) { } /// Canonical lower-case hex of exactly `N` bytes. -fn parse_hex(text: &str) -> Option<[u8; N]> { +pub(crate) fn parse_hex(text: &str) -> Option<[u8; N]> { let bytes: [u8; N] = decode_hex(text)?.try_into().ok()?; (encode_hex(&bytes) == text).then_some(bytes) } @@ -584,7 +584,7 @@ fn parse_signature(text: &str) -> Option { parse_hex::<64>(text).map(|bytes| Signature::from_bytes(&bytes)) } -fn check_identity(identity: &ProgramIdentity) -> Result { +pub(crate) fn check_identity(identity: &ProgramIdentity) -> Result { let author = parse_hex::<32>(&identity.author) .ok_or_else(|| "author is not 32 bytes of lower-case hex".to_owned())?; let author = VerifyingKey::from_bytes(&author) @@ -643,6 +643,18 @@ fn check_manifest(manifest: &BundleManifest) -> Result bool { + !category.is_empty() + && category.len() <= MAX_CATEGORY_BYTES + && category + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + /// The discovery metadata's bounds: a description within /// [`MAX_DESCRIPTION_BYTES`], and at most [`MAX_CATEGORIES`] distinct /// categories in the portable form. @@ -662,12 +674,7 @@ fn check_discovery(manifest: &BundleManifest) -> Result<(), String> { )); } for (index, category) in manifest.categories.iter().enumerate() { - let portable = !category.is_empty() - && category.len() <= MAX_CATEGORY_BYTES - && category - .bytes() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); - if !portable { + if !is_portable_category(category) { return Err(format!( "category {index} must be 1 to {MAX_CATEGORY_BYTES} lower-case ASCII letters, digits or '-'" )); diff --git a/pkgs/id/crates/id-worlds/src/program_gallery.rs b/pkgs/id/crates/id-worlds/src/program_gallery.rs index a7863d4671..e63af9483c 100644 --- a/pkgs/id/crates/id-worlds/src/program_gallery.rs +++ b/pkgs/id/crates/id-worlds/src/program_gallery.rs @@ -17,7 +17,10 @@ use std::collections::BTreeMap; use crate::program_bundle::{BundleManifest, BundleRecord}; -use crate::program_registry::{ListQuery, Registry, RegistryError}; +use crate::program_gallery_operator::{ + AuthorPage, OperatorData, OperatorError, OperatorOverlay, SignedCollection, check_author_key, +}; +use crate::program_registry::{AdmissionPolicy, ListQuery, Registry, RegistryError}; /// Most results one search returns, whatever the caller asks for. pub const MAX_SEARCH_RESULTS: usize = 200; @@ -200,14 +203,114 @@ fn searchable_text(manifest: &BundleManifest) -> String { pub struct Gallery { registry: Registry, index: SearchIndex, + operator: OperatorData, + dir: Option, } impl Gallery { - /// Serve `registry`, indexing every record it lists. + /// Serve `registry`, indexing every record it lists, with no operator + /// data and nothing kept on disk beyond what the registry keeps. #[must_use] pub fn new(registry: Registry) -> Self { let index = SearchIndex::rebuild(registry.list(&ListQuery::default())); - Self { registry, index } + Self { + registry, + index, + operator: OperatorData::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). + /// + /// # Errors + /// + /// The registry or the operator data does not load. + pub fn open_dir( + dir: impl Into, + policy: impl AdmissionPolicy + 'static, + ) -> anyhow::Result { + let dir = dir.into(); + let registry = Registry::open_dir(&dir, policy)?; + let operator = OperatorData::load(&dir)?; + let mut gallery = Self::new(registry); + gallery.operator = operator; + gallery.dir = Some(dir); + Ok(gallery) + } + + /// Every record `author` published here, addressed by the key alone + /// (G5), with the operator's tags for that author kept apart. + /// + /// # Errors + /// + /// `author` is not a key in canonical form. + pub fn author_page(&self, author: &str) -> Result { + check_author_key(author)?; + Ok(AuthorPage { + author: author.to_owned(), + records: self.registry.list(&ListQuery { + author: Some(author.to_owned()), + name: None, + }), + operator_tags: self + .operator + .overlay + .authors + .get(author) + .cloned() + .unwrap_or_default(), + }) + } + + /// Every featured collection, ordered by operator key then name. + pub fn collections(&self) -> impl Iterator { + self.operator.collections.values() + } + + /// One operator's collection by name. + #[must_use] + pub fn collection(&self, operator: &str, name: &str) -> Option<&SignedCollection> { + self.operator + .collections + .get(&(operator.to_owned(), name.to_owned())) + } + + /// Feature a collection (G4), keeping the higher revision, and store it + /// when the gallery has a directory. Returns whether it was kept. + /// + /// # Errors + /// + /// It does not verify, or it cannot be stored. + pub fn feature(&mut self, signed: &SignedCollection) -> Result { + let kept = self.operator.insert_collection(signed.clone())?; + if kept && let Some(dir) = &self.dir { + OperatorData::save_collection(dir, signed)?; + } + Ok(kept) + } + + /// The operator's tags (G2). + #[must_use] + pub const fn overlay(&self) -> &OperatorOverlay { + &self.operator.overlay + } + + /// Replace the operator's tags, storing them when the gallery has a + /// directory. + /// + /// # Errors + /// + /// They do not check, or they cannot be stored. + pub fn set_overlay(&mut self, overlay: OperatorOverlay) -> Result<(), OperatorError> { + overlay.check()?; + if let Some(dir) = &self.dir { + OperatorData::save_overlay(dir, &overlay)?; + } + self.operator.overlay = overlay; + Ok(()) } /// The registry behind this gallery. @@ -293,6 +396,7 @@ mod tests { use super::*; use crate::program_bundle::{ProgramBundle, ProgramSpec, export}; + use crate::program_gallery_operator::{OperatorOverlay, SignedCollection}; use crate::program_registry::{AdmitAll, sign_unpublish}; fn alice() -> SigningKey { @@ -527,4 +631,73 @@ mod tests { .unwrap_err(); assert_eq!(error, SearchError::QueryTooLong(MAX_QUERY_BYTES + 1)); } + + #[test] + fn an_author_page_is_addressed_by_key_with_operator_tags_apart() { + let mut gallery = gallery(); + let bob_key = crate::world_session::encode_hex(&bob().verifying_key().to_bytes()); + let mut overlay = OperatorOverlay::default(); + overlay + .authors + .insert(bob_key.clone(), vec!["prolific".to_owned()]); + gallery.set_overlay(overlay).unwrap(); + let page = gallery.author_page(&bob_key).unwrap(); + assert_eq!(page.author, bob_key); + assert_eq!( + names(&page.records), + vec![ + ("chess-puzzles".to_owned(), 3), + ("go".to_owned(), 1), + ("racer".to_owned(), 5), + ] + ); + assert_eq!(page.operator_tags, ["prolific"]); + for record in &page.records { + assert!( + !record + .verify() + .unwrap() + .categories + .contains(&"prolific".to_owned()), + "operator tags never enter signed categories" + ); + } + assert!(gallery.author_page("bob").is_err()); + let nobody = "ab".repeat(32); + assert!(gallery.author_page(&nobody).unwrap().records.is_empty()); + } + + #[test] + fn a_directory_gallery_keeps_collections_and_overlay_across_reopen() { + let dir = tempfile::tempdir().unwrap(); + let operator = SigningKey::from_bytes(&[9; 32]); + let chess = program(&alice(), "chess", 1, "Board game.", &["board"]); + { + let mut gallery = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + gallery.publish(&chess.to_bytes()).unwrap(); + let picks = + SignedCollection::sign("picks", "Picks", 1, vec![chess.identity()], &operator) + .unwrap(); + assert!(gallery.feature(&picks).unwrap()); + let mut overlay = OperatorOverlay::default(); + overlay.programs.insert( + chess.manifest().content_hash.clone(), + vec!["classic".to_owned()], + ); + gallery.set_overlay(overlay).unwrap(); + } + let gallery = Gallery::open_dir(dir.path(), AdmitAll).unwrap(); + assert_eq!(gallery.list(&ListQuery::default()), vec![chess.record()]); + let operator_key = crate::world_session::encode_hex(&operator.verifying_key().to_bytes()); + let picks = gallery.collection(&operator_key, "picks").unwrap(); + assert_eq!(picks.verify().unwrap().items, vec![chess.identity()]); + assert_eq!(gallery.collections().count(), 1); + assert_eq!( + gallery.overlay().tags_for(&[chess.record()]), + BTreeMap::from([( + chess.manifest().content_hash.clone(), + vec!["classic".to_owned()] + )]) + ); + } } diff --git a/pkgs/id/crates/id-worlds/src/program_gallery_operator.rs b/pkgs/id/crates/id-worlds/src/program_gallery_operator.rs new file mode 100644 index 0000000000..f7fd9de556 --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/program_gallery_operator.rs @@ -0,0 +1,520 @@ +//! The gallery's operator layer (#10004; v3 design +//! `doc/2026-11-14T13-33-00Z_design_id_program_ecosystem_v3/`, G2, G4, G5). +//! +//! Everything here is the operator's speech, never the author's, and is +//! kept apart from signed records so no surface can confuse the two: +//! +//! - [`SignedCollection`]: a featured collection, an ordered list of +//! program identities signed by the operator's own key and attributed to +//! it (G4). Any host can publish collections the same way, and a +//! collection never changes the records it lists. +//! - [`OperatorOverlay`]: the operator's own tags for programs and authors +//! (G2), stored and served as operator data beside, never inside, the +//! author-signed categories. +//! - [`AuthorPage`]: every record one author key published, addressed by +//! that key alone (G5), with the operator's tags for the author shown as +//! operator data. + +use std::collections::BTreeMap; +use std::path::Path; + +use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +use crate::program_bundle::{ + BundleRecord, ProgramIdentity, check_identity, is_portable_category, parse_hex, +}; +use crate::world_session::encode_hex; + +/// Domain separator for an operator's collection signature. +const COLLECTION_DOMAIN: &[u8] = b"developing-today/id-gallery-collection/v1\0"; + +/// Most programs one collection may list. +pub const MAX_COLLECTION_ITEMS: usize = 500; + +/// Longest collection title, in bytes. +pub const MAX_TITLE_BYTES: usize = 200; + +/// Most operator tags on one program or author. +pub const MAX_OPERATOR_TAGS: usize = 16; + +/// Largest signed collection document accepted, in bytes. +pub const MAX_COLLECTION_BYTES: usize = 256 * 1024; + +/// A featured collection, as the operator states it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Collection { + /// The operator's Ed25519 public key, lower-case hex: whose voice this is. + pub operator: String, + /// The collection's address under the operator, in the portable + /// category form (lower-case ASCII letters, digits and `-`). + pub name: String, + /// The title shown with the collection. + pub title: String, + /// The operator's monotonic revision of this collection. + pub revision: u64, + /// The featured programs, in the operator's order. + pub items: Vec, +} + +/// Why a collection, overlay or author key was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum OperatorError { + /// The collection document is malformed or out of bounds. + #[error("collection: {0}")] + Collection(String), + /// The collection is not signed by the operator it names. + #[error("collection signature: not signed by the operator it names")] + Signature, + /// An operator tag is not in the portable form, or there are too many. + #[error("overlay: {0}")] + Overlay(String), + /// An author key is not 32 bytes of lower-case hex. + #[error("author key is not 32 bytes of lower-case hex")] + AuthorKey, + /// Reading or writing operator data failed. + #[error("operator storage: {0}")] + Storage(String), +} + +/// A collection with the operator's signature over its exact JSON. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignedCollection { + /// The collection's exact JSON, as signed. + pub collection: String, + /// The operator's Ed25519 signature, lower-case hex. + pub signature: String, +} + +impl SignedCollection { + /// Sign `items` as the operator's collection `name`. + /// + /// # Errors + /// + /// The name, title or items are out of bounds. + pub fn sign( + name: &str, + title: &str, + revision: u64, + items: Vec, + operator: &SigningKey, + ) -> Result { + let collection = Collection { + operator: encode_hex(&operator.verifying_key().to_bytes()), + name: name.to_owned(), + title: title.to_owned(), + revision, + items, + }; + check_collection(&collection)?; + let collection = serde_json::to_string(&collection) + .map_err(|e| OperatorError::Collection(e.to_string()))?; + let signature = encode_hex(&operator.sign(&collection_message(&collection)).to_bytes()); + Ok(Self { + collection, + signature, + }) + } + + /// The collection, once its signature and bounds verify. + /// + /// # Errors + /// + /// The document is malformed, out of bounds, or not signed by the + /// operator it names. + pub fn verify(&self) -> Result { + if self.collection.len() > MAX_COLLECTION_BYTES { + return Err(OperatorError::Collection(format!( + "the document is {} bytes; the limit is {MAX_COLLECTION_BYTES}", + self.collection.len() + ))); + } + let collection: Collection = + id_core::json_unique::from_slice_without_duplicate_keys(self.collection.as_bytes()) + .map_err(|e| OperatorError::Collection(e.to_string()))?; + check_collection(&collection)?; + let operator = parse_hex::<32>(&collection.operator) + .and_then(|bytes| VerifyingKey::from_bytes(&bytes).ok()) + .ok_or(OperatorError::Signature)?; + let signature = parse_hex::<64>(&self.signature) + .map(|bytes| Signature::from_bytes(&bytes)) + .ok_or(OperatorError::Signature)?; + operator + .verify_strict(&collection_message(&self.collection), &signature) + .map_err(|_| OperatorError::Signature)?; + Ok(collection) + } +} + +fn collection_message(collection: &str) -> Vec { + let mut message = COLLECTION_DOMAIN.to_vec(); + message.extend_from_slice(blake3::hash(collection.as_bytes()).as_bytes()); + message +} + +fn check_collection(collection: &Collection) -> Result<(), OperatorError> { + if !is_portable_category(&collection.name) { + return Err(OperatorError::Collection( + "the name must be lower-case ASCII letters, digits or '-'".to_owned(), + )); + } + if collection.title.len() > MAX_TITLE_BYTES || collection.title.chars().any(char::is_control) { + return Err(OperatorError::Collection(format!( + "the title must be at most {MAX_TITLE_BYTES} bytes with no control characters" + ))); + } + if collection.items.len() > MAX_COLLECTION_ITEMS { + return Err(OperatorError::Collection(format!( + "{} items; the limit is {MAX_COLLECTION_ITEMS}", + collection.items.len() + ))); + } + for (index, item) in collection.items.iter().enumerate() { + check_identity(item) + .map_err(|reason| OperatorError::Collection(format!("item {index}: {reason}")))?; + } + Ok(()) +} + +/// The operator's own tags, kept apart from author-signed categories (G2). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperatorOverlay { + /// Tags per program, keyed by content hash. + #[serde(default)] + pub programs: BTreeMap>, + /// Tags per author, keyed by author key. + #[serde(default)] + pub authors: BTreeMap>, +} + +impl OperatorOverlay { + /// Check every key and tag. + /// + /// # Errors + /// + /// A key is not 32 bytes of lower-case hex, a tag is not in the portable + /// form, or one entry has too many tags. + pub fn check(&self) -> Result<(), OperatorError> { + for (key, tags) in self.programs.iter().chain(&self.authors) { + if parse_hex::<32>(key).is_none() { + return Err(OperatorError::Overlay(format!( + "{key:?} is not 32 bytes of lower-case hex" + ))); + } + if tags.len() > MAX_OPERATOR_TAGS { + return Err(OperatorError::Overlay(format!( + "{key} has {} tags; the limit is {MAX_OPERATOR_TAGS}", + tags.len() + ))); + } + if let Some(tag) = tags.iter().find(|tag| !is_portable_category(tag)) { + return Err(OperatorError::Overlay(format!( + "tag {tag:?} must be lower-case ASCII letters, digits or '-'" + ))); + } + } + Ok(()) + } + + /// The operator's tags for the programs among `records`, by content + /// hash. Records with none are left out. + #[must_use] + pub fn tags_for(&self, records: &[BundleRecord]) -> BTreeMap> { + records + .iter() + .filter_map(|record| record.verify().ok()) + .filter_map(|manifest| { + self.programs + .get(&manifest.content_hash) + .map(|tags| (manifest.content_hash, tags.clone())) + }) + .collect() + } +} + +/// One author's page, addressed by key alone (G5). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AuthorPage { + /// The author's key: the page's canonical address. + pub author: String, + /// Every record the key published here, by name and version. + pub records: Vec, + /// The operator's tags for this author: operator data, not the author's. + pub operator_tags: Vec, +} + +/// Check that `author` is an author key's canonical form. +/// +/// # Errors +/// +/// It is not 32 bytes of lower-case hex. +pub fn check_author_key(author: &str) -> Result<(), OperatorError> { + parse_hex::<32>(author) + .map(|_| ()) + .ok_or(OperatorError::AuthorKey) +} + +/// The operator data stored beside a gallery's bundles. +#[derive(Clone, Debug, Default)] +pub struct OperatorData { + /// Verified collections, keyed by (operator key, name). + pub collections: BTreeMap<(String, String), SignedCollection>, + /// The operator's tags. + pub overlay: OperatorOverlay, +} + +/// Directory, under a gallery directory, holding operator data. +pub const OPERATOR_DIR: &str = "operator"; +const COLLECTIONS_DIR: &str = "collections"; +const OVERLAY_FILE: &str = "overlay.json"; + +impl OperatorData { + /// Load operator data from `gallery_dir/operator`, if present. Every + /// collection is verified; one that does not verify stops the load. + /// + /// # Errors + /// + /// A file cannot be read or does not verify. + pub fn load(gallery_dir: &Path) -> Result { + let root = gallery_dir.join(OPERATOR_DIR); + let mut data = Self::default(); + let overlay = root.join(OVERLAY_FILE); + if overlay.is_file() { + let bytes = std::fs::read(&overlay).map_err(|e| storage(&overlay, &e))?; + data.overlay = id_core::json_unique::from_slice_without_duplicate_keys(&bytes) + .map_err(|e| OperatorError::Overlay(format!("{}: {e}", overlay.display())))?; + data.overlay.check()?; + } + let collections = root.join(COLLECTIONS_DIR); + if collections.is_dir() { + let mut paths: Vec<_> = std::fs::read_dir(&collections) + .map_err(|e| storage(&collections, &e))? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>() + .map_err(|e| storage(&collections, &e))?; + paths.sort(); + for path in paths { + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + let bytes = std::fs::read(&path).map_err(|e| storage(&path, &e))?; + let signed: SignedCollection = + id_core::json_unique::from_slice_without_duplicate_keys(&bytes).map_err( + |e| OperatorError::Collection(format!("{}: {e}", path.display())), + )?; + data.insert_collection(signed)?; + } + } + Ok(data) + } + + /// Add or replace a verified collection, keeping the higher revision. + /// Returns whether it was kept. + /// + /// # Errors + /// + /// The collection does not verify. + pub fn insert_collection(&mut self, signed: SignedCollection) -> Result { + let collection = signed.verify()?; + let key = (collection.operator, collection.name); + if let Some(existing) = self.collections.get(&key) + && existing.verify()?.revision >= collection.revision + { + return Ok(false); + } + self.collections.insert(key, signed); + Ok(true) + } + + /// Write a verified collection under `gallery_dir/operator/collections`. + /// + /// # Errors + /// + /// The collection does not verify, or the file cannot be written. + pub fn save_collection( + gallery_dir: &Path, + signed: &SignedCollection, + ) -> Result<(), OperatorError> { + let collection = signed.verify()?; + let dir = gallery_dir.join(OPERATOR_DIR).join(COLLECTIONS_DIR); + std::fs::create_dir_all(&dir).map_err(|e| storage(&dir, &e))?; + let path = dir.join(format!( + "{}-{}.json", + &collection.operator[..16], + collection.name + )); + let bytes = + serde_json::to_vec_pretty(signed).map_err(|e| OperatorError::Storage(e.to_string()))?; + std::fs::write(&path, bytes).map_err(|e| storage(&path, &e)) + } + + /// Write the operator overlay to `gallery_dir/operator/overlay.json`. + /// + /// # Errors + /// + /// The overlay does not check, or the file cannot be written. + pub fn save_overlay( + gallery_dir: &Path, + overlay: &OperatorOverlay, + ) -> Result<(), OperatorError> { + overlay.check()?; + let dir = gallery_dir.join(OPERATOR_DIR); + std::fs::create_dir_all(&dir).map_err(|e| storage(&dir, &e))?; + let path = dir.join(OVERLAY_FILE); + let bytes = serde_json::to_vec_pretty(overlay) + .map_err(|e| OperatorError::Storage(e.to_string()))?; + std::fs::write(&path, bytes).map_err(|e| storage(&path, &e)) + } +} + +fn storage(path: &Path, error: &std::io::Error) -> OperatorError { + OperatorError::Storage(format!("{}: {error}", path.display())) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::program_bundle::{ProgramSpec, export}; + + fn operator() -> SigningKey { + SigningKey::from_bytes(&[9; 32]) + } + + fn identity(name: &str) -> ProgramIdentity { + export( + name.as_bytes().to_vec(), + ProgramSpec { + name, + version: 1, + licence: None, + description: None, + categories: &[], + }, + &SigningKey::from_bytes(&[1; 32]), + ) + .unwrap() + .identity() + } + + #[test] + fn a_collection_verifies_under_its_operator_and_refuses_edits() { + let items = vec![identity("chess"), identity("go")]; + let signed = + SignedCollection::sign("staff-picks", "Staff picks", 1, items.clone(), &operator()) + .unwrap(); + let collection = signed.verify().unwrap(); + assert_eq!( + collection.operator, + encode_hex(&operator().verifying_key().to_bytes()) + ); + assert_eq!(collection.items, items); + + let reordered = SignedCollection { + collection: signed.collection.replacen("chess", "chesz", 1), + ..signed.clone() + }; + assert!(reordered.verify().is_err()); + + let other = SigningKey::from_bytes(&[8; 32]); + let forged = SignedCollection { + signature: encode_hex( + &other + .sign(&collection_message(&signed.collection)) + .to_bytes(), + ), + ..signed + }; + assert_eq!(forged.verify().unwrap_err(), OperatorError::Signature); + } + + #[test] + fn collection_bounds_are_refused_before_signing() { + let sign = |name: &str, title: &str| { + SignedCollection::sign(name, title, 1, Vec::new(), &operator()) + }; + assert!(sign("Staff Picks", "x").is_err()); + assert!(sign("picks", &"t".repeat(MAX_TITLE_BYTES + 1)).is_err()); + assert!(sign("picks", "a\nb").is_err()); + let mut bad = identity("chess"); + bad.content_hash = "zz".to_owned(); + assert!(SignedCollection::sign("picks", "t", 1, vec![bad], &operator()).is_err()); + } + + #[test] + fn overlay_tags_must_be_portable_and_keyed_by_hex() { + let hash = identity("chess").content_hash; + let mut overlay = OperatorOverlay::default(); + overlay + .programs + .insert(hash.clone(), vec!["miscategorised".to_owned()]); + assert!(overlay.check().is_ok()); + overlay + .programs + .insert(hash, vec!["Not Portable".to_owned()]); + assert!(overlay.check().is_err()); + let mut overlay = OperatorOverlay::default(); + overlay + .authors + .insert("not-a-key".to_owned(), vec!["verified".to_owned()]); + assert!(overlay.check().is_err()); + } + + #[test] + fn operator_data_round_trips_and_keeps_the_newest_revision() { + let dir = tempfile::tempdir().unwrap(); + let first = + SignedCollection::sign("picks", "Picks", 1, vec![identity("chess")], &operator()) + .unwrap(); + let second = + SignedCollection::sign("picks", "Picks", 2, vec![identity("go")], &operator()).unwrap(); + OperatorData::save_collection(dir.path(), &second).unwrap(); + let mut overlay = OperatorOverlay::default(); + overlay.authors.insert( + encode_hex(&operator().verifying_key().to_bytes()), + vec!["staff".to_owned()], + ); + OperatorData::save_overlay(dir.path(), &overlay).unwrap(); + + let mut loaded = OperatorData::load(dir.path()).unwrap(); + assert_eq!(loaded.overlay, overlay); + assert_eq!(loaded.collections.len(), 1); + assert!( + !loaded.insert_collection(first).unwrap(), + "an older revision is not kept" + ); + let kept = loaded + .collections + .values() + .next() + .unwrap() + .verify() + .unwrap(); + assert_eq!(kept.revision, 2); + + let path = dir + .path() + .join(OPERATOR_DIR) + .join(COLLECTIONS_DIR) + .join("forged.json"); + let forged = SignedCollection { + signature: "00".repeat(64), + ..second + }; + std::fs::write(&path, serde_json::to_vec(&forged).unwrap()).unwrap(); + assert_eq!( + OperatorData::load(dir.path()).unwrap_err(), + OperatorError::Signature + ); + } + + #[test] + fn author_keys_are_checked() { + assert!(check_author_key(&"ab".repeat(32)).is_ok()); + assert!(check_author_key(&"AB".repeat(32)).is_err()); + assert!(check_author_key("chess").is_err()); + } +}