use super::store::parse_form_urlencoded;
use super::{WEB_UI_CSP, handle_web_ui_with_actions, html_escape, redirect_see_other};
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use crate::serve::PageHandler;
use arks_repo::Repository;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
fn is_valid_repo_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 80
&& !name.starts_with('.')
&& !name.contains("..")
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
fn resolve_repo_git_dir(root: &Path, name: &str) -> Option<PathBuf> {
let bare_name = name.trim_end_matches(".git");
if !is_valid_repo_name(bare_name) {
return None;
}
let bare = root.join(format!("{bare_name}.git"));
if bare.join("HEAD").is_file() {
return Some(bare);
}
let non_bare = root.join(bare_name).join(".git");
if non_bare.join("HEAD").is_file() {
return Some(non_bare);
}
let direct = root.join(bare_name);
if direct.join("HEAD").is_file() {
return Some(direct);
}
None
}
fn read_repo_description(git_dir: &Path) -> String {
fs::read_to_string(git_dir.join("description"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && !s.starts_with("Unnamed repository"))
.unwrap_or_else(|| "Self-hosted Git repository".into())
}
fn list_repos(root: &Path) -> Vec<(String, PathBuf, String)> {
let mut out = Vec::new();
let Ok(rd) = fs::read_dir(root) else {
return out;
};
for ent in rd.flatten() {
let path = ent.path();
if !path.is_dir() {
continue;
}
let raw_name = ent.file_name().to_string_lossy().into_owned();
if raw_name.starts_with('.') {
continue;
}
let git_dir = if path.join("HEAD").is_file() {
Some(path.clone())
} else if path.join(".git").join("HEAD").is_file() {
Some(path.join(".git"))
} else {
None
};
if let Some(git_dir) = git_dir {
let display = raw_name.trim_end_matches(".git").to_string();
let desc = read_repo_description(&git_dir);
out.push((display, git_dir, desc));
continue;
}
if !is_valid_repo_name(&raw_name) {
continue;
}
let Ok(sub_rd) = fs::read_dir(&path) else {
continue;
};
for sub_ent in sub_rd.flatten() {
let sub_path = sub_ent.path();
if !sub_path.is_dir() {
continue;
}
let sub_raw = sub_ent.file_name().to_string_lossy().into_owned();
if sub_raw.starts_with('.') {
continue;
}
let sub_git_dir = if sub_path.join("HEAD").is_file() {
sub_path.clone()
} else if sub_path.join(".git").join("HEAD").is_file() {
sub_path.join(".git")
} else {
continue;
};
let sub_clean = sub_raw.trim_end_matches(".git");
if !is_valid_repo_name(sub_clean) {
continue;
}
let display = format!("{raw_name}/{sub_clean}");
let desc = read_repo_description(&sub_git_dir);
out.push((display, sub_git_dir, desc));
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
pub fn init_bare_repo(root: &Path, name: &str, description: &str) -> Result<PathBuf, String> {
let clean = name.trim().trim_end_matches(".git");
if !is_valid_repo_name(clean) {
return Err("Invalid repository name (use alphanumeric, '-', '_', '.')".into());
}
let target = root.join(format!("{clean}.git"));
if target.exists() {
return Err(format!("Repository '{clean}' already exists"));
}
fs::create_dir_all(target.join("objects").join("info")).map_err(|e| e.to_string())?;
fs::create_dir_all(target.join("objects").join("pack")).map_err(|e| e.to_string())?;
fs::create_dir_all(target.join("refs").join("heads")).map_err(|e| e.to_string())?;
fs::create_dir_all(target.join("refs").join("tags")).map_err(|e| e.to_string())?;
fs::write(target.join("HEAD"), "ref: refs/heads/main\n").map_err(|e| e.to_string())?;
fs::write(
target.join("config"),
"[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n[http]\n\treceivepack = true\n",
)
.map_err(|e| e.to_string())?;
let desc = if description.trim().is_empty() {
format!("{clean} — served by arks")
} else {
description.trim().to_string()
};
fs::write(target.join("description"), format!("{desc}\n")).map_err(|e| e.to_string())?;
Ok(target)
}
pub fn multi_repo_page_handler_full(
root_dir: impl Into<PathBuf>,
allow_local_actions: bool,
disable_lfs: bool,
disable_web_ui: bool,
has_basic_auth: bool,
) -> PageHandler {
let root = root_dir.into();
Arc::new(move |req: &HttpRequest| {
handle_multi_repo_full(
&root,
req,
allow_local_actions,
disable_lfs,
disable_web_ui,
has_basic_auth,
)
})
}
pub fn multi_repo_page_handler_opts(
root_dir: impl Into<PathBuf>,
allow_local_actions: bool,
disable_lfs: bool,
disable_web_ui: bool,
) -> PageHandler {
multi_repo_page_handler_full(
root_dir,
allow_local_actions,
disable_lfs,
disable_web_ui,
false,
)
}
pub fn multi_repo_page_handler(
root_dir: impl Into<PathBuf>,
allow_local_actions: bool,
) -> PageHandler {
multi_repo_page_handler_opts(root_dir, allow_local_actions, false, false)
}
#[allow(dead_code)]
pub fn handle_multi_repo(
root: &Path,
req: &HttpRequest,
allow_local_actions: bool,
) -> Option<HttpResponse> {
handle_multi_repo_opts(root, req, allow_local_actions, false, false)
}
pub fn handle_multi_repo_opts(
root: &Path,
req: &HttpRequest,
allow_local_actions: bool,
disable_lfs: bool,
disable_web_ui: bool,
) -> Option<HttpResponse> {
handle_multi_repo_full(
root,
req,
allow_local_actions,
disable_lfs,
disable_web_ui,
false,
)
}
pub fn handle_multi_repo_full(
root: &Path,
req: &HttpRequest,
allow_local_actions: bool,
disable_lfs: bool,
disable_web_ui: bool,
has_basic_auth: bool,
) -> Option<HttpResponse> {
let path = req.path.as_str();
let host = req.host.as_deref().unwrap_or("127.0.0.1:8080");
let scheme = if req.is_https() { "https" } else { "http" };
if !disable_web_ui {
if req.method == "GET" && (path == "/" || path.is_empty()) {
let resp = render_dashboard(root, host, scheme, req);
let global_dir = root.join(".arks-global-auth");
let gstore = super::store::ForgeStore::load_shared(&global_dir);
if let Some((user, csrf)) = super::auth_api::resolve_session_with_csrf(&gstore, req) {
return Some(super::decorate_html_for_session(resp, &user, &csrf));
}
return Some(resp);
}
if req.method == "GET" && path == "/robots.txt" {
return Some(HttpResponse {
status: 200,
content_type: "text/plain; charset=utf-8".into(),
body: b"User-agent: *\nDisallow: /admin\nDisallow: /settings\nDisallow: /api/\n"
.to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if req.method == "GET" && path == "/search" {
return Some(render_cross_repo_search(root, &req.query, req));
}
if matches!(path, "/register" | "/login" | "/logout") {
let global_dir = root.join(".arks-global-auth");
let _ = fs::create_dir_all(&global_dir);
let ctx = super::RepoContext {
name: "arks Multi-Repo Forge".into(),
description: "Global multi-repository authentication".into(),
default_branch: "main".into(),
branches: Vec::new(),
tags: Vec::new(),
clone_url: format!("{scheme}://{host}/"),
has_lfs: false,
};
if req.method == "GET" && path == "/register" {
return Some(render_root_auth_form("Create Global Account", "/register"));
}
if req.method == "GET" && path == "/login" {
return Some(render_root_auth_form("Sign in (Global)", "/login"));
}
if req.method == "POST" && path == "/register" {
if super::auth_api::registration_disabled() {
return Some(super::render_page(
403,
&ctx,
super::ActiveTab::Settings,
"Registration Disabled",
"Public self-registration is disabled by operator policy (ARKS_DISABLE_REGISTRATION).",
));
}
let form = parse_form_urlencoded(&req.body);
let username = form.get("username").map(|s| s.trim()).unwrap_or("");
let password = form.get("password").map(|s| s.as_str()).unwrap_or("");
if username.is_empty() || password.len() < 4 {
return Some(super::render_page(
400,
&ctx,
super::ActiveTab::Settings,
"Invalid registration",
"Username required and password must be at least 4 characters.",
));
}
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
if gstore.corrupt {
return Some(super::auth_api::corrupt_store_response());
}
if gstore.users.iter().any(|u| u.username == username) {
return Some(super::render_page(
409,
&ctx,
super::ActiveTab::Settings,
"User exists",
"Username already exists.",
));
}
let role = if gstore.users.is_empty() {
"admin"
} else {
super::auth_api::default_registration_role()
};
let now = super::store::now_unix();
gstore.users.push(super::store::UserAccount {
username: username.to_string(),
password_hash: super::auth_api::hash_user_password(username, password),
role: role.into(),
ssh_keys: Vec::new(),
created_at: now,
totp_secret_b32: None,
recovery_codes: Vec::new(),
});
let tok = super::auth_api::generate_token("arks_gsess_");
let csrf = super::auth_api::generate_token("csrf_g_");
gstore.sessions.push(super::store::SessionRecord {
token: tok.clone(),
username: username.to_string(),
csrf_token: csrf,
expires_at: now + 86400 * 30,
});
let _ = gstore.commit();
return Some(HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), "/".into()),
(
"Set-Cookie".into(),
super::auth_api::session_cookie_header(&tok, req, false),
),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
],
});
}
if req.method == "POST" && path == "/login" {
let form = parse_form_urlencoded(&req.body);
let username = form.get("username").map(|s| s.trim()).unwrap_or("");
let password = form.get("password").map(String::as_str).unwrap_or("");
if super::auth_api::is_login_rate_limited(username) {
let mut resp = super::render_page(
429,
&ctx,
super::ActiveTab::Settings,
"Too Many Requests",
"<div class=\"card\"><div class=\"card-body\">Too many failed login attempts. Try again in 60 seconds.</div></div>",
);
resp.extra_headers.push(("Retry-After".into(), "60".into()));
return Some(resp);
}
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
if gstore.corrupt {
return Some(super::auth_api::corrupt_store_response());
}
let Some(acct) = gstore
.users
.iter()
.find(|u| {
u.username == username
&& super::auth_api::verify_user_password(
username,
password,
&u.password_hash,
)
})
.cloned()
else {
super::auth_api::record_login_failure(username);
return Some(super::render_page(
401,
&ctx,
super::ActiveTab::Settings,
"Invalid credentials",
"<div class=\"card\"><div class=\"card-body\">Invalid username or password.</div></div>",
));
};
if let Some(ref secret) = acct.totp_secret_b32 {
let totp = form.get("totp").map(|s| s.trim()).unwrap_or("");
let totp_ok = super::admin_2fa::verify_totp_window(
secret,
totp,
super::store::now_unix(),
);
let mut used_recovery = false;
if !totp_ok {
if let Some(u) = gstore.users.iter_mut().find(|u| u.username == username) {
if let Some(pos) = u
.recovery_codes
.iter()
.position(|c| super::auth_api::ct_str_eq(c, totp))
{
u.recovery_codes.remove(pos);
used_recovery = true;
}
}
}
if !totp_ok && !used_recovery {
super::auth_api::record_login_failure(username);
return Some(super::render_page(
401,
&ctx,
super::ActiveTab::Settings,
"2FA Required",
"<div class=\"card\"><div class=\"card-body\">Valid 6-digit TOTP 2FA code or recovery code required.</div></div>",
));
}
}
let now = super::store::now_unix();
let tok = super::auth_api::generate_token("arks_gsess_");
let csrf = super::auth_api::generate_token("csrf_g_");
gstore.sessions.push(super::store::SessionRecord {
token: tok.clone(),
username: username.to_string(),
csrf_token: csrf,
expires_at: now + 86400 * 30,
});
let _ = gstore.commit();
return Some(HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), "/".into()),
(
"Set-Cookie".into(),
super::auth_api::session_cookie_header(&tok, req, false),
),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
],
});
}
if req.method == "POST" && path == "/logout" {
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
if gstore.corrupt {
return Some(super::auth_api::corrupt_store_response());
}
if let Err(denied) =
super::auth_api::verify_logout_csrf(&gstore, req, req.sec_fetch_site.as_deref())
{
return Some(denied);
}
let mut revoked_tokens = Vec::new();
if let Some(ref cookie_hdr) = req.cookie {
for part in cookie_hdr.split(';') {
if let Some(val) = part.trim().strip_prefix("arks_session=") {
gstore.sessions.retain(|s| s.token != val);
revoked_tokens.push(val.to_string());
}
}
}
let _ = gstore.commit();
if !revoked_tokens.is_empty() {
for (_, git_dir, _) in list_repos(root) {
let mut rstore = super::store::ForgeStore::lock_mut(&git_dir);
if rstore.corrupt {
continue;
}
let before = rstore.sessions.len();
rstore
.sessions
.retain(|s| !revoked_tokens.iter().any(|t| t == &s.token));
if rstore.sessions.len() != before {
let _ = rstore.commit();
}
}
}
return Some(HttpResponse {
status: 303,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![
("Location".into(), "/login".into()),
(
"Set-Cookie".into(),
super::auth_api::session_cookie_header("", req, true),
),
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
],
});
}
}
if req.method == "POST" && path == "/new-repo" {
let global_dir = root.join(".arks-global-auth");
let gstore = super::store::ForgeStore::load_shared(&global_dir);
if gstore.corrupt {
return Some(super::auth_api::corrupt_store_response());
}
if let Err(denied) = super::auth_api::enforce_write_rbac(&gstore, req) {
return Some(denied);
}
let form = parse_form_urlencoded(&req.body);
let name = form.get("name").map(|s| s.trim()).unwrap_or("");
let desc = form.get("description").map(|s| s.trim()).unwrap_or("");
return match init_bare_repo(root, name, desc) {
Ok(_) => {
let clean = name.trim().trim_end_matches(".git");
Some(redirect_see_other(&format!("/{clean}/")))
}
Err(e) => Some(HttpResponse {
status: 400,
content_type: "text/plain; charset=utf-8".into(),
body: format!("Failed to create repository: {e}\n").into_bytes(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
}),
};
}
if req.method == "GET" && path == "/style.css" {
return Some(HttpResponse {
status: 200,
content_type: "text/css; charset=utf-8".into(),
body: super::STYLESHEET.as_bytes().to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if req.method == "GET" && path == "/favicon.svg" {
return Some(HttpResponse {
status: 200,
content_type: "image/svg+xml".into(),
body: super::FAVICON_SVG.as_bytes().to_vec(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
});
}
if req.method == "GET" && path.starts_with("/assets/") {
if let Some((_, first_git, _)) = list_repos(root).into_iter().next() {
return handle_web_ui_with_actions(&first_git, req, allow_local_actions);
}
}
}
let trimmed = path.strip_prefix('/').unwrap_or(path);
let (first_seg, after_first) = match trimmed.split_once('/') {
Some((r, p)) => (r, Some(p)),
None => (trimmed, None),
};
let (repo_prefix_key, repo_clean_name, rest, git_dir) =
if let Some(dir) = resolve_repo_git_dir(root, first_seg) {
let clean = first_seg.trim_end_matches(".git").to_string();
let rest = match after_first {
Some(p) if !p.is_empty() => format!("/{p}"),
_ => "/".to_string(),
};
(clean.clone(), clean, rest, dir)
} else if is_valid_repo_name(first_seg) {
let after = after_first?;
let (second_seg, after_second) = match after.split_once('/') {
Some((r, p)) => (r, Some(p)),
None => (after, None),
};
let dir = resolve_repo_git_dir(&root.join(first_seg), second_seg)?;
let clean = second_seg.trim_end_matches(".git").to_string();
let rest = match after_second {
Some(p) if !p.is_empty() => format!("/{p}"),
_ => "/".to_string(),
};
(format!("{first_seg}/{clean}"), clean, rest, dir)
} else {
return None;
};
sync_global_auth_into_repo(root, &git_dir);
let mut sub_req = req.clone();
sub_req.path = rest.clone();
let is_dav = crate::dav::is_dav_method(&sub_req.method);
let is_dav_git_path = is_dav
&& (rest.starts_with("/refs/")
|| rest.starts_with("/objects/")
|| rest.contains("/info/refs")
|| (sub_req.method.eq_ignore_ascii_case("PROPFIND") && rest == "/"));
if rest.contains("/info/refs")
|| rest.contains("/info/lfs/")
|| rest.contains("/git-upload-pack")
|| rest.contains("/git-receive-pack")
|| rest.starts_with("/objects/")
|| rest == "/HEAD"
|| is_dav_git_path
{
let is_dav_write = is_dav && !sub_req.method.eq_ignore_ascii_case("PROPFIND");
let is_write = rest.contains("/git-receive-pack")
|| (rest.contains("/info/refs") && sub_req.query.contains("git-receive-pack"))
|| (rest.contains("/info/lfs/") && sub_req.method == "PUT")
|| is_dav_write;
if !has_basic_auth {
if let Err(denied) = super::auth_api::check_git_http_auth(&git_dir, &sub_req, is_write)
{
return Some(denied);
}
}
let Ok(mut repo) = Repository::open(&git_dir) else {
return Some(HttpResponse {
status: 500,
content_type: "text/plain".into(),
body: b"repository open failed\n".to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
});
};
return match handle_smart_http_auth_opts(&mut repo, &sub_req, None, !disable_lfs, scheme) {
Ok(resp) => Some(resp),
Err(e) => Some(HttpResponse {
status: 500,
content_type: "text/plain".into(),
body: format!("{e}\n").into_bytes(),
www_authenticate: None,
extra_headers: Vec::new(),
}),
};
}
if disable_web_ui {
if rest.starts_with("/api/v1/") || rest.starts_with("/repos/") {
return handle_web_ui_with_actions(&git_dir, &sub_req, allow_local_actions);
}
return None;
}
if req.method == "POST" && rest == "/settings/repo/delete" {
let gstore = super::store::ForgeStore::load_shared(&root.join(".arks-global-auth"));
if gstore.corrupt {
return Some(super::auth_api::corrupt_store_response());
}
let rbac_store = if gstore.users.is_empty() {
super::store::ForgeStore::load_shared(&git_dir)
} else {
gstore
};
if let Err(denied) = super::auth_api::enforce_admin_rbac(&rbac_store, req) {
return Some(denied);
}
let form = parse_form_urlencoded(&req.body);
let clean = repo_clean_name.as_str();
let confirm = form.get("confirm").map(|s| s.trim()).unwrap_or("");
if confirm != clean {
return Some(HttpResponse {
status: 400,
content_type: "text/plain; charset=utf-8".into(),
body: format!("Confirmation mismatch: type '{clean}' to delete repository.\n")
.into_bytes(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
});
}
let _ = fs::remove_dir_all(&git_dir);
return Some(redirect_see_other("/"));
}
let is_ssh_key_mutation = req.method == "POST"
&& (rest == "/settings/keys"
|| (rest.starts_with("/settings/keys/") && rest.ends_with("/delete")));
let prefix = format!("/{repo_prefix_key}");
let resp = handle_web_ui_with_actions(&git_dir, &sub_req, allow_local_actions)
.map(|resp| rewrite_response_for_repo_prefix(resp, &prefix));
if is_ssh_key_mutation {
if let Some(ref r) = resp {
if r.status == 303 {
sync_repo_ssh_keys_to_global(root, &git_dir);
}
}
}
resp
}
pub(crate) fn rewrite_response_for_repo_prefix(
mut resp: HttpResponse,
prefix: &str,
) -> HttpResponse {
for (k, v) in &mut resp.extra_headers {
if k.eq_ignore_ascii_case("location") {
*v = rewrite_repo_prefix_location(v, prefix);
}
}
if resp.content_type.starts_with("text/html") {
if let Ok(html) = String::from_utf8(resp.body.clone()) {
resp.body = rewrite_repo_prefix_html(&html, prefix).into_bytes();
}
}
resp
}
fn is_shared_root_asset(path: &str) -> bool {
path == "/style.css"
|| path == "/favicon.svg"
|| path.starts_with("/assets/")
|| path.starts_with("//")
}
pub(crate) fn rewrite_repo_prefix_location(loc: &str, prefix: &str) -> String {
if !loc.starts_with('/')
|| is_shared_root_asset(loc)
|| loc.starts_with(&format!("{prefix}/"))
|| loc == prefix
{
return loc.to_string();
}
format!("{prefix}{loc}")
}
pub(crate) fn rewrite_repo_prefix_html(html: &str, prefix: &str) -> String {
let mut out = html.replace(
"data-api-prefix=\"\"",
&format!("data-api-prefix=\"{}\"", html_escape(prefix)),
);
for attr in ["href=\"/", "action=\"/", "hx-get=\"/", "hx-post=\"/"] {
let mut rebuilt = String::with_capacity(out.len() + 256);
let mut rest = out.as_str();
while let Some(pos) = rest.find(attr) {
rebuilt.push_str(&rest[..pos]);
let after_quote = &rest[pos + attr.len() - 1..]; let end_quote = after_quote.find('"').unwrap_or(after_quote.len());
let target = &after_quote[..end_quote];
let attr_prefix = &attr[..attr.len() - 1]; rebuilt.push_str(attr_prefix);
if is_shared_root_asset(target)
|| target == prefix
|| target.starts_with(&format!("{prefix}/"))
{
rebuilt.push_str(target);
} else {
rebuilt.push_str(prefix);
rebuilt.push_str(target);
}
rest = &after_quote[end_quote..];
}
rebuilt.push_str(rest);
out = rebuilt;
}
out
}
fn render_dashboard(root: &Path, host: &str, scheme: &str, req: &HttpRequest) -> HttpResponse {
let repos = list_repos(root);
let mut rows = String::new();
let mut visible_count = 0usize;
for (name, git_dir, desc) in &repos {
sync_global_auth_into_repo(root, git_dir);
let rstore = super::store::ForgeStore::load_shared(git_dir);
if !super::auth_api::can_read_repo(&rstore, req) {
continue;
}
visible_count += 1;
let clone_url = format!("{scheme}://{host}/{name}.git");
let vis_badge = if rstore.visibility == "private" {
" <span class=\"badge\">private</span>"
} else {
""
};
rows.push_str(&format!(
"<tr><td><a href=\"/{}/\"><strong>{}</strong></a>{vis_badge}\
<div class=\"muted\">{}</div></td>\
<td class=\"mono mr-clone-cell\"><code>arks clone {}</code></td>\
<td class=\"mr-action-cell\"><a class=\"btn\" href=\"/{}/\">Open</a></td></tr>",
html_escape(name),
html_escape(name),
html_escape(desc),
html_escape(&clone_url),
html_escape(name),
));
}
if rows.is_empty() {
rows.push_str(
"<tr><td colspan=\"3\" class=\"muted\">No repositories yet. Create your first repository below.</td></tr>",
);
}
let html = format!(
"<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<title>arks Multi-Repo Forge</title>\
<link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
<header class=\"mr-header\">\
<div class=\"mr-header-inner\">\
<div class=\"mr-brand\">\
<a href=\"/\"><strong>arks Multi-Repo Forge</strong></a>\
<span class=\"badge badge-green\">{visible_count} repos</span>\
<a class=\"muted\" href=\"/search\">Search</a>\
<a class=\"muted\" href=\"/healthz\">Health</a>\
</div>\
<form class=\"mr-search-form\" method=\"get\" action=\"/search\">\
<input class=\"input\" type=\"search\" name=\"q\" placeholder=\"Search across repos...\" />\
<button class=\"btn\" type=\"submit\">Search</button>\
</form>\
<div class=\"mr-auth-actions\">\
<a class=\"btn\" href=\"/login\">Sign in</a>\
<a class=\"btn\" href=\"/register\">Register</a>\
</div>\
</div>\
</header>\
<main class=\"mr-main\">\
<div class=\"card\"><div class=\"card-header\"><strong>Repositories</strong></div>\
<table class=\"tree-table\">{rows}</table></div>\
<div class=\"card\"><div class=\"card-header\"><strong>New Repository</strong></div>\
<form class=\"card-body mr-new-repo-form\" method=\"post\" action=\"/new-repo\">\
<input class=\"input\" type=\"text\" name=\"name\" placeholder=\"Repository name (e.g. backend)\" required />\
<input class=\"input mr-new-repo-desc\" type=\"text\" name=\"description\" placeholder=\"Description (optional)\" />\
<button class=\"btn btn-primary\" type=\"submit\">Create Repository</button>\
</form></div>\
</main></body></html>"
);
HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
fn ssh_keys_equal(a: &[super::store::SshKeyRecord], b: &[super::store::SshKeyRecord]) -> bool {
a.len() == b.len()
&& a.iter()
.zip(b.iter())
.all(|(x, y)| x.title == y.title && x.public_key == y.public_key)
}
fn sync_repo_ssh_keys_to_global(root: &Path, git_dir: &Path) {
let rstore = super::store::ForgeStore::load_shared(git_dir);
if rstore.corrupt {
return;
}
let global_dir = root.join(".arks-global-auth");
let _ = fs::create_dir_all(&global_dir);
let mut gstore = super::store::ForgeStore::lock_mut(&global_dir);
if gstore.corrupt {
return;
}
for ru in &rstore.users {
if let Some(gu) = gstore.users.iter_mut().find(|u| u.username == ru.username) {
gu.ssh_keys = ru.ssh_keys.clone();
} else {
gstore.users.push(ru.clone());
}
}
super::auth_api::sync_authorized_keys(&global_dir, &gstore);
let _ = gstore.commit();
}
pub(crate) fn sync_global_auth_into_repo(root: &Path, git_dir: &Path) {
use std::collections::HashMap;
use std::sync::{OnceLock, RwLock};
type Stamp = (u64, Option<std::time::SystemTime>);
static SYNCED: OnceLock<RwLock<HashMap<(PathBuf, PathBuf), Stamp>>> = OnceLock::new();
let global_dir = root.join(".arks-global-auth");
let global_store_file = global_dir.join("arks-forge").join("store.json");
let Ok(meta) = fs::metadata(&global_store_file) else {
return;
};
let stamp: Stamp = (meta.len(), meta.modified().ok());
let key = (global_dir.clone(), git_dir.to_path_buf());
let map = SYNCED.get_or_init(|| RwLock::new(HashMap::new()));
if map
.read()
.unwrap_or_else(|e| e.into_inner())
.get(&key)
.copied()
== Some(stamp)
{
return;
}
let gstore = super::store::ForgeStore::load_shared(&global_dir);
if gstore.corrupt {
return;
}
let mut rstore = super::store::ForgeStore::lock_mut(git_dir);
if rstore.corrupt {
return;
}
let mut changed = false;
let mut keys_changed = false;
for u in &gstore.users {
if let Some(existing) = rstore.users.iter_mut().find(|e| e.username == u.username) {
if existing.password_hash != u.password_hash
|| existing.role != u.role
|| existing.totp_secret_b32 != u.totp_secret_b32
{
existing.password_hash = u.password_hash.clone();
existing.role = u.role.clone();
existing.totp_secret_b32 = u.totp_secret_b32.clone();
existing.recovery_codes = u.recovery_codes.clone();
changed = true;
}
if !ssh_keys_equal(&existing.ssh_keys, &u.ssh_keys) {
existing.ssh_keys = u.ssh_keys.clone();
changed = true;
keys_changed = true;
}
} else {
if !u.ssh_keys.is_empty() {
keys_changed = true;
}
rstore.users.push(u.clone());
changed = true;
}
}
let before_sessions = rstore.sessions.len();
rstore.sessions.retain(|s| {
!s.token.starts_with("arks_gsess_") || gstore.sessions.iter().any(|gs| gs.token == s.token)
});
if rstore.sessions.len() != before_sessions {
changed = true;
}
for s in &gstore.sessions {
if !rstore.sessions.iter().any(|e| e.token == s.token) {
rstore.sessions.push(s.clone());
changed = true;
}
}
for p in &gstore.pats {
if !rstore.pats.iter().any(|e| e.token_hash == p.token_hash) {
rstore.pats.push(p.clone());
changed = true;
}
}
if keys_changed {
super::auth_api::sync_authorized_keys(git_dir, &rstore);
}
if changed {
let _ = rstore.commit();
}
map.write()
.unwrap_or_else(|e| e.into_inner())
.insert(key, stamp);
}
fn render_root_auth_form(title: &str, action: &str) -> HttpResponse {
let totp_input = if action == "/login" {
"<input class=\"input\" type=\"text\" name=\"totp\" placeholder=\"2FA TOTP or recovery code (if enabled)\" />"
} else {
""
};
let html = format!(
"<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<title>{title} — arks</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
<main class=\"mr-auth-main\">\
<div class=\"card\"><div class=\"card-header\"><strong>{title}</strong></div>\
<form class=\"card-body mr-auth-form\" method=\"post\" action=\"{action}\">\
<input class=\"input\" type=\"text\" name=\"username\" placeholder=\"Username\" required />\
<input class=\"input\" type=\"password\" name=\"password\" placeholder=\"Password\" required />\
{totp_input}\
<button class=\"btn btn-primary\" type=\"submit\">{title}</button>\
</form></div>\
</main></body></html>"
);
HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
fn render_cross_repo_search(root: &Path, query: &str, req: &HttpRequest) -> HttpResponse {
let params = parse_form_urlencoded(query.as_bytes());
let q = params.get("q").map(|s| s.trim()).unwrap_or("");
let q_low = q.to_ascii_lowercase();
let repos = list_repos(root);
let mut rows = String::new();
let mut hits = 0usize;
if !q_low.is_empty() {
for (repo_name, git_dir, _) in &repos {
sync_global_auth_into_repo(root, git_dir);
let store = super::store::ForgeStore::load_shared(git_dir);
if !super::auth_api::can_read_repo(&store, req) {
continue;
}
for iss in &store.issues {
if iss.title.to_ascii_lowercase().contains(&q_low)
|| iss.body.to_ascii_lowercase().contains(&q_low)
{
hits += 1;
rows.push_str(&format!(
"<tr><td><span class=\"badge\">issue</span> \
<a href=\"/{}/issues/{}\"><strong>{} #{} — {}</strong></a></td></tr>",
html_escape(repo_name),
iss.id,
html_escape(repo_name),
iss.id,
html_escape(&iss.title),
));
}
}
if let Ok(repo) = Repository::open(git_dir) {
let default_br = super::head_branch_label(&repo);
if let Some(oid) = super::resolve_rev_oid(&repo, &default_br) {
if let Ok(tree) = arks_repo::commit_tree_map(&repo, &oid) {
for (path, _) in tree {
if path.to_ascii_lowercase().contains(&q_low) {
hits += 1;
rows.push_str(&format!(
"<tr><td><span class=\"badge badge-green\">file</span> \
<a href=\"/{}/blob/{}/{}\"><strong>{}/{}</strong></a></td></tr>",
html_escape(repo_name),
html_escape(&default_br),
html_escape(&path),
html_escape(repo_name),
html_escape(&path),
));
}
}
}
}
}
}
}
if rows.is_empty() {
rows.push_str("<tr><td class=\"muted\">No cross-repository matches found.</td></tr>");
}
let html = format!(
"<!doctype html><html lang=\"en\" data-theme=\"dark\"><head><meta charset=\"utf-8\">\
<title>Global Search — arks</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>\
<main class=\"mr-main\">\
<h1>Global Cross-Repo Search <span class=\"badge badge-green\">{hits} hits</span></h1>\
<form class=\"mr-search-bar\" method=\"get\" action=\"/search\">\
<input class=\"input\" type=\"text\" name=\"q\" value=\"{}\" placeholder=\"Search files & issues across all repos...\" />\
<button class=\"btn btn-primary\" type=\"submit\">Search</button>\
</form>\
<div class=\"card\"><table class=\"tree-table\">{rows}</table></div>\
</main></body></html>",
html_escape(q),
);
HttpResponse {
status: 200,
content_type: "text/html; charset=utf-8".into(),
body: html.into_bytes(),
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rewrite_repo_prefix_html_rewrites_data_api_prefix() {
let html = "<div id=\"repo-root\" data-api-prefix=\"\"><a href=\"/pulls\">Pulls</a></div>";
let out = rewrite_repo_prefix_html(html, "/alpha");
assert!(out.contains("data-api-prefix=\"/alpha\""));
assert!(out.contains("href=\"/alpha/pulls\""));
}
#[test]
fn multi_repo_honors_disable_web_ui_disable_lfs_and_forwarded_proto() {
let root = tempfile::tempdir().unwrap();
let _bare = init_bare_repo(root.path(), "alpha", "Alpha Repo").unwrap();
let req_root = HttpRequest::new("GET", "/", "", Vec::new());
assert!(handle_multi_repo_opts(root.path(), &req_root, false, false, true).is_none());
let req_repo_ui = HttpRequest::new("GET", "/alpha/", "", Vec::new());
assert!(handle_multi_repo_opts(root.path(), &req_repo_ui, false, false, true).is_none());
let req_lfs = HttpRequest::new(
"POST",
"/alpha.git/info/lfs/objects/batch",
"",
b"{\"operation\":\"download\",\"objects\":[]}".to_vec(),
);
let resp_lfs = handle_multi_repo_opts(root.path(), &req_lfs, false, true, false).unwrap();
assert_eq!(resp_lfs.status, 404);
let mut req_https = HttpRequest::new("GET", "/", "", Vec::new());
req_https.host = Some("git.example.invalid".into());
req_https.forwarded_proto = Some("https".into());
let dash = handle_multi_repo_opts(root.path(), &req_https, false, false, false).unwrap();
let html = String::from_utf8(dash.body).unwrap();
assert!(html.contains("https://git.example.invalid/alpha.git"));
}
#[test]
fn multi_repo_syncs_ssh_keys_to_global_authorized_keys_on_add_and_delete() {
let root = tempfile::tempdir().unwrap();
let _bare = init_bare_repo(root.path(), "beta", "Beta Repo").unwrap();
let add_req = HttpRequest::new(
"POST",
"/beta/settings/keys",
"",
b"username=alice&title=devkey&public_key=ssh-ed25519+AAAAC3NzaC1lZDI1NTE5AAAAITestKey"
.to_vec(),
);
let add_resp = handle_multi_repo_opts(root.path(), &add_req, false, false, false).unwrap();
assert_eq!(add_resp.status, 303);
let global_ak = root
.path()
.join(".arks-global-auth")
.join("arks-forge")
.join("authorized_keys");
let ak_added = fs::read_to_string(&global_ak).unwrap();
assert!(ak_added.contains("AAAAC3NzaC1lZDI1NTE5AAAAITestKey"));
{
let global_dir = root.path().join(".arks-global-auth");
let mut gstore = super::super::store::ForgeStore::lock_mut(&global_dir);
gstore.sessions.push(super::super::store::SessionRecord {
token: "arks_gsess_alice".into(),
username: "alice".into(),
csrf_token: "csrf_alice".into(),
expires_at: super::super::store::now_unix() + 3600,
});
gstore.commit().unwrap();
}
let mut del_req = HttpRequest::new(
"POST",
"/beta/settings/keys/alice/0/delete",
"",
b"_csrf=csrf_alice".to_vec(),
);
del_req.cookie = Some("arks_session=arks_gsess_alice".into());
let del_resp = handle_multi_repo_opts(root.path(), &del_req, false, false, false).unwrap();
assert_eq!(del_resp.status, 303);
let ak_after = fs::read_to_string(&global_ak).unwrap();
assert!(!ak_after.contains("AAAAC3NzaC1lZDI1NTE5AAAAITestKey"));
}
#[test]
fn list_repos_discovers_nested_owner_repo_and_logout_revokes_nested_sessions() {
let root = tempfile::tempdir().unwrap();
let _alpha = init_bare_repo(root.path(), "alpha", "Alpha Repo").unwrap();
let acme_dir = root.path().join("acme");
fs::create_dir_all(&acme_dir).unwrap();
let nested_bare = init_bare_repo(&acme_dir, "service", "Acme Service").unwrap();
let hidden_dir = root.path().join(".hidden");
fs::create_dir_all(&hidden_dir).unwrap();
let _hidden_repo = init_bare_repo(&hidden_dir, "secret", "Hidden").unwrap();
fs::create_dir_all(root.path().join(".arks-global-auth")).unwrap();
fs::create_dir_all(root.path().join(".git")).unwrap();
fs::write(
root.path().join(".git").join("HEAD"),
"ref: refs/heads/main\n",
)
.unwrap();
fs::create_dir_all(acme_dir.join(".nested-hidden")).unwrap();
fs::write(
acme_dir.join(".nested-hidden").join("HEAD"),
"ref: refs/heads/main\n",
)
.unwrap();
let names: Vec<String> = list_repos(root.path())
.into_iter()
.map(|(name, _, _)| name)
.collect();
assert_eq!(names, vec!["acme/service".to_string(), "alpha".to_string()]);
let global_dir = root.path().join(".arks-global-auth");
{
let mut gstore = super::super::store::ForgeStore::lock_mut(&global_dir);
gstore.users.push(super::super::store::UserAccount {
username: "alice".into(),
password_hash: super::super::auth_api::hash_user_password("alice", "pw"),
role: "admin".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
});
gstore.sessions.push(super::super::store::SessionRecord {
token: "arks_gsess_nested".into(),
username: "alice".into(),
csrf_token: "csrf_nested".into(),
expires_at: super::super::store::now_unix() + 3600,
});
gstore.commit().unwrap();
}
sync_global_auth_into_repo(root.path(), &nested_bare);
assert!(
super::super::store::ForgeStore::load_shared(&nested_bare)
.sessions
.iter()
.any(|s| s.token == "arks_gsess_nested")
);
let mut logout_req = HttpRequest::new("POST", "/logout", "", b"_csrf=csrf_nested".to_vec());
logout_req.cookie = Some("arks_session=arks_gsess_nested".into());
let logout_resp =
handle_multi_repo_opts(root.path(), &logout_req, false, false, false).unwrap();
assert_eq!(logout_resp.status, 303);
assert!(
super::super::store::ForgeStore::load_shared(&nested_bare)
.sessions
.is_empty(),
"global logout must revoke sessions in nested <owner>/<repo>.git repositories"
);
}
#[test]
fn multi_repo_enforces_webdav_write_auth_and_basic_auth_parity() {
let root = tempfile::tempdir().unwrap();
let alpha = init_bare_repo(root.path(), "alpha", "Alpha Repo").unwrap();
{
let mut st = super::super::store::ForgeStore::lock_mut(&alpha);
st.users.push(super::super::store::UserAccount {
username: "admin".into(),
password_hash: super::super::auth_api::hash_user_password("admin", "pw"),
role: "admin".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
});
st.users.push(super::super::store::UserAccount {
username: "reader".into(),
password_hash: super::super::auth_api::hash_user_password("reader", "pw"),
role: "reader".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
});
st.commit().unwrap();
}
for (method, path) in [
("PUT", "/alpha.git/refs/heads/hijack"),
("DELETE", "/alpha.git/refs/heads/main"),
("LOCK", "/alpha.git/refs/heads/main"),
("MKCOL", "/alpha.git/objects/ab"),
] {
let req = HttpRequest::new(method, path, "", Vec::new());
let resp =
handle_multi_repo_full(root.path(), &req, false, false, false, false).unwrap();
assert_eq!(
resp.status, 401,
"anonymous WebDAV {method} {path} must require authentication"
);
}
let mut reader_put = HttpRequest::new(
"PUT",
"/alpha.git/refs/heads/hijack",
"",
b"1111111111111111111111111111111111111111\n".to_vec(),
);
reader_put.authorization = Some(crate::basic_authorization_header("reader", "pw"));
let reader_resp =
handle_multi_repo_full(root.path(), &reader_put, false, false, false, false).unwrap();
assert_eq!(reader_resp.status, 403);
let propfind_req = HttpRequest::new("PROPFIND", "/alpha.git/", "", Vec::new());
let propfind_resp =
handle_multi_repo_full(root.path(), &propfind_req, false, false, false, false).unwrap();
assert_eq!(propfind_resp.status, 207);
let adv_req = HttpRequest::new(
"GET",
"/alpha.git/info/refs",
"service=git-receive-pack",
Vec::new(),
);
assert_eq!(
handle_multi_repo_full(root.path(), &adv_req, false, false, false, false)
.unwrap()
.status,
401
);
assert_eq!(
handle_multi_repo_full(root.path(), &adv_req, false, false, false, true)
.unwrap()
.status,
200
);
let mkcol_req = HttpRequest::new("MKCOL", "/alpha.git/objects/ab", "", Vec::new());
assert_eq!(
handle_multi_repo_full(root.path(), &mkcol_req, false, false, false, true)
.unwrap()
.status,
201
);
}
}