GITv

Put the web browser behind a sign-in with two-factor codes

Browse files

gitv-web now requires a username, password and TOTP code (RFC 6238, any authenticator app) for every page except the sign-in page and its assets. - `gitv-web setup` creates the account (Um9i by default) with a generated 20-character password, shown once, and a new authenticator secret printed with a QR code; --force replaces it. - The password is stored as an Argon2id hash in /var/lib/gitv-web/login (or $GITV_WEB_AUTH), private to its owner, and can be changed on the Account page or with `gitv-web password`. Changing it signs every other session out. - Codes work once and allow one step of clock drift. Five failures are free; after that sign-in locks for a minute, doubling up to fifteen. - Sessions are random tokens stored only as hashes, in a __Host- cookie that is HttpOnly, Secure and SameSite=Strict, lasting 12 hours. Sign-out and password changes need a per-session form token, and sign-in only redirects within the site. The credential and TOTP logic lives in the library (src/auth.rs) with typed errors; gitv-web moves to src/bin/gitv-web/ with the sign-in routes in login.rs. Web tests now run signed in, and tests/auth.rs covers sign-in, codes, lockout, sessions and password changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 12:37
Commit
74117876d4da
Parent
c70174e

11 files changed +1989−57

+222−0
@@ -58,6 +58,18 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "argon2"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"password-hash",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
@@ -122,6 +134,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bincode"
version = "1.3.3"
@@ -137,6 +155,24 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "blake2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"
dependencies = [
"digest",
]
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "bytes"
version = "1.12.2"
@@ -205,12 +241,33 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.5"
@@ -220,6 +277,42 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
@@ -276,18 +369,40 @@ dependencies = [
"slab",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "gitv"
version = "0.1.0"
dependencies = [
"argon2",
"axum",
"base64",
"clap",
"data-encoding",
"getrandom",
"hmac",
"html-escape",
"nix",
"pulldown-cmark",
"qrcode",
"rpassword",
"serde",
"sha1",
"sha2",
"shlex",
"subtle",
"syntect",
"thiserror",
"tokio",
]
@@ -297,6 +412,15 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "html-escape"
version = "0.3.1"
@@ -348,6 +472,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "hyper"
version = "1.12.0"
@@ -491,12 +624,33 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "password-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"
dependencies = [
"getrandom",
"phc",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "phc"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"
dependencies = [
"base64ct",
"ctutils",
"getrandom",
]
[[package]]
name = "pin-project-lite"
version = "0.2.18"
@@ -536,6 +690,12 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "qrcode"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace1a365f55004297f2cf24acfd96d02966246ca423385273b58a7dc873ee14d"
[[package]]
name = "quote"
version = "1.0.47"
@@ -545,12 +705,39 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "rpassword"
version = "7.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464"
dependencies = [
"libc",
"rtoolbox",
"windows-sys",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "ryu"
version = "1.0.23"
@@ -573,6 +760,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
@@ -631,6 +819,28 @@ dependencies = [
"serde",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -671,6 +881,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "3.0.10"
@@ -799,6 +1015,12 @@ dependencies = [
"once_cell",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicase"
version = "2.10.0"
+18−0
@@ -4,16 +4,34 @@ version = "0.1.0"
edition = "2024"
[dependencies]
argon2 = "0.6.0"
axum = "0.8.9"
base64 = "0.23.1"
clap = { version = "4.6.9", features = ["derive"] }
data-encoding = "2.11.1"
getrandom = "0.4.3"
hmac = "0.13.0"
html-escape = "0.3.1"
nix = { version = "0.32.0", features = ["user", "fs", "dir", "resource"] }
pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] }
qrcode = { version = "0.15.0", default-features = false }
rpassword = "7.5.5"
serde = { version = "1.0.229", features = ["derive"] }
sha1 = "0.11.0"
sha2 = "0.11.1"
shlex = "2.0.1"
subtle = "2.6.1"
syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-onig"] }
thiserror = "2.0.21"
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync"] }
[profile.release]
lto = "thin"
codegen-units = 1
# Password hashing is deliberately slow; unoptimised it makes debug builds and tests crawl.
[profile.dev.package.argon2]
opt-level = 3
[profile.dev.package.blake2]
opt-level = 3
+23−3
@@ -5,12 +5,30 @@ Private Git hosting over OpenSSH, plus a read-only web browser.
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `delete`, `add-key`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`src/render.rs`)
**Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has no per-owner access control: it shows every repository on the server to anyone who can reach it. It binds to localhost only, and is meant for one trusted audience behind the reverse proxy's login. Don't expose it more widely, or give web logins to people who shouldn't read every owner's code.
**Who can read what.** Over SSH each key reaches only its owner's repositories. The web browser has one account, and whoever signs in to it can read every repository on the server. It binds to localhost only; put it behind an HTTPS reverse proxy.
**Storage.** Repositories live in `/srv/gitv/repos/<owner>/<name>.git`. Owner and repository directories must be real directories: GITv refuses symlinks at either level rather than follow them out of the tree. Everything works through open directory handles: git runs inside the repository directory it opened, new repositories are built and published inside the open owner directory (never replacing anything already at the name), deletion removes through handles without following links, and the web index lists and fingerprints repositories the same way. A path swapped for a symlink after a check can't redirect any of it.
The browser follows the system's light or dark setting. Its stylesheet (`assets/style.css`) and the Red Hat Display, Text and Mono fonts (`assets/fonts`, SIL Open Font License) are built into the `gitv-web` binary, so the server needs no font packages.
## Web sign-in
The browser asks for a username, a password and a code from an authenticator app (TOTP, as used by Google Authenticator, 1Password, Aegis and others). Create the account once on the server, as the user the browser runs as (or as root, which hands the file to the `gitv-web` account):
```sh
gitv-web setup # account Um9i; --user NAME for another; --force to replace it
```
It prints a generated password (20 random characters, shown only this once), the authenticator secret, and a QR code to scan. Then sign in at the browser's address.
- **Change the password** under Account once signed in (it asks for the current password and a code), or on the server with `gitv-web password`. Either way every other session is signed out.
- **Lost the authenticator?** Run `gitv-web setup --force` on the server for a new password and secret.
- The account lives in `/var/lib/gitv-web/login` (or `$GITV_WEB_AUTH`), readable only by its owner. The password is stored as an Argon2id hash.
- Sessions last 12 hours and end when the browser restarts. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`).
- After five failed attempts sign-in locks for a minute, doubling with each further failure up to 15 minutes. A code works once.
Until the account exists, the browser answers every page with instructions to run `gitv-web setup`.
## Run locally
Set `GITV_REPOS` (and optionally `GITV_KEYS`) to point at a local tree. When `GITV_REPOS` is set, admin commands run without root.
@@ -20,7 +38,9 @@ cargo build
export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys
mkdir -p dev/repos
./target/debug/gitv create um9i demo
./target/debug/gitv-web serve --port 8080 # http://127.0.0.1:8080
export GITV_WEB_AUTH=$PWD/dev/web-login
./target/debug/gitv-web setup # note the password; scan the QR code
./target/debug/gitv-web serve --port 8080 # http://localhost:8080
```
`scripts/fake-ssh` stands in for ssh, so you can push and clone through `gitv serve` without an SSH server. The user part of the URL picks the owner whose key it acts as:
@@ -37,4 +57,4 @@ git clone um9i@local:um9i/myrepo.git
cargo test
```
`tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh. `tests/web.rs` builds a fixture repository and checks every page of a running `gitv-web` over HTTP, including escaping and the requests it must refuse. Neither needs an SSH server or network access; both write only to `target/tmp`.
`tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh. `tests/web.rs` builds a fixture repository and checks every page of a running `gitv-web` over HTTP, signed in, including escaping and the requests it must refuse. `tests/auth.rs` covers signing in, two-factor codes, lockout, sessions and changing the password. Neither needs an SSH server or network access; both write only to `target/tmp`.
@@ -41,6 +41,8 @@ code,pre,kbd,.mono{font-family:var(--f-mono)}
.logo{width:26px;height:26px;flex:none}
.logo rect{fill:var(--accent)}
.logo g{stroke:var(--surface)}
.account{display:inline-flex;align-items:center;min-height:44px;padding:0 4px;font-weight:500;color:var(--ink-2)}
.account:hover{color:var(--ink);text-decoration:none}
main{max-width:1080px;margin:0 auto;padding:32px 24px 72px}
/* Page and repository headings */
@@ -207,6 +209,29 @@ a.entry:hover .name{color:var(--accent)}
.diff .del .line{background:var(--del);color:var(--del-ink)}.diff .del .num{background:var(--del-num)}
.diff .hunk td{padding:4px 16px;color:var(--ink-2);background:var(--hunk)}
/* Sign-in and account forms */
.signin{max-width:400px;margin:40px auto 0}
.signin .title{margin:0 0 20px}
.form{display:flex;flex-direction:column;gap:16px;padding:24px}
.form-panel{max-width:560px}
.form-panel h2{margin:0;padding:18px 24px 0;font:700 19px/1.3 var(--f-display)}
.form-panel > form:not(.form){padding:16px 24px 24px}
.form-panel > .hint{padding:0 24px 20px;margin:-8px 0 0}
.form label{display:flex;flex-direction:column;gap:6px;font-size:14px;font-weight:600}
.form input{min-height:44px;padding:0 12px;font:400 16px var(--f-text);color:var(--ink);background:var(--surface);
border:1px solid var(--rule);border-radius:8px}
.form input:hover{border-color:var(--ink-2)}
.form input:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-color:var(--accent)}
.form input[inputmode="numeric"]{font-family:var(--f-mono);letter-spacing:.2em}
.hint{font-size:13px;font-weight:400;color:var(--ink-2)}
.button.primary{justify-content:center;min-height:44px;color:var(--surface);background:var(--accent);border-color:var(--accent);
font-weight:600;cursor:pointer}
.button.primary:hover{filter:brightness(1.08)}
button.button{cursor:pointer}
.alert{margin:0 0 16px;padding:12px 14px;font-size:14px;border-radius:8px;color:var(--del-ink);background:var(--del);
border:1px solid var(--del-num)}
.alert.ok{color:var(--add-ink);background:var(--add);border-color:var(--add-num)}
/* Empty and missing */
.empty{padding:48px 24px;text-align:center;color:var(--ink-2)}
.empty h2{margin:0 0 6px;font:700 20px/1.3 var(--f-display);color:var(--ink)}
+504−0
@@ -0,0 +1,504 @@
//! Sign-in for the web browser: one account, a password hashed with Argon2id, and a TOTP second
//! factor ([RFC 6238]) that works with any authenticator app.
//!
//! The account lives in one small file (see [`auth_path`]), readable only by its owner:
//!
//! ```text
//! user=Um9i
//! password=$argon2id$v=19$m=19456,t=2,p=1$...
//! totp=JBSWY3DPEHPK3PXP...
//! ```
//!
//! [RFC 6238]: https://www.rfc-editor.org/rfc/rfc6238
use std::fs;
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use argon2::Argon2;
use argon2::password_hash::phc::PasswordHash;
use argon2::password_hash::{PasswordHasher, PasswordVerifier};
use data_encoding::BASE32_NOPAD;
use hmac::{Hmac, KeyInit, Mac};
use sha1::Sha1;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
/// The account name `gitv-web setup` uses unless told otherwise.
pub const DEFAULT_USER: &str = "Um9i";
/// How authenticator apps label the account.
pub const ISSUER: &str = "GITv";
/// Shortest password accepted, in characters.
pub const MIN_PASSWORD: usize = 12;
/// Longest password accepted, in characters: hashing is deliberately slow, so this bounds it.
pub const MAX_PASSWORD: usize = 1024;
/// Seconds per TOTP code.
pub const TOTP_STEP: u64 = 30;
/// Digits per TOTP code.
pub const TOTP_DIGITS: u32 = 6;
/// Bytes in a TOTP secret: 160 bits, as RFC 4226 recommends for HMAC-SHA1.
const TOTP_SECRET_BYTES: usize = 20;
/// Characters for generated passwords: letters and digits without look-alikes (0/O, 1/l/I).
const PASSWORD_ALPHABET: &[u8] = b"abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
/// Why sign-in setup or a credential operation failed.
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error("sign-in isn't set up yet: {} doesn't exist; run `gitv-web setup`", .0.display())]
NotSetUp(PathBuf),
#[error("sign-in is already set up in {}; use --force to replace it", .0.display())]
AlreadySetUp(PathBuf),
#[error("couldn't read {}: {source}", path.display())]
Read { path: PathBuf, source: std::io::Error },
#[error("couldn't write {}: {source}", path.display())]
Write { path: PathBuf, source: std::io::Error },
#[error("{} is malformed: {reason}", path.display())]
Malformed { path: PathBuf, reason: &'static str },
#[error("use at least {MIN_PASSWORD} characters")]
PasswordTooShort,
#[error("use at most {MAX_PASSWORD} characters")]
PasswordTooLong,
#[error("couldn't hash the password: {0}")]
Hash(String),
#[error("couldn't get random bytes: {0}")]
Random(String),
}
/// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`.
pub fn auth_path() -> PathBuf {
std::env::var_os("GITV_WEB_AUTH").map_or_else(|| PathBuf::from("/var/lib/gitv-web/login"), PathBuf::from)
}
/// `N` bytes from the operating system's secure random source.
///
/// # Errors
/// [`AuthError::Random`] if the source is unavailable.
pub fn random_bytes<const N: usize>() -> Result<[u8; N], AuthError> {
let mut bytes = [0u8; N];
getrandom::fill(&mut bytes).map_err(|e| AuthError::Random(e.to_string()))?;
Ok(bytes)
}
/// A new random password: 20 characters from an alphabet of 56 without look-alikes (about 116
/// bits), in four groups of five so it can be read and typed.
///
/// # Errors
/// [`AuthError::Random`] if the random source is unavailable.
pub fn generate_password() -> Result<String, AuthError> {
// Rejection sampling: bytes at or above the largest multiple of the alphabet size would
// favour its first letters, so they're thrown away.
let limit = 256 - 256 % PASSWORD_ALPHABET.len();
let mut chars = Vec::with_capacity(20);
while chars.len() < 20 {
for byte in random_bytes::<32>()? {
if usize::from(byte) < limit && chars.len() < 20 {
chars.push(PASSWORD_ALPHABET[usize::from(byte) % PASSWORD_ALPHABET.len()]);
}
}
}
let groups: Vec<&str> = chars.chunks(5).map(|g| std::str::from_utf8(g).unwrap_or_default()).collect();
Ok(groups.join("-"))
}
/// Check a new password against the length rules.
///
/// # Errors
/// [`AuthError::PasswordTooShort`] or [`AuthError::PasswordTooLong`].
pub fn check_new_password(password: &str) -> Result<(), AuthError> {
match password.chars().count() {
n if n < MIN_PASSWORD => Err(AuthError::PasswordTooShort),
n if n > MAX_PASSWORD => Err(AuthError::PasswordTooLong),
_ => Ok(()),
}
}
/// Hash a password with Argon2id and a random salt, as a PHC string.
///
/// # Errors
/// [`AuthError::Hash`] if hashing fails.
pub fn hash_password(password: &str) -> Result<String, AuthError> {
Argon2::default()
.hash_password(password.as_bytes())
.map(|h| h.to_string())
.map_err(|e| AuthError::Hash(e.to_string()))
}
/// The TOTP code for `secret` at time step `step` (HMAC-SHA1, six digits).
pub fn totp_code(secret: &[u8], step: u64) -> u32 {
let Ok(mut mac) = Hmac::<Sha1>::new_from_slice(secret) else {
return 0; // Unreachable: HMAC accepts keys of any length.
};
mac.update(&step.to_be_bytes());
let digest = mac.finalize().into_bytes();
// RFC 4226 dynamic truncation.
let offset = usize::from(digest[digest.len() - 1] & 0x0f);
let value = u32::from_be_bytes([digest[offset], digest[offset + 1], digest[offset + 2], digest[offset + 3]]);
(value & 0x7fff_ffff) % 10u32.pow(TOTP_DIGITS)
}
/// The TOTP time step for a Unix time.
pub fn totp_step(unix_seconds: u64) -> u64 {
unix_seconds / TOTP_STEP
}
/// The web account: its name, its password's hash and its TOTP secret.
pub struct Credentials {
user: String,
password_hash: String,
totp_secret: Vec<u8>,
}
impl Credentials {
/// A new account with a new random TOTP secret.
///
/// # Errors
/// [`AuthError::PasswordTooShort`]/[`AuthError::PasswordTooLong`] for a password outside the
/// rules, [`AuthError::Hash`] or [`AuthError::Random`] if hashing or randomness fails.
pub fn new(user: &str, password: &str) -> Result<Credentials, AuthError> {
check_new_password(password)?;
Ok(Credentials {
user: user.to_string(),
password_hash: hash_password(password)?,
totp_secret: random_bytes::<TOTP_SECRET_BYTES>()?.to_vec(),
})
}
/// Read the account file.
///
/// # Errors
/// [`AuthError::NotSetUp`] if it doesn't exist, [`AuthError::Read`] if it can't be read, and
/// [`AuthError::Malformed`] if a field is missing or invalid.
pub fn load(path: &Path) -> Result<Credentials, AuthError> {
let text = fs::read_to_string(path).map_err(|source| match source.kind() {
std::io::ErrorKind::NotFound => AuthError::NotSetUp(path.to_path_buf()),
_ => AuthError::Read { path: path.to_path_buf(), source },
})?;
Credentials::parse(&text).map_err(|reason| AuthError::Malformed { path: path.to_path_buf(), reason })
}
fn parse(text: &str) -> Result<Credentials, &'static str> {
let field = |name: &str| {
text.lines().filter(|l| !l.starts_with('#')).find_map(|l| l.strip_prefix(name)?.strip_prefix('='))
};
let user = field("user").filter(|u| !u.is_empty()).ok_or("no user")?;
let password_hash = field("password").ok_or("no password")?;
PasswordHash::new(password_hash).map_err(|_| "the password hash isn't a PHC string")?;
let totp_secret =
BASE32_NOPAD.decode(field("totp").ok_or("no totp secret")?.as_bytes()).map_err(|_| "bad totp secret")?;
if totp_secret.len() < 16 {
return Err("the totp secret is too short");
}
Ok(Credentials { user: user.to_string(), password_hash: password_hash.to_string(), totp_secret })
}
/// Write the account file atomically, readable and writable by its owner only.
///
/// # Errors
/// [`AuthError::Write`] if the file or its temporary can't be written or renamed.
pub fn save(&self, path: &Path) -> Result<(), AuthError> {
let write_error = |source| AuthError::Write { path: path.to_path_buf(), source };
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = path.with_file_name(format!(".{name}.{}", std::process::id()));
let contents = format!(
"# GITv web sign-in. Keep this private: anyone who can read it can attack the password offline.\n\
user={}\npassword={}\ntotp={}\n",
self.user,
self.password_hash,
self.totp_secret_base32()
);
let written = (|| {
let mut file = fs::File::options().write(true).create_new(true).mode(0o600).open(&temporary)?;
file.write_all(contents.as_bytes())?;
file.sync_all()?;
fs::rename(&temporary, path)
})();
if written.is_err() {
let _ = fs::remove_file(&temporary);
}
written.map_err(write_error)
}
/// The account name.
pub fn user(&self) -> &str {
&self.user
}
/// Whether `user` is the account name, compared in constant time.
pub fn user_matches(&self, user: &str) -> bool {
self.user.as_bytes().ct_eq(user.as_bytes()).into()
}
/// Whether `password` is the account's password. Deliberately slow (Argon2id).
pub fn verify_password(&self, password: &str) -> bool {
PasswordHash::new(&self.password_hash)
.is_ok_and(|hash| Argon2::default().verify_password(password.as_bytes(), &hash).is_ok())
}
/// Replace the password.
///
/// # Errors
/// [`AuthError::PasswordTooShort`]/[`AuthError::PasswordTooLong`] or [`AuthError::Hash`].
pub fn set_password(&mut self, password: &str) -> Result<(), AuthError> {
check_new_password(password)?;
self.password_hash = hash_password(password)?;
Ok(())
}
/// The TOTP secret in base32, as authenticator apps take it.
pub fn totp_secret_base32(&self) -> String {
BASE32_NOPAD.encode(&self.totp_secret)
}
/// The `otpauth://` link authenticator apps scan.
pub fn otpauth_uri(&self) -> String {
let user = url_component(&self.user);
format!(
"otpauth://totp/{ISSUER}:{user}?secret={}&issuer={ISSUER}&algorithm=SHA1&digits={TOTP_DIGITS}&period={TOTP_STEP}",
self.totp_secret_base32()
)
}
/// The time step a six-digit `code` is valid for, allowing one step of clock drift either
/// way, and only steps after `after_step` so a code can't be used twice.
pub fn verify_code(&self, code: &str, unix_seconds: u64, after_step: u64) -> Option<u64> {
let digits = TOTP_DIGITS as usize;
if code.len() != digits || !code.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let now = totp_step(unix_seconds);
(now.saturating_sub(1)..=now + 1).filter(|step| *step > after_step).find(|step| {
let expected = format!("{:0digits$}", totp_code(&self.totp_secret, *step));
bool::from(expected.as_bytes().ct_eq(code.as_bytes()))
})
}
/// A digest of the password hash and TOTP secret. Sessions remember it, so changing either
/// (here or with `gitv-web password`/`setup`) signs every other session out.
pub fn fingerprint(&self) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(self.user.as_bytes());
hasher.update([0]);
hasher.update(self.password_hash.as_bytes());
hasher.update([0]);
hasher.update(&self.totp_secret);
hasher.finalize().into()
}
}
/// Percent-encode everything but unreserved characters, for the label in an `otpauth://` link.
fn url_component(value: &str) -> String {
value
.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
_ => format!("%{b:02X}"),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// The shared secret of RFC 6238's SHA-1 test vectors.
const RFC_SECRET: &[u8] = b"12345678901234567890";
fn account() -> Credentials {
Credentials {
user: DEFAULT_USER.into(),
password_hash: hash_password("correct horse battery").unwrap(),
totp_secret: RFC_SECRET.to_vec(),
}
}
mod totp_code {
use super::*;
#[test]
fn matches_the_rfc_6238_test_vectors() {
// RFC 6238 appendix B gives eight-digit codes; six-digit codes are their last six.
let vectors = [
(59, 94_287_082),
(1_111_111_109, 7_081_804),
(1_111_111_111, 14_050_471),
(1_234_567_890, 89_005_924),
(2_000_000_000, 69_279_037),
(20_000_000_000, 65_353_130),
];
for (time, eight_digits) in vectors {
assert_eq!(totp_code(RFC_SECRET, totp_step(time)), eight_digits % 1_000_000, "at time {time}");
}
}
}
mod verify_code {
use super::*;
#[test]
fn accepts_the_current_code() {
assert_eq!(account().verify_code("287082", 59, 0), Some(1));
}
#[test]
fn accepts_one_step_of_drift_either_way() {
let code = format!("{:06}", totp_code(RFC_SECRET, 100));
assert_eq!(account().verify_code(&code, 101 * TOTP_STEP, 0), Some(100));
assert_eq!(account().verify_code(&code, 99 * TOTP_STEP, 0), Some(100));
}
#[test]
fn rejects_codes_two_steps_away() {
let code = format!("{:06}", totp_code(RFC_SECRET, 100));
assert_eq!(account().verify_code(&code, 102 * TOTP_STEP, 0), None);
}
#[test]
fn rejects_a_code_already_used() {
assert_eq!(account().verify_code("287082", 59, 1), None);
}
#[test]
fn rejects_malformed_codes() {
for code in ["", "28708", "2870822", "28708a", " 287082", "287082"] {
assert_eq!(account().verify_code(code, 59, 0), None, "{code:?}");
}
}
}
mod passwords {
use super::*;
#[test]
fn generated_passwords_are_four_groups_of_five_from_the_alphabet() {
let password = generate_password().unwrap();
let groups: Vec<&str> = password.split('-').collect();
assert_eq!(groups.iter().map(|g| g.len()).collect::<Vec<_>>(), [5, 5, 5, 5], "{password}");
assert!(groups.concat().bytes().all(|b| PASSWORD_ALPHABET.contains(&b)), "{password}");
}
#[test]
fn generated_passwords_differ() {
assert_ne!(generate_password().unwrap(), generate_password().unwrap());
}
#[test]
fn generated_passwords_meet_the_rules() {
assert!(check_new_password(&generate_password().unwrap()).is_ok());
}
#[test]
fn short_passwords_are_refused() {
assert!(matches!(check_new_password("eleven char"), Err(AuthError::PasswordTooShort)));
}
#[test]
fn length_counts_characters_not_bytes() {
// Six two-byte characters are twelve bytes but only six characters.
assert!(matches!(check_new_password("éééééé"), Err(AuthError::PasswordTooShort)));
}
#[test]
fn overlong_passwords_are_refused() {
assert!(matches!(check_new_password(&"x".repeat(MAX_PASSWORD + 1)), Err(AuthError::PasswordTooLong)));
}
#[test]
fn the_right_password_verifies() {
assert!(account().verify_password("correct horse battery"));
}
#[test]
fn a_wrong_password_does_not_verify() {
assert!(!account().verify_password("correct horse battery!"));
}
#[test]
fn changing_the_password_changes_the_fingerprint() {
let mut credentials = account();
let before = credentials.fingerprint();
credentials.set_password("a whole new password").unwrap();
assert_ne!(credentials.fingerprint(), before);
}
}
mod user_matches {
use super::*;
#[test]
fn is_exact() {
let credentials = account();
assert!(credentials.user_matches("Um9i"));
assert!(!credentials.user_matches("um9i"), "names are case-sensitive");
assert!(!credentials.user_matches("Um9i "));
}
}
mod file {
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");
let path = dir.join("login");
let credentials = account();
credentials.save(&path).unwrap();
let loaded = Credentials::load(&path).unwrap();
assert_eq!(loaded.fingerprint(), credentials.fingerprint());
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn is_private_to_its_owner() {
let dir = scratch("private");
let path = dir.join("login");
account().save(&path).unwrap();
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn missing_means_not_set_up() {
let dir = scratch("missing");
assert!(matches!(Credentials::load(&dir.join("login")), Err(AuthError::NotSetUp(_))));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn malformed_files_are_refused() {
let cases = [
(
"no user",
"password=$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaA\ntotp=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ\n",
),
("no password", "user=Um9i\ntotp=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ\n"),
("not a hash", "user=Um9i\npassword=hunter2\ntotp=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ\n"),
("bad secret", "user=Um9i\npassword=$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaA\ntotp=not base32!\n"),
("short secret", "user=Um9i\npassword=$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaA\ntotp=GEZDGNA\n"),
];
for (name, text) in cases {
assert!(Credentials::parse(text).is_err(), "{name} was accepted");
}
}
}
mod otpauth_uri {
use super::*;
#[test]
fn names_the_issuer_account_and_secret() {
assert_eq!(
account().otpauth_uri(),
"otpauth://totp/GITv:Um9i?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=GITv&algorithm=SHA1&digits=6&period=30"
);
}
}
}
@@ -0,0 +1,638 @@
//! Signing in to the web browser: a password and an authenticator code, then a session cookie.
//!
//! Every page except the sign-in page and the static assets it needs sits behind
//! [`require_login`]. Sessions live in memory (a restart signs everyone out) and remember the
//! account's [fingerprint](gitv::auth::Credentials::fingerprint), so changing the password, here
//! or with `gitv-web password`, ends every other session.
use std::collections::HashMap;
use std::os::unix::fs::{DirBuilderExt, MetadataExt};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use axum::Extension;
use axum::extract::{Form, RawQuery, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use data_encoding::BASE64URL_NOPAD;
use gitv::auth::{
AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, generate_password, random_bytes,
};
use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use super::{SECURITY, layout, page, percent_decode};
/// 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.
const COOKIE: &str = "__Host-gitv";
/// How long a session lasts from sign-in.
const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60);
/// Failed attempts allowed before sign-in locks.
const FREE_FAILURES: u32 = 5;
/// The longest a lock lasts; it starts at a minute and doubles with each further failure.
const LONGEST_LOCK: Duration = Duration::from_secs(15 * 60);
/// Sign-in state shared by every request.
pub struct Login {
path: PathBuf,
loaded: Mutex<Option<Loaded>>,
/// Sessions by the SHA-256 of their token: the token itself is never stored.
sessions: Mutex<HashMap<[u8; 32], Session>>,
guard: Mutex<Guard>,
}
/// The account file as last read, and how to tell whether it has changed since.
struct Loaded {
stamp: (u64, i64, i64, u64),
credentials: Arc<Credentials>,
}
#[derive(Clone)]
struct Session {
expires: Instant,
fingerprint: [u8; 32],
csrf: String,
}
/// Brute-force protection. There is one account, so one counter: an attacker can delay its
/// owner, but can't guess faster than the lock allows.
#[derive(Default)]
struct Guard {
failures: u32,
locked_until: Option<Instant>,
/// The last TOTP step used, so a code works once.
last_step: u64,
}
/// What [`require_login`] hands a signed-in request.
#[derive(Clone)]
pub struct SignedIn {
token_hash: [u8; 32],
csrf: String,
}
impl Login {
/// Sign-in backed by the account file at [`auth_path`].
pub fn new() -> Arc<Login> {
Arc::new(Login {
path: auth_path(),
loaded: Mutex::new(None),
sessions: Mutex::new(HashMap::new()),
guard: Mutex::new(Guard::default()),
})
}
/// The account, re-read whenever the file changes (so `gitv-web password` takes effect
/// at once).
fn credentials(&self) -> Result<Arc<Credentials>, AuthError> {
let meta = std::fs::metadata(&self.path).map_err(|source| match source.kind() {
std::io::ErrorKind::NotFound => AuthError::NotSetUp(self.path.clone()),
_ => AuthError::Read { path: self.path.clone(), source },
})?;
let stamp = (meta.ino(), meta.mtime(), meta.mtime_nsec(), meta.len());
let mut loaded = self.loaded.lock().unwrap_or_else(|e| e.into_inner());
if let Some(current) = loaded.as_ref().filter(|l| l.stamp == stamp) {
return Ok(Arc::clone(&current.credentials));
}
let credentials = Arc::new(Credentials::load(&self.path)?);
*loaded = Some(Loaded { stamp, credentials: Arc::clone(&credentials) });
Ok(credentials)
}
/// The session a request's cookie names, if it's live and the account hasn't changed since.
fn session(&self, headers: &HeaderMap, credentials: &Credentials) -> Option<SignedIn> {
let token_hash = cookie_token(headers)?;
let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
let session = sessions.get(&token_hash)?;
if session.expires <= Instant::now() || session.fingerprint != credentials.fingerprint() {
sessions.remove(&token_hash);
return None;
}
Some(SignedIn { token_hash, csrf: session.csrf.clone() })
}
/// Start a session; returns the `Set-Cookie` value.
fn start_session(&self, fingerprint: [u8; 32]) -> Result<String, AuthError> {
let token = random_bytes::<32>()?;
let csrf = BASE64URL_NOPAD.encode(&random_bytes::<32>()?);
let now = Instant::now();
let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
sessions.retain(|_, s| s.expires > now);
sessions.insert(Sha256::digest(token).into(), Session { expires: now + SESSION_LIFETIME, fingerprint, csrf });
Ok(format!(
"{COOKIE}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
BASE64URL_NOPAD.encode(&token),
SESSION_LIFETIME.as_secs()
))
}
/// How long sign-in stays locked, if it is.
fn locked_for(&self) -> Option<Duration> {
let guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now()))
}
fn last_step(&self) -> u64 {
self.guard.lock().unwrap_or_else(|e| e.into_inner()).last_step
}
fn record_failure(&self) {
let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
guard.failures += 1;
// The first FREE_FAILURES are free; each one after locks for longer.
if let Some(over) = guard.failures.checked_sub(FREE_FAILURES + 1) {
let lock = Duration::from_secs(60).saturating_mul(1 << over.min(10)).min(LONGEST_LOCK);
guard.locked_until = Some(Instant::now() + lock);
}
}
fn record_success(&self, step: u64) {
let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
guard.failures = 0;
guard.locked_until = None;
guard.last_step = guard.last_step.max(step);
}
/// Check a password and authenticator code, counting failures and using up the code.
async fn check(&self, credentials: &Arc<Credentials>, user: Option<String>, password: String, code: &str) -> bool {
// Argon2 is deliberately slow: off the async threads.
let creds = Arc::clone(credentials);
let password_ok = tokio::task::spawn_blocking(move || {
let user_ok = user.is_none_or(|u| creds.user_matches(&u));
creds.verify_password(&password) && user_ok
})
.await
.unwrap_or(false);
let step = credentials.verify_code(code, unix_now(), self.last_step());
match step.filter(|_| password_ok) {
Some(step) => {
self.record_success(step);
true
}
None => {
self.record_failure();
false
}
}
}
}
/// The SHA-256 of the session token in a request's cookie.
fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> {
let token = headers
.get_all(header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.find_map(|pair| pair.trim().strip_prefix(COOKIE)?.strip_prefix('='))?;
let token = BASE64URL_NOPAD.decode(token.as_bytes()).ok().filter(|t| t.len() == 32)?;
Some(Sha256::digest(token).into())
}
fn unix_now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
/// Paths anyone may load: the sign-in page and what it needs to look right.
fn is_public(path: &str) -> bool {
matches!(path, "/login" | "/style.css" | "/favicon.svg") || path.starts_with("/fonts/")
}
/// 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, cookie: Option<String>) -> Response {
let mut response = (StatusCode::SEE_OTHER, SECURITY).into_response();
if let Ok(location) = HeaderValue::from_str(to) {
response.headers_mut().insert(header::LOCATION, location);
}
if let Some(cookie) = cookie.and_then(|c| HeaderValue::from_str(&c).ok()) {
response.headers_mut().insert(header::SET_COOKIE, cookie);
}
response
}
fn not_set_up() -> Response {
html(
StatusCode::SERVICE_UNAVAILABLE,
layout(
"Sign-in isn't set up",
r#"<section class="notfound"><h1 class="title">Sign-in isn’t set up</h1>
<p class="count">Create the account on the server, then reload this page:</p><code>gitv-web setup</code></section>"#,
false,
),
)
}
/// Let signed-in requests through; send everyone else to the sign-in page.
pub async fn require_login(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response {
if is_public(request.uri().path()) {
return next.run(request).await;
}
let credentials = match login.credentials() {
Ok(credentials) => credentials,
Err(AuthError::NotSetUp(_)) => return not_set_up(),
Err(error) => {
eprintln!("gitv-web: {error}");
return html(
StatusCode::SERVICE_UNAVAILABLE,
layout("Unavailable", "<p class=\"note\">Sign-in is unavailable.</p>", false),
);
}
};
if let Some(signed_in) = login.session(request.headers(), &credentials) {
request.extensions_mut().insert(signed_in);
return next.run(request).await;
}
let wanted = request.uri().path_and_query().map_or("/", |p| p.as_str());
redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), None)
}
// ---------------------------------------------------------------------------------------------
// Sign in and out
#[derive(Deserialize)]
pub struct SignInForm {
user: String,
password: String,
code: String,
#[serde(default)]
next: String,
}
fn sign_in_page(status: StatusCode, next: &str, message: &str) -> Response {
let message = if message.is_empty() {
String::new()
} else {
format!(r#"<p class="alert" role="alert">{}</p>"#, esc(message))
};
html(
status,
layout(
"Sign in",
&format!(
r#"<section class="signin"><h1 class="title">Sign in</h1>{message}
<form class="panel form" method="post" action="/login">
<label>Username<input name="user" autocomplete="username" autocapitalize="none" spellcheck="false" required></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
<label>Authenticator code<input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{{6}}" maxlength="6" required></label>
<input type="hidden" name="next" value="{}">
<button class="button primary" type="submit">Sign in</button></form></section>"#,
attr(safe_next(next))
),
false,
),
)
}
fn locked_page(wait: Duration) -> Response {
let minutes = wait.as_secs().div_ceil(60).max(1);
let plural = if minutes == 1 { "" } else { "s" };
sign_in_page(
StatusCode::TOO_MANY_REQUESTS,
"/",
&format!("Too many failed sign-ins. Try again in {minutes} minute{plural}."),
)
}
pub async fn sign_in_form(State(login): State<Arc<Login>>, headers: HeaderMap, RawQuery(query): RawQuery) -> Response {
let next = query
.as_deref()
.and_then(|q| q.split('&').find_map(|p| p.strip_prefix("next=")))
.map(|n| String::from_utf8_lossy(&percent_decode(n)).into_owned())
.unwrap_or_else(|| "/".into());
// Already signed in: carry on to where they were going.
if let Ok(credentials) = login.credentials()
&& login.session(&headers, &credentials).is_some()
{
return redirect(safe_next(&next), None);
}
sign_in_page(StatusCode::OK, &next, "")
}
pub async fn sign_in(State(login): State<Arc<Login>>, Form(form): Form<SignInForm>) -> Response {
if let Some(wait) = login.locked_for() {
return locked_page(wait);
}
let credentials = match login.credentials() {
Ok(credentials) => credentials,
Err(AuthError::NotSetUp(_)) => return not_set_up(),
Err(error) => {
eprintln!("gitv-web: {error}");
return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.");
}
};
if !login.check(&credentials, Some(form.user), form.password, &form.code).await {
// One message for every mistake, so a guess reveals nothing about which part was wrong.
return match login.locked_for() {
Some(wait) => locked_page(wait),
None => sign_in_page(StatusCode::UNAUTHORIZED, &form.next, "That username, password or code isn’t right."),
};
}
match login.start_session(credentials.fingerprint()) {
Ok(cookie) => redirect(safe_next(&form.next), Some(cookie)),
Err(error) => {
eprintln!("gitv-web: {error}");
sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.")
}
}
}
#[derive(Deserialize)]
pub struct CsrfForm {
csrf: String,
}
/// Whether a form carries this session's token: forms posted from other sites don't.
fn csrf_ok(signed_in: &SignedIn, token: &str) -> bool {
signed_in.csrf.as_bytes().ct_eq(token.as_bytes()).into()
}
pub async fn sign_out(
State(login): State<Arc<Login>>,
Extension(signed_in): Extension<SignedIn>,
Form(form): Form<CsrfForm>,
) -> Response {
if !csrf_ok(&signed_in, &form.csrf) {
return html(
StatusCode::FORBIDDEN,
page("Not allowed", r#"<p class="note">That form has expired. Go back and try again.</p>"#),
);
}
login.sessions.lock().unwrap_or_else(|e| e.into_inner()).remove(&signed_in.token_hash);
let clear = format!("{COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0");
redirect("/login", Some(clear))
}
// ---------------------------------------------------------------------------------------------
// Account
#[derive(Deserialize)]
pub struct ChangePasswordForm {
csrf: String,
current: String,
new: String,
repeat: String,
code: String,
}
fn account_page(status: StatusCode, user: &str, signed_in: &SignedIn, message: &str, ok: bool) -> Response {
let message = match message {
"" => String::new(),
m if ok => format!(r#"<p class="alert ok" role="status">{}</p>"#, esc(m)),
m => format!(r#"<p class="alert" role="alert">{}</p>"#, esc(m)),
};
let csrf = attr(&signed_in.csrf);
html(
status,
page(
"Account",
&format!(
r#"<div class="pagehead"><h1 class="title">Account</h1><p class="count">Signed in as {user}</p></div>{message}
<section class="panel form-panel"><h2>Change password</h2>
<form class="form" method="post" action="/account">
<input type="hidden" name="csrf" value="{csrf}">
<label>Current password<input name="current" type="password" autocomplete="current-password" required></label>
<label>New password<span class="hint">At least {MIN_PASSWORD} characters.</span><input name="new" type="password" autocomplete="new-password" minlength="{MIN_PASSWORD}" required></label>
<label>Repeat new password<input name="repeat" type="password" autocomplete="new-password" minlength="{MIN_PASSWORD}" required></label>
<label>Authenticator code<input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{{6}}" maxlength="6" required></label>
<button class="button primary" type="submit">Change password</button></form>
<p class="hint">Changing the password signs out every other session.</p></section>
<section class="panel form-panel"><h2>Sign out</h2>
<form method="post" action="/logout"><input type="hidden" name="csrf" value="{csrf}"><button class="button" type="submit">Sign out</button></form></section>"#,
user = esc(user)
),
),
)
}
pub async fn account(State(login): State<Arc<Login>>, Extension(signed_in): Extension<SignedIn>) -> Response {
match login.credentials() {
Ok(credentials) => account_page(StatusCode::OK, credentials.user(), &signed_in, "", false),
Err(_) => not_set_up(),
}
}
pub async fn change_password(
State(login): State<Arc<Login>>,
Extension(signed_in): Extension<SignedIn>,
Form(form): Form<ChangePasswordForm>,
) -> Response {
let Ok(credentials) = login.credentials() else { return not_set_up() };
let user = credentials.user().to_string();
let refuse = |status, message: &str| account_page(status, &user, &signed_in, message, false);
if !csrf_ok(&signed_in, &form.csrf) {
return refuse(StatusCode::FORBIDDEN, "That form has expired. Try again.");
}
if let Some(wait) = login.locked_for() {
let minutes = wait.as_secs().div_ceil(60).max(1);
return refuse(
StatusCode::TOO_MANY_REQUESTS,
&format!("Too many failed attempts. Try again in {minutes} minutes."),
);
}
if form.new != form.repeat {
return refuse(StatusCode::BAD_REQUEST, "The new passwords don’t match.");
}
if let Err(error) = check_new_password(&form.new) {
return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}."));
}
if !login.check(&credentials, None, form.current, &form.code).await {
return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right.");
}
let path = login.path.clone();
let new = form.new;
let saved = tokio::task::spawn_blocking(move || {
let mut updated = Credentials::load(&path)?;
updated.set_password(&new)?;
updated.save(&path)?;
Ok::<_, AuthError>(updated.fingerprint())
})
.await;
let fingerprint = match saved {
Ok(Ok(fingerprint)) => fingerprint,
Ok(Err(error)) => {
eprintln!("gitv-web: changing the password: {error}");
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed.");
}
Err(error) => {
eprintln!("gitv-web: changing the password: {error}");
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed.");
}
};
// Every other session ends; this one carries on with the new account fingerprint.
{
let mut sessions = login.sessions.lock().unwrap_or_else(|e| e.into_inner());
sessions.retain(|token, _| *token == signed_in.token_hash);
if let Some(session) = sessions.get_mut(&signed_in.token_hash) {
session.fingerprint = fingerprint;
}
}
account_page(StatusCode::OK, &user, &signed_in, "Password changed. Other sessions have been signed out.", true)
}
// ---------------------------------------------------------------------------------------------
// Command line
/// `gitv-web setup`: create the account with a generated password and a new authenticator
/// secret, and print both, with a QR code for authenticator apps.
///
/// # Errors
/// [`AuthError::AlreadySetUp`] if the account exists and `force` isn't set, or any error from
/// creating and saving it.
pub fn setup(user: &str, force: bool) -> Result<(), AuthError> {
let path = auth_path();
if path.exists() && !force {
return Err(AuthError::AlreadySetUp(path));
}
prepare_directory(&path)?;
let password = generate_password()?;
let credentials = Credentials::new(user, &password)?;
credentials.save(&path)?;
give_to_service(&path);
println!("Web sign-in is set up for {user} in {}.\n", path.display());
println!(" Password: {password}");
println!(" 2FA secret: {}\n", credentials.totp_secret_base32());
println!("Add the account to an authenticator app by scanning this code, or by entering the secret:\n");
if let Ok(code) = qrcode::QrCode::new(credentials.otpauth_uri().as_bytes()) {
println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());
}
println!("\n {}\n", credentials.otpauth_uri());
println!("The password is shown only now. Change it after signing in, under Account, or with: gitv-web password");
Ok(())
}
/// `gitv-web password`: set a new password, typed twice at the terminal. Signs every session out.
///
/// # Errors
/// [`AuthError::NotSetUp`] before `setup`, a password outside the rules, or a mismatch.
pub fn change_password_at_terminal() -> Result<(), String> {
let path = auth_path();
let mut credentials = Credentials::load(&path).map_err(|e| e.to_string())?;
let first = rpassword::prompt_password(format!("New web password for {}: ", credentials.user()))
.map_err(|e| format!("couldn't read the password (run this in a terminal): {e}"))?;
check_new_password(&first).map_err(|e| e.to_string())?;
let second = rpassword::prompt_password("Repeat it: ").map_err(|e| e.to_string())?;
if first != second {
return Err("the passwords differ; nothing changed".into());
}
credentials.set_password(&first).map_err(|e| e.to_string())?;
credentials.save(&path).map_err(|e| e.to_string())?;
give_to_service(&path);
println!("Password changed for {}. Every session has been signed out.", credentials.user());
Ok(())
}
/// Create the account file's directory if needed, private to its owner.
fn prepare_directory(path: &Path) -> Result<(), AuthError> {
let Some(directory) = path.parent().filter(|d| !d.as_os_str().is_empty()) else { return Ok(()) };
if !directory.exists() {
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(directory)
.map_err(|source| AuthError::Write { path: directory.to_path_buf(), source })?;
give_to_service(directory);
}
Ok(())
}
/// Run as root, hand a file to the `gitv-web` service account so the server can read it (and
/// save password changes). Without that account, or as anyone else, leave it as is.
fn give_to_service(path: &Path) {
if !nix::unistd::geteuid().is_root() {
return;
}
if let Ok(Some(user)) = nix::unistd::User::from_name("gitv-web") {
let _ = std::os::unix::fs::chown(path, Some(user.uid.as_raw()), Some(user.gid.as_raw()));
}
}
#[cfg(test)]
mod tests {
use super::*;
mod safe_next {
use super::*;
#[test]
fn keeps_local_paths() {
assert_eq!(safe_next("/ada/site/tree?ref=main"), "/ada/site/tree?ref=main");
}
#[test]
fn refuses_other_sites() {
for next in ["//evil.example/", "/\\evil.example", "https://evil.example/", "evil", "", "/a\r\nb"] {
assert_eq!(safe_next(next), "/", "{next:?}");
}
}
}
mod is_public {
use super::*;
#[test]
fn covers_only_the_sign_in_page_and_its_assets() {
for path in ["/login", "/style.css", "/favicon.svg", "/fonts/text.woff2"] {
assert!(is_public(path), "{path}");
}
for path in ["/", "/account", "/logout", "/ada/site/tree", "/login/../ada", "/loginx"] {
assert!(!is_public(path), "{path}");
}
}
}
mod lock {
use super::*;
fn login() -> Login {
Login {
path: PathBuf::new(),
loaded: Mutex::new(None),
sessions: Mutex::new(HashMap::new()),
guard: Mutex::new(Guard::default()),
}
}
#[test]
fn allows_the_first_failures() {
let login = login();
(0..FREE_FAILURES).for_each(|_| login.record_failure());
assert!(login.locked_for().is_none());
}
#[test]
fn locks_after_too_many_failures() {
let login = login();
(0..=FREE_FAILURES).for_each(|_| login.record_failure());
assert!(login.locked_for().is_some_and(|wait| wait <= Duration::from_secs(60)));
}
#[test]
fn grows_but_never_past_the_longest_lock() {
let login = login();
(0..FREE_FAILURES + 30).for_each(|_| login.record_failure());
assert!(login.locked_for().is_some_and(|wait| wait > Duration::from_secs(14 * 60) && wait <= LONGEST_LOCK));
}
#[test]
fn success_clears_it() {
let login = login();
(0..=FREE_FAILURES).for_each(|_| login.record_failure());
login.record_success(1);
assert!(login.locked_for().is_none());
}
}
}
@@ -1,8 +1,11 @@
//! Read-only web browser for GITv repositories, served on localhost behind Caddy.
//! Read-only web browser for GITv repositories, served on localhost behind Caddy, behind a
//! sign-in with a password and an authenticator code (see [`login`]).
//!
//! Every repository on the server is visible to anyone who can reach this service: it is meant
//! for one trusted audience behind the proxy's login, not for per-owner access like SSH.
mod login;
use std::borrow::Cow;
use std::cell::OnceCell;
use std::cmp::Reverse;
@@ -13,10 +16,11 @@ use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::Router;
use axum::extract::{Path, RawQuery};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Router, routing::get};
use axum::routing::{get, post};
use clap::{Parser, Subcommand};
use gitv::render;
use gitv::{
@@ -27,10 +31,10 @@ use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
use nix::sys::stat::SFlag;
use std::os::fd::{AsFd, OwnedFd};
const STYLESHEET: &str = include_str!("../../assets/style.css");
const FONT_DISPLAY: &[u8] = include_bytes!("../../assets/fonts/display.woff2");
const FONT_TEXT: &[u8] = include_bytes!("../../assets/fonts/text.woff2");
const FONT_MONO: &[u8] = include_bytes!("../../assets/fonts/mono.woff2");
const STYLESHEET: &str = include_str!("../../../assets/style.css");
const FONT_DISPLAY: &[u8] = include_bytes!("../../../assets/fonts/display.woff2");
const FONT_TEXT: &[u8] = include_bytes!("../../../assets/fonts/text.woff2");
const FONT_MONO: &[u8] = include_bytes!("../../../assets/fonts/mono.woff2");
const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#0f6b5f"/><g fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round"><circle cx="11" cy="9" r="2.6"/><circle cx="11" cy="23" r="2.6"/><circle cx="22" cy="12" r="2.6"/><path d="M11 11.6v8.8M22 14.6c0 4-3.4 5-11 6"/></g></svg>"##;
/// The stylesheet's URL carries a hash of its contents, so browsers can cache it for good and
@@ -111,6 +115,17 @@ enum Action {
#[arg(long, default_value_t = 8080)]
port: u16,
},
/// Create the web account: a generated password and an authenticator (2FA) secret
Setup {
/// The account name
#[arg(long, default_value = gitv::auth::DEFAULT_USER)]
user: String,
/// Replace an existing account, signing every session out
#[arg(long)]
force: bool,
},
/// Change the web account's password, typed at the terminal
Password,
}
enum View {
@@ -124,7 +139,7 @@ enum View {
const SECURITY: [(header::HeaderName, &str); 4] = [
(
header::CONTENT_SECURITY_POLICY,
"default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'",
"default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::REFERRER_POLICY, "no-referrer"),
@@ -292,7 +307,14 @@ fn size(bytes: usize) -> String {
}
}
/// A page for someone signed in: the top bar links to their account.
fn page(title: &str, body: &str) -> String {
layout(title, body, true)
}
/// A page, with the account link in the top bar only when `signed_in`.
fn layout(title: &str, body: &str, signed_in: bool) -> String {
let account = if signed_in { r#"<a class="account" href="/account">Account</a>"# } else { "" };
format!(
r##"<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
@@ -301,7 +323,7 @@ fn page(title: &str, body: &str) -> String {
<link rel="preload" href="/fonts/display.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/fonts/text.woff2" as="font" type="font/woff2" crossorigin></head>
<body><a class="skip" href="#main">Skip to content</a>
<header class="top"><div class="bar"><a class="mark" href="/">{LOGO}GITv</a></div></header>
<header class="top"><div class="bar"><a class="mark" href="/">{LOGO}GITv</a>{account}</div></header>
<main id="main">{body}</main></body></html>"##,
title = esc(title),
style = STYLE_URL.as_str(),
@@ -1401,36 +1423,61 @@ async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View {
})
}
#[tokio::main]
async fn main() {
let Action::Serve { port } = Cli::parse().action;
// Load the syntax definitions now rather than on the first visitor's request.
tokio::task::spawn_blocking(render::warm_up);
let app = Router::new()
.route("/", get(|| blocking(view_index)))
.route("/style.css", get(|| async { stylesheet() }))
.route("/favicon.svg", get(|| async { static_file("image/svg+xml", FAVICON.as_bytes()) }))
.route("/fonts/display.woff2", get(|| async { static_file("font/woff2", FONT_DISPLAY) }))
.route("/fonts/text.woff2", get(|| async { static_file("font/woff2", FONT_TEXT) }))
.route("/fonts/mono.woff2", get(|| async { static_file("font/woff2", FONT_MONO) }))
.route(
"/{owner}/{name}",
get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, None, &parse_query(q.as_deref())))
}),
)
.route(
"/{owner}/{name}/{view}",
get(|Path((o, n, v)): Path<(String, String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref())))
}),
)
.fallback(|| async { View::Missing });
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.expect("bind port");
// Print the bound address (not the requested port), so `--port 0` works for tests.
let address = listener.local_addr().expect("local address");
println!("gitv-web listening on http://{address} (repos: {})", repos_root().display());
axum::serve(listener, app).await.expect("server");
fn main() -> std::process::ExitCode {
let outcome = match Cli::parse().action {
Action::Serve { port } => serve(port),
Action::Setup { user, force } => login::setup(&user, force).map_err(|e| e.to_string()),
Action::Password => login::change_password_at_terminal(),
};
match outcome {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(error) => {
eprintln!("gitv-web: {error}");
std::process::ExitCode::FAILURE
}
}
}
fn serve(port: u16) -> Result<(), String> {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| e.to_string())?;
runtime.block_on(async {
// Load the syntax definitions now rather than on the first visitor's request.
tokio::task::spawn_blocking(render::warm_up);
let login = login::Login::new();
let app = Router::new()
.route("/", get(|| blocking(view_index)))
.route("/style.css", get(|| async { stylesheet() }))
.route("/favicon.svg", get(|| async { static_file("image/svg+xml", FAVICON.as_bytes()) }))
.route("/fonts/display.woff2", get(|| async { static_file("font/woff2", FONT_DISPLAY) }))
.route("/fonts/text.woff2", get(|| async { static_file("font/woff2", FONT_TEXT) }))
.route("/fonts/mono.woff2", get(|| async { static_file("font/woff2", FONT_MONO) }))
.route("/login", get(login::sign_in_form).post(login::sign_in))
.route("/logout", post(login::sign_out))
.route("/account", get(login::account).post(login::change_password))
.route(
"/{owner}/{name}",
get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, None, &parse_query(q.as_deref())))
}),
)
.route(
"/{owner}/{name}/{view}",
get(|Path((o, n, v)): Path<(String, String, String)>, RawQuery(q): RawQuery| {
blocking(move || route(&o, &n, Some(&v), &parse_query(q.as_deref())))
}),
)
.fallback(|| async { View::Missing })
// Every route above, and the fallback, sits behind the sign-in check.
.layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login))
.with_state(login);
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await
.map_err(|e| format!("can't listen on port {port}: {e}"))?;
// Print the bound address (not the requested port), so `--port 0` works for tests.
let address = listener.local_addr().map_err(|e| e.to_string())?;
println!("gitv-web listening on http://{address} (repos: {})", repos_root().display());
axum::serve(listener, app).await.map_err(|e| e.to_string())
})
}
#[cfg(test)]
@@ -1,5 +1,6 @@
//! Shared pieces of GITv: configuration, name rules and read-only git access.
pub mod auth;
pub mod render;
use std::ffi::{OsStr, OsString};
+348−0
@@ -0,0 +1,348 @@
//! Signing in to `gitv-web`: who gets in, who doesn't, and what a session can do.
mod common;
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;
use common::{Host, Server, scratch, session_cookie, stderr};
/// A host with one (empty) repository, shared by every test; each test runs its own server.
fn repos() -> &'static PathBuf {
static REPOS: OnceLock<PathBuf> = OnceLock::new();
REPOS.get_or_init(|| {
let host = Host::new("auth-host");
assert!(host.admin(&["create", "ada", "notes"]).status.success());
host.repos.clone()
})
}
fn sign_in(s: &Server, user: &str, password: &str, code: &str, next: &str) -> common::Response {
s.post_signed_out("/login", &[("user", user), ("password", password), ("code", code), ("next", next)])
}
mod signed_out {
use super::*;
#[test]
fn pages_redirect_to_sign_in_and_remember_where_you_were_going() {
let s = Server::start_signed_out(repos());
let response = s.get_signed_out("/ada/notes/tree?ref=main");
assert_eq!(response.status, 303);
assert_eq!(response.header("location"), "/login?next=/ada/notes/tree%3Fref%3Dmain");
}
#[test]
fn nothing_private_is_reachable() {
let s = Server::start_signed_out(repos());
for path in ["/", "/ada/notes", "/ada/notes/raw?path=x", "/ada/notes/log", "/account", "/nope", "/login/../"] {
let response = s.get_signed_out(path);
assert_eq!(response.status, 303, "{path} was served");
assert!(response.header("location").starts_with("/login"), "{path}");
}
}
#[test]
fn writes_are_refused_before_anything_else() {
let s = Server::start_signed_out(repos());
assert_eq!(s.post_signed_out("/logout", &[("csrf", "x")]).status, 303);
assert_eq!(s.post_signed_out("/account", &[("csrf", "x")]).status, 303);
}
#[test]
fn the_sign_in_page_and_its_assets_are_public() {
let s = Server::start_signed_out(repos());
for path in ["/login", "/style.css", "/favicon.svg", "/fonts/text.woff2"] {
assert_eq!(s.get_signed_out(path).status, 200, "{path}");
}
}
#[test]
fn the_sign_in_page_reveals_no_repositories() {
let s = Server::start_signed_out(repos());
let html = s.get_signed_out("/login").text();
assert!(html.contains(r#"<form class="panel form" method="post" action="/login">"#), "{html}");
assert!(!html.contains("notes") && !html.contains("/account"), "{html}");
}
#[test]
fn the_sign_in_page_sends_the_security_headers() {
let s = Server::start_signed_out(repos());
let csp = s.get_signed_out("/login").header("content-security-policy").to_string();
assert!(csp.contains("default-src 'none'") && csp.contains("form-action 'self'"), "{csp}");
}
}
mod signing_in {
use super::*;
#[test]
fn the_right_details_start_a_hardened_session() {
let s = Server::start_signed_out(repos());
let response = sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "/ada/notes/tree");
assert_eq!((response.status, response.header("location")), (303, "/ada/notes/tree"));
let cookie = response.header("set-cookie");
for part in ["__Host-gitv=", "Path=/", "HttpOnly", "Secure", "SameSite=Strict", "Max-Age=43200"] {
assert!(cookie.contains(part), "{part} missing from {cookie}");
}
}
#[test]
fn the_session_opens_private_pages() {
let s = Server::start(repos());
assert_eq!(s.get("/ada/notes/tree").status, 200);
}
#[test]
fn every_wrong_detail_gets_the_same_answer() {
let s = Server::start_signed_out(repos());
let password = s.account.password.clone();
let cases = [
("wrong user", "um9i", password.as_str(), s.account.code(0)),
("wrong password", "Um9i", "not the password", s.account.code(0)),
("wrong code", "Um9i", password.as_str(), "000000".to_string()),
("old code", "Um9i", password.as_str(), s.account.code(-3)),
];
for (name, user, password, code) in &cases {
let response = sign_in(&s, user, password, code, "/");
assert_eq!(response.status, 401, "{name}");
assert!(response.text().contains("That username, password or code isn’t right."), "{name}");
assert!(session_cookie(&response).is_none(), "{name} got a session");
}
}
#[test]
fn a_code_works_only_once() {
let s = Server::start_signed_out(repos());
let code = s.account.code(0);
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &code, "/").status, 303);
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &code, "/").status, 401);
}
#[test]
fn the_next_code_still_works_after_one_is_used() {
let s = Server::start_signed_out(repos());
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "/").status, 303);
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &s.account.code(1), "/").status, 303);
}
#[test]
fn it_never_sends_you_to_another_site() {
let s = Server::start_signed_out(repos());
let response = sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "//evil.example/");
assert_eq!(response.header("location"), "/");
}
#[test]
fn too_many_failures_lock_it_even_for_the_right_details() {
let s = Server::start_signed_out(repos());
for _ in 0..5 {
assert_eq!(sign_in(&s, "Um9i", "wrong password", &s.account.code(0), "/").status, 401);
}
assert_eq!(sign_in(&s, "Um9i", "wrong password", &s.account.code(0), "/").status, 429);
let response = sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "/");
assert_eq!(response.status, 429, "the lock let the right details in");
assert!(response.text().contains("Too many failed sign-ins. Try again in 1 minute."), "{}", response.text());
}
#[test]
fn a_forged_cookie_is_not_a_session() {
let mut s = Server::start_signed_out(repos());
s.cookie = Some("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".into());
assert_eq!(s.get("/").status, 303);
}
}
mod signing_out {
use super::*;
fn csrf(s: &Server) -> String {
let html = s.get("/account").text();
let start = html.find(r#"name="csrf" value=""#).expect("a csrf field") + r#"name="csrf" value=""#.len();
html[start..start + html[start..].find('"').unwrap()].to_string()
}
#[test]
fn ends_the_session() {
let s = Server::start(repos());
let response = s.post("/logout", &[("csrf", &csrf(&s))]);
assert_eq!((response.status, response.header("location")), (303, "/login"));
assert!(response.header("set-cookie").contains("Max-Age=0"));
assert_eq!(s.get("/").status, 303, "the old cookie still works");
}
#[test]
fn needs_the_form_token() {
let s = Server::start(repos());
assert_eq!(s.post("/logout", &[("csrf", "forged")]).status, 403);
assert_eq!(s.get("/").status, 200, "a forged sign-out ended the session");
}
}
mod changing_the_password {
use super::*;
fn csrf(s: &Server) -> String {
let html = s.get("/account").text();
let start = html.find(r#"name="csrf" value=""#).expect("a csrf field") + r#"name="csrf" value=""#.len();
html[start..start + html[start..].find('"').unwrap()].to_string()
}
fn change(s: &Server, csrf: &str, current: &str, new: &str, repeat: &str, code: &str) -> common::Response {
s.post("/account", &[("csrf", csrf), ("current", current), ("new", new), ("repeat", repeat), ("code", code)])
}
#[test]
fn works_and_keeps_this_session() {
let s = Server::start(repos());
let response = change(
&s,
&csrf(&s),
&s.account.password,
"a brand new password",
"a brand new password",
&s.account.code(1),
);
assert_eq!(response.status, 200, "{}", response.text());
assert!(response.text().contains("Password changed."));
assert_eq!(s.get("/").status, 200);
}
#[test]
fn the_new_password_works_and_the_old_one_does_not() {
let s = Server::start(repos());
let old = s.account.password.clone();
let new = "another new password";
assert_eq!(change(&s, &csrf(&s), &old, new, new, &s.account.code(1)).status, 200);
// Codes used so far: the sign-in's (step 0) and the change's (step +1).
assert_eq!(sign_in(&s, "Um9i", &old, &s.account.code(1), "/").status, 401);
let loaded = gitv::auth::Credentials::load(&s.account.file).unwrap();
assert!(loaded.verify_password(new) && !loaded.verify_password(&old));
}
#[test]
fn signs_out_every_other_session() {
// Two sessions and a password change need three unused codes; codes only work in
// increasing order, so use the previous, current and next steps in turn.
let mut first = Server::start_signed_out(repos());
let response = sign_in(&first, "Um9i", &first.account.password, &first.account.code(-1), "/");
first.cookie = session_cookie(&response);
let response = sign_in(&first, "Um9i", &first.account.password, &first.account.code(0), "/");
let mut second = Server::start_signed_out(repos());
second.port = first.port;
second.cookie = session_cookie(&response);
assert_eq!(second.get("/").status, 200);
let new = "yet another new password";
let response = change(&first, &csrf(&first), &first.account.password, new, new, &first.account.code(1));
assert_eq!(response.status, 200, "{}", response.text());
assert_eq!(second.get("/").status, 303, "the other session survived");
assert_eq!(first.get("/").status, 200, "this session was ended");
}
#[test]
fn needs_the_current_password() {
let s = Server::start(repos());
let response =
change(&s, &csrf(&s), "not it", "a brand new password", "a brand new password", &s.account.code(1));
assert_eq!(response.status, 401);
assert!(gitv::auth::Credentials::load(&s.account.file).unwrap().verify_password(&s.account.password));
}
#[test]
fn needs_a_code() {
let s = Server::start(repos());
let response =
change(&s, &csrf(&s), &s.account.password, "a brand new password", "a brand new password", "000000");
assert_eq!(response.status, 401);
}
#[test]
fn needs_the_form_token() {
let s = Server::start(repos());
let response = change(
&s,
"forged",
&s.account.password,
"a brand new password",
"a brand new password",
&s.account.code(1),
);
assert_eq!(response.status, 403);
}
#[test]
fn refuses_mismatched_new_passwords() {
let s = Server::start(repos());
let response = change(
&s,
&csrf(&s),
&s.account.password,
"a brand new password",
"a brand new passw0rd",
&s.account.code(1),
);
assert_eq!(response.status, 400);
assert!(response.text().contains("The new passwords don’t match."));
}
#[test]
fn refuses_short_new_passwords() {
let s = Server::start(repos());
let response = change(&s, &csrf(&s), &s.account.password, "too short", "too short", &s.account.code(1));
assert_eq!(response.status, 400);
assert!(response.text().contains("use at least 12 characters"), "{}", response.text());
}
#[test]
fn on_the_server_signs_everyone_out() {
let s = Server::start(repos());
assert_eq!(s.get("/").status, 200);
// What `gitv-web password` does: rewrite the account file with a new password.
let mut credentials = gitv::auth::Credentials::load(&s.account.file).unwrap();
credentials.set_password("changed on the server").unwrap();
credentials.save(&s.account.file).unwrap();
assert_eq!(s.get("/").status, 303);
}
}
mod setup {
use super::*;
#[test]
fn refuses_to_replace_an_account_without_force() {
let dir = scratch("auth-setup-twice");
common::Account::create(&dir);
let out = Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap();
assert!(!out.status.success());
assert!(stderr(&out).contains("already set up"), "{}", stderr(&out));
}
#[test]
fn with_force_replaces_it_and_signs_everyone_out() {
let s = Server::start(repos());
let out = Command::new(common::GITV_WEB)
.args(["setup", "--force"])
.env("GITV_WEB_AUTH", &s.account.file)
.output()
.unwrap();
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(s.get("/").status, 303);
}
#[test]
fn uses_um9i_by_default() {
let dir = scratch("auth-setup-user");
let account = common::Account::create(&dir);
assert_eq!(gitv::auth::Credentials::load(&account.file).unwrap().user(), "Um9i");
}
#[test]
fn without_an_account_the_site_says_how_to_set_one_up() {
let s = Server::start_signed_out(repos());
std::fs::remove_file(&s.account.file).unwrap();
let response = s.get_signed_out("/");
assert_eq!(response.status, 503);
assert!(response.text().contains("gitv-web setup"));
}
}
@@ -131,23 +131,88 @@ pub fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).into_owned()
}
/// A running `gitv-web`, stopped when dropped.
/// A web account made by `gitv-web setup`: where it's stored, and what it printed.
pub struct Account {
pub file: PathBuf,
pub password: String,
pub secret: Vec<u8>,
}
impl Account {
/// Run `gitv-web setup` for a new account in `dir`.
pub fn create(dir: &Path) -> Account {
let file = dir.join("login");
let out = Command::new(GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap();
assert!(out.status.success(), "setup failed: {}", stderr(&out));
let printed = stdout(&out);
let field = |label: &str| {
printed
.lines()
.find_map(|l| l.trim().strip_prefix(label))
.map(|v| v.trim().to_string())
.unwrap_or_else(|| panic!("no {label} in: {printed}"))
};
let password = field("Password:");
let secret = data_encoding::BASE32_NOPAD.decode(field("2FA secret:").as_bytes()).unwrap();
Account { file, password, secret }
}
/// The authenticator code `offset` steps from now.
pub fn code(&self, offset: i64) -> String {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
let step = gitv::auth::totp_step(now).saturating_add_signed(offset);
format!("{:06}", gitv::auth::totp_code(&self.secret, step))
}
}
/// A fresh, private directory for one server's account.
fn account_dir() -> PathBuf {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
scratch(&format!("web-account-{}-{n}", std::process::id()))
}
/// A running `gitv-web`, stopped when dropped. Unless started signed out, it has its own
/// account and a signed-in session, which [`Server::get`] uses.
pub struct Server {
child: Child,
pub port: u16,
pub account: Account,
pub cookie: Option<String>,
}
impl Server {
/// A server with its own account, already signed in.
pub fn start(repos: &Path) -> Server {
Server::start_with(repos, None)
let mut server = Server::start_with(repos, None);
server.sign_in_now();
server
}
/// Start with at most `limit` open file descriptors.
/// Like [`Server::start`], with at most `limit` open file descriptors.
pub fn start_limited(repos: &Path, limit: u64) -> Server {
Server::start_with(repos, Some(limit))
let mut server = Server::start_with(repos, Some(limit));
server.sign_in_now();
server
}
/// A server with its own account, not signed in.
pub fn start_signed_out(repos: &Path) -> Server {
Server::start_with(repos, None)
}
/// Sign in with the account's password and the current code, keeping the cookie.
pub fn sign_in_now(&mut self) {
let code = self.account.code(0);
let password = self.account.password.clone();
let response = self
.post_signed_out("/login", &[("user", "Um9i"), ("password", &password), ("code", &code), ("next", "/")]);
assert_eq!(response.status, 303, "sign-in failed: {}", response.text());
self.cookie = Some(session_cookie(&response).expect("a session cookie"));
}
fn start_with(repos: &Path, limit: Option<u64>) -> Server {
let account = Account::create(&account_dir());
let mut command = Command::new(GITV_WEB);
if let Some(limit) = limit {
use std::os::unix::process::CommandExt;
@@ -162,6 +227,7 @@ impl Server {
let mut child = command
.args(["serve", "--port", "0"])
.env("GITV_REPOS", repos)
.env("GITV_WEB_AUTH", &account.file)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
@@ -174,14 +240,54 @@ 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 }
Server { child, port, account, cookie: None }
}
/// GET with the session cookie, if signed in.
pub fn get(&self, path: &str) -> Response {
get(self.port, path)
request(self.port, "GET", path, self.cookie.as_deref(), None)
}
/// GET without any cookie.
pub fn get_signed_out(&self, path: &str) -> Response {
request(self.port, "GET", path, None, None)
}
/// POST a form with the session cookie, if signed in.
pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Response {
request(self.port, "POST", path, self.cookie.as_deref(), Some(&form_body(form)))
}
/// POST a form without any cookie.
pub fn post_signed_out(&self, path: &str, form: &[(&str, &str)]) -> Response {
request(self.port, "POST", path, None, Some(&form_body(form)))
}
}
/// The session token a response's `Set-Cookie` gives, if any.
pub fn session_cookie(response: &Response) -> Option<String> {
response
.header("set-cookie")
.strip_prefix("__Host-gitv=")?
.split(';')
.next()
.filter(|t| !t.is_empty())
.map(String::from)
}
/// `application/x-www-form-urlencoded`, as a browser sends a form.
fn form_body(form: &[(&str, &str)]) -> String {
let encode = |v: &str| -> String {
v.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
_ => format!("%{b:02X}"),
})
.collect()
};
form.iter().map(|(k, v)| format!("{}={}", encode(k), encode(v))).collect::<Vec<_>>().join("&")
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.child.kill();
@@ -205,10 +311,18 @@ impl Response {
}
}
/// A plain HTTP/1.1 GET, enough for testing a local server.
pub fn get(port: u16, path: &str) -> Response {
/// A plain HTTP/1.1 request, enough for testing a local server.
fn request(port: u16, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Response {
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
write!(stream, "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
let mut head = format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n");
if let Some(cookie) = cookie {
head += &format!("Cookie: __Host-gitv={cookie}\r\n");
}
let body = form.unwrap_or("");
if form.is_some() {
head += &format!("Content-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\n", body.len());
}
write!(stream, "{head}\r\n{body}").unwrap();
let mut raw = Vec::new();
stream.read_to_end(&mut raw).unwrap();
let split = raw.windows(4).position(|w| w == b"\r\n\r\n").expect("no header end");
@@ -588,14 +588,9 @@ fn bad_requests_are_not_found() {
#[test]
fn writes_are_refused() {
// Signed in, so the request reaches the router, which only serves reads here.
let s = server();
let mut stream = std::net::TcpStream::connect(("127.0.0.1", s.port)).unwrap();
use std::io::{Read, Write};
write!(stream, "POST /ada/site/tree HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.unwrap();
let mut reply = String::new();
stream.read_to_string(&mut reply).unwrap();
assert!(reply.starts_with("HTTP/1.1 405"), "{reply}");
assert_eq!(s.post("/ada/site/tree", &[]).status, 405);
}
#[test]