From c478f7ffd6a786d2096aa730a4bede78fef3c466 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:19:22 -0700 Subject: [PATCH] rngit: add node config, permissions, repo layout, and the list request --- Cargo.lock | 6 + crates/rns-git/Cargo.toml | 10 + crates/rns-git/src/bin/rngit-rs.rs | 291 +++++++++++++++++ crates/rns-git/src/lib.rs | 1 + crates/rns-git/src/server/config.rs | 232 +++++++++++++ crates/rns-git/src/server/default_config.txt | 165 ++++++++++ crates/rns-git/src/server/handlers.rs | 139 ++++++++ crates/rns-git/src/server/layout.rs | 247 ++++++++++++++ crates/rns-git/src/server/mod.rs | 30 ++ crates/rns-git/src/server/perms.rs | 323 +++++++++++++++++++ 10 files changed, 1444 insertions(+) create mode 100644 crates/rns-git/src/bin/rngit-rs.rs create mode 100644 crates/rns-git/src/server/config.rs create mode 100644 crates/rns-git/src/server/default_config.txt create mode 100644 crates/rns-git/src/server/handlers.rs create mode 100644 crates/rns-git/src/server/layout.rs create mode 100644 crates/rns-git/src/server/mod.rs create mode 100644 crates/rns-git/src/server/perms.rs diff --git a/Cargo.lock b/Cargo.lock index 184b803..87175f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1650,11 +1650,17 @@ name = "rns-git" version = "1.4.0" dependencies = [ "base64", + "clap", "hex", + "nix 0.29.0", "rmpv", "rns-identity", + "rns-runtime", "rns-tools", "serde_json", + "tempfile", + "tokio", + "tracing", ] [[package]] diff --git a/crates/rns-git/Cargo.toml b/crates/rns-git/Cargo.toml index 499888b..4cab0a9 100644 --- a/crates/rns-git/Cargo.toml +++ b/crates/rns-git/Cargo.toml @@ -11,13 +11,23 @@ autobins = false [dependencies] rns-tools = { path = "../rns-tools" } rns-identity = { workspace = true } +rns-runtime = { workspace = true } +tracing = { workspace = true } +clap = { workspace = true } +tokio = { workspace = true } +nix = { workspace = true } rmpv = { workspace = true } base64 = { workspace = true } hex = { workspace = true } [dev-dependencies] serde_json = { workspace = true } +tempfile = { workspace = true } [[bin]] name = "rngcs-rs" path = "src/bin/rngcs-rs.rs" + +[[bin]] +name = "rngit-rs" +path = "src/bin/rngit-rs.rs" diff --git a/crates/rns-git/src/bin/rngit-rs.rs b/crates/rns-git/src/bin/rngit-rs.rs new file mode 100644 index 0000000..860a49d --- /dev/null +++ b/crates/rns-git/src/bin/rngit-rs.rs @@ -0,0 +1,291 @@ +//! `rngit-rs`: the Reticulum Git repository node (`RNS/Utilities/rngit/server.py@1.6.0`). + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{Duration, Instant}; + +use clap::Parser; +use rns_git::server::config::{ + NodeConfig, load_or_create_identity, read_or_create_config, resolve_config_dir, +}; +use rns_git::server::handlers::handle_list; +use rns_git::server::layout::{Repositories, git_available}; +use rns_git::server::{APP_NAME, PATH_LIST}; +use rns_identity::destination::{AllowPolicy, Destination}; +use rns_identity::identity::Identity; +use rns_runtime::config::ConfigError; +use rns_runtime::destination_runtime::DestinationRuntimeOptions; +use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers}; +use rns_runtime::link_manager::{DestinationAnnounceOptions, RequestOutcome}; +use rns_tools::{LogLevel, RS_RETICULUM_VERSION}; + +const JOBS_INTERVAL: Duration = Duration::from_secs(5); + +#[derive(Parser)] +#[command( + name = "rngit-rs", + about = "Reticulum Git Repository Node", + disable_version_flag = true +)] +struct Args { + /// path to alternative config directory + #[arg(long)] + config: Option, + /// path to alternative Reticulum config directory + #[arg(long)] + rnsconfig: Option, + /// print identity and destination info and exit + #[arg(short = 'p', long = "print-identity")] + print_identity: bool, + /// rngit is running as a service and should log to file + #[arg(short = 's', long)] + service: bool, + #[arg(short = 'v', long, action = clap::ArgAction::Count)] + verbose: u8, + #[arg(short = 'q', long, action = clap::ArgAction::Count)] + quiet: u8, + #[arg(long)] + version: bool, +} + +/// `RNS.LOG_MAXSIZE` (`RNS/__init__.py:74`). +const LOG_MAXSIZE: u64 = 5 * 1024 * 1024; + +/// The `-s` log file: appended per line and rotated to `.1` past +/// `LOG_MAXSIZE`, falling back to stderr as `RNS.log` falls back to the console. +#[derive(Clone)] +struct ServerLog(PathBuf); + +impl std::io::Write for ServerLog { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let appended = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&self.0) + .and_then(|mut file| file.write_all(buf).map(|()| file.metadata())); + match appended { + Ok(Ok(meta)) if meta.len() > LOG_MAXSIZE => { + let mut rotated = self.0.clone().into_os_string(); + rotated.push(".1"); + let _ = std::fs::remove_file(&rotated); + let _ = std::fs::rename(&self.0, &rotated); + } + Ok(_) => {} + Err(_) => std::io::stderr().write_all(buf)?, + } + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +fn prettyhex(hash: &[u8]) -> String { + format!("<{}>", hex::encode(hash)) +} + +fn non_empty(value: Option) -> Option { + value.filter(|v| !v.is_empty()) +} + +#[tokio::main] +async fn main() { + let mut argv: Vec = std::env::args().collect(); + if argv.get(1).map(String::as_str) == Some("node") { + argv.remove(1); + } + let args = Args::parse_from(argv); + if args.version { + println!("rngit-rs {RS_RETICULUM_VERSION}"); + return; + } + let verbosity = if args.service { + 0 + } else { + i64::from(args.verbose) - i64::from(args.quiet) + }; + let configdir = non_empty(args.config.clone()).map(PathBuf::from); + let rnsconfig = non_empty(args.rnsconfig.clone()); + + if !git_available() { + eprintln!("The \"git\" command is not available. Aborting server startup."); + std::process::exit(255); + } + let configdir = resolve_config_dir(configdir.as_deref()); + let text = match read_or_create_config(&configdir) { + Ok(text) => text, + Err(e) => { + eprintln!( + "Could not load the configuration at {}: {e}", + configdir.display() + ); + std::process::exit(1); + } + }; + let config = match NodeConfig::parse(&text, verbosity) { + Ok(config) => config, + Err(e @ ConfigError::InvalidValue { .. }) => { + eprintln!("{e}"); + std::process::exit(1); + } + Err(e) => { + eprintln!( + "Could not parse the configuration at {}/config", + configdir.display() + ); + eprintln!("Check your configuration file for errors! ({e})"); + std::process::exit(255); + } + }; + // RNS.Reticulum applies the Reticulum config loglevel first; rngit's own key overrides it. + let rns_dir = rns_runtime::platform::resolve_config_dir(rnsconfig.as_deref()); + let level = match config.loglevel { + Some(level) => LogLevel::clamped(level), + None => { + let configured = rns_runtime::config::Config::from_file(&rns_dir.join("config")) + .ok() + .and_then(|c| c.section("logging")?.get_int("loglevel")); + let (verbose, quiet) = if args.service { + (0, 0) + } else { + (args.verbose, args.quiet) + }; + rns_tools::Utility::Rnir.loglevel(configured, verbose, quiet, args.service) + } + }; + let timestamps = rns_tools::config_log_timestamps(&rns_dir); + if args.service { + let log = ServerLog(configdir.join("server_log")); + rns_tools::init_tracing(level, timestamps, false, move || log.clone()); + } else { + rns_tools::init_tracing(level, timestamps, true, std::io::stdout); + } + + let identity = match load_or_create_identity(&configdir.join("repositories_identity")) { + Ok(identity) => identity, + Err(e) => { + eprintln!("Could not initialize repositories identity. Exiting now. ({e})"); + std::process::exit(255); + } + }; + let destination_hash = Destination::hash_from_name_and_identity(APP_NAME, Some(&identity.hash)); + + if args.print_identity { + let path = configdir.join("client_identity"); + let client = if path.is_file() { + Identity::from_file(&path) + } else { + let id = Identity::new(); + id.to_file(&path).map(|_| id) + }; + let Ok(client) = client else { + eprintln!("Could not load {}", path.display()); + std::process::exit(1); + }; + println!("Git Peer Identity : {}", prettyhex(&client.hash)); + println!("Repository Node Identity : {}", prettyhex(&identity.hash)); + println!( + "Repositories Destination : {}", + prettyhex(&destination_hash) + ); + if config.serve_nomadnet { + let nomad = + Destination::hash_from_name_and_identity("nomadnetwork.node", Some(&identity.hash)); + println!("Nomad Network Destination : {}", prettyhex(&nomad)); + } + return; + } + + let interrupt = ShutdownSignal::new(); + let _signal_rx = install_signal_handlers(interrupt.clone()); + let foreground = Arc::new(AtomicBool::new(!args.service)); + let handle = match rns_runtime::reticulum::init( + rnsconfig.as_deref(), + None, + ShutdownSignal::new(), + foreground, + ) + .await + { + Ok(handle) => handle, + Err(e) => { + eprintln!("failed to start reticulum: {e}"); + std::process::exit(1); + } + }; + handle.wants_destination_type(APP_NAME).await; + tracing::info!(target: rns_tools::NOTICE_TARGET, "Starting Reticulum Git Node..."); + + let repositories = match Repositories::load(&config) { + Ok(repositories) => Arc::new(repositories), + Err(e) => { + tracing::error!("Could not load repositories: {e:?}"); + rns_tools::exit(&handle, 1).await; + } + }; + + let registered = match handle + .register_destination(identity, APP_NAME, DestinationRuntimeOptions::default()) + .await + { + Ok(registered) => registered, + Err(e) => { + tracing::error!("Could not register the repositories destination: {e}"); + rns_tools::exit(&handle, 1).await; + } + }; + let list_repos = repositories.clone(); + let ok = registered + .handle + .register_request_handler( + PATH_LIST, + AllowPolicy::AllowAll, + Vec::new(), + true, + move |request| { + let hash = request.remote_identity.as_ref().map(|id| id.hash); + tracing::debug!("List request from remote {:?}", hash.map(hex::encode)); + match handle_list(&list_repos, hash.as_ref(), &request.value) { + Some(reply) => RequestOutcome::ReplyBytes(reply), + None => RequestOutcome::Drop, + } + }, + ) + .await; + if !matches!(ok, Ok(true)) { + tracing::error!("Could not register the {PATH_LIST} handler"); + rns_tools::exit(&handle, 1).await; + } + tracing::info!( + target: rns_tools::NOTICE_TARGET, + "Reticulum Git Node listening on {}", + prettyhex(&destination_hash) + ); + + // The jobs loop (server.py:2656-2661): the first tick announces when an interval is set. + let announce_interval = config.announce_interval; + let mut last_announce: Option = None; + loop { + tokio::select! { + _ = interrupt.wait() => break, + _ = tokio::time::sleep(JOBS_INTERVAL) => {} + } + let due = last_announce + .is_none_or(|last| last.elapsed().as_secs_f64() > announce_interval as f64); + if announce_interval != 0 && due { + tracing::debug!("Announcing repositories destination"); + if let Err(e) = registered + .handle + .announce(DestinationAnnounceOptions::default()) + .await + { + tracing::warn!("Could not announce: {e}"); + } + last_announce = Some(Instant::now()); + } + } + println!(); + rns_tools::exit(&handle, 0).await; +} diff --git a/crates/rns-git/src/lib.rs b/crates/rns-git/src/lib.rs index 470d97b..b651fd0 100644 --- a/crates/rns-git/src/lib.rs +++ b/crates/rns-git/src/lib.rs @@ -1,4 +1,5 @@ //! Git over Reticulum: a port of `RNS/Utilities/rngit` from Reticulum 1.6.0. pub mod commitsigs; +pub mod server; pub mod util; diff --git a/crates/rns-git/src/server/config.rs b/crates/rns-git/src/server/config.rs new file mode 100644 index 0000000..3b0c057 --- /dev/null +++ b/crates/rns-git/src/server/config.rs @@ -0,0 +1,232 @@ +//! Node configuration: `ReticulumGitNode.__init__` and `__apply_config` +//! (`server.py:2018-2249@1.6.0`). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use rns_identity::identity::Identity; +use rns_runtime::config::{Config, ConfigError, ConfigSection}; +use rns_tools::rsg::pyfmt::py_fromhex; + +use super::perms::{ALL_TGTS, resolve_identity_alias}; +use super::py_len; + +/// The file upstream writes when the config directory has none +/// (`__default_rngit_config__`, `server.py:4913-5080`). +pub const DEFAULT_CONFIG: &str = include_str!("default_config.txt"); + +pub const DEFAULT_NODE_NAME: &str = "Anonymous Git Node"; +const LOG_NONE: i64 = -1; +const LOG_EXTREME: i64 = 8; + +/// What `__apply_config` takes from the config file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NodeConfig { + pub node_name: String, + /// Seconds; 0 never announces. + pub announce_interval: i64, + /// Seconds; 0 disables periodic mirror sync. + pub mirror_interval: i64, + pub record_stats: bool, + pub serve_nomadnet: bool, + /// `[logging] loglevel` plus verbosity, clamped; `None` when the key is absent. + pub loglevel: Option, + /// Alias name to lowercase identity hash hex. + pub aliases: BTreeMap, + pub stats_ignored: Vec>, + pub stats_push_ignored: Vec>, + pub blocked_identities: Vec>, + /// `[repositories]` group name to the configured path, before `~` expansion. + pub repositories: BTreeMap, + /// `[access]` group name to its permission statements. + pub access: BTreeMap>, +} + +impl Default for NodeConfig { + fn default() -> Self { + Self { + node_name: DEFAULT_NODE_NAME.to_string(), + announce_interval: 0, + mirror_interval: 24 * 60 * 60, + record_stats: false, + serve_nomadnet: false, + loglevel: None, + aliases: BTreeMap::new(), + stats_ignored: Vec::new(), + stats_push_ignored: Vec::new(), + blocked_identities: Vec::new(), + repositories: BTreeMap::new(), + access: BTreeMap::new(), + } + } +} + +fn invalid(section: &str, key: &str, message: &str) -> ConfigError { + ConfigError::InvalidValue { + section: section.to_string(), + key: key.to_string(), + message: message.to_string(), + } +} + +/// ConfigObj `as_int`, which raises on a value `int()` rejects. +fn as_int(section: &ConfigSection, name: &str, key: &str) -> Result { + section + .get_int(key) + .ok_or_else(|| invalid(name, key, "not an integer")) +} + +/// ConfigObj `as_bool`, which raises on anything but its boolean words. +fn as_bool(section: &ConfigSection, name: &str, key: &str) -> Result { + section + .get_bool(key) + .ok_or_else(|| invalid(name, key, "not a boolean")) +} + +impl NodeConfig { + /// Parse config text as `__apply_config` reads it. `verbosity` is the + /// `-v` count minus the `-q` count, 0 in service mode. + pub fn parse(text: &str, verbosity: i64) -> Result { + let config = Config::parse(text)?; + let mut node = NodeConfig::default(); + + if let Some(section) = config.section("aliases") { + for alias in section.values.keys() { + let Some(hexhash) = section.get(alias) else { + tracing::warn!( + "Invalid identity hash for alias {alias} in configuration file, ignoring" + ); + continue; + }; + let hash = py_fromhex(hexhash).ok().filter(|h| !h.is_empty()); + let Some(hash) = hash.filter(|_| py_len(hexhash) == 32) else { + tracing::warn!( + "Invalid identity hash for alias {alias} in configuration file, ignoring" + ); + continue; + }; + if ALL_TGTS.contains(&alias.as_str()) { + tracing::warn!("Invalid alias {alias} in configuration file, ignoring"); + continue; + } + node.aliases + .entry(alias.clone()) + .or_insert_with(|| hex::encode(hash)); + } + } + + if let Some(section) = config.section("rngit") { + let name = "rngit"; + if let Some(value) = section.get("node_name") { + node.node_name = value.to_string(); + } + if section.has("announce_interval") { + node.announce_interval = as_int(section, name, "announce_interval")? * 60; + } + if section.has("mirror_interval") { + node.mirror_interval = (as_int(section, name, "mirror_interval")? * 3600).max(0); + } + if section.has("record_stats") { + node.record_stats = as_bool(section, name, "record_stats")?; + } + for (key, target) in [ + ("stats_ignore_identities", &mut node.stats_ignored), + ("stats_push_ignore_identities", &mut node.stats_push_ignored), + ("blocked_identities", &mut node.blocked_identities), + ] { + for entry in section.get_list(key).unwrap_or_default() { + let resolved = resolve_identity_alias(&entry, &node.aliases); + if py_len(&resolved) != 32 { + continue; + } + match py_fromhex(&resolved) { + Ok(hash) if !target.contains(&hash) => target.push(hash), + Ok(_) => {} + Err(_) => tracing::warn!("Invalid identity hash in {key}: {resolved}"), + } + } + } + } + + if let Some(section) = config.section("logging").filter(|s| s.has("loglevel")) { + let level = as_int(section, "logging", "loglevel")? + verbosity; + node.loglevel = Some(level.clamp(LOG_NONE, LOG_EXTREME)); + } + + if let Some(section) = config.section("pages").filter(|s| s.has("serve_nomadnet")) { + node.serve_nomadnet = as_bool(section, "pages", "serve_nomadnet")?; + } + + if let Some(section) = config.section("repositories") { + for key in section.values.keys() { + if let Some(path) = section.get(key) { + node.repositories.insert(key.clone(), path.to_string()); + } + } + } + + if let Some(section) = config.section("access") { + for key in section.values.keys() { + node.access + .insert(key.clone(), section.get_list(key).unwrap_or_default()); + } + } + + Ok(node) + } +} + +/// The config directory as `ReticulumGitNode.__init__` picks it +/// (`server.py:2021-2028`). +pub fn resolve_config_dir(configdir: Option<&Path>) -> PathBuf { + if let Some(dir) = configdir { + return dir.to_path_buf(); + } + let etc = Path::new("/etc/rngit"); + if etc.is_dir() && etc.join("config").is_file() { + return etc.to_path_buf(); + } + let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default()); + let user = home.join(".config/rngit"); + if user.is_dir() && user.join("config").is_file() { + return user; + } + home.join(".rngit") +} + +/// The config text, writing [`DEFAULT_CONFIG`] first when the file is +/// missing (`__create_default_config`, `server.py:2070-2075`). +pub fn read_or_create_config(configdir: &Path) -> std::io::Result { + let path = configdir.join("config"); + if path.is_file() { + return std::fs::read_to_string(path); + } + tracing::info!("Could not load config file, creating default configuration file..."); + std::fs::create_dir_all(configdir)?; + std::fs::write(&path, DEFAULT_CONFIG)?; + Ok(DEFAULT_CONFIG.to_string()) +} + +/// Load `repositories_identity`, creating it when missing. +pub fn load_or_create_identity( + path: &Path, +) -> Result { + if path.is_file() { + return Identity::from_file(path); + } + let identity = Identity::new(); + identity.to_file(path)?; + Ok(identity) +} + +/// Python `os.path.expanduser` for `~` and `~/...`. +pub fn expand_user(path: &str) -> PathBuf { + match path.strip_prefix('~') { + Some(rest) if rest.is_empty() || rest.starts_with('/') => { + let mut home = std::env::var_os("HOME").unwrap_or_default(); + home.push(rest); + PathBuf::from(home) + } + _ => PathBuf::from(path), + } +} diff --git a/crates/rns-git/src/server/default_config.txt b/crates/rns-git/src/server/default_config.txt new file mode 100644 index 0000000..8d34dd7 --- /dev/null +++ b/crates/rns-git/src/server/default_config.txt @@ -0,0 +1,165 @@ +# This is the default rngit config file. +# You will need to edit it to specify repository locations and +# access permissions. + +[rngit] + +# Automatic announce interval in minutes. +# 6 hours by default. + +announce_interval = 360 + +# An optional name for this node, included +# in announces. + +# node_name = Anonymous Git Node + +# You can enable collecting view, fetch and push statistics +# which can be displayed on the stats pages of repositories. +# Remember to set the "s" (stats) permission appropriately +# for statistics to actually be viewable by anyone. + +# record_stats = no +# stats_ignore_identities = 9710b86ba12c42d1d8f30f74fe509286 +# stats_push_ignore_identities = 5bffebe038654304dafcbe12cbcd0412 + +# You can block specific identities from any interaction +# with this node. + +# blocked_identities = d31aeea49873006f13b3415520666a4e + +# To make it easier to handle scrapers, crawlers, slopware +# and other annoyances, you can block unidentified peers by +# adding the null_ident hash to to blocked identities. + +# blocked_identities = d7db22f63b453c23bb0688dde565b7c1 + +[repositories] + +# You can define multiple repository groups, each with a path +# to the directory containing "repo_name.git" directories. + +internal = /path/to/directory/with/git/repositories +public = /another/path/to/directory/with/git/repositories +showcase = /another/path/to/directory/with/git/repositories + +# To add a short description to your repositories, you can +# either place a "repo_name.description" file in the same +# directory as the repository folder, or set it in the bare +# repository with `git config repository.description`. + +# If you have mirrored repositories with the "rngit mirror" +# command, you can configure the global mirroring interval +# in hours. + +# mirror_interval = 24 + + +[aliases] + +# You can define aliases for commonly used identity hashes +# in this section. Each line must be in the format +# aliased_name = IDENTITY_HASH +# +# These hashes are used for the permissions system and +# identity resolution. For rngit CLI client operations, +# aliases must be defined in ~/.rngit/client_config. + +# alice = d09285e660cfe27cee6d9a0beb58b7e0 +# bob = ffcffb4e255e156e77f79b82c13086a6 + +[access] + +# You can apply permissions for all repositories within +# different repository collections like this: + +public = r:all, w:9710b86ba12c42d1d8f30f74fe509286 +internal = rw:9710b86ba12c42d1d8f30f74fe509286 + +# By default, all repositories sourced from the con- +# figured repository collection paths have no permissions +# enabled, and will be neither readable nor writable. +# +# The following permissions are supported: +# r = read (clone, fetch, view) +# w = write (push, create and manage work documents) +# rw = read/write +# c = create (create new repositories in group) +# s = stats (view repository statistics) +# rel = release (create and manage releases) +# i = interact (comment on work documents) +# p = propose (propose new work documents) +# adm = admin (full administrative access) +# +# To configure permissions per repository, you must create +# an ".allowed" file matching the repository name. If the +# repository is in a folder called "my_project.git", create +# a "my_project.allowed" file next to it. This file must +# contain a permission statement on each line in the form of +# "r:IDENTITY_HASH", "w:IDENTITY_HASH" or "r:IDENTITY_HASH". +# Instead of IDENTITY_HASH, you can also use "all" or "none". +# +# You can also make the allow-files executable, and have them +# evaluate or source the permissions from somewhere else, +# and then output the results to stdout. +# +# Additionally, you can create a "group.allowed" file in the +# root of a repository group directory, which will apply to +# all repositories within this group. The same syntax and +# functionality applies here. + + +[pages] +# You can run a nomadnet-compatible page node to serve +# repository information if required. Access permissions +# will follow those configured per group and repository. +# +# The page server supports automatic markdown to micron +# conversion for repository readmes and other files. If +# you have the pygments Python module installed, syntax +# highlighting will also be automatically applied. +# +# The page server is highly customizable, and you can +# provide custom templates for each page type by placing +# a corresponding "template_name.mu" file in the +# ~/.rngit/templates directory. The supported template +# names are "base", "front", "group", "repo", "tree", +# "blob", "commits", "commit", "refs", "stats", "releases", +# "release", "work" and "work_doc". You should include a +# {PAGE_CONTENT} variable somewhere in your templates, +# the rendered page content will be injected into this +# variable. + +# serve_nomadnet = no + +# It is possible to disable Nerd Font icons and instead +# use simpler (but more compatible) unicode icons. + +# unicode_icons = yes + +# You can configure whether the page server should try +# to convert media files to WebP on the fly, for serving +# to nomadnet clients. Enabled by default, but will +# require an available encoding backend installed on +# your system. Supported backends utilities are "magick", +# "convert", "gm", "ffmpeg" and "avconv". If any one is +# installed, rngit will auto-detect and use it, but you +# can force a specific backend with the environment +# variable RNGIT_MEDIA_BACKEND. + +# media_conversion = yes + + +[logging] +# Valid log levels are 0 through 8: +# 0: Log only critical information +# 1: Log errors and lower log levels +# 2: Log warnings and lower log levels +# 3: Log notices and lower log levels +# 4: Log info and lower (this is the default) +# 5: Verbose logging +# 6: Debug logging +# 7: Pathing logging +# 8: Extreme logging + +loglevel = 4 diff --git a/crates/rns-git/src/server/handlers.rs b/crates/rns-git/src/server/handlers.rs new file mode 100644 index 0000000..fa31c03 --- /dev/null +++ b/crates/rns-git/src/server/handlers.rs @@ -0,0 +1,139 @@ +//! `/git/*` request handlers (`server.py:2870-2929@1.6.0`). + +use std::process::{Command, Stdio}; + +use rmpv::Value; + +use super::layout::{Repositories, parse_repository_path}; +use super::perms::Perm; +use super::{IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_REMOTE_FAIL}; + +fn status(code: u8, message: &str) -> Vec { + let mut reply = vec![code]; + reply.extend_from_slice(message.as_bytes()); + reply +} + +/// Python truthiness of an unpacked request value. +fn truthy(value: &Value) -> bool { + match value { + Value::Nil => false, + Value::Boolean(b) => *b, + Value::Integer(i) => i.as_i64() != Some(0) && i.as_u64() != Some(0), + Value::F32(f) => *f != 0.0, + Value::F64(f) => *f != 0.0, + Value::String(s) => !s.as_bytes().is_empty(), + Value::Binary(b) => !b.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Map(m) => !m.is_empty(), + Value::Ext(_, d) => !d.is_empty(), + } +} + +/// `data.get(key)` for an integer or string key. +fn get<'a>(map: &'a [(Value, Value)], key: &Value) -> Option<&'a Value> { + map.iter().find(|(k, _)| k == key).map(|(_, v)| v) +} + +/// A request map and its parsed repository path. +type Parsed<'a> = (&'a [(Value, Value)], Option<(&'a str, &'a str)>); + +/// Common checks of every handler (`server.py:2872-2874`); `Err` is the reply. +/// `Ok(None)` is upstream raising before its try (key 0 not a string), which +/// sends no response. +fn request_path<'a>( + identity: Option<&[u8; 16]>, + data: &'a Value, +) -> Result>, Vec> { + if identity.is_none() { + return Err(status(RES_DISALLOWED, "Not identified")); + } + let Value::Map(map) = data else { + return Err(status(RES_INVALID_REQ, "Invalid request")); + }; + let Some(path) = get(map, &Value::from(IDX_REPOSITORY)) else { + return Err(status(RES_INVALID_REQ, "No repository specified")); + }; + let Some(path) = path.as_str() else { + return Ok(None); + }; + Ok(Some((map, parse_repository_path(path)))) +} + +/// `handle_list` (`server.py:2870-2929`). `None` sends no response. +pub fn handle_list( + repos: &Repositories, + identity: Option<&[u8; 16]>, + data: &Value, +) -> Option> { + let (map, path) = match request_path(identity, data) { + Err(reply) => return Some(reply), + Ok(None) => return None, + Ok(Some(parsed)) => parsed, + }; + let hash = identity.expect("checked"); + let (group, repo) = path.unwrap_or(("", "")); + let for_push = get(map, &Value::from("for_push")).is_some_and(truthy); + let read = path.is_some() && repos.resolve_permission(hash, group, repo, Perm::Read); + let write = path.is_some() && repos.resolve_permission(hash, group, repo, Perm::Write); + let access = if for_push { write } else { read }; + if !access { + let message = if read { "Not allowed" } else { "Not found" }; + return Some(status(RES_NOT_FOUND, message)); + } + let repository = repos.repository(group, repo).expect("resolved"); + let mut head_ref = "master".to_string(); + let head = std::fs::read(repository.path.join("HEAD")).unwrap_or_default(); + if let Some(rest) = head.strip_prefix(b"ref: ") { + // bytes.strip() then decode("utf-8", errors="ignore") + let ws = |b: &u8| b" \t\n\r\x0b\x0c".contains(b); + let start = rest.iter().position(|b| !ws(b)).unwrap_or(rest.len()); + let end = rest.iter().rposition(|b| !ws(b)).map_or(start, |i| i + 1); + head_ref = rest[start..end] + .utf8_chunks() + .map(|chunk| chunk.valid()) + .collect(); + } + let output = Command::new("git") + .args(["for-each-ref", "--format", "%(objectname) %(refname)"]) + .current_dir(&repository.path) + .stdin(Stdio::null()) + .output(); + let output = match output { + Ok(output) if output.status.success() => output, + Ok(output) => { + tracing::error!( + "Error while listing refs for {group}/{repo}: {}", + String::from_utf8_lossy(&output.stderr) + ); + return Some(status(RES_REMOTE_FAIL, "Could not list refs")); + } + Err(e) => { + tracing::error!("Error while handling list request for {group}/{repo}: {e}"); + return Some(status(RES_REMOTE_FAIL, "Remote error")); + } + }; + let Ok(stdout) = String::from_utf8(output.stdout) else { + return Some(status(RES_REMOTE_FAIL, "Remote error")); + }; + let mut seen = std::collections::HashSet::new(); + let mut lines = Vec::new(); + for line in stdout.trim().split('\n') { + if line.trim().is_empty() { + continue; + } + if let Some((_, name)) = line.split_once(' ') + && seen.insert(name.to_string()) + { + lines.push(line); + } + } + let text = if lines.is_empty() { + format!("@{head_ref} HEAD\n") + } else { + format!("{}\n@{head_ref} HEAD\n", lines.join("\n")) + }; + let mut reply = vec![super::RES_OK]; + reply.extend_from_slice(text.as_bytes()); + Some(reply) +} diff --git a/crates/rns-git/src/server/layout.rs b/crates/rns-git/src/server/layout.rs new file mode 100644 index 0000000..3f552cf --- /dev/null +++ b/crates/rns-git/src/server/layout.rs @@ -0,0 +1,247 @@ +//! Repository groups and repositories on disk (`load_repository_group`, +//! `update_group_permissions`, `load_repository`, `server.py:2528-2645@1.6.0`). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use super::config::{NodeConfig, expand_user}; +use super::perms::{AllowedError, Perm, Permissions, load_allowed_permissions}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Repository { + /// The directory name, including any `.git` suffix. + pub name: String, + pub group: String, + pub path: PathBuf, + /// Upstream source URL of a fork or mirror. + pub fork: Option, + pub mirror: Option, + pub permissions: Permissions, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Group { + pub name: String, + /// The expanded configured path, kept as written (a trailing `/` stays). + pub path: String, + pub repositories: BTreeMap, + /// Whether the group's `.allowed` file is executable. + pub dynamic_perms: bool, + pub permissions: Permissions, +} + +/// Groups and their repositories, as the node holds them. +#[derive(Debug, Clone, Default)] +pub struct Repositories { + pub groups: BTreeMap, + pub aliases: BTreeMap, + pub blocked: Vec>, +} + +/// A `git` call in `cwd` with output captured; `None` when it cannot run +/// or exits non-zero, as `check=True` raising into a bare `except`. +fn git_stdout(cwd: &Path, args: &[&str]) -> Option { + let output = Command::new("git") + .args(args) + .current_dir(cwd) + .stdin(Stdio::null()) + .output() + .ok()?; + if !output.status.success() { + return None; + } + Some(String::from_utf8_lossy(&output.stdout).trim().to_string()) +} + +/// `_ensure_git` (`server.py:2709-2712`). +pub fn git_available() -> bool { + Command::new("git") + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) +} + +/// `__is_fork` / `__is_mirror` (`server.py:2734-2760`). +fn upstream_source(path: &Path, kind: &str) -> Option { + if git_stdout(path, &["config", "repository.rngit.type"])? != kind { + return None; + } + git_stdout(path, &["config", "repository.rngit.upstream.source"]) +} + +impl Repositories { + /// Load every `[repositories]` group whose path is a directory. + pub fn load(config: &NodeConfig) -> Result { + let mut repos = Repositories { + groups: BTreeMap::new(), + aliases: config.aliases.clone(), + blocked: config.blocked_identities.clone(), + }; + for (name, raw_path) in &config.repositories { + let path = expand_user(raw_path); + if !path.is_dir() { + tracing::warn!( + "The path \"{}\" specified for repository group \"{name}\" does not exist, skipping.", + path.display() + ); + continue; + } + repos.load_group(name, &path.to_string_lossy(), config)?; + } + Ok(repos) + } + + /// `load_repository_group` (`server.py:2528-2546`). + pub fn load_group( + &mut self, + name: &str, + path: &str, + config: &NodeConfig, + ) -> Result<(), AllowedError> { + let group = self + .groups + .entry(name.to_string()) + .or_insert_with(|| Group { + name: name.to_string(), + path: path.to_string(), + repositories: BTreeMap::new(), + dynamic_perms: false, + permissions: Permissions::default(), + }); + if group.path != path { + tracing::error!( + "Repository group path did not match existing entry while loading {name}, aborting load" + ); + return Ok(()); + } + self.update_group_permissions(name, config); + let entries = std::fs::read_dir(path).map_err(AllowedError::Io)?; + for entry in entries { + let entry = entry.map_err(AllowedError::Io)?; + let entry_path = format!("{path}/{}", entry.file_name().to_string_lossy()); + self.load_repository(name, Path::new(&entry_path))?; + } + Ok(()) + } + + /// `update_group_permissions` (`server.py:2548-2602`): the group's + /// `.allowed` file first, then its `[access]` statements appended. + pub fn update_group_permissions(&mut self, name: &str, config: &NodeConfig) { + let aliases = self.aliases.clone(); + let Some(group) = self.groups.get_mut(name) else { + tracing::warn!( + "Attempt to set group permissions for non-existing group {name}, aborting" + ); + return; + }; + let mut permissions = Permissions::default(); + let allowed = PathBuf::from(format!("{}.allowed", group.path)); + if allowed.is_file() { + match load_allowed_permissions(&allowed, &aliases) { + Ok((loaded, dynamic)) => { + permissions = loaded; + group.dynamic_perms = dynamic; + } + Err(e) => tracing::error!( + "Could not load group permissions from {}: {e:?}", + allowed.display() + ), + } + } else { + group.dynamic_perms = false; + } + for statement in config.access.get(name).into_iter().flatten() { + permissions.add_statement(statement, &aliases); + } + group.permissions = permissions; + } + + /// `load_repository` (`server.py:2621-2645`). A repository `.allowed` + /// file that cannot be read is an error, as upstream lets it raise. + pub fn load_repository(&mut self, group_name: &str, path: &Path) -> Result { + let Some(group) = self.groups.get_mut(group_name) else { + return Ok(false); + }; + let path_str = path.to_string_lossy(); + if !path.is_dir() || path_str.ends_with(".work") || path_str.ends_with(".releases") { + return Ok(false); + } + if git_stdout(path, &["rev-parse", "--git-dir"]).as_deref() != Some(".") { + tracing::warn!("The directory \"{path_str}\" is not a git repository, skipping"); + return Ok(false); + } + if git_stdout(path, &["config", "--bool", "core.bare"]).as_deref() != Some("true") { + tracing::warn!("The directory \"{path_str}\" is not a bare git repository, skipping"); + tracing::warn!( + "You can change it to a bare repository using \"git config --bool core.bare true\"." + ); + return Ok(false); + } + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let allowed = PathBuf::from(format!("{path_str}.allowed")); + let (permissions, _) = load_allowed_permissions(&allowed, &self.aliases)?; + let repository = Repository { + name: name.clone(), + group: group_name.to_string(), + path: path.to_path_buf(), + fork: upstream_source(path, "fork"), + mirror: upstream_source(path, "mirror"), + permissions, + }; + group.repositories.insert(name, repository); + Ok(true) + } + + /// `resolve_permission` (`server.py:2311-2369`), the only resolver that + /// checks the blocklist. + pub fn resolve_permission( + &self, + hash: &[u8; 16], + group: &str, + repository: &str, + perm: Perm, + ) -> bool { + if self.blocked.iter().any(|b| b.as_slice() == hash) { + return false; + } + let Some(g) = self.groups.get(group) else { + return false; + }; + let Some(r) = g.repositories.get(repository) else { + return false; + }; + super::perms::resolve_repository(&g.permissions, &r.permissions, hash, perm) + } + + /// `resolve_group_permission` (`server.py:2371-2396`). + pub fn resolve_group_permission(&self, hash: &[u8; 16], group: &str, perm: Perm) -> bool { + self.groups + .get(group) + .is_some_and(|g| super::perms::resolve_group(&g.permissions, hash, perm)) + } + + pub fn repository(&self, group: &str, repository: &str) -> Option<&Repository> { + self.groups.get(group)?.repositories.get(repository) + } +} + +/// `parse_request_repository_path` (`server.py:2292-2300`). +pub fn parse_repository_path(path: &str) -> Option<(&str, &str)> { + let mut parts = path.split('/'); + let (Some(group), Some(repo), None) = (parts.next(), parts.next(), parts.next()) else { + return None; + }; + (super::py_len(group) <= 256 && super::py_len(repo) <= 256).then_some((group, repo)) +} + +/// `parse_request_group_path` (`server.py:2302-2309`). +pub fn parse_group_path(path: &str) -> Option<&str> { + (!path.contains('/') && super::py_len(path) <= 256).then_some(path) +} diff --git a/crates/rns-git/src/server/mod.rs b/crates/rns-git/src/server/mod.rs new file mode 100644 index 0000000..2ce2318 --- /dev/null +++ b/crates/rns-git/src/server/mod.rs @@ -0,0 +1,30 @@ +//! The rngit repository node (`RNS/Utilities/rngit/server.py@1.6.0`). + +pub mod config; +pub mod handlers; +pub mod layout; +pub mod perms; + +/// `APP_NAME` plus the aspect (`__init__.py:31`, `server.py:2063`). +pub const APP_NAME: &str = "git.repositories"; + +pub const PATH_LIST: &str = "/git/list"; +pub const PATH_FETCH: &str = "/git/fetch"; +pub const PATH_PUSH: &str = "/git/push"; +pub const PATH_DELETE: &str = "/git/delete"; +pub const PATH_CREATE: &str = "/git/create"; + +pub const RES_OK: u8 = 0x00; +pub const RES_DISALLOWED: u8 = 0x01; +pub const RES_INVALID_REQ: u8 = 0x02; +pub const RES_NOT_FOUND: u8 = 0x03; +pub const RES_REMOTE_FAIL: u8 = 0xFF; + +pub const IDX_REPOSITORY: u8 = 0x00; +pub const IDX_RESULT_CODE: u8 = 0x01; +pub const IDX_GROUP: u8 = 0x02; + +/// Python `len(s)`: the number of code points. +pub(crate) fn py_len(s: &str) -> usize { + s.chars().count() +} diff --git a/crates/rns-git/src/server/perms.rs b/crates/rns-git/src/server/perms.rs new file mode 100644 index 0000000..ec1f5d9 --- /dev/null +++ b/crates/rns-git/src/server/perms.rs @@ -0,0 +1,323 @@ +//! Permission statements, `.allowed` files and the permission decision +//! (`server.py:2251-2526@1.6.0`). + +use std::collections::BTreeMap; +use std::path::Path; + +use super::py_len; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Perm { + Read, + Write, + ReadWrite, + Create, + Stats, + Release, + Interact, + Propose, + Admin, +} + +impl Perm { + /// The wire value (`PERM_*`, `server.py:1927-1935`). + pub fn code(self) -> u8 { + match self { + Perm::Read => 0x01, + Perm::Write => 0x02, + Perm::ReadWrite => 0x03, + Perm::Create => 0x04, + Perm::Stats => 0x05, + Perm::Release => 0x06, + Perm::Interact => 0x07, + Perm::Propose => 0x08, + Perm::Admin => 0xFE, + } + } + + fn from_word(word: &str) -> Option { + Some(match word { + "r" | "read" => Perm::Read, + "w" | "write" => Perm::Write, + "rw" | "readwrite" => Perm::ReadWrite, + "c" | "create" => Perm::Create, + "s" | "stats" => Perm::Stats, + "rel" | "release" => Perm::Release, + "i" | "interact" => Perm::Interact, + "p" | "propose" => Perm::Propose, + "adm" | "admin" => Perm::Admin, + _ => return None, + }) + } + + /// The permission list this perm reads; `None` for read-write, which + /// the resolvers reject. + fn list(self) -> Option { + Some(match self { + Perm::Read => PermList::Read, + Perm::Write => PermList::Write, + Perm::Create => PermList::Create, + Perm::Stats => PermList::Stats, + Perm::Release => PermList::Release, + Perm::Interact => PermList::Interact, + Perm::Propose => PermList::Propose, + Perm::Admin => PermList::Admin, + Perm::ReadWrite => return None, + }) + } +} + +/// One of the eight stored lists (`ALL_PERMS`, `server.py:1945`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum PermList { + Read, + Write, + Create, + Stats, + Release, + Interact, + Propose, + Admin, +} + +impl PermList { + pub const ALL: [PermList; 8] = [ + PermList::Read, + PermList::Write, + PermList::Create, + PermList::Stats, + PermList::Release, + PermList::Interact, + PermList::Propose, + PermList::Admin, + ]; + + pub fn name(self) -> &'static str { + match self { + PermList::Read => "read", + PermList::Write => "write", + PermList::Create => "create", + PermList::Stats => "stats", + PermList::Release => "release", + PermList::Interact => "interact", + PermList::Propose => "propose", + PermList::Admin => "admin", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Target { + None, + All, + /// Identity hash bytes; `bytes.fromhex` can yield fewer than 16, which + /// upstream stores and never matches. + Identity(Vec), +} + +impl Target { + /// The wire value (`TGT_NONE`/`TGT_ALL`, `server.py:1947-1948`). + pub fn code(&self) -> Option { + match self { + Target::None => Some(0x01), + Target::All => Some(0x02), + Target::Identity(_) => None, + } + } +} + +pub const TGT_NONE_SMPHR: [&str; 3] = ["n", "none", "nobody"]; +pub const TGT_ALL_SMPHR: [&str; 3] = ["a", "all", "everyone"]; +pub const ALL_TGTS: [&str; 6] = ["n", "none", "nobody", "a", "all", "everyone"]; + +/// `__resolve_identity_alias` (`server.py:2251-2261`). +pub fn resolve_identity_alias(alias: &str, aliases: &BTreeMap) -> String { + if ALL_TGTS.contains(&alias.to_lowercase().as_str()) { + return alias.to_string(); + } + let is_hash = py_len(alias) == 32 + && rns_tools::rsg::pyfmt::py_fromhex(alias).is_ok_and(|h| !h.is_empty()); + if is_hash { + return alias.to_string(); + } + aliases + .get(alias) + .cloned() + .unwrap_or_else(|| alias.to_string()) +} + +/// `parse_permission` (`server.py:2263-2290`): either half is `None` when +/// it does not parse. +pub fn parse_permission( + statement: &str, + aliases: &BTreeMap, +) -> (Option, Option) { + let comps: Vec<&str> = statement.split(':').collect(); + if comps.len() != 2 { + return (None, None); + } + let perm = Perm::from_word(&comps[0].to_lowercase()); + let target = resolve_identity_alias(comps[1], aliases); + let target = if TGT_NONE_SMPHR.contains(&target.as_str()) { + Some(Target::None) + } else if TGT_ALL_SMPHR.contains(&target.as_str()) { + Some(Target::All) + } else if py_len(&target) == 32 { + match rns_tools::rsg::pyfmt::py_fromhex(&target) { + Ok(hash) => Some(Target::Identity(hash)), + Err(e) => { + tracing::error!("Invalid identity hash \"{target}\" in access permissions: {e}"); + None + } + } + } else { + None + }; + (perm, target) +} + +/// The eight permission lists of a group or repository. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Permissions { + lists: BTreeMap>, +} + +impl Permissions { + pub fn get(&self, list: PermList) -> &[Target] { + self.lists.get(&list).map(Vec::as_slice).unwrap_or(&[]) + } + + fn add(&mut self, list: PermList, target: &Target) { + let entries = self.lists.entry(list).or_default(); + if !entries.contains(target) { + entries.push(target.clone()); + } + } + + /// Add one parsed statement; `rw` adds to both read and write. + pub fn add_statement(&mut self, statement: &str, aliases: &BTreeMap) { + let (Some(perm), Some(target)) = parse_permission(statement, aliases) else { + return; + }; + match perm.list() { + Some(list) => self.add(list, &target), + None => { + self.add(PermList::Read, &target); + self.add(PermList::Write, &target); + } + } + } + + /// `permissions_from_allowed_input` (`server.py:2470-2510`). + pub fn from_allowed_input(input: &str, aliases: &BTreeMap) -> Self { + let mut perms = Permissions::default(); + for line in py_splitlines(input) { + let statement = line.trim(); + if !statement.starts_with('#') { + perms.add_statement(statement, aliases); + } + } + perms + } +} + +/// Python `str.splitlines`. +fn py_splitlines(text: &str) -> Vec<&str> { + let mut lines = Vec::new(); + let mut start = 0; + let mut iter = text.char_indices().peekable(); + while let Some((i, c)) = iter.next() { + let end = match c { + '\r' => { + if let Some((_, '\n')) = iter.peek() { + iter.next(); + i + 2 + } else { + i + 1 + } + } + '\n' | '\x0b' | '\x0c' | '\x1c' | '\x1d' | '\x1e' | '\u{85}' | '\u{2028}' + | '\u{2029}' => i + c.len_utf8(), + _ => continue, + }; + lines.push(&text[start..i]); + start = end; + } + if start < text.len() { + lines.push(&text[start..]); + } + lines +} + +/// Error from reading an `.allowed` file; upstream raises here. +#[derive(Debug)] +pub enum AllowedError { + Io(std::io::Error), + NotUtf8, +} + +/// `load_allowed_permissions` (`server.py:2512-2526`): an executable file is +/// run with no arguments and its stdout parsed (the exit status is +/// ignored); the flag says whether it was run. +pub fn load_allowed_permissions( + path: &Path, + aliases: &BTreeMap, +) -> Result<(Permissions, bool), AllowedError> { + if !path.is_file() { + return Ok((Permissions::default(), false)); + } + let executable = nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok(); + let (raw, dynamic) = if executable { + let output = std::process::Command::new(path) + .stdin(std::process::Stdio::inherit()) + .stderr(std::process::Stdio::inherit()) + .output() + .map_err(AllowedError::Io)?; + (output.stdout, true) + } else { + (std::fs::read(path).map_err(AllowedError::Io)?, false) + }; + let input = String::from_utf8(raw).map_err(|_| AllowedError::NotUtf8)?; + Ok((Permissions::from_allowed_input(&input, aliases), dynamic)) +} + +fn decide(list: &[Target], admins: &[Target], hash: &[u8; 16]) -> Option { + let me = Target::Identity(hash.to_vec()); + if list.contains(&Target::None) { + Some(false) + } else if list.contains(&Target::All) || list.contains(&me) || admins.contains(&me) { + Some(true) + } else { + None + } +} + +/// `resolve_permission`'s decision once group and repository are known +/// (`server.py:2311-2369`); the blocklist is checked by the caller. +pub fn resolve_repository( + group: &Permissions, + repository: &Permissions, + hash: &[u8; 16], + perm: Perm, +) -> bool { + let Some(list) = perm.list() else { + return false; + }; + let repo_list = repository.get(list); + if let Some(decision) = decide(repo_list, repository.get(PermList::Admin), hash) { + return decision; + } + if !repo_list.is_empty() { + return false; + } + decide(group.get(list), group.get(PermList::Admin), hash).unwrap_or(false) +} + +/// `resolve_group_permission`'s decision (`server.py:2371-2396`); upstream +/// does not check the blocklist here. +pub fn resolve_group(group: &Permissions, hash: &[u8; 16], perm: Perm) -> bool { + let Some(list) = perm.list() else { + return false; + }; + decide(group.get(list), group.get(PermList::Admin), hash).unwrap_or(false) +}