use super::store::parse_form_urlencoded;
use super::{WEB_UI_CSP, handle_web_ui_with_actions, handle_web_ui_with_mount, redirect_see_other};
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use crate::serve::PageHandler;
use crate::web::core::ctx::{MountPrefix, RequestCtx};
use crate::web::core::html::{Attr, HtmlBuf, Render};
use crate::web::ui::components::{Badge, BadgeTone, Card, Form, TextInput};
use crate::web::ui::shell::{Page, ShellKind, respond_page};
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 == "OPTIONS" {
let allow = match path {
"/" | "" | "/robots.txt" | "/search" => Some("GET, HEAD, OPTIONS"),
"/register" | "/login" => Some("GET, HEAD, POST, OPTIONS"),
"/logout" => Some("POST, OPTIONS"),
_ => None,
};
if let Some(allow) = allow {
return Some(HttpResponse {
status: 204,
content_type: "text/plain; charset=utf-8".into(),
body: Vec::new(),
www_authenticate: None,
extra_headers: vec![("Allow".into(), allow.into())],
});
}
}
if matches!(req.method.as_str(), "GET" | "HEAD") && (path == "/" || path.is_empty()) {
let req_ctx = global_request_ctx(root, req);
return Some(render_dashboard(root, host, scheme, &req_ctx));
}
if matches!(req.method.as_str(), "GET" | "HEAD") && 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 matches!(req.method.as_str(), "GET" | "HEAD") && path == "/search" {
let req_ctx = global_request_ctx(root, req);
return Some(render_cross_repo_search(root, &req.query, &req_ctx));
}
if matches!(path, "/register" | "/login" | "/logout") {
let global_dir = root.join(".arks-global-auth");
let _ = fs::create_dir_all(&global_dir);
let req_ctx = global_request_ctx(root, req);
if matches!(req.method.as_str(), "GET" | "HEAD") && path == "/register" {
return Some(render_root_auth_form(
&req_ctx,
"Create Global Account",
"/register",
));
}
if matches!(req.method.as_str(), "GET" | "HEAD") && path == "/login" {
return Some(render_root_auth_form(
&req_ctx,
"Sign in (Global)",
"/login",
));
}
if req.method == "POST" && path == "/register" {
if super::auth_api::registration_disabled() {
return Some(render_root_auth_message(
&req_ctx,
403,
"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(render_root_auth_message(
&req_ctx,
400,
"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(render_root_auth_message(
&req_ctx,
409,
"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(),
external_ids: 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: super::auth_api::hash_session_token(&tok),
username: username.to_string(),
csrf_token: csrf,
expires_at: now + super::auth_api::SESSION_ABS_SECS,
last_seen_at: now,
});
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 = render_root_auth_message(
&req_ctx,
429,
"Too Many Requests",
"Too many failed login attempts. Try again in 60 seconds.",
);
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(render_root_auth_message(
&req_ctx,
401,
"Invalid credentials",
"Invalid username or password.",
));
};
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(render_root_auth_message(
&req_ctx,
401,
"2FA Required",
"Valid 6-digit TOTP 2FA code or recovery code required.",
));
}
}
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: super::auth_api::hash_session_token(&tok),
username: username.to_string(),
csrf_token: csrf,
expires_at: now + super::auth_api::SESSION_ABS_SECS,
last_seen_at: now,
});
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 {
if let Some(val) = super::auth_api::extract_session_cookie_value(cookie_hdr) {
gstore
.sessions
.retain(|s| !super::auth_api::session_token_matches(&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| super::auth_api::session_token_matches(&s.token, t))
});
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 let Some(asset_resp) = crate::web::core::assets::serve_core_asset(req) {
return Some(asset_resp);
}
if let Some(pwa_resp) = crate::web::core::pwa::serve_pwa_route(req) {
return Some(pwa_resp);
}
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_mount(
&git_dir,
&sub_req,
allow_local_actions,
MountPrefix::new(&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
}
fn global_request_ctx<'a>(root: &Path, req: &'a HttpRequest) -> RequestCtx<'a> {
let global_dir = root.join(".arks-global-auth");
let gstore = super::store::ForgeStore::load_shared(&global_dir);
let session = super::auth_api::resolve_session_ctx(&gstore, req);
RequestCtx::new(req, MountPrefix::root())
.with_session(session)
.with_store(gstore)
}
fn render_root_auth_message(
req_ctx: &RequestCtx<'_>,
status: u16,
title: &str,
message: &str,
) -> HttpResponse {
respond_page(
req_ctx,
Page {
status,
title,
description: "Global multi-repository authentication",
shell: ShellKind::MinimalAuth,
main: Card::flush_simple(title, |b: &mut HtmlBuf| {
b.el("div", &[Attr::Class("card-body")], message);
}),
extra_css: &[],
extra_js: &[],
},
)
}
fn render_dashboard(
root: &Path,
host: &str,
scheme: &str,
req_ctx: &RequestCtx<'_>,
) -> HttpResponse {
let repos = list_repos(root);
let mut visible: Vec<(String, String, String, bool)> = Vec::new();
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_ctx.req) {
continue;
}
let clone_url = format!("{scheme}://{host}/{name}.git");
let is_private = rstore.visibility == "private";
visible.push((name.clone(), desc.clone(), clone_url, is_private));
}
let visible_count = visible.len();
respond_page(
req_ctx,
Page {
status: 200,
title: "arks Multi-Repo Forge",
description: "Self-hosted multi-repository Git forge powered by arks serve",
shell: ShellKind::MultiRepoRoot {
repo_count: Some(visible_count),
},
main: |out: &mut HtmlBuf| {
Card::flush_simple("Repositories", |c: &mut HtmlBuf| {
c.el("table", &[Attr::Class("tree-table")], |t: &mut HtmlBuf| {
if visible.is_empty() {
t.el("tr", &[], |tr: &mut HtmlBuf| {
tr.el(
"td",
&[Attr::Colspan("3"), Attr::Class("muted")],
"No repositories yet. Create your first repository below.",
);
});
} else {
for (name, desc, clone_url, is_private) in &visible {
let href = format!("/{name}/");
let clone_cmd = format!("arks clone {clone_url}");
t.el("tr", &[], |tr: &mut HtmlBuf| {
tr.el("td", &[], |td: &mut HtmlBuf| {
td.el("a", &[Attr::Href(&href)], |a: &mut HtmlBuf| {
a.el("strong", &[], name.as_str());
});
if *is_private {
td.text(" ");
Badge::new("private", BadgeTone::Neutral).render_to(td);
}
td.el("div", &[Attr::Class("muted")], desc.as_str());
});
tr.el(
"td",
&[Attr::Class("mono mr-clone-cell")],
|td: &mut HtmlBuf| {
td.el("code", &[], clone_cmd.as_str());
},
);
tr.el(
"td",
&[Attr::Class("mr-action-cell")],
|td: &mut HtmlBuf| {
td.el(
"a",
&[Attr::Class("btn"), Attr::Href(&href)],
"Open",
);
},
);
});
}
}
});
})
.render_to(out);
Card::flush_simple("New Repository", |c: &mut HtmlBuf| {
Form::post(
req_ctx,
"/new-repo",
"card-body mr-new-repo-form",
|f: &mut HtmlBuf| {
TextInput::text("name", "", "Repository name (e.g. backend)")
.required()
.render_to(f);
TextInput::text("description", "", "Description (optional)")
.with_class("mr-new-repo-desc")
.render_to(f);
f.el(
"button",
&[Attr::Class("btn btn-primary"), Attr::Type("submit")],
"Create Repository",
);
},
)
.render_to(c);
})
.render_to(out);
},
extra_css: &[],
extra_js: &[],
},
)
}
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;
}
merge_repo_users_into_global(&mut gstore.users, &rstore.users);
super::auth_api::sync_authorized_keys(&global_dir, &gstore);
let _ = gstore.commit();
}
pub(crate) fn merge_repo_users_into_global(
global: &mut Vec<super::store::UserAccount>,
repo_users: &[super::store::UserAccount],
) {
let bootstrap = global.is_empty();
for ru in repo_users {
if let Some(gu) = global.iter_mut().find(|u| u.username == ru.username) {
gu.ssh_keys = ru.ssh_keys.clone();
} else {
let mut imported = ru.clone();
if !bootstrap {
imported.role = "reader".into();
imported.totp_secret_b32 = None;
imported.recovery_codes = Vec::new();
}
global.push(imported);
}
}
}
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(req_ctx: &RequestCtx<'_>, title: &str, action: &str) -> HttpResponse {
let page_title = format!("{title} — arks");
respond_page(
req_ctx,
Page {
status: 200,
title: &page_title,
description: "Global multi-repository authentication",
shell: ShellKind::MinimalAuth,
main: Card::flush_simple(title, |c: &mut HtmlBuf| {
Form::post(
req_ctx,
action,
"card-body mr-auth-form",
|f: &mut HtmlBuf| {
TextInput::text("username", "", "Username")
.required()
.render_to(f);
TextInput::password("password", "Password")
.required()
.render_to(f);
if action == "/login" {
TextInput::text("totp", "", "2FA TOTP or recovery code (if enabled)")
.render_to(f);
}
f.el(
"button",
&[Attr::Class("btn btn-primary"), Attr::Type("submit")],
title,
);
},
)
.render_to(c);
}),
extra_css: &[],
extra_js: &[],
},
)
}
fn render_cross_repo_search(root: &Path, query: &str, req_ctx: &RequestCtx<'_>) -> 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);
enum SearchHit {
Issue {
repo: String,
id: u64,
title: String,
},
File {
repo: String,
branch: String,
path: String,
},
}
let mut matches: Vec<SearchHit> = Vec::new();
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_ctx.req) {
continue;
}
for iss in &store.issues {
if iss.title.to_ascii_lowercase().contains(&q_low)
|| iss.body.to_ascii_lowercase().contains(&q_low)
{
matches.push(SearchHit::Issue {
repo: repo_name.clone(),
id: iss.id,
title: iss.title.clone(),
});
}
}
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) {
matches.push(SearchHit::File {
repo: repo_name.clone(),
branch: default_br.clone(),
path,
});
}
}
}
}
}
}
}
let hits_label = format!("{} hits", matches.len());
respond_page(
req_ctx,
Page {
status: 200,
title: "Global Search — arks",
description: "Cross-repository file and issue search",
shell: ShellKind::MultiRepoRoot { repo_count: None },
main: |out: &mut HtmlBuf| {
out.el("h1", &[], |h: &mut HtmlBuf| {
h.text("Global Cross-Repo Search ");
Badge::new(&hits_label, BadgeTone::Green).render_to(h);
});
Form::get("/search", "mr-search-bar", |f: &mut HtmlBuf| {
TextInput::text("q", q, "Search files & issues across all repos...")
.render_to(f);
f.el(
"button",
&[Attr::Class("btn btn-primary"), Attr::Type("submit")],
"Search",
);
})
.render_to(out);
out.el("div", &[Attr::Class("card")], |c: &mut HtmlBuf| {
c.el("table", &[Attr::Class("tree-table")], |t: &mut HtmlBuf| {
if matches.is_empty() {
t.el("tr", &[], |tr: &mut HtmlBuf| {
tr.el(
"td",
&[Attr::Class("muted")],
"No cross-repository matches found.",
);
});
} else {
for hit in &matches {
t.el("tr", &[], |tr: &mut HtmlBuf| {
tr.el("td", &[], |td: &mut HtmlBuf| match hit {
SearchHit::Issue { repo, id, title } => {
Badge::new("issue", BadgeTone::Neutral).render_to(td);
td.text(" ");
let href = format!("/{repo}/issues/{id}");
let label = format!("{repo} #{id} — {title}");
td.el("a", &[Attr::Href(&href)], |a: &mut HtmlBuf| {
a.el("strong", &[], label.as_str());
});
}
SearchHit::File { repo, branch, path } => {
Badge::new("file", BadgeTone::Green).render_to(td);
td.text(" ");
let href = format!("/{repo}/blob/{branch}/{path}");
let label = format!("{repo}/{path}");
td.el("a", &[Attr::Href(&href)], |a: &mut HtmlBuf| {
a.el("strong", &[], label.as_str());
});
}
});
});
}
}
});
});
},
extra_css: &[],
extra_js: &[],
},
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn multi_repo_first_pass_ssr_emits_mount_prefix_and_native_csrf() {
let root = tempfile::tempdir().unwrap();
let _bare = init_bare_repo(root.path(), "alpha", "Alpha Repo").unwrap();
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(),
external_ids: Vec::new(),
});
gstore.sessions.push(super::super::store::SessionRecord {
token: "arks_sess_fp".into(),
username: "alice".into(),
csrf_token: "csrf_fp_token".into(),
expires_at: super::super::store::now_unix() + 3600,
last_seen_at: 0,
});
gstore.commit().unwrap();
}
let mut req = HttpRequest::new("GET", "/alpha/issues", "", Vec::new());
req.cookie = Some("arks_session=arks_sess_fp".into());
let resp = handle_multi_repo_opts(root.path(), &req, false, false, false).unwrap();
assert_eq!(resp.status, 200);
let html = String::from_utf8(resp.body).unwrap();
assert!(html.contains("<meta name=\"arks-mount\" content=\"/alpha\">"));
assert!(html.contains("<meta name=\"arks-csrf\" content=\"csrf_fp_token\">"));
assert!(html.contains("action=\"/alpha/issues\""));
assert!(html.contains("name=\"_csrf\" value=\"csrf_fp_token\""));
assert!(html.contains("href=\"/alpha/pulls\""));
assert!(html.contains("@alice"));
let mut post_req = HttpRequest::new(
"POST",
"/alpha/issues",
"",
b"_csrf=csrf_fp_token&title=First+Pass+Issue".to_vec(),
);
post_req.cookie = Some("arks_session=arks_sess_fp".into());
let post_resp =
handle_multi_repo_opts(root.path(), &post_req, false, false, false).unwrap();
assert_eq!(post_resp.status, 303);
assert!(
post_resp
.extra_headers
.iter()
.any(|(k, v)| k.eq_ignore_ascii_case("location") && v == "/alpha/issues/1"),
"POST /alpha/issues must redirect to /alpha/issues/1 natively"
);
let mut htmx_req = HttpRequest::new("GET", "/alpha/issues", "", Vec::new());
htmx_req.cookie = Some("arks_session=arks_sess_fp".into());
htmx_req.headers.push(("HX-Request".into(), "true".into()));
htmx_req
.headers
.push(("HX-Target".into(), "main-content".into()));
let partial = handle_multi_repo_opts(root.path(), &htmx_req, false, false, false).unwrap();
assert_eq!(partial.status, 200);
let frag = String::from_utf8(partial.body).unwrap();
assert!(!frag.contains("<!doctype html>"));
assert!(frag.contains("First Pass Issue"));
}
#[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,
last_seen_at: 0,
});
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(),
external_ids: 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,
last_seen_at: 0,
});
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(),
external_ids: 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(),
external_ids: 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
);
}
#[test]
fn empty_multi_repo_root_serves_core_assets_and_native_mount_meta() {
let root = tempfile::tempdir().unwrap();
let js_req = HttpRequest::new("GET", "/assets/app.js", "", Vec::new());
let js_resp = handle_multi_repo(root.path(), &js_req, false)
.expect("empty multi-repo root must serve /assets/app.js");
assert_eq!(js_resp.status, 200);
let etag = js_resp
.extra_headers
.iter()
.find(|(k, _)| k == "ETag")
.map(|(_, v)| v.clone())
.expect("ETag header on /assets/app.js");
let mut cached_req = HttpRequest::new("GET", "/assets/app.js", "", Vec::new());
cached_req.headers.push(("If-None-Match".into(), etag));
let cached_resp = handle_multi_repo(root.path(), &cached_req, false).unwrap();
assert_eq!(cached_resp.status, 304);
let root_req = HttpRequest::new("GET", "/", "", Vec::new());
let root_resp = handle_multi_repo(root.path(), &root_req, false).unwrap();
assert_eq!(root_resp.status, 200);
let html = String::from_utf8(root_resp.body).unwrap();
assert!(html.contains("<meta name=\"arks-mount\" content=\"\">"));
}
}
#[cfg(test)]
mod global_merge_tests {
use super::merge_repo_users_into_global;
use crate::web_ui::store::UserAccount;
fn user(name: &str, role: &str) -> UserAccount {
UserAccount {
username: name.into(),
password_hash: String::new(),
role: role.into(),
ssh_keys: Vec::new(),
created_at: 0,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
}
}
#[test]
fn repo_local_admin_is_not_escalated_into_global_store() {
let mut global = vec![user("root", "admin")];
merge_repo_users_into_global(&mut global, &[user("mallory", "admin")]);
let m = global.iter().find(|u| u.username == "mallory").unwrap();
assert_eq!(m.role, "reader");
}
#[test]
fn known_global_user_keeps_global_role() {
let mut global = vec![user("root", "admin"), user("bob", "reader")];
merge_repo_users_into_global(&mut global, &[user("bob", "admin")]);
let b = global.iter().find(|u| u.username == "bob").unwrap();
assert_eq!(b.role, "reader");
}
#[test]
fn bootstrap_global_store_keeps_operator_role() {
let mut global = Vec::new();
merge_repo_users_into_global(&mut global, &[user("op", "admin")]);
assert_eq!(global[0].role, "admin");
}
}