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
93 changes: 93 additions & 0 deletions pkgs/id/crates/id-cli/src/cli/gallery.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
},
/// 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<String>,
},
/// 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<String>,
},
/// 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<u32>,
},
/// 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<String>,
/// An author's public key.
#[arg(long)]
author: Option<String>,
/// The tags, in the portable form (lower-case letters, digits, `-`).
tags: Vec<String>,
},
}
14 changes: 10 additions & 4 deletions pkgs/id/crates/id-cli/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -474,10 +476,11 @@ pub struct ServeArgs {
///
/// The web interface answers `/api/gallery/records`,
/// `/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.
/// `/api/gallery/authors/<key>`, `/api/gallery/collections` and
/// `/api/gallery/transparency` from the verified bundle files
/// (`<content-hash>.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<std::path::PathBuf>,
/// Host a multiplayer world over Iroh (and `/ws/world` with `--web`).
Expand Down Expand Up @@ -1374,6 +1377,9 @@ pub enum Command {
/// ```
#[command(subcommand)]
World(Box<WorldCommand>),
/// 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)]
Expand Down
51 changes: 51 additions & 0 deletions pkgs/id/crates/id-cli/src/cli/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
195 changes: 195 additions & 0 deletions pkgs/id/crates/id-cli/src/commands/gallery.rs
Original file line number Diff line number Diff line change
@@ -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());
}
}
Loading