diff --git a/crates/rns-git/src/bin/rngit-rs.rs b/crates/rns-git/src/bin/rngit-rs.rs index fd9de0b..130846f 100644 --- a/crates/rns-git/src/bin/rngit-rs.rs +++ b/crates/rns-git/src/bin/rngit-rs.rs @@ -19,11 +19,13 @@ use rns_git::server::handlers::{ Reply, handle_create, handle_delete, handle_fetch, handle_list, handle_push, }; use rns_git::server::layout::{Repositories, git_available}; +use rns_git::server::perms_mgmt::handle_perms; use rns_git::server::releases::handle_release; use rns_git::server::stats::{STATS_JOB_INTERVAL, Stats}; +use rns_git::server::work::handle_work; use rns_git::server::{ - APP_NAME, PATH_CREATE, PATH_DELETE, PATH_FETCH, PATH_FORK, PATH_LIST, PATH_MIRROR, PATH_PUSH, - PATH_RELEASE, PATH_SYNC, + APP_NAME, PATH_CREATE, PATH_DELETE, PATH_FETCH, PATH_FORK, PATH_LIST, PATH_MIRROR, PATH_PERMS, + PATH_PUSH, PATH_RELEASE, PATH_SYNC, PATH_WORK, }; use rns_identity::destination::{AllowPolicy, Destination}; use rns_identity::identity::Identity; @@ -45,6 +47,9 @@ const REPLY_LIMIT: usize = 64 * 1024; /// this one keeps a release job's share of the deferred budget small. const RELEASE_REPLY_LIMIT: usize = 4 * 1024 * 1024; +/// Work lists and views carry whole documents (each up to `WORK_DOC_LIMIT`). +const WORK_REPLY_LIMIT: usize = 4 * 1024 * 1024; + /// Admission for the git handlers: the manager's three copies of the request /// (payload, value, byte view) and a status-byte or file-backed reply; a refused /// job answers with `RES_REMOTE_FAIL` and a reason the remote helper prints. @@ -118,6 +123,37 @@ fn deferred( } } +type IdentityHandler = Box< + dyn Fn(&RwLock, Option<&Identity>, &rmpv::Value) -> Option> + Send + Sync, +>; + +/// Run a status-byte handler that needs the caller's public key on the blocking pool. +fn deferred_with_identity( + repositories: Arc>, + handler: Arc, +) -> impl Fn(DestinationRequest, DeferredRequestResponder) + Send + 'static { + move |request, responder| { + let repositories = repositories.clone(); + let handler = Arc::clone(&handler); + tokio::task::spawn_blocking(move || { + let outcome = match handler( + &repositories, + request.remote_identity.as_ref(), + &request.value, + ) { + None => RequestOutcome::Drop, + Some(bytes) if bytes.capacity() > responder.response_byte_limit() => { + let mut reply = vec![rns_git::server::RES_REMOTE_FAIL]; + reply.extend_from_slice(b"Reply too large for this node"); + RequestOutcome::ReplyBytes(reply) + } + Some(bytes) => RequestOutcome::ReplyBytes(bytes), + }; + let _ = responder.respond(outcome); + }); + } +} + #[derive(Parser)] #[command( name = "rngit-rs", @@ -295,6 +331,144 @@ async fn clone_subcommand(op: Operation, argv: Vec) { rns_git::client::forks::run(op, args).await } +#[derive(Parser)] +#[command( + name = "rngit-rs work", + about = "Reticulum Git Work Document Manager", + disable_version_flag = true +)] +struct WorkCliArgs { + /// path to alternative config directory + #[arg(long)] + config: Option, + /// path to alternative Reticulum config directory + #[arg(long)] + rnsconfig: Option, + /// path to identity + #[arg(short = 'i', long, value_name = "PATH")] + identity: Option, + /// document scope: active, completed or all + #[arg(long, default_value = "active")] + scope: String, + /// document title for create + #[arg(short = 't', long)] + title: Option, + /// document ID + #[arg(short = 'd', long = "id", allow_negative_numbers = true)] + id: Option, + /// URL of remote repository + repository: Option, + /// list, view, create, propose, edit, delete, update, complete, activate or perms + operation: Option, + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + #[arg(short = 'q', long, action = clap::ArgAction::Count)] + quiet: u8, + #[arg(long)] + version: bool, +} + +#[derive(Parser)] +#[command( + name = "rngit-rs perms", + about = "Reticulum Git Release Manager", + disable_version_flag = true +)] +struct PermsCliArgs { + /// path to alternative config directory + #[arg(long)] + config: Option, + /// path to alternative Reticulum config directory + #[arg(long)] + rnsconfig: Option, + /// path to release identity + #[arg(short = 'i', long, value_name = "PATH")] + identity: Option, + /// URL of remote group or repository + remote: String, + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + #[arg(short = 'q', long, action = clap::ArgAction::Count)] + quiet: u8, + #[arg(long)] + version: bool, +} + +/// `rngit work` (`server.py:182-191`, `255-260`, `106-122`). +async fn work_subcommand(argv: Vec) { + use rns_git::client::work::{CommonArgs, WorkArgs, run_client, run_work}; + let args = WorkCliArgs::parse_from(argv); + if args.version { + println!("rngit-rs {RS_RETICULUM_VERSION}"); + return; + } + if args.operation.as_deref().is_none_or(str::is_empty) { + let _ = WorkCliArgs::command().print_help(); + println!(); + } + let common = CommonArgs { + config: args.config, + rnsconfig: args.rnsconfig, + identity: args.identity, + verbose: args.verbose, + quiet: args.quiet, + }; + let operation = args.operation; + let work = WorkArgs { + remote: args.repository, + scope: args.scope, + doc_id: args.id, + title: args.title, + }; + run_client( + common, + rns_git::server::PATH_WORK, + Box::new(move |out, input, config, connect, identity| { + run_work( + out, + input, + config, + connect, + identity, + operation.as_deref(), + &work, + ) + }), + ) + .await +} + +/// `rngit perms` (`server.py:175-180`, `245-253`, `100-104`). +async fn perms_subcommand(argv: Vec) { + use rns_git::client::perms::{perms_target, run_perms}; + use rns_git::client::work::{CommonArgs, run_client}; + let args = PermsCliArgs::parse_from(argv); + if args.version { + println!("rngit-rs {RS_RETICULUM_VERSION}"); + return; + } + let Some((remote, target)) = perms_target(&args.remote) else { + let _ = PermsCliArgs::command().print_help(); + println!("\nInvalid URL"); + std::process::exit(1); + }; + let common = CommonArgs { + config: args.config, + rnsconfig: args.rnsconfig, + identity: args.identity, + verbose: args.verbose, + quiet: args.quiet, + }; + run_client( + common, + rns_git::server::PATH_PERMS, + Box::new(move |out, _input, config, connect, _identity| { + run_perms(out, config, connect, &remote, target) + }), + ) + .await +} + #[derive(Parser)] #[command( name = "rngit-rs release", @@ -783,6 +957,14 @@ async fn main() { } release(args).await; return; + } else if argv.get(1).map(String::as_str) == Some("work") { + argv.remove(1); + work_subcommand(argv).await; + return; + } else if argv.get(1).map(String::as_str) == Some("perms") { + argv.remove(1); + perms_subcommand(argv).await; + return; } else if argv.get(1).map(String::as_str) == Some("create") { argv.remove(1); let args = CreateArgs::parse_from(argv); @@ -1024,6 +1206,28 @@ async fn main() { rns_tools::exit(&handle, 1).await; } } + // Work documents verify signatures, so these handlers take the whole identity. + let perms_config = Arc::new(config.clone()); + let work: IdentityHandler = Box::new(handle_work); + let perms: IdentityHandler = + Box::new(move |r, i, d| Some(handle_perms(r, &perms_config, i.map(|i| &i.hash), d))); + for (path, handler) in [(PATH_WORK, work), (PATH_PERMS, perms)] { + let ok = registered + .handle + .register_deferred_request_handler_with( + path, + AllowPolicy::AllowAll, + Vec::new(), + true, + admission(WORK_REPLY_LIMIT), + deferred_with_identity(repositories.clone(), Arc::new(handler)), + ) + .await; + if !matches!(ok, Ok(true)) { + tracing::error!("Could not register the {path} handler"); + rns_tools::exit(&handle, 1).await; + } + } tracing::info!( target: rns_tools::NOTICE_TARGET, "Reticulum Git Node listening on {}", diff --git a/crates/rns-git/src/client/mod.rs b/crates/rns-git/src/client/mod.rs index 246b5cb..3365f91 100644 --- a/crates/rns-git/src/client/mod.rs +++ b/crates/rns-git/src/client/mod.rs @@ -1,4 +1,6 @@ //! `rngit` client subcommands (`ReticulumGitClient`, `server.py:281-1830@1.6.0`). pub mod forks; +pub mod perms; pub mod releases; +pub mod work; diff --git a/crates/rns-git/src/client/perms.rs b/crates/rns-git/src/client/perms.rs new file mode 100644 index 0000000..2cffb71 --- /dev/null +++ b/crates/rns-git/src/client/perms.rs @@ -0,0 +1,84 @@ +//! `rngit perms` (`group_permissions` and `repository_permissions`, +//! `server.py:1241-1339@1.6.0`). + +use std::io::Write; + +use rmpv::Value; + +use super::releases::{Connect, Fail}; +use super::work::edit_remote_permissions; +use crate::server::client::ClientConfig; +use crate::server::{IDX_GROUP, IDX_REPOSITORY}; + +/// Which file a `perms` URL names: 4 components a group, 5 a repository. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PermsTarget { + Group, + Repository, +} + +/// `args.remote.rstrip("/")` and the component count (`server.py:245-249`); +/// `None` is "Invalid URL". +pub fn perms_target(remote: &str) -> Option<(String, PermsTarget)> { + let remote = remote.trim_end_matches('/').to_string(); + match remote.split('/').count() { + 5 => Some((remote, PermsTarget::Repository)), + 4 => Some((remote, PermsTarget::Group)), + _ => None, + } +} + +fn map(entries: Vec<(Value, Value)>) -> Value { + Value::Map(entries) +} + +/// `rngit perms ` once Reticulum is up. `Ok` is the exit code. +pub fn run_perms( + out: &mut dyn Write, + config: &ClientConfig, + connect: &mut Connect<'_>, + remote: &str, + target: PermsTarget, +) -> Result { + let mut link = connect(remote, "Failed to establish link")?; + let _ = write!(out, "\r \r"); + let (key, name, operation) = match target { + PermsTarget::Group => ( + Value::from(IDX_GROUP), + config + .parse_remote_group_url(remote) + .map_err(Fail::Abort)? + .1, + "gperms", + ), + PermsTarget::Repository => { + let (_, group, repo) = config.parse_remote_url(remote).map_err(Fail::Abort)?; + ( + Value::from(IDX_REPOSITORY), + format!("{group}/{repo}"), + "rperms", + ) + } + }; + let get = map(vec![ + (key.clone(), Value::from(name.as_str())), + (Value::from("operation"), Value::from(operation)), + (Value::from("step"), Value::from("get")), + ]); + let set = |content: String| { + map(vec![ + (key.clone(), Value::from(name.as_str())), + (Value::from("operation"), Value::from(operation)), + (Value::from("step"), Value::from("set")), + (Value::from("content"), Value::from(content)), + ]) + }; + if edit_remote_permissions(out, link.as_mut(), get, set)? { + match target { + PermsTarget::Group => writeln!(out, "Permissions updated for group {name}"), + PermsTarget::Repository => writeln!(out, "Permissions updated for {name}"), + } + .ok(); + } + Ok(0) +} diff --git a/crates/rns-git/src/client/work.rs b/crates/rns-git/src/client/work.rs new file mode 100644 index 0000000..d11e5b2 --- /dev/null +++ b/crates/rns-git/src/client/work.rs @@ -0,0 +1,999 @@ +//! `rngit work` (`ReticulumGitClient.work_*` and the editor helpers, +//! `server.py:1347-1923@1.6.0`). + +use std::io::{BufRead, Write}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use rmpv::Value; +use rns_identity::identity::Identity; +use rns_runtime::lifecycle::ShutdownSignal; + +use super::releases::{Connect, Fail, Remote, Response}; +use crate::server::client::{ClientConfig, client_config_dir}; +use crate::server::{APP_NAME, IDX_REPOSITORY}; + +/// `COMMENT_TEMPLATE`, `CREATE_DOC_TEMPLATE` and `PERMISSIONS_TEMPLATE` (`server.py:5086-5088`). +pub const COMMENT_TEMPLATE: &str = "# Remove this line and enter your update. Save and exit when done, or save an empty document to abort abort."; +pub const CREATE_DOC_TEMPLATE: &str = "# Remove this line and enter your document content. Save and exit when done, or save an empty document to abort abort."; +pub const PERMISSIONS_TEMPLATE: &str = "# No permissions are currently defined for this entity. Add them below, and save and exit when you are done."; + +/// The `rngit work` operations (`server.py:112-122`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WorkOp { + List, + View, + Create, + Propose, + Edit, + Delete, + Update, + Complete, + Activate, + Perms, +} + +impl WorkOp { + pub fn parse(name: &str) -> Option { + Some(match name { + "list" => WorkOp::List, + "view" => WorkOp::View, + "create" => WorkOp::Create, + "propose" => WorkOp::Propose, + "edit" => WorkOp::Edit, + "delete" => WorkOp::Delete, + "update" => WorkOp::Update, + "complete" => WorkOp::Complete, + "activate" => WorkOp::Activate, + "perms" => WorkOp::Perms, + _ => return None, + }) + } +} + +/// What `rngit work` was given on the command line. +#[derive(Debug, Clone, Default)] +pub struct WorkArgs { + pub remote: Option, + pub scope: String, + pub doc_id: Option, + pub title: Option, +} + +fn abort(message: impl Into) -> Result { + Err(Fail::Abort(message.into())) +} + +fn s(v: &str) -> Value { + Value::from(v) +} + +pub(crate) fn field<'a>(value: &'a Value, key: &str) -> Option<&'a Value> { + match value { + Value::Map(entries) => entries + .iter() + .find(|(k, _)| k.as_str() == Some(key)) + .map(|(_, v)| v), + _ => None, + } +} + +fn py_str(value: &Value) -> String { + rns_tools::rsg::pyfmt::py_str(value) +} + +/// `send_request` and the shared reply checks: the body after a zero status. +pub(crate) fn exchange( + remote: &mut dyn Remote, + data: Value, + timeout: u64, + prefix: &str, +) -> Result, Fail> { + let Some(response) = remote.request(data, Duration::from_secs(timeout)) else { + return abort("Request failed or timed out"); + }; + let Response::Bytes(bytes) = response else { + return abort("No response from remote"); + }; + if bytes.is_empty() { + return abort("No response from remote"); + } + if bytes[0] != 0 { + let text: String = bytes[1..].utf8_chunks().map(|c| c.valid()).collect(); + return abort(format!("{prefix}{text}")); + } + Ok(bytes[1..].to_vec()) +} + +pub(crate) fn unpack(body: &[u8], context: &str) -> Result { + rmpv::decode::read_value(&mut &body[..]).map_err(|e| Fail::Abort(format!("{context}: {e}"))) +} + +/// Python `str.capitalize()`. +fn capitalize(text: &str) -> String { + let mut chars = text.chars(); + match chars.next() { + Some(first) => first + .to_uppercase() + .chain(chars.flat_map(char::to_lowercase)) + .collect(), + None => String::new(), + } +} + +/// Python `f"{text: String { + format!( + "{text}{}", + " ".repeat(width.saturating_sub(text.chars().count())) + ) +} + +fn timestamp(value: Option<&Value>) -> f64 { + match value { + Some(Value::F64(f)) => *f, + Some(Value::F32(f)) => f64::from(*f), + Some(Value::Integer(i)) => i.as_f64().unwrap_or(0.0), + _ => 0.0, + } +} + +/// `time.strftime("%Y-%m-%d %H:%M[:%S]", time.localtime(ts))`. +fn strftime(ts: f64, seconds: bool) -> String { + let time = ts.floor() as nix::libc::time_t; + let mut tm = std::mem::MaybeUninit::::zeroed(); + // SAFETY: both pointers are valid for the call; localtime_r is reentrant. + if unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) }.is_null() { + return String::new(); + } + // SAFETY: localtime_r filled `tm` when it returned non-null. + let tm = unsafe { tm.assume_init() }; + let mut out = format!( + "{:04}-{:02}-{:02} {:02}:{:02}", + tm.tm_year + 1900, + tm.tm_mon + 1, + tm.tm_mday, + tm.tm_hour, + tm.tm_min + ); + if seconds { + out.push_str(&format!(":{:02}", tm.tm_sec)); + } + out +} + +/// The editor `_edit_work_content` and `_edit_permissions` run: `$EDITOR`, +/// else the first of nano, vim and vi that `which` finds. +fn find_editor(out: &mut dyn Write) -> Option { + let editor = std::env::var("EDITOR").unwrap_or_default(); + if !editor.is_empty() { + return Some(editor); + } + let found = ["nano", "vim", "vi"].into_iter().find(|fallback| { + std::process::Command::new("which") + .arg(fallback) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + }); + if found.is_none() { + let _ = writeln!( + out, + "No editor found. Please set $EDITOR environment variable." + ); + } + found.map(str::to_string) +} + +/// Write `template` to a kept temporary file, run `[editor, path]` and read +/// the file back. A file the editor could not be started on is left behind. +fn run_editor( + out: &mut dyn Write, + editor: &str, + template: &str, + suffix: &str, +) -> Result, String> { + let file = tempfile::Builder::new() + .prefix("tmp") + .suffix(suffix) + .tempfile() + .map_err(|e| e.to_string())?; + let (mut file, path) = file.keep().map_err(|e| e.to_string())?; + file.write_all(template.as_bytes()) + .map_err(|e| e.to_string())?; + drop(file); + let _ = out.flush(); + let status = std::process::Command::new(editor) + .arg(&path) + .status() + .map_err(|e| e.to_string())?; + if !status.success() { + let code = status.code().unwrap_or_else(|| { + use std::os::unix::process::ExitStatusExt; + -status.signal().unwrap_or(0) + }); + let _ = writeln!(out, "Editor exited with error code {code}"); + let _ = std::fs::remove_file(&path); + return Ok(None); + } + let edited = crate::server::work::read_text(&path).map_err(|e| e.to_string())?; + let _ = std::fs::remove_file(&path); + Ok(Some(edited)) +} + +fn py_strip(s: &str) -> &str { + s.trim_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)) +} + +/// `_edit_work_content` (`server.py:1844-1887`): template lines are dropped, +/// the rest stripped; empty is None. +pub fn edit_work_content(out: &mut dyn Write, content: &str, is_comment: bool) -> Option { + let editor = find_editor(out)?; + let template = if !content.is_empty() { + content + } else if is_comment { + COMMENT_TEMPLATE + } else { + CREATE_DOC_TEMPLATE + }; + match run_editor(out, &editor, template, ".md") { + Ok(edited) => { + let edited = edited?; + let lines: Vec<&str> = edited + .split('\n') + .filter(|line| { + let line = py_strip(line); + !(line.starts_with(COMMENT_TEMPLATE) || line.starts_with(CREATE_DOC_TEMPLATE)) + }) + .collect(); + let result = py_strip(&lines.join("\n")).to_string(); + (!result.is_empty()).then_some(result) + } + Err(e) => { + tracing::error!("Error editing work content: {e}"); + None + } + } +} + +/// `_edit_permissions` (`server.py:1889-1923`): the file as saved, even empty. +pub fn edit_permissions(out: &mut dyn Write, content: &str) -> Option { + let editor = find_editor(out)?; + let template = if content.is_empty() { + PERMISSIONS_TEMPLATE + } else { + content + }; + match run_editor(out, &editor, template, ".txt") { + Ok(edited) => edited, + Err(e) => { + tracing::error!("Error editing permissions: {e}"); + None + } + } +} + +fn request(repo_path: &str, fields: Vec<(&str, Value)>) -> Value { + let mut map = vec![(Value::from(IDX_REPOSITORY), s(repo_path))]; + map.extend(fields.into_iter().map(|(k, v)| (s(k), v))); + Value::Map(map) +} + +const CLEAR: &str = "\r \r"; + +/// `work_list` after the Link is up (`server.py:1359-1402`). +fn work_list( + out: &mut dyn Write, + remote: &mut dyn Remote, + repo_path: &str, + scope: &str, +) -> Result<(), Fail> { + let data = request( + repo_path, + vec![("operation", s("list")), ("scope", s(scope))], + ); + let sent = exchange(remote, data, 120, "Remote error: "); + let _ = write!(out, "{CLEAR}"); + let body = sent?; + let result = if body.is_empty() { + Value::Map(vec![ + (s("active"), Value::Array(vec![])), + (s("completed"), Value::Array(vec![])), + ]) + } else { + unpack(&body, "Error listing work documents")? + }; + let docs_of = |name: &str| -> Vec { + match field(&result, name) { + Some(Value::Array(items)) => items.clone(), + _ => Vec::new(), + } + }; + let shown: Vec<&str> = if scope == "all" { + vec!["active", "completed", "proposed"] + } else { + vec![scope] + }; + for name in shown { + let docs = docs_of(name); + if docs.is_empty() { + if scope != "all" { + let _ = writeln!(out, "No {name} work documents found."); + } + continue; + } + let header = format!("\n{} documents", capitalize(name)); + let _ = writeln!(out, "{header}"); + let _ = writeln!(out, "{}\n", "=".repeat(header.chars().count())); + let _ = writeln!( + out, + "{} {} {} {} Comments", + pad("ID", 4), + pad("Title", 30), + pad("Author", 17), + pad("Created", 18) + ); + let _ = writeln!(out, "{}", "-".repeat(80)); + for doc in &docs { + let id = field(doc, "id").map_or("?".to_string(), py_str); + let mut title = field(doc, "title").map_or("Untitled".to_string(), py_str); + if title.chars().count() > 29 { + title = format!("{}…", title.chars().take(29).collect::()); + } + let author: String = field(doc, "author") + .map(py_str) + .unwrap_or_default() + .chars() + .take(16) + .collect(); + let created_ts = timestamp(field(doc, "created")); + let created = if created_ts != 0.0 { + strftime(created_ts, false) + } else { + "unknown".into() + }; + let comments = field(doc, "comments").map_or("0".to_string(), py_str); + let _ = writeln!( + out, + "{} {} {} {} {comments}", + pad(&id, 4), + pad(&title, 30), + pad(&format!("{author}…"), 17), + pad(&created, 18) + ); + } + let _ = writeln!(out); + } + if scope == "all" + && ["active", "completed", "proposed"] + .iter() + .all(|n| docs_of(n).is_empty()) + { + let _ = writeln!(out, "No work documents found."); + } + Ok(()) +} + +/// `work_view` after the Link is up (`server.py:1416-1477`). +fn work_view( + out: &mut dyn Write, + remote: &mut dyn Remote, + repo_path: &str, + doc_id: i64, + scope: &str, +) -> Result<(), Fail> { + let data = request( + repo_path, + vec![ + ("operation", s("view")), + ("doc_id", Value::from(doc_id)), + ("scope", s(scope)), + ], + ); + let sent = exchange(remote, data, 120, "Remote error: "); + let _ = write!(out, "{CLEAR}"); + let body = sent?; + if body.is_empty() { + return abort("Empty response from remote"); + } + let doc = unpack(&body, "Error viewing work document")?; + let missing = |key: &str| Fail::Abort(format!("Error viewing work document: '{key}'")); + let meta = field(&doc, "meta").ok_or_else(|| missing("meta"))?; + let meta_field = |key: &str| field(meta, key).ok_or_else(|| missing(key)); + let content = field(&doc, "content").map(py_str).unwrap_or_default(); + let mut author = format!("{} (not locally validated)", py_str(meta_field("author")?)); + let mut signature_text = "Document not signed"; + if let (Some(Value::Binary(sig)), Some(Value::Binary(key))) = + (field(meta, "signature"), field(meta, "identity")) + && sig.len() == 64 + && key.len() == 64 + { + signature_text = "Not valid"; + if let (Ok(identity), Ok(sig)) = ( + Identity::from_public_key(key), + <[u8; 64]>::try_from(sig.as_slice()), + ) && identity.verify(content.as_bytes(), &sig) + { + signature_text = "Valid"; + author = format!("<{}>", hex::encode(identity.hash)); + } + } + let heading = format!( + "{} (#{})", + py_str(meta_field("title")?), + py_str(field(&doc, "id").ok_or_else(|| missing("id"))?) + ); + let comments = match field(&doc, "comments") { + Some(Value::Array(items)) => items.clone(), + _ => Vec::new(), + }; + let _ = writeln!(out, "{heading}"); + let _ = writeln!(out, "{}", "=".repeat(heading.chars().count())); + let _ = writeln!(out, "Author : {author}"); + let _ = writeln!(out, "Signature : {signature_text}"); + let _ = writeln!(out, "Status : {}", capitalize(scope)); + let _ = writeln!( + out, + "Created : {}", + strftime(timestamp(Some(meta_field("created")?)), true) + ); + let _ = writeln!( + out, + "Edited : {}", + strftime(timestamp(Some(meta_field("edited")?)), true) + ); + let _ = writeln!(out, "Format : {}", py_str(meta_field("format")?)); + let _ = writeln!(out, "Updates : {}", comments.len()); + let _ = writeln!(out); + let _ = writeln!( + out, + "{}", + py_str(field(&doc, "content").ok_or_else(|| missing("content"))?) + ); + if !comments.is_empty() { + let _ = writeln!(out, "\nUpdates\n======="); + for c in &comments { + let get = |key: &str| field(c, key).ok_or_else(|| missing(key)); + let line = format!( + "#{} by {} at {}", + py_str(get("id")?), + py_str(get("author")?), + strftime(timestamp(Some(get("created")?)), true) + ); + let _ = writeln!(out, "\n{line}"); + let _ = writeln!(out, "{}", "-".repeat(line.chars().count())); + let _ = writeln!(out, "{}", py_str(get("content")?)); + } + } + let _ = writeln!(out); + Ok(()) +} + +fn sign(identity: &Identity, content: &str) -> Result { + match identity.sign(content.as_bytes()) { + Some(sig) => Ok(Value::Binary(sig.to_vec())), + None => abort("Could not sign work document"), + } +} + +fn result_field(body: &[u8], key: &str, context: &str) -> Result { + let value = unpack(body, context)?; + field(&value, key) + .map(py_str) + .ok_or_else(|| Fail::Abort(format!("{context}: '{key}'"))) +} + +/// `work_create` and `work_propose` after the Link is up (`server.py:1491-1567`). +fn work_new( + out: &mut dyn Write, + remote: &mut dyn Remote, + identity: &Identity, + repo_path: &str, + title: &str, + propose: bool, +) -> Result<(), Fail> { + let Some(content) = edit_work_content(out, "", false) else { + let _ = writeln!( + out, + "{}", + if propose { + "Proposal cancelled" + } else { + "Creation cancelled" + } + ); + return Ok(()); + }; + let signature = sign(identity, &content)?; + let operation = if propose { "propose" } else { "create" }; + let data = request( + repo_path, + vec![ + ("operation", s(operation)), + ("title", s(title)), + ("content", s(&content)), + ("format", s("markdown")), + ("signature", signature), + ], + ); + let body = exchange(remote, data, 600, "Server error: ")?; + if body.is_empty() { + let _ = writeln!( + out, + "{}", + if propose { + "Work document proposed" + } else { + "Work document created" + } + ); + } else { + let context = "Error creating work document"; + let scope = result_field(&body, "scope", context)?; + let id = result_field(&body, "id", context)?; + let _ = writeln!(out, "Work document created as {scope} #{id}"); + } + Ok(()) +} + +/// `work_edit` after the Link is up (`server.py:1581-1621`). +fn work_edit( + out: &mut dyn Write, + remote: &mut dyn Remote, + identity: &Identity, + repo_path: &str, + args: &WorkArgs, + doc_id: i64, +) -> Result<(), Fail> { + let scope = args.scope.as_str(); + let view = request( + repo_path, + vec![ + ("operation", s("view")), + ("doc_id", Value::from(doc_id)), + ("scope", s(scope)), + ], + ); + let body = exchange(remote, view, 600, "Remote error: ")?; + let doc = unpack(&body, "Error editing work document")?; + let missing = |key: &str| Fail::Abort(format!("Error editing work document: '{key}'")); + let current_content = py_str(field(&doc, "content").ok_or_else(|| missing("content"))?); + let meta = field(&doc, "meta").ok_or_else(|| missing("meta"))?; + let current_title = field(meta, "title") + .ok_or_else(|| missing("title"))? + .clone(); + let Some(content) = edit_work_content(out, ¤t_content, false) else { + let _ = writeln!(out, "Edit cancelled"); + return Ok(()); + }; + let signature = sign(identity, &content)?; + let title = match args.title.as_deref().filter(|t| !t.is_empty()) { + Some(title) => s(title), + None => current_title, + }; + let data = request( + repo_path, + vec![ + ("operation", s("edit")), + ("doc_id", Value::from(doc_id)), + ("scope", s(scope)), + ("content", s(&content)), + ("title", title), + ("signature", signature), + ], + ); + exchange(remote, data, 600, "Remote error: ")?; + let _ = writeln!(out, "Work document {scope} #{doc_id} updated"); + Ok(()) +} + +/// `work_delete` after the Link is up (`server.py:1635-1661`). +fn work_delete( + out: &mut dyn Write, + input: &mut dyn BufRead, + remote: &mut dyn Remote, + repo_path: &str, + doc_id: i64, + scope: &str, +) -> Result<(), Fail> { + let _ = write!( + out, + "Are you sure you want to delete {scope} work document #{doc_id}? [y/N]: " + ); + let _ = out.flush(); + let mut line = String::new(); + let confirm = match input.read_line(&mut line) { + Ok(0) | Err(_) => "n".to_string(), + Ok(_) => py_strip(line.trim_end_matches('\n')).to_lowercase(), + }; + if confirm != "y" { + let _ = writeln!(out, "Deletion cancelled"); + return Ok(()); + } + let data = request( + repo_path, + vec![ + ("operation", s("delete")), + ("doc_id", Value::from(doc_id)), + ("scope", s(scope)), + ], + ); + exchange(remote, data, 120, "Remote error: ")?; + let _ = writeln!(out, "Work document {scope} #{doc_id} deleted"); + Ok(()) +} + +/// `work_comment` after the Link is up (`server.py:1675-1704`). +fn work_comment( + out: &mut dyn Write, + remote: &mut dyn Remote, + repo_path: &str, + doc_id: i64, + scope: &str, +) -> Result<(), Fail> { + let Some(content) = edit_work_content(out, "", true) else { + let _ = writeln!(out, "Update cancelled"); + return Ok(()); + }; + let data = request( + repo_path, + vec![ + ("operation", s("comment")), + ("doc_id", Value::from(doc_id)), + ("scope", s(scope)), + ("content", s(&content)), + ("format", s("markdown")), + ], + ); + let body = exchange(remote, data, 600, "Remote error: ")?; + if body.is_empty() { + let _ = writeln!(out, "Update added"); + } else { + let id = result_field(&body, "id", "Error adding comment")?; + let _ = writeln!(out, "Update #{id} added to {scope} document #{doc_id}"); + } + Ok(()) +} + +/// `work_complete` and `work_activate` after the Link is up (`server.py:1718-1782`). +fn work_move( + out: &mut dyn Write, + remote: &mut dyn Remote, + repo_path: &str, + doc_id: i64, + activate: bool, +) -> Result<(), Fail> { + let (operation, done, context) = if activate { + ("activate", "activated", "Error activating work document") + } else { + ("complete", "completed", "Error completing work document") + }; + let data = request( + repo_path, + vec![("operation", s(operation)), ("doc_id", Value::from(doc_id))], + ); + let body = exchange(remote, data, 120, "Remote error: ")?; + if body.is_empty() { + let _ = writeln!(out, "Work document {done}"); + } else { + let id = result_field(&body, "id", context)?; + let _ = writeln!(out, "Work document #{id} {done}"); + } + Ok(()) +} + +/// The get, edit and set round of every permissions command +/// (`server.py:1255-1287`, `1796-1834`). +pub(crate) fn edit_remote_permissions( + out: &mut dyn Write, + remote: &mut dyn Remote, + get: Value, + set: impl FnOnce(String) -> Value, +) -> Result { + let body = exchange(remote, get, 120, "Remote error: ")?; + let current = if body.is_empty() { + String::new() + } else { + let result = unpack(&body, "Error editing permissions")?; + field(&result, "content").map(py_str).unwrap_or_default() + }; + let Some(content) = edit_permissions(out, ¤t) else { + let _ = writeln!(out, "Edit cancelled"); + return Ok(false); + }; + exchange(remote, set(content), 120, "Remote error: ")?; + Ok(true) +} + +/// `rngit work ` once Reticulum is up +/// (`server.py:106-122`, `1347-1838`). `Ok` is the exit code. +pub fn run_work( + out: &mut dyn Write, + input: &mut dyn BufRead, + config: &ClientConfig, + connect: &mut Connect<'_>, + identity: &Identity, + operation: Option<&str>, + args: &WorkArgs, +) -> Result { + let Some(op) = operation.and_then(WorkOp::parse) else { + let _ = writeln!(out, "Invalid operation"); + return Ok(1); + }; + let Some(remote) = args.remote.as_deref().filter(|r| !r.is_empty()) else { + return abort("No remote specified"); + }; + let needs_id = !matches!(op, WorkOp::List | WorkOp::Create | WorkOp::Propose); + if needs_id && args.doc_id.is_none() { + return abort("No document ID specified"); + } + let title = args.title.as_deref().filter(|t| !t.is_empty()); + if matches!(op, WorkOp::Create | WorkOp::Propose) && title.is_none() { + return abort("No title specified"); + } + let failed = if matches!(op, WorkOp::List | WorkOp::View) { + "Link establishment failed" + } else { + "Failed to establish link" + }; + let mut link = connect(remote, failed)?; + if !matches!(op, WorkOp::List | WorkOp::View) { + let _ = write!(out, "{CLEAR}"); + } + let (_, group, repo) = config.parse_remote_url(remote).map_err(Fail::Abort)?; + let repo_path = format!("{group}/{repo}"); + let remote = link.as_mut(); + let doc_id = args.doc_id.unwrap_or_default(); + let scope = args.scope.as_str(); + match op { + WorkOp::List => work_list(out, remote, &repo_path, scope)?, + WorkOp::View => work_view(out, remote, &repo_path, doc_id, scope)?, + WorkOp::Create => work_new( + out, + remote, + identity, + &repo_path, + title.unwrap_or_default(), + false, + )?, + WorkOp::Propose => work_new( + out, + remote, + identity, + &repo_path, + title.unwrap_or_default(), + true, + )?, + WorkOp::Edit => work_edit(out, remote, identity, &repo_path, args, doc_id)?, + WorkOp::Delete => work_delete(out, input, remote, &repo_path, doc_id, scope)?, + WorkOp::Update => work_comment(out, remote, &repo_path, doc_id, scope)?, + WorkOp::Complete => work_move(out, remote, &repo_path, doc_id, false)?, + WorkOp::Activate => work_move(out, remote, &repo_path, doc_id, true)?, + WorkOp::Perms => { + let get = request( + &repo_path, + vec![ + ("operation", s("perms")), + ("doc_id", Value::from(doc_id)), + ("step", s("get")), + ], + ); + let set = |content: String| { + request( + &repo_path, + vec![ + ("operation", s("perms")), + ("doc_id", Value::from(doc_id)), + ("step", s("set")), + ("content", s(&content)), + ], + ) + }; + if edit_remote_permissions(out, remote, get, set)? { + let _ = writeln!(out, "Permissions updated for work document #{doc_id}"); + } + } + } + Ok(0) +} + +/// Requests over an established Link; the Link closes when this is dropped, +/// as upstream's `finally: link.teardown()`. +struct SessionRemote { + runtime: tokio::runtime::Handle, + session: rns_runtime::link_session::LinkSessionHandle, + path: &'static str, +} + +impl Remote for SessionRemote { + fn request(&mut self, data: Value, timeout: Duration) -> Option { + let options = rns_runtime::link_session::RequestOptions { + timeout: Some(timeout), + ..Default::default() + }; + let request = self.session.request_with_options(self.path, data, options); + let response = self + .runtime + .block_on(async { + tokio::time::timeout(timeout + Duration::from_secs(30), request).await + }) + .ok()? + .ok()?; + Some(match response.value { + Value::Binary(bytes) => Response::Bytes(bytes), + other => Response::Other(other), + }) + } +} + +impl Drop for SessionRemote { + fn drop(&mut self) { + self.runtime.block_on(self.session.close()); + } +} + +/// The options every `rngit` client subcommand shares. +#[derive(Debug, Clone, Default)] +pub struct CommonArgs { + pub config: Option, + pub rnsconfig: Option, + pub identity: Option, + pub verbose: u8, + pub quiet: u8, +} + +/// The body of a client subcommand, run on the blocking pool once Reticulum, +/// the identity and the client config are ready. +pub type ClientBody = Box< + dyn FnOnce( + &mut dyn Write, + &mut dyn BufRead, + &ClientConfig, + &mut Connect<'_>, + &Identity, + ) -> Result + + Send, +>; + +/// `program_setup` and `ReticulumGitClient.__init__` for a client task, then +/// `body` with a `connect_remote` whose requests go to `path`; never returns. +pub async fn run_client(common: CommonArgs, path: &'static str, body: ClientBody) -> ! { + let non_empty = |v: Option| v.filter(|v| !v.is_empty()); + let configdir = client_config_dir(non_empty(common.config).map(PathBuf::from).as_deref()); + let rnsconfig = non_empty(common.rnsconfig); + let rns_dir = rns_runtime::platform::resolve_config_dir(rnsconfig.as_deref()); + let configured = rns_runtime::config::Config::from_file(&rns_dir.join("config")) + .ok() + .and_then(|c| c.section("logging")?.get_int("loglevel")); + let level = rns_tools::Utility::Rnir.loglevel(configured, common.verbose, common.quiet, false); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&rns_dir), + true, + std::io::stdout, + ); + let handle = match rns_runtime::reticulum::init( + rnsconfig.as_deref(), + None, + ShutdownSignal::new(), + Arc::new(AtomicBool::new(true)), + ) + .await + { + Ok(handle) => handle, + Err(e) => { + eprintln!("failed to start reticulum: {e}"); + std::process::exit(1); + } + }; + handle.wants_destination_type(APP_NAME).await; + if let Err(e) = std::fs::create_dir_all(&configdir) { + println!("Could not create {}: {e}", configdir.display()); + rns_tools::exit(&handle, 1).await; + } + let identity_path = non_empty(common.identity) + .map(PathBuf::from) + .unwrap_or_else(|| configdir.join("client_identity")); + let identity = if identity_path.is_file() { + Identity::from_file(&identity_path).ok() + } else { + let id = Identity::new(); + id.to_file(&identity_path).ok().map(|_| id) + }; + let Some(identity) = identity else { + println!("Could not initialize client identity"); + rns_tools::exit(&handle, 1).await; + }; + let config = match ClientConfig::load_or_create(&configdir) { + Ok(config) => config, + Err(e) => { + tracing::error!( + "Could not parse the configuration at {}", + configdir.join("client_config").display() + ); + tracing::error!("Check your configuration file for errors! ({e})"); + rns_tools::exit(&handle, 255).await; + } + }; + let runtime = tokio::runtime::Handle::current(); + let link_handle = handle.clone(); + let result = tokio::task::spawn_blocking(move || { + let mut out = std::io::stdout(); + let mut input = std::io::stdin().lock(); + let link_identity = identity.clone(); + let mut connect = |remote: &str, failure: &str| -> Result, Fail> { + let destination = config + .parse_remote_destination_url(remote) + .map_err(Fail::Abort)?; + let Ok(destination) = <[u8; 16]>::try_from(destination.as_slice()) else { + return abort("Invalid destination hash length"); + }; + let path_timeout = runtime + .block_on(rns_tools::medium_path_timeout(&link_handle)) + .max(15.0); + print!("Requesting path... "); + let _ = std::io::stdout().flush(); + if runtime + .block_on( + link_handle.await_path(destination, Duration::from_secs_f64(path_timeout)), + ) + .is_err() + { + println!(); + return abort(format!( + "Could not resolve path to <{}>", + hex::encode(destination) + )); + } + print!("\rPath resolved "); + print!("\rEstablishing link... "); + let _ = std::io::stdout().flush(); + let hops = runtime + .block_on(link_handle.hops_to(destination)) + .unwrap_or(1); + let first_hop = runtime + .block_on(link_handle.first_hop_timeout(destination)) + .map_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT, |d| { + d.as_secs_f64() + }); + let establishment = + first_hop + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT * f64::from(hops.max(1)); + let options = rns_runtime::reticulum::LinkConnectOptions { + path_timeout: Duration::from_secs_f64(path_timeout), + establishment_timeout: Some(Duration::from_secs_f64(establishment.max(15.0))), + client_label: "rngit".to_string(), + identify: true, + ..Default::default() + }; + let session = runtime + .block_on(link_handle.connect_link(destination, link_identity.clone(), options)) + .map_err(|_| Fail::Abort(failure.to_string()))?; + print!("\rLink established "); + let _ = std::io::stdout().flush(); + Ok(Box::new(SessionRemote { + runtime: runtime.clone(), + session: session.handle, + path, + })) + }; + let result = body(&mut out, &mut input, &config, &mut connect, &identity); + let _ = out.flush(); + result + }) + .await + .unwrap_or_else(|e| Err(Fail::Raised(format!("client task failed: {e}")))); + match result { + Ok(code) => rns_tools::exit(&handle, code).await, + Err(Fail::Abort(message)) => { + println!("{message}"); + rns_tools::exit(&handle, 1).await + } + Err(Fail::Raised(message)) => { + eprintln!("{message}"); + rns_tools::exit(&handle, 1).await + } + } +} diff --git a/crates/rns-git/src/server/client.rs b/crates/rns-git/src/server/client.rs index 9e3dffd..c7b2d49 100644 --- a/crates/rns-git/src/server/client.rs +++ b/crates/rns-git/src/server/client.rs @@ -112,6 +112,16 @@ impl ClientConfig { Self::decode(&hexhash) } + /// `parse_remote_group_url` (`server.py:446-454`): hash and group. + pub fn parse_remote_group_url(&self, remote: &str) -> Result<(Vec, String), String> { + let (hexhash, components) = self.destination(remote)?; + if components.len() != 2 { + return Err("Invalid number of URL components".into()); + } + let hash = Self::decode(&hexhash)?; + Ok((hash, components[1].clone())) + } + /// `parse_remote_url` (`server.py:405-413`): hash, group and repository. pub fn parse_remote_url(&self, remote: &str) -> Result<(Vec, String, String), String> { let (hexhash, components) = self.destination(remote)?; diff --git a/crates/rns-git/src/server/mod.rs b/crates/rns-git/src/server/mod.rs index 047e4ac..ab1e842 100644 --- a/crates/rns-git/src/server/mod.rs +++ b/crates/rns-git/src/server/mod.rs @@ -6,8 +6,10 @@ pub mod forks; pub mod handlers; pub mod layout; pub mod perms; +pub mod perms_mgmt; pub mod releases; pub mod stats; +pub mod work; /// `APP_NAME` plus the aspect (`__init__.py:31`, `server.py:2063`). pub const APP_NAME: &str = "git.repositories"; @@ -21,6 +23,8 @@ pub const PATH_FORK: &str = "/git/fork"; pub const PATH_SYNC: &str = "/git/sync"; pub const PATH_MIRROR: &str = "/git/mirror"; pub const PATH_RELEASE: &str = "/mgmt/release"; +pub const PATH_PERMS: &str = "/mgmt/perms"; +pub const PATH_WORK: &str = "/mgmt/work"; pub const RES_OK: u8 = 0x00; pub const RES_DISALLOWED: u8 = 0x01; diff --git a/crates/rns-git/src/server/perms.rs b/crates/rns-git/src/server/perms.rs index ec1f5d9..d333453 100644 --- a/crates/rns-git/src/server/perms.rs +++ b/crates/rns-git/src/server/perms.rs @@ -222,7 +222,7 @@ impl Permissions { } /// Python `str.splitlines`. -fn py_splitlines(text: &str) -> Vec<&str> { +pub(crate) fn py_splitlines(text: &str) -> Vec<&str> { let mut lines = Vec::new(); let mut start = 0; let mut iter = text.char_indices().peekable(); diff --git a/crates/rns-git/src/server/perms_mgmt.rs b/crates/rns-git/src/server/perms_mgmt.rs new file mode 100644 index 0000000..b01436b --- /dev/null +++ b/crates/rns-git/src/server/perms_mgmt.rs @@ -0,0 +1,297 @@ +//! `/mgmt/perms`: group and repository permission files +//! (`handle_perms` and helpers, `server.py:4443-4643@1.6.0`). + +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::RwLock; + +use rmpv::Value; + +use super::config::NodeConfig; +use super::handlers::{get, identity_text, log_request, status, truthy}; +use super::layout::{Repositories, parse_group_path, parse_repository_path}; +use super::perms::{Perm, load_allowed_permissions, parse_permission, py_splitlines}; +use super::{ + IDX_GROUP, IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK, + RES_REMOTE_FAIL, +}; + +/// Upstream raised inside its `try`, replying "Remote error". +struct Raised; + +fn py_strip(s: &str) -> &str { + s.trim_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)) +} + +/// The validation every permission setter runs (`server.py:4380-4393`, +/// `4504-4517`): the first statement that does not parse, by 1-based line. +pub(crate) fn invalid_line(content: &str, aliases: &BTreeMap) -> Option { + for (number, line) in py_splitlines(content).into_iter().enumerate() { + let stripped = py_strip(line); + if stripped.is_empty() || stripped.starts_with('#') { + continue; + } + if let (None, _) | (_, None) = parse_permission(stripped, aliases) { + return Some(format!( + "Invalid permission \"{stripped}\" on line {}", + number + 1 + )); + } + } + None +} + +fn get_str<'a>(data: &'a [(Value, Value)], key: &str) -> Option<&'a Value> { + get(data, &Value::from(key)) +} + +/// `data.get("content", "")`, which must be a `str` for `splitlines`. +fn content_of(data: &[(Value, Value)]) -> Result { + match get_str(data, "content") { + None => Ok(String::new()), + Some(Value::String(s)) => s.as_str().map(str::to_string).ok_or(Raised), + Some(_) => Err(Raised), + } +} + +/// `step == "get"` / `"set"`; `Err` is the reply. +fn step(data: &[(Value, Value)]) -> Result> { + match get_str(data, "step") + .filter(|s| truthy(s)) + .map(Value::as_str) + { + None => Err(status(RES_INVALID_REQ, "Invalid request")), + Some(Some("get")) => Ok(false), + Some(Some("set")) => Ok(true), + Some(_) => Err(status(RES_INVALID_REQ, "Invalid step")), + } +} + +/// The `get` step: the file's text, or "" when there is none. +fn read_allowed(path: &Path, what: &str) -> Vec { + let text = if path.is_file() { + match super::work::read_text(path) { + Ok(text) => text, + Err(e) => { + tracing::error!("Error getting {what} permissions: {e}"); + return status(RES_REMOTE_FAIL, "Error getting permissions"); + } + } + } else { + String::new() + }; + let mut reply = vec![RES_OK]; + rmpv::encode::write_value( + &mut reply, + &Value::Map(vec![(Value::from("content"), Value::from(text))]), + ) + .expect("msgpack write to memory"); + reply +} + +/// The file part of the `set` step: refuse an executable resolver, then +/// write through `.tmp` and a rename. `Ok(None)` was written. +fn write_allowed(path: &Path, content: &str) -> Option> { + if nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok() { + return Some(status( + RES_DISALLOWED, + "Executable permission resolvers can only be modified node-side", + )); + } + let mut tmp = path.as_os_str().to_os_string(); + tmp.push(".tmp"); + let tmp = PathBuf::from(tmp); + let written = std::fs::File::create(&tmp) + .and_then(|mut f| f.write_all(content.as_bytes())) + .and_then(|_| std::fs::rename(&tmp, path)); + match written { + Ok(()) => None, + Err(e) => { + tracing::error!("Error setting permissions: {e}"); + Some(status(RES_REMOTE_FAIL, "Error setting permissions")) + } + } +} + +/// `_group_permissions` and its steps (`server.py:4473-4547`). +fn group_permissions( + repos: &RwLock, + config: &NodeConfig, + hash: &[u8; 16], + group: Option<&str>, + data: &[(Value, Value)], +) -> Result, Raised> { + let guard = repos.read().unwrap_or_else(|e| e.into_inner()); + let resolve = |perm| group.is_some_and(|g| guard.resolve_group_permission(hash, g, perm)); + if !resolve(Perm::Read) { + return Ok(status(RES_NOT_FOUND, "Not found")); + } + if !resolve(Perm::Admin) { + return Ok(status(RES_DISALLOWED, "Not allowed")); + } + let set = match step(data) { + Ok(set) => set, + Err(reply) => return Ok(reply), + }; + let group = group.expect("resolved"); + let allowed = PathBuf::from(format!("{}.allowed", guard.groups[group].path)); + if !set { + return Ok(read_allowed(&allowed, "group")); + } + let content = content_of(data)?; + if let Some(message) = invalid_line(&content, &guard.aliases) { + return Ok(status(RES_INVALID_REQ, &message)); + } + if let Some(reply) = write_allowed(&allowed, &content) { + return Ok(reply); + } + drop(guard); + repos + .write() + .unwrap_or_else(|e| e.into_inner()) + .update_group_permissions(group, config); + tracing::info!( + "Permissions for group {group} updated by <{}>", + hex::encode(hash) + ); + Ok(vec![RES_OK]) +} + +/// `update_repository_permissions` (`server.py:2604-2619`): the repository +/// file alone replaces the repository's lists. +fn update_repository_permissions(repos: &mut Repositories, group: &str, repository: &str) { + let aliases = repos.aliases.clone(); + let Some(repo) = repos + .groups + .get_mut(group) + .and_then(|g| g.repositories.get_mut(repository)) + else { + return; + }; + let allowed = PathBuf::from(format!("{}.allowed", repo.path.display())); + match load_allowed_permissions(&allowed, &aliases) { + Ok((permissions, _)) => repo.permissions = permissions, + Err(e) => tracing::error!( + "Could not update repository permissions for {group}/{repository} from {}: {e:?}", + allowed.display() + ), + } +} + +/// `_repository_permissions` and its steps (`server.py:4549-4635`). Setting +/// takes group READ and ADMIN on top of repository ADMIN. +fn repository_permissions( + repos: &RwLock, + hash: &[u8; 16], + group: &str, + repository: &str, + data: &[(Value, Value)], +) -> Result, Raised> { + let guard = repos.read().unwrap_or_else(|e| e.into_inner()); + if !guard.resolve_permission(hash, group, repository, Perm::Read) { + return Ok(status(RES_NOT_FOUND, "Not found")); + } + let set = match step(data) { + Ok(set) => set, + Err(reply) => return Ok(reply), + }; + let allowed = PathBuf::from(format!( + "{}.allowed", + guard.groups[group].repositories[repository].path.display() + )); + if !set { + return Ok(read_allowed(&allowed, "repository")); + } + if !guard.resolve_group_permission(hash, group, Perm::Read) { + return Ok(status(RES_NOT_FOUND, "Not found")); + } + if !guard.resolve_group_permission(hash, group, Perm::Admin) { + return Ok(status(RES_DISALLOWED, "Not allowed")); + } + let content = content_of(data)?; + if let Some(message) = invalid_line(&content, &guard.aliases) { + return Ok(status(RES_INVALID_REQ, &message)); + } + if let Some(reply) = write_allowed(&allowed, &content) { + return Ok(reply); + } + drop(guard); + update_repository_permissions( + &mut repos.write().unwrap_or_else(|e| e.into_inner()), + group, + repository, + ); + tracing::info!( + "Permissions for repository {group}/{repository} updated by <{}>", + hex::encode(hash) + ); + Ok(vec![RES_OK]) +} + +/// `handle_perms` (`server.py:4443-4471`). +pub fn handle_perms( + repos: &RwLock, + config: &NodeConfig, + identity: Option<&[u8; 16]>, + data: &Value, +) -> Vec { + { + let guard = repos.read().unwrap_or_else(|e| e.into_inner()); + let message = format!( + "Permissions request from remote {}", + identity_text(identity) + ); + log_request(&guard, &message, identity); + } + let Some(hash) = identity else { + return status(RES_DISALLOWED, "Not identified"); + }; + let Value::Map(data) = data else { + return status(RES_INVALID_REQ, "Invalid request"); + }; + let reply = (|| -> Result, Raised> { + let Some(operation) = get_str(data, "operation").filter(|o| truthy(o)) else { + return Ok(status(RES_INVALID_REQ, "Invalid request")); + }; + match operation.as_str() { + Some("gperms") => { + let Some(group) = get(data, &Value::from(IDX_GROUP)) else { + return Ok(status(RES_INVALID_REQ, "No group specified")); + }; + let group = parse_group_path(group.as_str().ok_or(Raised)?); + group_permissions(repos, config, hash, group, data) + } + Some("rperms") => { + let Some(path) = get(data, &Value::from(IDX_REPOSITORY)) else { + return Ok(status(RES_INVALID_REQ, "No repository specified")); + }; + let path = parse_repository_path(path.as_str().ok_or(Raised)?); + let (group, repository) = path.unwrap_or(("", "")); + let (read, admin) = { + let guard = repos.read().unwrap_or_else(|e| e.into_inner()); + let resolve = |perm| { + path.is_some() && guard.resolve_permission(hash, group, repository, perm) + }; + (resolve(Perm::Read), resolve(Perm::Admin)) + }; + if !admin { + return Ok(if read { + status(RES_DISALLOWED, "Not allowed") + } else { + status(RES_NOT_FOUND, "Not found") + }); + } + repository_permissions(repos, hash, group, repository, data) + } + _ => Ok(status(RES_INVALID_REQ, "Invalid request")), + } + })(); + reply.unwrap_or_else(|Raised| { + tracing::error!( + "Error while handling permissions request from {}", + identity_text(identity) + ); + status(RES_REMOTE_FAIL, "Remote error") + }) +} diff --git a/crates/rns-git/src/server/work.rs b/crates/rns-git/src/server/work.rs new file mode 100644 index 0000000..d22bab1 --- /dev/null +++ b/crates/rns-git/src/server/work.rs @@ -0,0 +1,984 @@ +//! `/mgmt/work`: work documents on the server +//! (`handle_work` and `resolve_doc_permission`, `server.py:2398-2468`, +//! `3789-4441@1.6.0`). + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, RwLock}; + +use rmpv::Value; +use rns_identity::identity::Identity; + +use super::handlers::{get, identity_text, log_request, status, truthy}; +use super::layout::{Repositories, parse_repository_path}; +use super::perms::{Perm, PermList, Permissions, Target, resolve_repository}; +use super::perms_mgmt::invalid_line; +use super::{ + IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK, RES_REMOTE_FAIL, +}; + +/// `WORK_DOC_LIMIT` (`server.py:1976`), counted in code points. +pub const WORK_DOC_LIMIT: usize = 256 * 1024; + +/// Upstream raised inside its `try`, replying "Remote error". +struct Raised; + +const SCOPES: [&str; 3] = ["active", "completed", "proposed"]; + +/// Deferred jobs run in parallel; ids are picked from the directory listing, +/// so concurrent creates would otherwise share an id. +static WORK_LOCK: Mutex<()> = Mutex::new(()); + +/// Python `str.isspace()`. +fn py_space(c: char) -> bool { + c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c) +} + +fn py_strip(s: &str) -> &str { + s.trim_matches(py_space) +} + +/// A request map, read by string key as upstream's `data.get(...)`. +struct Request<'a>(&'a [(Value, Value)]); + +impl Request<'_> { + fn get(&self, key: &str) -> Option<&Value> { + get(self.0, &Value::from(key)) + } + + /// `data.get(key, default)` where only a `str` can equal the names it is + /// compared with; `None` is a value that matches no name. + fn name(&self, key: &str, default: &str) -> Option { + match self.get(key) { + None => Some(default.to_string()), + Some(Value::String(s)) => s.as_str().map(str::to_string), + Some(_) => None, + } + } + + /// `data.get(key, "")` followed by a `str` method: anything else raises. + fn text(&self, key: &str) -> Result { + match self.get(key) { + None => Ok(String::new()), + Some(Value::String(s)) => s.as_str().map(str::to_string).ok_or(Raised), + Some(_) => Err(Raised), + } + } +} + +fn valid_scope(scope: &Option) -> bool { + scope + .as_deref() + .is_some_and(|s| SCOPES.contains(&s) || s == "all") +} + +/// Python `int()` on an unpacked value; `Err` where it raises. +fn py_int(value: &Value) -> Result { + match value { + Value::Integer(i) => i + .as_i64() + .map(i128::from) + .or_else(|| i.as_u64().map(i128::from)) + .ok_or(Raised), + Value::F32(f) if f.is_finite() => Ok(*f as i128), + Value::F64(f) if f.is_finite() => Ok(*f as i128), + Value::Boolean(b) => Ok(i128::from(*b)), + Value::String(s) => s.as_str().ok_or(Raised).and_then(py_int_str), + Value::Binary(b) => std::str::from_utf8(b) + .map_err(|_| Raised) + .and_then(py_int_str), + _ => Err(Raised), + } +} + +fn py_int_str(text: &str) -> Result { + let trimmed = py_strip(text); + let (negative, digits) = match trimmed.strip_prefix(['+', '-']) { + Some(rest) => (trimmed.starts_with('-'), rest), + None => (false, trimmed), + }; + if digits.is_empty() + || digits.starts_with('_') + || digits.ends_with('_') + || digits.contains("__") + { + return Err(Raised); + } + let mut value: i128 = 0; + for c in digits.chars().filter(|c| *c != '_') { + let digit = i128::from(c.to_digit(10).ok_or(Raised)?); + value = value + .checked_mul(10) + .and_then(|v| v.checked_add(digit)) + .ok_or(Raised)?; + } + Ok(if negative { -value } else { value }) +} + +fn int_value(n: i128) -> Value { + match (i64::try_from(n), u64::try_from(n)) { + (Ok(v), _) => Value::from(v), + (_, Ok(v)) => Value::from(v), + _ => Value::Nil, + } +} + +/// `doc_id = data.get("doc_id")`, the `is None` check and `int(doc_id)`. +fn doc_id(data: &Request) -> Result> { + match data.get("doc_id") { + None | Some(Value::Nil) => Err(status(RES_INVALID_REQ, "No document ID specified")), + Some(value) => py_int(value).map_err(|_| status(RES_INVALID_REQ, "Invalid document ID")), + } +} + +/// The first scope holding `/` as a directory. +fn find_doc( + work_path: &Path, + doc_id: i128, + scopes: &[&'static str], +) -> Option<(&'static str, PathBuf)> { + scopes.iter().find_map(|scope| { + let dir = work_path.join(scope).join(doc_id.to_string()); + dir.is_dir().then_some((*scope, dir)) + }) +} + +fn allowed_path(work_path: &Path, doc_id: i128) -> PathBuf { + PathBuf::from(format!("{}/{doc_id}.allowed", work_path.display())) +} + +/// `resolve_doc_permission` (`server.py:2398-2468`): the document's +/// `.allowed` file decides first, then the repository and group as +/// `resolve_permission` does, without the blocklist. +pub fn resolve_doc_permission( + repos: &Repositories, + hash: &[u8; 16], + path: Option<(&str, &str)>, + doc_id: i128, + perm: Perm, +) -> bool { + let Some((group_name, repository_name)) = path else { + return false; + }; + let Some(group) = repos.groups.get(group_name) else { + return false; + }; + let Some(repository) = group.repositories.get(repository_name) else { + return false; + }; + let list = match perm { + Perm::Read => PermList::Read, + Perm::Write => PermList::Write, + Perm::Create => PermList::Create, + Perm::Interact => PermList::Interact, + Perm::Propose => PermList::Propose, + Perm::Admin => PermList::Admin, + Perm::ReadWrite | Perm::Stats | Perm::Release => return false, + }; + let work_path = PathBuf::from(format!("{}.work", repository.path.display())); + let allowed = allowed_path(&work_path, doc_id); + let mut input = String::new(); + if work_path.is_dir() && allowed.is_file() { + match std::fs::read_to_string(&allowed) { + Ok(text) => input = text, + Err(e) => tracing::error!( + "Error while resolving document permission for {group_name}/{repository_name}/{doc_id}: {e}" + ), + } + } + let doc = Permissions::from_allowed_input(&input, &repos.aliases); + let me = Target::Identity(hash.to_vec()); + let doc_list = doc.get(list); + if doc_list.contains(&Target::None) { + return false; + } + if doc_list.contains(&Target::All) + || doc_list.contains(&me) + || doc.get(PermList::Admin).contains(&me) + { + return true; + } + resolve_repository(&group.permissions, &repository.permissions, hash, perm) +} + +/// Python's text-mode read: UTF-8, with `\r\n` and `\r` read as `\n`. +pub(crate) fn read_text(path: &Path) -> std::io::Result { + let text = std::fs::read_to_string(path)?; + Ok(text.replace("\r\n", "\n").replace('\r', "\n")) +} + +/// `_work_load_document`: any read or decode failure is None. +fn load_document(path: &Path) -> Option { + let bytes = std::fs::read(path).ok()?; + rmpv::decode::read_value(&mut &bytes[..]).ok() +} + +/// `_work_save_document` (`server.py:3888-3900`). +fn save_document(path: &Path, document: &Value) -> bool { + let saved = (|| -> std::io::Result<()> { + let dir = path.parent().unwrap_or(Path::new(".")); + if !dir.is_dir() { + std::fs::create_dir_all(dir)?; + } + let tmp = append_suffix(path, ".tmp"); + std::fs::File::create(&tmp)?.write_all(&pack(document))?; + std::fs::rename(&tmp, path) + })(); + if let Err(e) = &saved { + tracing::error!("Error persisting work document: {e}"); + } + saved.is_ok() +} + +/// Write `text` through `.tmp` and a rename, as upstream's permission writers. +fn write_replacing(path: &Path, text: &str) -> std::io::Result<()> { + let tmp = append_suffix(path, ".tmp"); + std::fs::File::create(&tmp)?.write_all(text.as_bytes())?; + std::fs::rename(&tmp, path) +} + +fn append_suffix(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.as_os_str().to_os_string(); + name.push(suffix); + PathBuf::from(name) +} + +fn pack(value: &Value) -> Vec { + let mut bytes = Vec::new(); + rmpv::encode::write_value(&mut bytes, value).expect("msgpack write to memory"); + bytes +} + +fn ok_with(value: Value) -> Vec { + let mut reply = vec![RES_OK]; + reply.extend_from_slice(&pack(&value)); + reply +} + +fn map(entries: Vec<(&str, Value)>) -> Value { + Value::Map( + entries + .into_iter() + .map(|(k, v)| (Value::from(k), v)) + .collect(), + ) +} + +/// Numeric entry names of a directory, as `[int(d) for d in listdir if d.isdigit()]`. +fn numeric_entries(dir: &Path) -> Vec<(i128, PathBuf)> { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + entries + .filter_map(|e| e.ok()) + .filter_map(|e| { + let name = e.file_name().to_string_lossy().into_owned(); + let numeric = !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit()); + numeric + .then(|| name.parse::().ok()) + .flatten() + .map(|id| (id, e.path())) + }) + .collect() +} + +/// `_work_get_next_id` and `_work_get_next_comment_id`: one past the highest +/// numeric entry, minimum 1. Entries of any type count. +fn next_in(dir: &Path) -> i128 { + numeric_entries(dir) + .iter() + .map(|(id, _)| id + 1) + .max() + .unwrap_or(1) +} + +fn next_id(work_path: &Path) -> i128 { + SCOPES + .iter() + .map(|s| next_in(&work_path.join(s))) + .max() + .unwrap_or(1) +} + +fn meta_of(document: &Value) -> &[(Value, Value)] { + let meta = match document { + Value::Map(entries) => get(entries, &Value::from("meta")), + _ => None, + }; + match meta { + Some(Value::Map(entries)) => entries, + _ => &[], + } +} + +/// `meta.get(key, default)`. +fn meta_get(meta: &[(Value, Value)], key: &str, default: Value) -> Value { + get(meta, &Value::from(key)).cloned().unwrap_or(default) +} + +fn doc_get(document: &Value, key: &str, default: Value) -> Value { + match document { + Value::Map(entries) => get(entries, &Value::from(key)).cloned().unwrap_or(default), + _ => default, + } +} + +/// `RNS.hexrep(meta.get("author"), delimit=False) if meta.get("author") else ""`. +fn author_text(meta: &[(Value, Value)]) -> Value { + match get(meta, &Value::from("author")) { + Some(Value::Binary(b)) if !b.is_empty() => Value::from(hex::encode(b)), + _ => Value::from(""), + } +} + +fn is_author(document: &Value, hash: &[u8; 16]) -> bool { + matches!(get(meta_of(document), &Value::from("author")), Some(Value::Binary(b)) if b.as_slice() == hash) +} + +/// The stored format: the value when it is one of the two names, else markdown. +fn stored_format(format: Option<&Value>) -> Value { + match format.and_then(Value::as_str) { + Some(f @ ("markdown" | "micron")) => Value::from(f), + _ => Value::from("markdown"), + } +} + +fn now() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) +} + +/// Python `len()` of an unpacked value; `Err` where it raises. +fn py_len_of(value: &Value) -> Result { + match value { + Value::String(s) => s.as_str().map(super::py_len).ok_or(Raised), + Value::Binary(b) => Ok(b.len()), + Value::Array(a) => Ok(a.len()), + Value::Map(m) => Ok(m.len()), + _ => Err(Raised), + } +} + +/// The signature checks shared by create, propose and edit. `Ok(None)` passes. +fn check_signature( + signature: Option<&Value>, + identity: &Identity, + signed: &[u8], +) -> Result>, Raised> { + let Some(signature) = signature.filter(|s| truthy(s)) else { + return Ok(Some(status(RES_INVALID_REQ, "No signature provided"))); + }; + if py_len_of(signature)? != 64 { + return Ok(Some(status(RES_INVALID_REQ, "Invalid signature length"))); + } + let valid = match signature { + Value::Binary(b) => { + <[u8; 64]>::try_from(b.as_slice()).is_ok_and(|sig| identity.verify(signed, &sig)) + } + _ => false, + }; + Ok((!valid).then(|| status(RES_INVALID_REQ, "Invalid signature"))) +} + +/// `_work_list` (`server.py:3902-3936`). +fn work_list( + work_path: &Path, + data: &Request, + repos: &Repositories, + hash: &[u8; 16], + path: Option<(&str, &str)>, +) -> Vec { + let scope = data.name("scope", "active"); + let mut result = Vec::new(); + for folder in SCOPES { + let mut docs: Vec<(f64, Value)> = Vec::new(); + let folder_path = work_path.join(folder); + let listed = scope.as_deref().is_some_and(|s| s == folder || s == "all"); + let entries = if listed && folder_path.is_dir() { + std::fs::read_dir(&folder_path) + .map(|e| e.filter_map(|e| e.ok()).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + for entry in entries { + let doc_dir = entry.path(); + if !doc_dir.is_dir() { + continue; + } + let Ok(doc_id) = py_int_str(&entry.file_name().to_string_lossy()) else { + continue; + }; + if !resolve_doc_permission(repos, hash, path, doc_id, Perm::Read) { + continue; + } + let root = doc_dir.join("root"); + if !root.is_file() { + continue; + } + let Some(doc) = load_document(&root).filter(truthy) else { + continue; + }; + let meta = meta_of(&doc); + let comments = numeric_entries(&doc_dir) + .iter() + .filter(|(_, p)| p.is_file()) + .count(); + let created = meta_get(meta, "created", Value::from(0)); + let sort_key = created + .as_f64() + .or_else(|| created.as_i64().map(|v| v as f64)) + .unwrap_or(0.0); + docs.push(( + sort_key, + map(vec![ + ("id", int_value(doc_id)), + ("title", meta_get(meta, "title", Value::from("Untitled"))), + ("created", created), + ("edited", meta_get(meta, "edited", Value::from(0))), + ("author", author_text(meta)), + ("format", meta_get(meta, "format", Value::from("markdown"))), + ("comments", Value::from(comments as u64)), + ]), + )); + } + // Newest first; a stable sort keeps the listing order of ties. + docs.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); + result.push(( + folder, + Value::Array(docs.into_iter().map(|(_, v)| v).collect()), + )); + } + ok_with(map(result)) +} + +/// `_work_view` (`server.py:3938-3996`). +fn work_view(work_path: &Path, data: &Request) -> Vec { + if !valid_scope(&data.name("scope", "all")) { + return status(RES_INVALID_REQ, "Invalid request"); + } + let doc_id = match doc_id(data) { + Ok(id) => id, + Err(reply) => return reply, + }; + let Some((scope, doc_dir)) = find_doc(work_path, doc_id, &SCOPES) else { + return status(RES_NOT_FOUND, "Not found"); + }; + let root = doc_dir.join("root"); + if !root.is_file() { + return status(RES_NOT_FOUND, "Document not found"); + } + let Some(doc) = load_document(&root).filter(truthy) else { + return status(RES_REMOTE_FAIL, "Error loading document"); + }; + let mut comments: Vec<(i128, Value)> = numeric_entries(&doc_dir) + .into_iter() + .filter(|(_, p)| p.is_file()) + .filter_map(|(id, p)| { + let comment = load_document(&p).filter(truthy)?; + let meta = meta_of(&comment); + Some(( + id, + map(vec![ + ("id", int_value(id)), + ("content", doc_get(&comment, "content", Value::from(""))), + ("created", meta_get(meta, "created", Value::from(0))), + ("edited", meta_get(meta, "edited", Value::from(0))), + ("author", author_text(meta)), + ("format", meta_get(meta, "format", Value::from("markdown"))), + ]), + )) + }) + .collect(); + comments.sort_by_key(|(id, _)| *id); + let meta = meta_of(&doc); + ok_with(map(vec![ + ("id", int_value(doc_id)), + ("scope", Value::from(scope)), + ("content", doc_get(&doc, "content", Value::from(""))), + ( + "comments", + Value::Array(comments.into_iter().map(|(_, v)| v).collect()), + ), + ( + "meta", + map(vec![ + ("title", meta_get(meta, "title", Value::from("Untitled"))), + ("created", meta_get(meta, "created", Value::from(0))), + ("edited", meta_get(meta, "edited", Value::from(0))), + ("author", author_text(meta)), + ("identity", meta_get(meta, "identity", Value::Nil)), + ("signature", meta_get(meta, "signature", Value::Nil)), + ("format", meta_get(meta, "format", Value::from("markdown"))), + ]), + ), + ])) +} + +/// `_work_create` and `_work_propose` (`server.py:3998-4085`), which differ +/// in the scope they store under and the ownership file propose writes. +fn work_new( + work_path: &Path, + data: &Request, + identity: &Identity, + scope: &str, +) -> Result, Raised> { + let title = py_strip(&data.text("title")?).to_string(); + let content = py_strip(&data.text("content")?).to_string(); + let format = data + .get("format") + .cloned() + .unwrap_or(Value::from("markdown")); + if let Some(reply) = check_signature(data.get("signature"), identity, content.as_bytes())? { + return Ok(reply); + } + if super::py_len(&title) + super::py_len(&content) + py_len_of(&format)? > WORK_DOC_LIMIT { + return Ok(status(RES_INVALID_REQ, "Content limit exceeded")); + } + if title.is_empty() { + return Ok(status(RES_INVALID_REQ, "Title is required")); + } + if content.is_empty() { + return Ok(status(RES_INVALID_REQ, "Content is required")); + } + let doc_id = next_id(work_path); + let doc_dir = work_path.join(scope).join(doc_id.to_string()); + let now = now(); + let document = map(vec![ + ("content", Value::from(content.as_str())), + ( + "meta", + map(vec![ + ("format", stored_format(Some(&format))), + ("title", Value::from(title.as_str())), + ("created", Value::F64(now)), + ("edited", Value::F64(now)), + ("author", Value::Binary(identity.hash.to_vec())), + ( + "signature", + data.get("signature").cloned().unwrap_or(Value::Nil), + ), + ( + "identity", + Value::Binary(identity.get_public_key().to_vec()), + ), + ]), + ), + ]); + if !save_document(&doc_dir.join("root"), &document) { + return Ok(status(RES_REMOTE_FAIL, "Error saving document")); + } + if scope == "proposed" { + let owner = hex::encode(identity.hash); + if let Err(e) = write_replacing( + &allowed_path(work_path, doc_id), + &format!("i:{owner}\nw:{owner}\n"), + ) { + tracing::error!("Error setting permissions: {e}"); + return Ok(status(RES_REMOTE_FAIL, "Error setting document ownership")); + } + } + Ok(ok_with(map(vec![ + ("id", int_value(doc_id)), + ("scope", Value::from(scope)), + ]))) +} + +/// `_work_edit` (`server.py:4087-4147`). +fn work_edit(work_path: &Path, data: &Request, identity: &Identity) -> Result, Raised> { + let scope = data.name("scope", "active"); + let content = data.text("content")?; + let title = match data.get("title") { + None => String::new(), + Some(Value::String(s)) => s.as_str().ok_or(Raised)?.to_string(), + Some(v) if !truthy(v) => String::new(), + Some(_) => return Err(Raised), + }; + let size = super::py_len(&title) + super::py_len(&content); + if !valid_scope(&scope) { + return Ok(status(RES_INVALID_REQ, "Invalid request")); + } + if let Some(reply) = check_signature(data.get("signature"), identity, content.as_bytes())? { + return Ok(reply); + } + if size > WORK_DOC_LIMIT { + return Ok(status(RES_INVALID_REQ, "Content limit exceeded")); + } + if content.is_empty() && title.is_empty() { + return Ok(status(RES_INVALID_REQ, "No changes specified")); + } + let Some(raw_id) = data.get("doc_id").filter(|v| truthy(v)) else { + return Ok(status(RES_INVALID_REQ, "No document ID specified")); + }; + let Ok(doc_id) = py_int(raw_id) else { + return Ok(status(RES_INVALID_REQ, "Invalid document ID")); + }; + let Some((_, doc_dir)) = find_doc(work_path, doc_id, &SCOPES) else { + return Ok(status(RES_NOT_FOUND, "Not found")); + }; + let root = doc_dir.join("root"); + if !root.is_file() { + return Ok(status(RES_NOT_FOUND, "Document not found")); + } + let Some(mut doc) = load_document(&root).filter(truthy) else { + return Ok(status(RES_REMOTE_FAIL, "Error loading document")); + }; + if !is_author(&doc, &identity.hash) { + return Ok(status(RES_DISALLOWED, "No access, not author")); + } + let Value::Map(entries) = &mut doc else { + return Err(Raised); + }; + fn put(entries: &mut Vec<(Value, Value)>, key: &str, value: Value) { + match entries.iter_mut().find(|(k, _)| k.as_str() == Some(key)) { + Some((_, slot)) => *slot = value, + None => entries.push((Value::from(key), value)), + } + } + let Some(Value::Map(meta)) = entries + .iter_mut() + .find(|(k, _)| k.as_str() == Some("meta")) + .map(|(_, v)| v) + else { + return Err(Raised); + }; + if !title.is_empty() { + put(meta, "title", Value::from(py_strip(&title))); + } + put(meta, "edited", Value::F64(now())); + put( + meta, + "signature", + data.get("signature").cloned().unwrap_or(Value::Nil), + ); + put( + meta, + "identity", + Value::Binary(identity.get_public_key().to_vec()), + ); + if !content.is_empty() { + put(entries, "content", Value::from(py_strip(&content))); + } + if !save_document(&root, &doc) { + return Ok(status(RES_REMOTE_FAIL, "Error saving document")); + } + Ok(vec![RES_OK]) +} + +/// `_work_delete` (`server.py:4149-4197`). +fn work_delete( + work_path: &Path, + data: &Request, + repos: &Repositories, + hash: &[u8; 16], + path: Option<(&str, &str)>, +) -> Result, Raised> { + if !valid_scope(&data.name("scope", "active")) { + return Ok(status(RES_INVALID_REQ, "Invalid request")); + } + let doc_id = match doc_id(data) { + Ok(id) => id, + Err(reply) => return Ok(reply), + }; + // Upstream joins `None` into the path when no scope holds the document. + let (_, doc_dir) = find_doc(work_path, doc_id, &SCOPES).ok_or(Raised)?; + let root = doc_dir.join("root"); + if !root.is_file() { + return Ok(status(RES_NOT_FOUND, "Document not found")); + } + let Some(doc) = load_document(&root).filter(truthy) else { + return Ok(status(RES_REMOTE_FAIL, "Error loading document")); + }; + if !(is_author(&doc, hash) || resolve_doc_permission(repos, hash, path, doc_id, Perm::Admin)) { + return Ok(status(RES_DISALLOWED, "No access, not author")); + } + if let Err(e) = std::fs::remove_file(allowed_path(work_path, doc_id)) { + tracing::error!( + "Error while deleting permissions file for {}/{doc_id}: {e}", + work_path.display() + ); + return Ok(status(RES_REMOTE_FAIL, "Remote error")); + } + if let Err(e) = std::fs::remove_dir_all(&doc_dir) { + tracing::error!("Error deleting work document: {e}"); + return Ok(status(RES_REMOTE_FAIL, "Remote error")); + } + Ok(vec![RES_OK]) +} + +/// `_work_comment` (`server.py:4199-4248`). +fn work_comment(work_path: &Path, data: &Request, identity: &Identity) -> Result, Raised> { + let scope = data.name("scope", "active"); + let content = py_strip(&data.text("content")?).to_string(); + if !valid_scope(&scope) { + return Ok(status(RES_INVALID_REQ, "Invalid request")); + } + if super::py_len(&content) > WORK_DOC_LIMIT { + return Ok(status(RES_INVALID_REQ, "Content limit exceeded")); + } + let doc_id = match doc_id(data) { + Ok(id) => id, + Err(reply) => return Ok(reply), + }; + if content.is_empty() { + return Ok(status(RES_INVALID_REQ, "Content is required")); + } + let (_, doc_dir) = find_doc(work_path, doc_id, &SCOPES).ok_or(Raised)?; + if !doc_dir.join("root").is_file() { + return Ok(status(RES_NOT_FOUND, "Document not found")); + } + let comment_id = next_in(&doc_dir); + let now = now(); + let comment = map(vec![ + ("content", Value::from(content.as_str())), + ( + "meta", + map(vec![ + ("format", stored_format(data.get("format"))), + ("title", Value::Nil), + ("created", Value::F64(now)), + ("edited", Value::F64(now)), + ( + "signature", + data.get("signature").cloned().unwrap_or(Value::Nil), + ), + ("author", Value::Binary(identity.hash.to_vec())), + ]), + ), + ]); + if !save_document(&doc_dir.join(comment_id.to_string()), &comment) { + return Ok(status(RES_REMOTE_FAIL, "Error saving comment")); + } + Ok(ok_with(map(vec![("id", int_value(comment_id))]))) +} + +/// `shutil.move(src, dst)` for a directory: into `dst` when it is an existing +/// directory, creating missing parents. +fn move_dir(src: &Path, dst: &Path) -> std::io::Result<()> { + let dst = if dst.is_dir() { + dst.join(src.file_name().unwrap_or_default()) + } else { + dst.to_path_buf() + }; + if dst.exists() { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + "Destination path already exists", + )); + } + if let Some(parent) = dst.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::rename(src, &dst) +} + +/// `_work_complete` and `_work_activate` (`server.py:4250-4318`). +fn work_move( + work_path: &Path, + data: &Request, + repos: &Repositories, + hash: &[u8; 16], + path: Option<(&str, &str)>, + to: &'static str, +) -> Vec { + let doc_id = match doc_id(data) { + Ok(id) => id, + Err(reply) => return reply, + }; + let from: &[&'static str] = if to == "completed" { + &["active"] + } else { + &["completed", "proposed"] + }; + let Some((_, doc_dir)) = find_doc(work_path, doc_id, from) else { + return status(RES_NOT_FOUND, "Document not found"); + }; + let Some(doc) = load_document(&doc_dir.join("root")).filter(truthy) else { + return status(RES_REMOTE_FAIL, "Error loading document"); + }; + if !is_author(&doc, hash) && !resolve_doc_permission(repos, hash, path, doc_id, Perm::Admin) { + return status(RES_DISALLOWED, "Not allowed"); + } + if let Err(e) = move_dir(&doc_dir, &work_path.join(to).join(doc_id.to_string())) { + tracing::error!("Error moving work document: {e}"); + return status(RES_REMOTE_FAIL, "Remote error"); + } + ok_with(map(vec![ + ("id", int_value(doc_id)), + ("scope", Value::from(to)), + ])) +} + +/// `_work_perms` and its get/set steps (`server.py:4320-4440`). +fn work_perms( + work_path: &Path, + data: &Request, + repos: &Repositories, + hash: &[u8; 16], + path: Option<(&str, &str)>, +) -> Result, Raised> { + let (group, repo) = path.unwrap_or(("", "")); + let resolve = |perm| path.is_some() && repos.resolve_permission(hash, group, repo, perm); + let manage = resolve(Perm::Interact) && resolve(Perm::Write); + if !resolve(Perm::Read) { + return Ok(status(RES_NOT_FOUND, "Not found")); + } + if !manage { + return Ok(status(RES_DISALLOWED, "Not allowed")); + } + let step = data.get("step").filter(|s| truthy(s)); + let set = match step.map(Value::as_str) { + None => return Ok(status(RES_INVALID_REQ, "Invalid request")), + Some(Some("get")) => false, + Some(Some("set")) => true, + Some(_) => return Ok(status(RES_INVALID_REQ, "Invalid step")), + }; + // `content` is read before the document checks; `splitlines` raises later. + let content = data.get("content").cloned(); + let doc_id = match doc_id(data) { + Ok(id) => id, + Err(reply) => return Ok(reply), + }; + let Some((_, doc_dir)) = find_doc(work_path, doc_id, &SCOPES) else { + return Ok(status(RES_NOT_FOUND, "Document not found")); + }; + let Some(doc) = load_document(&doc_dir.join("root")).filter(truthy) else { + return Ok(status(RES_REMOTE_FAIL, "Error loading document")); + }; + let admin = resolve_doc_permission(repos, hash, path, doc_id, Perm::Admin); + if !((is_author(&doc, hash) && manage) || admin) { + return Ok(status(RES_DISALLOWED, "Not allowed")); + } + let allowed = allowed_path(work_path, doc_id); + if !set { + let text = if allowed.is_file() { + match read_text(&allowed) { + Ok(text) => text, + Err(e) => { + tracing::error!("Error getting document permissions: {e}"); + return Ok(status(RES_REMOTE_FAIL, "Error getting permissions")); + } + } + } else { + String::new() + }; + return Ok(ok_with(map(vec![("content", Value::from(text))]))); + } + let content = match content { + None => String::new(), + Some(Value::String(s)) => s.as_str().ok_or(Raised)?.to_string(), + Some(_) => return Err(Raised), + }; + if let Some(message) = invalid_line(&content, &repos.aliases) { + return Ok(status(RES_INVALID_REQ, &message)); + } + if let Err(e) = write_replacing(&allowed, &content) { + tracing::error!("Error setting permissions: {e}"); + return Ok(status(RES_REMOTE_FAIL, "Error setting permissions")); + } + Ok(vec![RES_OK]) +} + +/// `handle_work` (`server.py:3789-3862`). `None` sends no response. +pub fn handle_work( + repos: &RwLock, + identity: Option<&Identity>, + data: &Value, +) -> Option> { + let repos = repos.read().unwrap_or_else(|e| e.into_inner()); + let hash = identity.map(|i| i.hash); + log_request( + &repos, + &format!("Work request from remote {}", identity_text(hash.as_ref())), + hash.as_ref(), + ); + let Some(identity) = identity else { + return Some(status(RES_DISALLOWED, "Not identified")); + }; + let hash = identity.hash; + let Value::Map(entries) = data else { + return Some(status(RES_INVALID_REQ, "Invalid request")); + }; + let Some(repository) = get(entries, &Value::from(IDX_REPOSITORY)) else { + return Some(status(RES_INVALID_REQ, "No repository specified")); + }; + let request = Request(entries); + let Some(operation) = request.get("operation").filter(|v| truthy(v)) else { + return Some(status(RES_INVALID_REQ, "Invalid request")); + }; + // `parse_request_repository_path` raises outside any try: no response. + let path = parse_repository_path(repository.as_str()?); + let operation = operation.as_str().unwrap_or(""); + let (group, repo) = path.unwrap_or(("", "")); + let resolve = |perm| path.is_some() && repos.resolve_permission(&hash, group, repo, perm); + let mut read = resolve(Perm::Read); + let mut write = resolve(Perm::Write); + let mut interact = resolve(Perm::Interact); + let propose = resolve(Perm::Propose); + let admin = resolve(Perm::Admin); + if !read { + return Some(status(RES_NOT_FOUND, "Not found")); + } + if let Some(raw_id) = request.get("doc_id").filter(|v| truthy(v)) + && ["read", "view", "comment", "edit", "delete", "perms"].contains(&operation) + { + let Ok(doc_id) = py_int(raw_id) else { + return Some(status(RES_INVALID_REQ, "Invalid request")); + }; + let doc = |perm| resolve_doc_permission(&repos, &hash, path, doc_id, perm); + read = doc(Perm::Read) || admin; + if !read { + return Some(status(RES_NOT_FOUND, "Document not found")); + } + if operation == "comment" || operation == "edit" { + interact |= doc(Perm::Interact); + } + if operation == "edit" { + write |= doc(Perm::Write); + } + } + let comment_access = interact && (read || write); + let manage_access = interact && write; + let access = match operation { + "list" | "view" => read, + "comment" => comment_access, + "propose" => propose, + "create" | "edit" | "delete" | "complete" | "activate" => manage_access, + "perms" => admin, + _ => false, + }; + if !access { + return Some(status(RES_DISALLOWED, "Not allowed")); + } + let repository = repos.repository(group, repo)?; + let _serial = WORK_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let work_path = PathBuf::from(format!("{}.work", repository.path.display())); + let reply = match operation { + "list" => Ok(work_list(&work_path, &request, &repos, &hash, path)), + "view" => Ok(work_view(&work_path, &request)), + "comment" => work_comment(&work_path, &request, identity), + "create" => work_new(&work_path, &request, identity, "active"), + "propose" => work_new(&work_path, &request, identity, "proposed"), + "edit" => work_edit(&work_path, &request, identity), + "delete" => work_delete(&work_path, &request, &repos, &hash, path), + "complete" => Ok(work_move( + &work_path, + &request, + &repos, + &hash, + path, + "completed", + )), + "activate" => Ok(work_move( + &work_path, &request, &repos, &hash, path, "active", + )), + "perms" => work_perms(&work_path, &request, &repos, &hash, path), + _ => Ok(status(RES_INVALID_REQ, "Invalid request")), + }; + Some(reply.unwrap_or_else(|Raised| { + tracing::error!("Error while handling work request for {group}/{repo}"); + status(RES_REMOTE_FAIL, "Remote error") + })) +}