Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions pkgs/id/crates/id-cli/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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/<hash>` and `/api/gallery/search` from the
/// verified bundle files (`<content-hash>.idpb`) in the directory.
/// Every file is verified when the server starts.
/// `/api/gallery/bundles/<hash>`, `/api/gallery/search`,
/// `/api/gallery/authors/<key>` and `/api/gallery/collections` from the
/// verified bundle files (`<content-hash>.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<std::path::PathBuf>,
/// Host a multiplayer world over Iroh (and `/ws/world` with `--web`).
Expand Down
20 changes: 10 additions & 10 deletions pkgs/id/crates/id-cli/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
207 changes: 196 additions & 11 deletions pkgs/id/crates/id-web/src/gallery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand All @@ -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.
Expand All @@ -49,6 +60,12 @@ pub fn gallery_routes() -> Router<Option<SharedGallery>> {
.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.
Expand All @@ -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<String>,
/// 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<String, Vec<String>>,
}

/// 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<BundleRecord>,
/// The operator's own tags for this author (G2): operator speech.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub operator_tags: Vec<String>,
}

/// 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<FeaturedAnswer>,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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<Option<SharedGallery>>,
Path(author): Path<String>,
) -> 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<Option<SharedGallery>>) -> 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<Option<SharedGallery>>,
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<FeaturedAnswer> {
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,
Expand Down Expand Up @@ -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");
}
}
1 change: 1 addition & 0 deletions pkgs/id/crates/id-worlds/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
23 changes: 15 additions & 8 deletions pkgs/id/crates/id-worlds/src/program_bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,7 @@ fn push_segment(out: &mut Vec<u8>, segment: &[u8]) {
}

/// Canonical lower-case hex of exactly `N` bytes.
fn parse_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
pub(crate) fn parse_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
let bytes: [u8; N] = decode_hex(text)?.try_into().ok()?;
(encode_hex(&bytes) == text).then_some(bytes)
}
Expand All @@ -584,7 +584,7 @@ fn parse_signature(text: &str) -> Option<Signature> {
parse_hex::<64>(text).map(|bytes| Signature::from_bytes(&bytes))
}

fn check_identity(identity: &ProgramIdentity) -> Result<VerifyingKey, String> {
pub(crate) fn check_identity(identity: &ProgramIdentity) -> Result<VerifyingKey, String> {
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)
Expand Down Expand Up @@ -643,6 +643,18 @@ fn check_manifest(manifest: &BundleManifest) -> Result<VerifyingKey, BundleError
Ok(author)
}

/// Whether `category` is in the portable form every registry's taxonomy
/// reads the same: 1 to [`MAX_CATEGORY_BYTES`] lower-case ASCII letters,
/// digits and `-`. Operator tags (v3 G2) use the same form.
#[must_use]
pub fn is_portable_category(category: &str) -> 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.
Expand All @@ -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 '-'"
));
Expand Down
Loading