v0.2.0 is 3 commits ahead of v0.1.0.
Swap17 files changed +2829−134
+285−0
| @@ -58,6 +58,65 @@ 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 = "askama" | ||
| version = "0.16.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" | ||
| dependencies = [ | ||
| "askama_macros", | ||
| "itoa", | ||
| "percent-encoding", | ||
| "serde", | ||
| "serde_json", | ||
| ] | ||
| [[package]] | ||
| name = "askama_derive" | ||
| version = "0.16.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" | ||
| dependencies = [ | ||
| "askama_parser", | ||
| "memchr", | ||
| "proc-macro2", | ||
| "quote", | ||
| "rustc-hash", | ||
| "syn", | ||
| ] | ||
| [[package]] | ||
| name = "askama_macros" | ||
| version = "0.16.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" | ||
| dependencies = [ | ||
| "askama_derive", | ||
| ] | ||
| [[package]] | ||
| name = "askama_parser" | ||
| version = "0.16.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" | ||
| dependencies = [ | ||
| "rustc-hash", | ||
| "unicode-ident", | ||
| "winnow", | ||
| ] | ||
| [[package]] | ||
| name = "atomic-waker" | ||
| version = "1.1.2" | ||
| @@ -122,6 +181,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 +202,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 +288,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 +324,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 +416,41 @@ 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", | ||
| "askama", | ||
| "axum", | ||
| "base64", | ||
| "clap", | ||
| "data-encoding", | ||
| "getrandom", | ||
| "hmac", | ||
| "html-escape", | ||
| "nix", | ||
| "pulldown-cmark", | ||
| "qrcode", | ||
| "rpassword", | ||
| "serde", | ||
| "sha1", | ||
| "sha2", | ||
| "shlex", | ||
| "subtle", | ||
| "syntect", | ||
| "thiserror", | ||
| "tokio", | ||
| ] | ||
| @@ -297,6 +460,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 +520,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 +672,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 +738,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 +753,45 @@ 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 = "rustc-hash" | ||
| version = "2.1.3" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" | ||
| [[package]] | ||
| name = "ryu" | ||
| version = "1.0.23" | ||
| @@ -573,6 +814,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" | ||
| dependencies = [ | ||
| "serde_core", | ||
| "serde_derive", | ||
| ] | ||
| [[package]] | ||
| @@ -631,6 +873,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 +935,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 +1069,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" | ||
| @@ -857,6 +1133,15 @@ dependencies = [ | ||
| "windows-link", | ||
| ] | ||
| [[package]] | ||
| name = "winnow" | ||
| version = "1.0.5" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" | ||
| dependencies = [ | ||
| "memchr", | ||
| ] | ||
| [[package]] | ||
| name = "zlib-rs" | ||
| version = "0.6.8" | ||
+19−0
| @@ -4,16 +4,35 @@ version = "0.1.0" | ||
| edition = "2024" | ||
| [dependencies] | ||
| argon2 = "0.6.0" | ||
| askama = { version = "0.16.1", default-features = false, features = ["derive", "std"] } | ||
| 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. Root-run setup hands the default service directory to `gitv-web`. If you point `GITV_WEB_AUTH` into an existing custom directory, give the service write and search access there first. 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`. | ||
+37−0
| @@ -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)} | ||
| @@ -229,3 +254,15 @@ a.entry:hover .name{color:var(--accent)} | ||
| @media (prefers-reduced-motion:no-preference){ | ||
| a.entry,.repo-row,.tabs a,.button,.segmented a,.refmenu summary,.menu a{transition:background-color .12s,border-color .12s,color .12s} | ||
| } | ||
| .tree-row{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr) max-content;align-items:center;column-gap:12px;padding-right:16px} | ||
| .tree-row:hover,.tree-row:focus-within{background:var(--sunk)} | ||
| .tree-row .entry{min-width:0} | ||
| .entry-commit{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink-2)} | ||
| .entry-commit:hover,.entry-commit:focus-visible{color:var(--accent);text-decoration:underline} | ||
| .tree-row time{justify-self:end;white-space:nowrap;color:var(--ink-2);font-size:13px} | ||
| @media(max-width:650px){ | ||
| .tree-row{grid-template-columns:minmax(0,1fr) max-content} | ||
| .tree-row time{grid-column:2;grid-row:1} | ||
| .entry-commit{grid-column:1/-1;padding:0 0 8px 42px;font-size:13px} | ||
| } | ||
src/auth.rsAdded
+819−0
| @@ -0,0 +1,819 @@ | ||
| //! 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), | ||
| #[error("the account changed meanwhile (someone else changed the password or reset it); nothing was saved")] | ||
| Changed, | ||
| #[error("use a user name of 1 to {MAX_USER} visible characters, without spaces")] | ||
| BadUser, | ||
| #[error("couldn't hand {} to the service account: {source}", path.display())] | ||
| Ownership { path: PathBuf, source: nix::errno::Errno }, | ||
| } | ||
| /// Longest account name accepted, in characters. | ||
| pub const MAX_USER: usize = 64; | ||
| /// Check an account name: 1 to [`MAX_USER`] characters, none of them whitespace or control | ||
| /// characters, so it reads back from the account file exactly as written. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::BadUser`] otherwise. | ||
| pub fn check_user(user: &str) -> Result<(), AuthError> { | ||
| let length = user.chars().count(); | ||
| let visible = user.chars().all(|c| !c.is_whitespace() && !c.is_control()); | ||
| if (1..=MAX_USER).contains(&length) && visible { Ok(()) } else { Err(AuthError::BadUser) } | ||
| } | ||
| /// Who files written for the web service must belong to. `None` leaves them with whoever | ||
| /// writes them; a root-run command passes the service account's ids (see [`service_owner`]). | ||
| pub type Owner = Option<(nix::unistd::Uid, nix::unistd::Gid)>; | ||
| /// Run as root, the `gitv-web` service account, which must own everything it reads and | ||
| /// changes; otherwise (or without that account) `None`. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Read`] if the account database can't be read. | ||
| pub fn service_owner() -> Result<Owner, AuthError> { | ||
| if !nix::unistd::geteuid().is_root() { | ||
| return Ok(None); | ||
| } | ||
| let user = nix::unistd::User::from_name("gitv-web") | ||
| .map_err(|e| AuthError::Read { path: PathBuf::from("/etc/passwd"), source: e.into() })?; | ||
| Ok(user.map(|u| (u.uid, u.gid))) | ||
| } | ||
| /// Give an open file to `owner`, through its handle. | ||
| fn hand_over(file: &fs::File, path: &Path, owner: Owner) -> Result<(), AuthError> { | ||
| let Some((uid, gid)) = owner else { return Ok(()) }; | ||
| nix::unistd::fchown(file, Some(uid), Some(gid)) | ||
| .map_err(|source| AuthError::Ownership { path: path.to_path_buf(), source }) | ||
| } | ||
| /// How [`Credentials`] are published. | ||
| enum Publish { | ||
| Replace, | ||
| OnlyIfAbsent, | ||
| } | ||
| /// A hidden name beside `path` that no other writer, in this process or another, will use. | ||
| fn unique_sibling(path: &Path, purpose: &str) -> Result<PathBuf, AuthError> { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let nonce = data_encoding::HEXLOWER.encode(&random_bytes::<8>()?); | ||
| Ok(path.with_file_name(format!(".{name}.{purpose}-{}-{nonce}", std::process::id()))) | ||
| } | ||
| /// Exclusive permission to change the account file, held by every writer (`setup`, | ||
| /// `password`, the web Account page) across processes, so their read-check-write steps can't | ||
| /// interleave. Released when dropped. | ||
| pub struct WriteLock { | ||
| _lock: nix::fcntl::Flock<fs::File>, | ||
| } | ||
| /// Take the account file's [`WriteLock`], waiting for any other writer to finish. The lock file | ||
| /// is given to `owner`, so a root-run command never leaves one the service can't open. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Write`] if the lock file can't be opened or locked. | ||
| pub fn lock_for_writing(path: &Path, owner: Owner) -> Result<WriteLock, AuthError> { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let lock_path = path.with_file_name(format!(".{name}.lock")); | ||
| let file = fs::File::options() | ||
| .create(true) | ||
| .append(true) | ||
| .mode(0o600) | ||
| .open(&lock_path) | ||
| .map_err(|source| AuthError::Write { path: lock_path.clone(), source })?; | ||
| // The service must be able to take this lock too, to save password changes. | ||
| hand_over(&file, &lock_path, owner)?; | ||
| let lock = nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive) | ||
| .map_err(|(_, e)| AuthError::Write { path: lock_path, source: e.into() })?; | ||
| Ok(WriteLock { _lock: lock }) | ||
| } | ||
| /// Change the password, but only if the account is still the one that authorized the change: | ||
| /// `authorized` is the [fingerprint](Credentials::fingerprint) the caller checked. A reset or | ||
| /// another change in between makes this refuse rather than overwrite it. Returns the new | ||
| /// fingerprint. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Changed`] if the account changed since it was checked, a password outside | ||
| /// the rules, or any error reading or writing the file. | ||
| pub fn change_password( | ||
| path: &Path, | ||
| authorized: [u8; 32], | ||
| new_password: &str, | ||
| owner: Owner, | ||
| ) -> Result<[u8; 32], AuthError> { | ||
| check_new_password(new_password)?; | ||
| let _lock = lock_for_writing(path, owner)?; | ||
| let mut credentials = Credentials::load(path)?; | ||
| if credentials.fingerprint() != authorized { | ||
| return Err(AuthError::Changed); | ||
| } | ||
| credentials.set_password(new_password)?; | ||
| credentials.save(path, owner)?; | ||
| Ok(credentials.fingerprint()) | ||
| } | ||
| /// Check an authenticator code and use it up, for good: the last accepted time step is kept in | ||
| /// a file beside the account (tied to the authenticator secret), read and written under the | ||
| /// [`WriteLock`], so a code works once across restarts and across processes. Returns whether | ||
| /// the code was accepted. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Write`] or [`AuthError::Read`] if the record can't be read or written; the | ||
| /// code is then not accepted. | ||
| pub fn consume_code(path: &Path, credentials: &Credentials, code: &str, unix_seconds: u64) -> Result<bool, AuthError> { | ||
| let _lock = lock_for_writing(path, None)?; | ||
| let record = sibling(path, "used"); | ||
| let secret_id = data_encoding::HEXLOWER.encode(&Sha256::digest(&credentials.totp_secret)); | ||
| let last_step = match fs::read_to_string(&record) { | ||
| Ok(text) => text | ||
| .split_once(' ') | ||
| .filter(|(id, _)| *id == secret_id) | ||
| .and_then(|(_, step)| step.trim().parse::<u64>().ok()) | ||
| .unwrap_or(0), | ||
| Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, | ||
| Err(source) => return Err(AuthError::Read { path: record, source }), | ||
| }; | ||
| let Some(step) = credentials.verify_code(code, unix_seconds, last_step) else { return Ok(false) }; | ||
| write_replacing(&record, format!("{secret_id} {step}\n").as_bytes(), None)?; | ||
| Ok(true) | ||
| } | ||
| /// `.NAME.SUFFIX` beside `path`. | ||
| fn sibling(path: &Path, suffix: &str) -> PathBuf { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| path.with_file_name(format!(".{name}.{suffix}")) | ||
| } | ||
| /// Write `contents` to `path` atomically through a unique temporary file, private to its | ||
| /// owner, replacing what's there. | ||
| fn write_replacing(path: &Path, contents: &[u8], owner: Owner) -> Result<(), AuthError> { | ||
| write_atomically(path, contents, owner, Publish::Replace) | ||
| } | ||
| /// Write through a unique temporary file, given to `owner` by handle before it's published, so | ||
| /// the published file is never anyone else's even for a moment. | ||
| fn write_atomically(path: &Path, contents: &[u8], owner: Owner, mode: Publish) -> Result<(), AuthError> { | ||
| let write_error = |source| AuthError::Write { path: path.to_path_buf(), source }; | ||
| let temporary = unique_sibling(path, "tmp")?; | ||
| // Created exclusively under a name no other writer uses; only then is it ours to clean up. | ||
| let mut file = | ||
| fs::File::options().write(true).create_new(true).mode(0o600).open(&temporary).map_err(write_error)?; | ||
| let written = (|| { | ||
| file.write_all(contents).map_err(write_error)?; | ||
| file.sync_all().map_err(write_error)?; | ||
| hand_over(&file, path, owner)?; | ||
| let flags = match mode { | ||
| Publish::Replace => nix::fcntl::RenameFlags::empty(), | ||
| // One atomic step that fails if the name exists, instead of a rename (which would | ||
| // replace it) or a link-then-unlink (whose second step could fail after success). | ||
| Publish::OnlyIfAbsent => nix::fcntl::RenameFlags::RENAME_NOREPLACE, | ||
| }; | ||
| nix::fcntl::renameat2(nix::fcntl::AT_FDCWD, &temporary, nix::fcntl::AT_FDCWD, path, flags).map_err( | ||
| |e| match e { | ||
| nix::errno::Errno::EEXIST => AuthError::AlreadySetUp(path.to_path_buf()), | ||
| e => write_error(e.into()), | ||
| }, | ||
| ) | ||
| })(); | ||
| if written.is_err() { | ||
| let _ = fs::remove_file(&temporary); | ||
| } | ||
| written | ||
| } | ||
| /// 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::BadUser`] for an unusable name, [`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_user(user)?; | ||
| 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| check_user(u).is_ok()).ok_or("no valid 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, replacing any existing one, readable and writable by | ||
| /// its owner only, and given to `owner` before it's published. Hold a [`WriteLock`] around | ||
| /// the read-check-write that leads here. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Write`] if the file can't be written or renamed, [`AuthError::Ownership`] | ||
| /// if it can't be handed over. | ||
| pub fn save(&self, path: &Path, owner: Owner) -> Result<(), AuthError> { | ||
| write_replacing(path, self.serialize().as_bytes(), owner) | ||
| } | ||
| /// Like [`Credentials::save`], but only if no account file exists yet, so two first-time | ||
| /// setups can't both succeed with different accounts. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::AlreadySetUp`] if an account file appeared, or as [`Credentials::save`]. | ||
| pub fn save_new(&self, path: &Path, owner: Owner) -> Result<(), AuthError> { | ||
| write_atomically(path, self.serialize().as_bytes(), owner, Publish::OnlyIfAbsent) | ||
| } | ||
| fn serialize(&self) -> String { | ||
| 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() | ||
| ) | ||
| } | ||
| /// 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, None).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, None).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 writers { | ||
| use super::*; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-w-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn a_change_authorized_against_an_older_account_is_refused() { | ||
| let dir = scratch("stale"); | ||
| let path = dir.join("login"); | ||
| let before = account(); | ||
| before.save(&path, None).unwrap(); | ||
| let authorized = before.fingerprint(); | ||
| // An operator resets the account in between. | ||
| let reset = Credentials::new("Um9i", "the operator's reset").unwrap(); | ||
| reset.save(&path, None).unwrap(); | ||
| let result = change_password(&path, authorized, "the user's new password", None); | ||
| assert!(matches!(result, Err(AuthError::Changed)), "the stale change went through"); | ||
| assert!( | ||
| Credentials::load(&path).unwrap().verify_password("the operator's reset"), | ||
| "the reset was overwritten" | ||
| ); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_current_change_is_saved() { | ||
| let dir = scratch("current"); | ||
| let path = dir.join("login"); | ||
| let credentials = account(); | ||
| credentials.save(&path, None).unwrap(); | ||
| let fingerprint = change_password(&path, credentials.fingerprint(), "a fresh password", None).unwrap(); | ||
| let saved = Credentials::load(&path).unwrap(); | ||
| assert!(saved.verify_password("a fresh password") && saved.fingerprint() == fingerprint); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn save_new_never_replaces_an_account() { | ||
| let dir = scratch("new"); | ||
| let path = dir.join("login"); | ||
| account().save_new(&path, None).unwrap(); | ||
| let second = Credentials::new("Um9i", "a different account").unwrap(); | ||
| assert!(matches!(second.save_new(&path, None), Err(AuthError::AlreadySetUp(_)))); | ||
| assert!(Credentials::load(&path).unwrap().verify_password("correct horse battery")); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn concurrent_saves_in_one_process_all_land_whole() { | ||
| let dir = scratch("concurrent"); | ||
| let path = dir.join("login"); | ||
| let saves: Vec<_> = (0..8) | ||
| .map(|_| { | ||
| let path = path.clone(); | ||
| std::thread::spawn(move || account().save(&path, None)) | ||
| }) | ||
| .collect(); | ||
| for save in saves { | ||
| save.join().unwrap().unwrap(); | ||
| } | ||
| assert!(Credentials::load(&path).is_ok()); | ||
| let leftovers: Vec<_> = fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect(); | ||
| assert_eq!(leftovers, [std::ffi::OsString::from("login")], "temporaries were left behind"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
| mod users { | ||
| use super::*; | ||
| #[test] | ||
| fn ordinary_names_are_accepted() { | ||
| for user in ["Um9i", "ada", "a.b-c_d", &"x".repeat(MAX_USER)] { | ||
| assert!(check_user(user).is_ok(), "{user}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn names_that_would_not_read_back_are_refused() { | ||
| for user in ["", "two words", "line\nbreak", "tab\t", " leading", &"x".repeat(MAX_USER + 1), "bell\u{7}"] { | ||
| assert!(matches!(check_user(user), Err(AuthError::BadUser)), "{user:?}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn an_account_with_a_bad_name_is_never_created() { | ||
| assert!(matches!(Credentials::new("", "a long enough password"), Err(AuthError::BadUser))); | ||
| } | ||
| } | ||
| mod codes_across_processes { | ||
| use super::*; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-c-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn a_code_is_accepted_once_even_by_a_fresh_reader() { | ||
| let dir = scratch("once"); | ||
| let path = dir.join("login"); | ||
| account().save(&path, None).unwrap(); | ||
| assert!(consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| // Nothing in memory carries over: the record on disk refuses it. | ||
| assert!(!consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_new_authenticator_secret_starts_afresh() { | ||
| let dir = scratch("fresh"); | ||
| let path = dir.join("login"); | ||
| account().save(&path, None).unwrap(); | ||
| assert!(consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| let mut replaced = account(); | ||
| replaced.totp_secret = b"another secret of twenty".to_vec(); | ||
| let code = format!("{:06}", totp_code(&replaced.totp_secret, 1)); | ||
| assert!(consume_code(&path, &replaced, &code, 59).unwrap(), "the old secret's record blocked the new one"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
| 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" | ||
| ); | ||
| } | ||
| } | ||
| } | ||
+762−0
| @@ -0,0 +1,762 @@ | ||
| //! 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, OpenOptionsExt}; | ||
| use std::os::unix::process::CommandExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | ||
| use axum::Extension; | ||
| use axum::extract::{Form, FromRequest, 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>, | ||
| /// Password checks running at once. Argon2 is deliberately costly in memory and time, and | ||
| /// the sign-in form is open to anyone, so a burst of guesses queues here. | ||
| hashing: Arc<tokio::sync::Semaphore>, | ||
| /// Sign-in attempts admitted at once, waiting or running. Past this, more are turned away | ||
| /// before their bodies are even read, so a flood can't pile up passwords in memory. | ||
| admission: Arc<tokio::sync::Semaphore>, | ||
| /// Password checks started, for tests to confirm the bound holds. | ||
| #[cfg(test)] | ||
| checks_started: std::sync::atomic::AtomicUsize, | ||
| } | ||
| /// Sign-in attempts admitted at once (see [`Login::admission`]). | ||
| const ADMITTED_ATTEMPTS: usize = 32; | ||
| /// Largest sign-in or account form accepted, in bytes: far more than the fields need. | ||
| pub const FORM_LIMIT: usize = 8 * 1024; | ||
| /// Password checks allowed to run at once. | ||
| const CONCURRENT_CHECKS: usize = 2; | ||
| /// What checking a password and code found. | ||
| enum Checked { | ||
| Right, | ||
| Wrong, | ||
| /// Sign-in was locked by the time this attempt's turn came. | ||
| Locked(Duration), | ||
| /// The record of used codes couldn't be read or written, so no code can be trusted. | ||
| Unavailable, | ||
| } | ||
| /// 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>, | ||
| } | ||
| /// 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::at(auth_path())) | ||
| } | ||
| fn at(path: PathBuf) -> Login { | ||
| Login { | ||
| path, | ||
| loaded: Mutex::new(None), | ||
| sessions: Mutex::new(HashMap::new()), | ||
| guard: Mutex::new(Guard::default()), | ||
| hashing: Arc::new(tokio::sync::Semaphore::new(CONCURRENT_CHECKS)), | ||
| admission: Arc::new(tokio::sync::Semaphore::new(ADMITTED_ATTEMPTS)), | ||
| #[cfg(test)] | ||
| checks_started: std::sync::atomic::AtomicUsize::new(0), | ||
| } | ||
| } | ||
| /// 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(¤t.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())) | ||
| } | ||
| #[cfg(test)] | ||
| fn record_failure(&self) { | ||
| Self::fail(&mut self.guard.lock().unwrap_or_else(|e| e.into_inner())); | ||
| } | ||
| fn fail(guard: &mut Guard) { | ||
| 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); | ||
| } | ||
| } | ||
| /// Check a password and authenticator code, counting failures and using up the code. | ||
| /// | ||
| /// Waits for one of [`CONCURRENT_CHECKS`] slots first, then looks at the lock again, since | ||
| /// failures may have locked sign-in while this attempt waited. The hashing job holds its | ||
| /// slot until it has recorded its result, so no waiting attempt can start between a failure | ||
| /// and the lock it causes, and a cancelled request still counts. | ||
| async fn check( | ||
| self: &Arc<Self>, | ||
| credentials: &Arc<Credentials>, | ||
| user: Option<String>, | ||
| password: String, | ||
| code: &str, | ||
| ) -> Checked { | ||
| let Ok(permit) = Arc::clone(&self.hashing).acquire_owned().await else { return Checked::Wrong }; | ||
| if let Some(wait) = self.locked_for() { | ||
| return Checked::Locked(wait); | ||
| } | ||
| #[cfg(test)] | ||
| self.checks_started.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| let (login, creds, code) = (Arc::clone(self), Arc::clone(credentials), code.to_string()); | ||
| tokio::task::spawn_blocking(move || { | ||
| 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, password_ok, &code) | ||
| }) | ||
| .await | ||
| .unwrap_or(Checked::Wrong) | ||
| } | ||
| /// 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, password_ok: bool, code: &str) -> Checked { | ||
| let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner()); | ||
| let code_ok = password_ok | ||
| && match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) { | ||
| Ok(accepted) => accepted, | ||
| Err(error) => { | ||
| eprintln!("gitv-web: checking an authenticator code: {error}"); | ||
| return Checked::Unavailable; | ||
| } | ||
| }; | ||
| if code_ok { | ||
| guard.failures = 0; | ||
| guard.locked_until = None; | ||
| Checked::Right | ||
| } else { | ||
| Self::fail(&mut guard); | ||
| match guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now())) { | ||
| Some(wait) => Checked::Locked(wait), | ||
| None => Checked::Wrong, | ||
| } | ||
| } | ||
| } | ||
| } | ||
| /// 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()) | ||
| } | ||
| /// 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. This wraps every | ||
| /// route except the few public ones, which are routed separately by exact path, so no prefix | ||
| /// rule can ever make a repository page public. | ||
| pub async fn require_login(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response { | ||
| 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 { | ||
| html( | ||
| status, | ||
| super::templates::SignIn { title: "Sign in", signed_in: false, next: safe_next(next), message }.to_string(), | ||
| ) | ||
| } | ||
| 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>>, request: Request) -> Response { | ||
| // Turned away before the body is read when too many attempts are already waiting. | ||
| let Ok(_admitted) = Arc::clone(&login.admission).try_acquire_owned() else { | ||
| return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, "/", "Sign-in is busy. Try again in a moment."); | ||
| }; | ||
| if let Some(wait) = login.locked_for() { | ||
| return locked_page(wait); | ||
| } | ||
| // Too large (over FORM_LIMIT) or malformed: refused with the rejection's own status. | ||
| let form = match Form::<SignInForm>::from_request(request, &()).await { | ||
| Ok(Form(form)) => form, | ||
| Err(rejection) => { | ||
| return sign_in_page(rejection.status(), "/", "That sign-in form wasn’t accepted. Try again."); | ||
| } | ||
| }; | ||
| 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."); | ||
| } | ||
| }; | ||
| match login.check(&credentials, Some(form.user), form.password, &form.code).await { | ||
| Checked::Right => {} | ||
| Checked::Locked(wait) => return locked_page(wait), | ||
| Checked::Unavailable => { | ||
| return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now."); | ||
| } | ||
| // One message for every mistake, so a guess reveals nothing about which part was wrong. | ||
| Checked::Wrong => { | ||
| return 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}.")); | ||
| } | ||
| match login.check(&credentials, None, form.current, &form.code).await { | ||
| Checked::Right => {} | ||
| Checked::Locked(wait) => { | ||
| 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."), | ||
| ); | ||
| } | ||
| Checked::Wrong => return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right."), | ||
| Checked::Unavailable => { | ||
| return refuse(StatusCode::SERVICE_UNAVAILABLE, "Changing the password is unavailable right now."); | ||
| } | ||
| } | ||
| // Saved only if the account is still the one just checked: an operator's reset in the | ||
| // meantime wins, rather than being overwritten by a change authorized against the old one. | ||
| let (path, authorized, new) = (login.path.clone(), credentials.fingerprint(), form.new); | ||
| let saved = tokio::task::spawn_blocking(move || gitv::auth::change_password(&path, authorized, &new, None)).await; | ||
| let fingerprint = match saved { | ||
| Ok(Ok(fingerprint)) => fingerprint, | ||
| Ok(Err(AuthError::Changed)) => { | ||
| return refuse( | ||
| StatusCode::CONFLICT, | ||
| "The account was changed while you were doing this, so nothing was saved. Sign in again.", | ||
| ); | ||
| } | ||
| 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> { | ||
| // A bad name is refused before anything is made, so --force can't swap a working account | ||
| // for one that won't load. | ||
| gitv::auth::check_user(user)?; | ||
| let path = auth_path(); | ||
| // Run as root, everything is made for the service account, which must read the account | ||
| // and take its lock to save password changes. | ||
| let owner = gitv::auth::service_owner()?; | ||
| prepare_directory(&path, owner)?; | ||
| let _lock = gitv::auth::lock_for_writing(&path, owner)?; | ||
| if path.exists() && !force { | ||
| return Err(AuthError::AlreadySetUp(path)); | ||
| } | ||
| let password = generate_password()?; | ||
| let credentials = Credentials::new(user, &password)?; | ||
| // Without --force, publishing itself refuses to replace an account, whatever the lock. | ||
| if force { | ||
| credentials.save(&path, owner)? | ||
| } else { | ||
| credentials.save_new(&path, owner)? | ||
| } | ||
| 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 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()); | ||
| } | ||
| // Typing took a while: apply the change only to the account that was loaded before it. | ||
| let owner = gitv::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv::auth::change_password(&path, credentials.fingerprint(), &first, owner).map_err(|e| e.to_string())?; | ||
| 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 and given to `owner`. | ||
| fn prepare_directory(path: &Path, owner: gitv::auth::Owner) -> Result<(), AuthError> { | ||
| let directory = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); | ||
| let write_error = |source| AuthError::Write { path: directory.to_owned(), source }; | ||
| // Only hand over a leaf we created or the dedicated service directory. An override | ||
| // can point into a shared directory whose ownership must stay with its administrator. | ||
| let mut created = false; | ||
| if !directory.exists() { | ||
| if let Some(parent) = directory.parent().filter(|p| !p.as_os_str().is_empty()) { | ||
| std::fs::DirBuilder::new().recursive(true).mode(0o700).create(parent).map_err(write_error)?; | ||
| } | ||
| match std::fs::DirBuilder::new().mode(0o700).create(directory) { | ||
| Ok(()) => created = true, | ||
| Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} | ||
| Err(e) => return Err(write_error(e)), | ||
| } | ||
| } | ||
| if let Some((uid, gid)) = owner { | ||
| if created || directory == Path::new("/var/lib/gitv-web") { | ||
| let dir = std::fs::File::options() | ||
| .read(true) | ||
| .custom_flags(nix::libc::O_DIRECTORY | nix::libc::O_NOFOLLOW) | ||
| .open(directory) | ||
| .map_err(write_error)?; | ||
| nix::unistd::fchown(&dir, Some(uid), Some(gid)) | ||
| .map_err(|source| AuthError::Ownership { path: directory.to_owned(), source })?; | ||
| } | ||
| // Check as the service, including traversal of ancestors and filesystem ACLs. | ||
| let accessible = std::process::Command::new("/usr/bin/test") | ||
| .arg("-w") | ||
| .arg(directory) | ||
| .arg("-a") | ||
| .arg("-x") | ||
| .arg(directory) | ||
| .uid(uid.as_raw()) | ||
| .gid(gid.as_raw()) | ||
| .status() | ||
| .map_err(write_error)?; | ||
| if !accessible.success() { | ||
| return Err(write_error(std::io::Error::new( | ||
| std::io::ErrorKind::PermissionDenied, | ||
| "gitv-web needs write and search access to the account directory and search access to its parents", | ||
| ))); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
| #[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 lock { | ||
| use super::*; | ||
| fn login() -> Login { | ||
| Login::at(PathBuf::new()) | ||
| } | ||
| #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| async fn a_burst_of_guesses_hashes_only_until_the_lock_falls() { | ||
| let login = Arc::new(login()); | ||
| let credentials = Arc::new(Credentials::new("Um9i", "the real password").unwrap()); | ||
| let guesses: Vec<_> = (0..20) | ||
| .map(|_| { | ||
| let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials)); | ||
| tokio::spawn(async move { login.check(&credentials, None, "a wrong guess".into(), "123456").await }) | ||
| }) | ||
| .collect(); | ||
| for guess in guesses { | ||
| let _ = guess.await; | ||
| } | ||
| // Five free failures lock sign-in on the sixth; at most the other slot's check was | ||
| // already running then. Everyone still waiting sees the lock and hashes nothing. | ||
| let started = login.checks_started.load(std::sync::atomic::Ordering::Relaxed); | ||
| assert!(started <= FREE_FAILURES as usize + CONCURRENT_CHECKS, "{started} password checks ran"); | ||
| } | ||
| #[tokio::test] | ||
| async fn a_full_queue_turns_sign_ins_away_unread() { | ||
| // A real account, so an attempt that got through would be judged (and fail). | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-admission-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| std::fs::create_dir_all(&dir).unwrap(); | ||
| Credentials::new("Um9i", "the real password").unwrap().save(&dir.join("login"), None).unwrap(); | ||
| let login = Arc::new(Login::at(dir.join("login"))); | ||
| let _taken: Vec<_> = | ||
| (0..ADMITTED_ATTEMPTS).map(|_| Arc::clone(&login.admission).try_acquire_owned().unwrap()).collect(); | ||
| let request = Request::builder() | ||
| .method("POST") | ||
| .uri("/login") | ||
| .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| .body(axum::body::Body::from("user=Um9i&password=guess&code=123456")) | ||
| .unwrap(); | ||
| let response = sign_in(State(Arc::clone(&login)), request).await; | ||
| assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); | ||
| assert_eq!(login.guard.lock().unwrap().failures, 0, "the attempt was judged anyway"); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[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()); | ||
| { | ||
| let mut guard = login.guard.lock().unwrap(); | ||
| guard.failures = 0; | ||
| guard.locked_until = None; | ||
| } | ||
| assert!(login.locked_for().is_none()); | ||
| } | ||
| } | ||
| } | ||
src/bin/gitv-web/main.rsRenamed
+157−115
| @@ -1,8 +1,12 @@ | ||
| //! 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; | ||
| mod templates; | ||
| use std::borrow::Cow; | ||
| use std::cell::OnceCell; | ||
| use std::cmp::Reverse; | ||
| @@ -13,10 +17,12 @@ 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::DefaultBodyLimit; | ||
| 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 +33,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 | ||
| @@ -42,9 +48,6 @@ static STYLE_URL: LazyLock<String> = LazyLock::new(|| { | ||
| format!("/style.css?v={:012x}", hasher.finish() & 0xffff_ffff_ffff) | ||
| }); | ||
| /// The favicon's branch glyph, coloured by the stylesheet so it follows light and dark mode. | ||
| const LOGO: &str = r#"<svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" 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>"#; | ||
| const PAGE: usize = 50; | ||
| /// Largest file the Raw view serves; bigger files are for `git clone`. | ||
| const RAW_LIMIT: usize = 50 << 20; | ||
| @@ -111,6 +114,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 +138,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,20 +306,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 { | ||
| format!( | ||
| r##"<!doctype html><html lang="en"><head><meta charset="utf-8"> | ||
| <meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| <title>{title} | GITv</title> | ||
| <link rel="stylesheet" href="{style}"><link rel="icon" href="/favicon.svg" type="image/svg+xml"> | ||
| <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> | ||
| <main id="main">{body}</main></body></html>"##, | ||
| title = esc(title), | ||
| style = STYLE_URL.as_str(), | ||
| ) | ||
| 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 { | ||
| templates::Layout { title, body, signed_in }.to_string() | ||
| } | ||
| fn view_missing() -> String { | ||
| @@ -532,6 +540,29 @@ impl Repo { | ||
| } | ||
| } | ||
| /// Latest change to one entry at this immutable revision. Keep the original path bytes | ||
| /// for Git and cache the timestamp itself so relative dates stay fresh. | ||
| fn entry_commit(&self, commit: &str, path: &[u8]) -> Option<templates::EntryCommit> { | ||
| let key = self.key("entry-commit", commit, &encode(path)); | ||
| let record = cached(key, || { | ||
| let args = ["log", "-1", "--format=%H%x00%ct%x00%cI%x00%s%x00%B", commit, "--"].map(OsStr::new); | ||
| self.git(&[args.as_slice(), &[OsStr::from_bytes(path)]].concat()).filter(|out| !out.is_empty()) | ||
| })?; | ||
| let mut fields = record.splitn(5, '\0'); | ||
| let oid = fields.next()?; | ||
| let stamp = fields.next()?; | ||
| let datetime = fields.next()?; | ||
| let subject = subject_or_placeholder(fields.next()?); | ||
| let message = fields.next()?.trim_end(); | ||
| Some(templates::EntryCommit { | ||
| url: self.url("commit", &[("id", oid)]), | ||
| subject: subject.into(), | ||
| message: if message.is_empty() { subject } else { message }.into(), | ||
| when: ago(stamp, datetime.split('T').next().unwrap_or(datetime)), | ||
| datetime: datetime.into(), | ||
| }) | ||
| } | ||
| /// Commits reachable from `commit`. A commit's history never changes, so the count is cached. | ||
| fn commit_count(&self, commit: &str) -> usize { | ||
| let key = format!("count:{}:{commit}", self.dir.path.display()); | ||
| @@ -882,29 +913,21 @@ fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| ); | ||
| } | ||
| for item in &entries { | ||
| let path = join(&path, &item.name); | ||
| let (view, class, glyph) = match item.kind.as_str() { | ||
| "tree" => ("tree", "entry dir", "dir"), | ||
| "commit" => { | ||
| // A submodule: its commits live in another repository, so there's nothing to open. | ||
| let _ = write!( | ||
| body, | ||
| r#"<li><span class="entry sub">{}<span class="name">{}</span><span class="quiet">Submodule at {}</span></span></li>"#, | ||
| icon("module"), | ||
| esc(&lossy(&item.name)), | ||
| &item.oid[..item.oid.len().min(7)] | ||
| ); | ||
| continue; | ||
| } | ||
| _ => ("blob", "entry", "file"), | ||
| "tree" => (Some("tree"), "entry dir", "dir"), | ||
| "commit" => (None, "entry sub", "module"), | ||
| _ => (Some("blob"), "entry", "file"), | ||
| }; | ||
| let href = repo.url_at(view, &reference, &join(&path, &item.name), ""); | ||
| let _ = write!( | ||
| body, | ||
| r#"<li><a class="{class}" href="{}">{}<span class="name">{}</span></a></li>"#, | ||
| attr(&href), | ||
| icon(glyph), | ||
| esc(&lossy(&item.name)) | ||
| ); | ||
| let row = templates::TreeRow { | ||
| name: lossy(&item.name), | ||
| class, | ||
| icon: icon(glyph), | ||
| href: view.map(|view| repo.url_at(view, &reference, &path, "")), | ||
| short_id: &item.oid[..item.oid.len().min(7)], | ||
| commit: repo.entry_commit(&commit, &path), | ||
| }; | ||
| let _ = write!(body, "{row}"); | ||
| } | ||
| body += "</ul></div>"; | ||
| @@ -1079,51 +1102,37 @@ fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| ])?; | ||
| let lines: Vec<&str> = out.lines().collect(); | ||
| let tags = repo.tags_by_commit(); | ||
| let mut rows = String::new(); | ||
| for line in lines.iter().take(PAGE) { | ||
| // Subject last, split at most five ways: a subject containing 0x1f stays whole. | ||
| let Some(head) = Head::parse(line) else { continue }; | ||
| let Head { oid, subject, author, stamp, date } = &head; | ||
| let chips: String = tags | ||
| .get(oid) | ||
| let mut rows = Vec::new(); | ||
| for head in lines.iter().take(PAGE).filter_map(|line| Head::parse(line)) { | ||
| let labels = tags | ||
| .get(&head.oid) | ||
| .into_iter() | ||
| .flatten() | ||
| .map(|t| { | ||
| format!( | ||
| r#"<a class="tagchip" href="{}">{}{}</a>"#, | ||
| attr(&repo.url("tree", &[("ref", &repo.tag_ref(t))])), | ||
| icon("tag"), | ||
| esc(t) | ||
| ) | ||
| }) | ||
| .map(|name| templates::TagLink { name, url: repo.url("tree", &[("ref", &repo.tag_ref(name))]) }) | ||
| .collect(); | ||
| let _ = write!( | ||
| rows, | ||
| r#"<li class="commit-row"><div class="cmain"><a class="csubj" href="{}">{}</a>{chips}<span class="cmeta">{} committed {}</span></div>{}</li>"#, | ||
| attr(&repo.url("commit", &[("id", oid)])), | ||
| esc(subject_or_placeholder(subject)), | ||
| esc(author), | ||
| ago(stamp, date), | ||
| repo.sha_link(oid) | ||
| ); | ||
| } | ||
| let mut pager = String::new(); | ||
| let page_link = |n: usize, label: &str| { | ||
| format!( | ||
| r#"<a class="button" href="{}">{label}</a>"#, | ||
| attr(&repo.url("log", &[("ref", &reference), ("page", &n.to_string())])) | ||
| ) | ||
| }; | ||
| pager += &if number > 0 { page_link(number - 1, "Newer") } else { "<span></span>".into() }; | ||
| if lines.len() > PAGE { | ||
| pager += &page_link(number + 1, "Older"); | ||
| rows.push(templates::CommitRow { | ||
| url: repo.url("commit", &[("id", &head.oid)]), | ||
| subject: subject_or_placeholder(&head.subject).to_owned(), | ||
| short_id: head.oid.chars().take(7).collect(), | ||
| author: head.author, | ||
| when: ago(&head.stamp, &head.date), | ||
| tags: labels, | ||
| }); | ||
| } | ||
| let body = repo.masthead("log", &reference, Some(&commit)) | ||
| + &repo.locator("log", &reference, b"") | ||
| + &format!( | ||
| r#"<div class="panel"><ul class="rows">{rows}</ul></div><nav class="pager" aria-label="Pages">{pager}</nav>"# | ||
| ); | ||
| Some(View::Html(page(&format!("Commits on {reference}"), &body))) | ||
| let page_url = |n: usize| repo.url("log", &[("ref", &reference), ("page", &n.to_string())]); | ||
| Some(View::Html( | ||
| templates::History { | ||
| title: format!("Commits on {reference}"), | ||
| signed_in: true, | ||
| masthead: repo.masthead("log", &reference, Some(&commit)), | ||
| locator: repo.locator("log", &reference, b""), | ||
| rows, | ||
| newer: number.checked_sub(1).map(page_url), | ||
| older: (lines.len() > PAGE).then(|| page_url(number + 1)), | ||
| tag_icon: icon("tag"), | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// One changed file: how git names it (raw bytes, from NUL-delimited output) and its status. | ||
| @@ -1401,36 +1410,69 @@ 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(); | ||
| // Anyone may load these exact paths: the sign-in page and what it needs to look right. | ||
| let public = Router::new() | ||
| .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).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), | ||
| ); | ||
| // Everything else, including any path not matched above, needs a session. | ||
| let private = Router::new() | ||
| .route("/", get(|| blocking(view_index))) | ||
| .route("/logout", post(login::sign_out).layer(DefaultBodyLimit::max(login::FORM_LIMIT))) | ||
| .route( | ||
| "/account", | ||
| get(login::account).post(login::change_password).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), | ||
| ) | ||
| .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 }) | ||
| .layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login)); | ||
| let app = public.merge(private).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)] | ||
+66−0
| @@ -0,0 +1,66 @@ | ||
| use askama::Template; | ||
| /// Wraps HTML already rendered and escaped by the existing page builders. | ||
| #[derive(Template)] | ||
| #[template(path = "layout.html")] | ||
| pub(super) struct Layout<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub body: &'a str, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "login.html")] | ||
| pub(super) struct SignIn<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub next: &'a str, | ||
| pub message: &'a str, | ||
| } | ||
| pub(super) struct TagLink<'a> { | ||
| pub name: &'a str, | ||
| pub url: String, | ||
| } | ||
| pub(super) struct CommitRow<'a> { | ||
| pub url: String, | ||
| pub subject: String, | ||
| pub short_id: String, | ||
| pub author: String, | ||
| pub when: String, | ||
| pub tags: Vec<TagLink<'a>>, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "history.html")] | ||
| pub(super) struct History<'a> { | ||
| pub title: String, | ||
| pub signed_in: bool, | ||
| // Existing HTML renderers escape repository data inside these fragments. | ||
| pub masthead: String, | ||
| pub locator: String, | ||
| pub tag_icon: String, | ||
| pub rows: Vec<CommitRow<'a>>, | ||
| pub newer: Option<String>, | ||
| pub older: Option<String>, | ||
| } | ||
| pub(super) struct EntryCommit { | ||
| pub url: String, | ||
| pub subject: String, | ||
| pub message: String, | ||
| pub when: String, | ||
| pub datetime: String, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "tree-row.html")] | ||
| pub(super) struct TreeRow<'a> { | ||
| pub name: std::borrow::Cow<'a, str>, | ||
| pub class: &'static str, | ||
| pub icon: String, | ||
| pub href: Option<String>, | ||
| pub short_id: &'a str, | ||
| pub commit: Option<EntryCommit>, | ||
| } | ||
+1−0
| @@ -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}; | ||
templates/base.htmlAdded
+9−0
| @@ -0,0 +1,9 @@ | ||
| <!doctype html><html lang="en"><head><meta charset="utf-8"> | ||
| <meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| <title>{{ title }} | GITv</title> | ||
| <link rel="stylesheet" href="{{ super::STYLE_URL.as_str() }}"><link rel="icon" href="/favicon.svg" type="image/svg+xml"> | ||
| <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="/"><svg class="logo" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="8"/><g fill="none" 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>GITv</a>{% if signed_in %}<a class="account" href="/account">Account</a>{% endif %}</div></header> | ||
| <main id="main">{% block content %}{% endblock %}</main></body></html> | ||
+15−0
| @@ -0,0 +1,15 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }}{{ locator|safe }} | ||
| <div class="panel"><ul class="rows"> | ||
| {% for row in rows %} | ||
| <li class="commit-row"><div class="cmain"><a class="csubj" href="{{ row.url }}">{{ row.subject }}</a> | ||
| {% for tag in row.tags %}<a class="tagchip" href="{{ tag.url }}">{{ tag_icon|safe }}{{ tag.name }}</a>{% endfor %} | ||
| <span class="cmeta">{{ row.author }} committed {{ row.when }}</span></div><a class="sha" href="{{ row.url }}">{{ row.short_id }}</a></li> | ||
| {% endfor %} | ||
| </ul></div> | ||
| <nav class="pager" aria-label="Pages"> | ||
| {% if let Some(url) = newer %}<a class="button" href="{{ url }}">Newer</a>{% else %}<span></span>{% endif %} | ||
| {% if let Some(url) = older %}<a class="button" href="{{ url }}">Older</a>{% endif %} | ||
| </nav> | ||
| {% endblock %} | ||
+2−0
| @@ -0,0 +1,2 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %}{{ body|safe }}{% endblock %} | ||
templates/login.htmlAdded
+8−0
| @@ -0,0 +1,8 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %}<section class="signin"><h1 class="title">Sign in</h1>{% if !message.is_empty() %}<p class="alert" role="alert">{{ message }}</p>{% endif %} | ||
| <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="{{ next }}"> | ||
| <button class="button primary" type="submit">Sign in</button></form></section>{% endblock %} | ||
+11−0
| @@ -0,0 +1,11 @@ | ||
| <li class="tree-row"> | ||
| {% if let Some(url) = href %} | ||
| <a class="{{ class }}" href="{{ url }}">{{ icon|safe }}<span class="name">{{ name }}</span></a> | ||
| {% else %} | ||
| <span class="{{ class }}">{{ icon|safe }}<span class="name">{{ name }}</span><span class="quiet">Submodule at {{ short_id }}</span></span> | ||
| {% endif %} | ||
| {% if let Some(change) = commit %} | ||
| <a class="entry-commit" href="{{ change.url }}" title="{{ change.message }}">{{ change.subject }}</a> | ||
| <time datetime="{{ change.datetime }}" title="{{ change.datetime }}">{{ change.when }}</time> | ||
| {% endif %} | ||
| </li> | ||
tests/auth.rsAdded
+464−0
| @@ -0,0 +1,464 @@ | ||
| //! 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()); | ||
| // An owner named like a public asset folder: its repositories are still private. | ||
| assert!(host.admin(&["create", "fonts", "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 an_owner_named_like_an_asset_folder_stays_private() { | ||
| let s = Server::start_signed_out(repos()); | ||
| for path in ["/fonts/notes/tree", "/fonts/notes", "/fonts/notes/log", "/fonts/text.woff2/x"] { | ||
| let response = s.get_signed_out(path); | ||
| assert_eq!(response.status, 303, "{path} was served signed out"); | ||
| } | ||
| } | ||
| #[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 a_code_sent_by_many_requests_at_once_lets_one_in() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let code = s.account.code(0); | ||
| let statuses: Vec<u16> = std::thread::scope(|scope| { | ||
| let attempts: Vec<_> = | ||
| (0..8).map(|_| scope.spawn(|| sign_in(&s, "Um9i", &s.account.password, &code, "/").status)).collect(); | ||
| attempts.into_iter().map(|a| a.join().unwrap()).collect() | ||
| }); | ||
| assert_eq!(statuses.iter().filter(|s| **s == 303).count(), 1, "{statuses:?}"); | ||
| } | ||
| #[test] | ||
| fn a_burst_of_guesses_meets_the_lock() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let statuses: Vec<u16> = std::thread::scope(|scope| { | ||
| let attempts: Vec<_> = | ||
| (0..20).map(|_| scope.spawn(|| sign_in(&s, "Um9i", "a wrong guess", "123456", "/").status)).collect(); | ||
| attempts.into_iter().map(|a| a.join().unwrap()).collect() | ||
| }); | ||
| // Five free failures, plus at most the two checks already hashing when the lock fell. | ||
| let judged = statuses.iter().filter(|s| **s == 401).count(); | ||
| assert!(judged <= 5 + 2, "{judged} guesses were checked: {statuses:?}"); | ||
| assert!(statuses.iter().all(|s| *s == 401 || *s == 429), "{statuses:?}"); | ||
| } | ||
| #[test] | ||
| fn a_used_code_stays_used_after_a_restart() { | ||
| let first = Server::start_signed_out(repos()); | ||
| let code = first.account.code(0); | ||
| assert_eq!(sign_in(&first, "Um9i", &first.account.password, &code, "/").status, 303); | ||
| let account = first.account.clone(); | ||
| drop(first); | ||
| let restarted = Server::start_signed_out_as(repos(), account); | ||
| assert_eq!(sign_in(&restarted, "Um9i", &restarted.account.password, &code, "/").status, 401); | ||
| } | ||
| #[test] | ||
| fn two_servers_on_one_account_accept_a_code_once() { | ||
| let one = Server::start_signed_out(repos()); | ||
| let two = Server::start_signed_out_as(repos(), one.account.clone()); | ||
| let code = one.account.code(0); | ||
| let statuses: Vec<u16> = std::thread::scope(|scope| { | ||
| let attempts: Vec<_> = [&one, &two, &one, &two] | ||
| .into_iter() | ||
| .map(|s| scope.spawn(|| sign_in(s, "Um9i", &s.account.password, &code, "/").status)) | ||
| .collect(); | ||
| attempts.into_iter().map(|a| a.join().unwrap()).collect() | ||
| }); | ||
| assert_eq!(statuses.iter().filter(|s| **s == 303).count(), 1, "{statuses:?}"); | ||
| } | ||
| #[test] | ||
| fn oversized_forms_are_refused_unread() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let huge = "x".repeat(64 * 1024); | ||
| assert_eq!(sign_in(&s, "Um9i", &huge, "123456", "/").status, 413); | ||
| } | ||
| #[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, None).unwrap(); | ||
| assert_eq!(s.get("/").status, 303); | ||
| } | ||
| } | ||
| mod setup { | ||
| use super::*; | ||
| #[test] | ||
| fn root_setup_refuses_an_unwritable_custom_directory_before_publication() { | ||
| let Some(_) = gitv::auth::service_owner().unwrap() else { return }; | ||
| let dir = scratch("auth-setup-root-owned"); | ||
| std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); | ||
| 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("write and search access")); | ||
| assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0); | ||
| } | ||
| #[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 two_setups_at_once_leave_one_account() { | ||
| let dir = scratch("auth-setup-race"); | ||
| let file = dir.join("login"); | ||
| let results: Vec<bool> = std::thread::scope(|scope| { | ||
| let runs: Vec<_> = (0..4) | ||
| .map(|_| { | ||
| scope.spawn(|| { | ||
| Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap() | ||
| }) | ||
| }) | ||
| .collect(); | ||
| runs.into_iter().map(|r| r.join().unwrap().status.success()).collect() | ||
| }); | ||
| assert_eq!(results.iter().filter(|ok| **ok).count(), 1, "{results:?}"); | ||
| assert!(gitv::auth::Credentials::load(&file).is_ok()); | ||
| } | ||
| #[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 refuses_user_names_that_would_not_read_back_and_keeps_the_account() { | ||
| let dir = scratch("auth-setup-bad-user"); | ||
| let account = common::Account::create(&dir); | ||
| for user in ["", "two words", "line\nbreak"] { | ||
| let out = Command::new(common::GITV_WEB) | ||
| .args(["setup", "--force", "--user", user]) | ||
| .env("GITV_WEB_AUTH", &account.file) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success(), "{user:?} was accepted"); | ||
| assert!(stderr(&out).contains("user name"), "{}", stderr(&out)); | ||
| } | ||
| let kept = gitv::auth::Credentials::load(&account.file).unwrap(); | ||
| assert!(kept.verify_password(&account.password), "a refused setup replaced the account"); | ||
| } | ||
| #[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")); | ||
| } | ||
| } | ||
+132−9
| @@ -131,23 +131,97 @@ 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. | ||
| #[derive(Clone)] | ||
| 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) | ||
| } | ||
| /// A server using an existing account (another server's, say), not signed in. | ||
| pub fn start_signed_out_as(repos: &Path, account: Account) -> Server { | ||
| Server::launch(repos, None, account) | ||
| } | ||
| /// 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 { | ||
| Server::launch(repos, limit, Account::create(&account_dir())) | ||
| } | ||
| fn launch(repos: &Path, limit: Option<u64>, account: Account) -> Server { | ||
| let mut command = Command::new(GITV_WEB); | ||
| if let Some(limit) = limit { | ||
| use std::os::unix::process::CommandExt; | ||
| @@ -162,6 +236,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,12 +249,52 @@ 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 { | ||
| @@ -205,10 +320,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"); | ||
+19−7
| @@ -348,6 +348,23 @@ fn tree_lists_folders_first_and_renders_the_readme() { | ||
| assert!(html.contains("<pre class=\"code\">") && html.contains("hl-"), "fenced code is highlighted"); | ||
| } | ||
| #[test] | ||
| fn tree_rows_link_each_entry_to_its_own_change() { | ||
| let html = server().get("/ada/site/tree").text(); | ||
| for (name, oid, message) in | ||
| [("README.md", &fixture().first, "With a body line."), ("src", &fixture().removal, "Remove old.txt")] | ||
| { | ||
| let row = html | ||
| .split("<li class=\"tree-row\">") | ||
| .skip(1) | ||
| .map(|row| row.split("</li>").next().unwrap()) | ||
| .find(|row| row.contains(&format!(">{name}<"))) | ||
| .unwrap(); | ||
| assert!(row.contains(&format!("/ada/site/commit?id={oid}")), "{row}"); | ||
| assert!(row.contains(message) && row.contains("<time datetime="), "{row}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn tree_shows_submodules_without_links() { | ||
| let s = server(); | ||
| @@ -588,14 +605,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] | ||