Fold small duplicated helpers into one each
Browse files- unix_now lives in gitv-core instead of a copy in each binary - name() is check_name() for clap rather than a second copy of the rule - Repo::reference replaces the same ref-or-default line in three views - one html() response helper, with the security headers, for every page - the auth unit tests share one scratch() instead of three Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 22:13
- Commit
- 0414385a8954
- Parent
- 0f4caaa
10 files changed +35−48
| @@ -300,6 +300,11 @@ pub fn git_protocol(value: &str) -> Option<&str> { | ||
| (value.len() <= 64 && value.bytes().all(|b| b.is_ascii_alphanumeric() || b"=:.".contains(&b))).then_some(value) | ||
| } | ||
| /// Seconds since the Unix epoch, or 0 if the clock is set before it. | ||
| pub fn unix_now() -> u64 { | ||
| std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) | ||
| } | ||
| /// Make a rename or new file in `path`'s directory durable: until the directory itself is | ||
| /// synced, a crash can leave the old name, or none, in place of what was just published. | ||
| pub fn sync_directory_of(path: &Path) -> std::io::Result<()> { | ||
| @@ -552,6 +552,14 @@ fn url_component(value: &str) -> String { | ||
| mod tests { | ||
| use super::*; | ||
| /// A fresh, empty directory for one test. | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| /// The shared secret of RFC 6238's SHA-1 test vectors. | ||
| const RFC_SECRET: &[u8] = b"12345678901234567890"; | ||
| @@ -689,13 +697,6 @@ mod tests { | ||
| use super::*; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn round_trips() { | ||
| let dir = scratch("round-trip"); | ||
| @@ -744,13 +745,6 @@ mod tests { | ||
| mod writers { | ||
| use super::*; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-w-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn a_change_authorized_against_an_older_account_is_refused() { | ||
| let dir = scratch("stale"); | ||
| @@ -839,13 +833,6 @@ mod tests { | ||
| mod codes_across_processes { | ||
| use super::*; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-c-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn lock_requires_a_private_regular_file_with_one_link() { | ||
| use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; | ||
| @@ -1,7 +1,5 @@ | ||
| //! Small pieces of HTML shared by every page: icons, dates, sizes and the page layout. | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| use crate::templates; | ||
| pub(crate) fn icon(name: &str) -> String { | ||
| @@ -28,8 +26,7 @@ pub(crate) fn icon(name: &str) -> String { | ||
| /// "3 hours ago" for recent times, the calendar date (as git printed it) after a month. | ||
| pub(crate) fn ago(stamp: &str, date: &str) -> String { | ||
| let Ok(then) = stamp.parse::<u64>() else { return date.to_string() }; | ||
| let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); | ||
| let span = now.saturating_sub(then); | ||
| let span = gitv_core::unix_now().saturating_sub(then); | ||
| let unit = |n: u64, word: &str| format!("{n} {word}{} ago", if n == 1 { "" } else { "s" }); | ||
| match span { | ||
| 0..60 => "just now".into(), | ||
| @@ -10,7 +10,7 @@ use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; | ||
| use std::os::unix::process::CommandExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | ||
| use std::time::{Duration, Instant}; | ||
| use axum::Extension; | ||
| use axum::extract::{Form, FromRequest, RawQuery, Request, State}; | ||
| @@ -18,7 +18,7 @@ use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; | ||
| use axum::middleware::Next; | ||
| use axum::response::{IntoResponse, Response}; | ||
| use data_encoding::BASE64URL_NOPAD; | ||
| use gitv_core::percent_decode; | ||
| use gitv_core::{percent_decode, unix_now}; | ||
| use gitv_web::auth::{ | ||
| AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, generate_password, random_bytes, | ||
| }; | ||
| @@ -26,8 +26,8 @@ use serde::Deserialize; | ||
| use sha2::{Digest, Sha256}; | ||
| use subtle::ConstantTimeEq; | ||
| use super::SECURITY; | ||
| use super::throttle::{Client, Throttle}; | ||
| use super::{SECURITY, html}; | ||
| /// The session cookie. The `__Host-` prefix makes browsers insist on `Secure`, `Path=/` and no | ||
| /// `Domain`, so no other site or subdomain can set or overwrite it. | ||
| @@ -277,20 +277,12 @@ fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> { | ||
| Some(Sha256::digest(token).into()) | ||
| } | ||
| fn unix_now() -> u64 { | ||
| SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) | ||
| } | ||
| /// Where to go after signing in: a path on this site, never another site (`//evil.example`). | ||
| fn safe_next(next: &str) -> &str { | ||
| let local = next.starts_with('/') && !next.starts_with("//") && !next.starts_with("/\\"); | ||
| if local && !next.bytes().any(|b| b.is_ascii_control()) { next } else { "/" } | ||
| } | ||
| fn html(status: StatusCode, body: String) -> Response { | ||
| (status, SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response() | ||
| } | ||
| fn redirect(to: &str, cookies: &[String]) -> Response { | ||
| let mut response = (StatusCode::SEE_OTHER, SECURITY).into_response(); | ||
| if let Ok(location) = HeaderValue::from_str(to) { | ||
| @@ -118,7 +118,7 @@ impl View { | ||
| async fn response(self, visitor: Visitor) -> Response { | ||
| match self { | ||
| View::LoginRequired => StatusCode::UNAUTHORIZED.into_response(), | ||
| View::Html(body) => (SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response(), | ||
| View::Html(body) => html(StatusCode::OK, body), | ||
| View::Raw(cmd, size, name) => raw_response(visitor, *cmd, size, name).await, | ||
| View::Busy => StatusCode::SERVICE_UNAVAILABLE.into_response(), | ||
| View::Redirect(to) => Redirect::to(&to).into_response(), | ||
| @@ -128,8 +128,12 @@ impl View { | ||
| } | ||
| fn missing(signed_in: bool) -> Response { | ||
| let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")]; | ||
| (StatusCode::NOT_FOUND, SECURITY, html, view_missing(signed_in)).into_response() | ||
| html(StatusCode::NOT_FOUND, view_missing(signed_in)) | ||
| } | ||
| /// An HTML page, with the security headers every page sends. | ||
| fn html(status: StatusCode, body: String) -> Response { | ||
| (status, SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response() | ||
| } | ||
| fn static_file(kind: &'static str, data: &'static [u8]) -> Response { | ||
| @@ -11,7 +11,7 @@ use crate::urls::{Q, clean_path, file_name, lossy, param, parent_of}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let reference = repo.reference(q); | ||
| let path = clean_path(q.get("path")?)?; | ||
| let commit = repo.reader.resolve(&reference)?; | ||
| let item = entry(repo, &commit, &path)?; | ||
| @@ -7,7 +7,7 @@ use crate::urls::{Q, lossy, param}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let reference = repo.reference(q); | ||
| let number: usize = param(q, "page").and_then(|p| p.parse().ok()).unwrap_or(0); | ||
| let skip = number.checked_mul(PAGE)?; | ||
| let commit = repo.reader.resolve(&reference)?; | ||
| @@ -71,6 +71,11 @@ impl Repo { | ||
| if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) } | ||
| } | ||
| /// The reference a page's `ref` parameter names, or the default branch. | ||
| pub(crate) fn reference(&self, q: &Q) -> Vec<u8> { | ||
| q.get("ref").cloned().unwrap_or_else(|| self.reader.default_ref()) | ||
| } | ||
| /// A tree, blob or raw link for a path, which may not be UTF-8. | ||
| pub(crate) fn url_at(&self, view: &str, reference: &[u8], path: &[u8], extra: &str) -> String { | ||
| let mut url = self.url(view, &[]); | ||
| @@ -13,7 +13,7 @@ use crate::urls::{Q, clean_path, encode, join, lossy, param, parent_of, spec}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref").cloned().unwrap_or_else(|| repo.reader.default_ref()); | ||
| let reference = repo.reference(q); | ||
| let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; | ||
| let Some(commit) = repo.reader.resolve(&reference) else { | ||
| if !repo.reader.heads().is_empty() { | ||
| @@ -11,7 +11,7 @@ use base64::Engine; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv_core::{ | ||
| NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at, | ||
| open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, valid_name, | ||
| open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, unix_now, valid_name, | ||
| }; | ||
| use nix::errno::Errno; | ||
| use nix::fcntl::{Flock, FlockArg, OFlag, RenameFlags, openat, renameat2}; | ||
| @@ -93,8 +93,9 @@ enum Action { | ||
| }, | ||
| } | ||
| /// [`check_name`], for clap's argument parsing. | ||
| fn name(value: &str) -> Result<String, String> { | ||
| if valid_name(value) { Ok(value.to_string()) } else { Err(NAME_RULE.into()) } | ||
| check_name(value).map(str::to_string) | ||
| } | ||
| fn check_name(value: &str) -> Result<&str, String> { | ||
| @@ -299,10 +300,6 @@ const TRASH_DAYS: u64 = 30; | ||
| /// The trash directory inside each owner's directory. Its leading dot keeps it out of every listing. | ||
| const TRASH: &str = ".trash"; | ||
| fn unix_now() -> u64 { | ||
| SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) | ||
| } | ||
| /// The owner's trash directory, created (private, and the git account's) if needed. | ||
| fn trash_directory(owner_dir: &OwnedFd) -> Result<OwnedFd, String> { | ||
| match mkdirat(owner_dir, TRASH, Mode::S_IRWXU) { | ||