GITv

Send HSTS, keep access logs, and log every sign-in attempt

Browse files

Caddy now sends Strict-Transport-Security and writes a rotated JSON access log, which leaves cookie and authorization values out. gitv-web logs each judged sign-in and password change to the journal with the client's address (or IPv6 /64) and whether the password or the code was wrong, so a known password shows up as "right password, wrong code". Attempts refused during a lockout aren't logged, so a flood can't fill the journal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 16:00
Commit
a26d15d9b761
Parent
ddf3dff

6 files changed +102−10

+10−0
@@ -93,6 +93,16 @@ Fedora's distribution-provided systemd defaults. OpenSSH uses
`deploy/gitv-purge.service` and `deploy/gitv-purge.timer` in `/etc/systemd/system`, enabled with
`systemctl enable --now gitv-purge.timer`.
**Logs.** Caddy sends HSTS (a year, so browsers never fall back to plain HTTP) and writes one JSON line per request to `/var/log/caddy/gitv-access.log`. The log rotates at 50 MiB and keeps 30 days; Caddy leaves cookie and authorization values out of it. Create the folder for Caddy once with `install -d -o caddy -g caddy -m 0750 /var/log/caddy`, then run `caddy validate --config /etc/caddy/Caddyfile` before reloading.
gitv-web logs every judged sign-in and password change to the journal, with the client's address (or IPv6 /64) and whether the password or the code was wrong:
```sh
journalctl -u gitv-web -g 'sign-in|password change'
```
`right password, wrong code` means someone knows the password: change it. Attempts refused while a client is locked out aren't logged, so a flood can't fill the journal.
## Backups
`deploy/gitv-backup` snapshots everything the server can't rebuild: the repositories (with their trash, reflogs, push logs and visibility markers), `/etc/gitv` (the SSH keys) and `/var/lib/gitv-web` (the web sign-in). Each snapshot is a plain copy in `/mnt/gitv-backup/gitv/snapshots/<UTC time>/`. Files unchanged since the previous snapshot are hard links to it, so a day's snapshot costs only what changed. Each repository is copied under a lock that pushes also take, so no copy catches a push half way. Every copy is then checked with `git fsck`, and only a snapshot that passes becomes `latest`. Snapshots are kept for 30 days.
@@ -1,3 +1,18 @@
git.um9i.dev {
reverse_proxy 127.0.0.1:8080
# Browsers that have visited once refuse plain HTTP for a year, so the Secure session
# cookie can't be stripped by a downgrade.
header Strict-Transport-Security "max-age=31536000; includeSubDomains"
# One JSON line per request. Caddy leaves Cookie, Set-Cookie and Authorization values
# out of these logs, so session tokens never reach the disk.
log {
output file /var/log/caddy/gitv-access.log {
roll_size 50MiB
roll_keep 10
roll_keep_for 720h
}
format json
}
reverse_proxy 127.0.0.1:8080
}
@@ -173,6 +173,7 @@ impl Login {
/// and the lock it causes, and a cancelled request still counts.
async fn check(
self: &Arc<Self>,
purpose: &'static str,
credentials: &Arc<Credentials>,
client: Client,
user: Option<String>,
@@ -190,7 +191,7 @@ impl Login {
let _permit = permit;
let user_ok = user.is_none_or(|u| creds.user_matches(&u));
let password_ok = creds.verify_password(&password) && user_ok;
login.settle(&creds, client, password_ok, &code)
login.settle(purpose, &creds, client, password_ok, &code)
})
.await
.unwrap_or(Checked::Wrong)
@@ -199,7 +200,18 @@ impl Login {
/// Record a check's result. The code is checked and used up in one step, under the account
/// file's lock and recorded on disk, so it works once: across simultaneous requests,
/// restarts and processes alike.
fn settle(&self, credentials: &Credentials, client: Client, password_ok: bool, code: &str) -> Checked {
///
/// Every judged attempt goes to the log (the journal, under systemd) with the client, and
/// whether the password or the code was wrong. Visitors only ever hear that something was;
/// the operator can see a right password with a wrong code, which means the password is known.
fn settle(
&self,
purpose: &'static str,
credentials: &Credentials,
client: Client,
password_ok: bool,
code: &str,
) -> Checked {
let code_ok = password_ok
&& match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) {
Ok(accepted) => accepted,
@@ -211,13 +223,21 @@ impl Login {
let mut throttle = self.throttle();
if code_ok {
throttle.succeed(client);
eprintln!("gitv-web: {purpose} succeeded from {client}");
Checked::Right
} else {
let now = Instant::now();
throttle.fail(client, now);
let wrong = if password_ok { "right password, wrong code" } else { "wrong password" };
match throttle.locked_for(client, now) {
Some(wait) => Checked::Locked(wait),
None => Checked::Wrong,
Some(wait) => {
eprintln!("gitv-web: {purpose} failed from {client} ({wrong}); locked out for {}s", wait.as_secs());
Checked::Locked(wait)
}
None => {
eprintln!("gitv-web: {purpose} failed from {client} ({wrong})");
Checked::Wrong
}
}
}
}
@@ -379,7 +399,7 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo
return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.");
}
};
match login.check(&credentials, client, Some(form.user), form.password, &form.code).await {
match login.check("sign-in", &credentials, client, Some(form.user), form.password, &form.code).await {
Checked::Right => {}
Checked::Locked(wait) => return locked_page(wait),
Checked::Unavailable => {
@@ -495,7 +515,7 @@ pub async fn change_password(
if let Err(error) = check_new_password(&form.new) {
return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}."));
}
match login.check(&credentials, client, None, form.current, &form.code).await {
match login.check("password change", &credentials, client, None, form.current, &form.code).await {
Checked::Right => {}
Checked::Locked(wait) => {
return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait)));
@@ -688,7 +708,7 @@ mod tests {
.map(|_| {
let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials));
tokio::spawn(async move {
login.check(&credentials, unknown(), None, "a wrong guess".into(), "123456").await
login.check("sign-in", &credentials, unknown(), None, "a wrong guess".into(), "123456").await
})
})
.collect();
@@ -68,6 +68,16 @@ impl Client {
}
}
/// The address, or the /64 for IPv6, as the logs show it.
impl std::fmt::Display for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
IpAddr::V4(v4) => write!(f, "{v4}"),
IpAddr::V6(v6) => write!(f, "{v6}/64"),
}
}
}
impl<S: Send + Sync> FromRequestParts<S> for Client {
type Rejection = std::convert::Infallible;
@@ -240,6 +250,12 @@ mod tests {
assert_eq!(ip("::ffff:203.0.113.7"), ip("203.0.113.7"));
}
#[test]
fn clients_show_as_their_address_or_64() {
assert_eq!(ip("203.0.113.7").to_string(), "203.0.113.7");
assert_eq!(ip("2001:db8:1:2:aaaa::1").to_string(), "2001:db8:1:2::/64");
}
#[test]
fn forwarded_addresses_are_believed_only_from_loopback() {
let parts = |peer: &str, forwarded: Option<&str>| {
@@ -235,6 +235,27 @@ mod signing_in {
assert_eq!(attempt("2001:db8:9:9::2", "wrong password", "000000"), 429);
}
#[test]
fn attempts_are_logged_with_their_client_and_what_was_wrong() {
let s = Server::start_signed_out(repos());
let attempt = |address: &str, password: &str, code: &str| {
let form = [("user", "Um9i"), ("password", password), ("code", code), ("next", "/")];
s.post_signed_out_from(address, "/login", &form).status
};
assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 401);
// A code valid in none of the steps the server accepts (one either side of now).
let valid = [s.account.code(-1), s.account.code(0), s.account.code(1)];
let wrong_code =
["000000", "111111", "222222", "333333"].into_iter().find(|c| !valid.iter().any(|v| v == c)).unwrap();
assert_eq!(attempt("203.0.113.8", &s.account.password, wrong_code), 401);
assert_eq!(attempt("2001:db8:1:2::5", &s.account.password, &s.account.code(0)), 303);
let log = s.logged();
assert!(log.contains("sign-in failed from 203.0.113.7 (wrong password)"), "{log}");
assert!(log.contains("sign-in failed from 203.0.113.8 (right password, wrong code)"), "{log}");
assert!(log.contains("sign-in succeeded from 2001:db8:1:2::/64"), "{log}");
assert!(!log.contains(&s.account.password), "the password never reaches the log");
}
#[test]
fn a_forged_cookie_is_not_a_session() {
let mut s = Server::start_signed_out(repos());
@@ -180,6 +180,8 @@ pub struct Server {
pub port: u16,
pub account: Account,
pub cookie: Option<String>,
/// Where the server's stderr (its log) goes.
pub log: PathBuf,
}
impl Server {
@@ -233,12 +235,15 @@ impl Server {
});
}
}
static LAUNCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let number = LAUNCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let log = account.file.with_file_name(format!("server-{}-{number}.log", std::process::id()));
let mut child = command
.args(["serve", "--port", "0"])
.env("GITV_REPOS", repos)
.env("GITV_WEB_AUTH", &account.file)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.stderr(fs::File::create(&log).unwrap())
.spawn()
.unwrap();
let mut line = String::new();
@@ -249,7 +254,12 @@ impl Server {
.and_then(|rest| rest.split_whitespace().next())
.and_then(|p| p.parse().ok())
.unwrap_or_else(|| panic!("unexpected startup line: {line}"));
Server { child, port, account, cookie: None }
Server { child, port, account, cookie: None, log }
}
/// What the server has logged so far.
pub fn logged(&self) -> String {
fs::read_to_string(&self.log).unwrap_or_default()
}
/// GET with the session cookie, if signed in.