v0.3.0 is 61 commits ahead of v0.2.0.
Swap- 45cf485
- caf6319
- 2188fe3
- 1be53be
- 96810b9
- 4d496f4
- 217c970
- 7f0fe6d
- a4d3c9a
- a76c350
- 94562a0
- 9fa8012
- 85bbb02
- d57b798
- 3e9c128
- d087586
- 0fb1e46
- 7fc2fe7
- 1a2cc85
- 0414385
- 0f4caaa
- 4f9e91e
- 12b9bf3
- 4788d2f
- 26d14b5
- a47d6e4
- baecb32
- 2badbef
- c73daf9
- 6e8596b
- e6e0b23
- 9c80326
- 0ad5ce4
- 835619c
- dd59c34
- 44b30d1
- 9a916b2
- 1e37b1f
- 9d62c18
- 01924c9
- 7becb1a
- a50b863
- e5e8041
- 91e1c78
- f5068ab
- 0eac27b
- 511be5f
- 48807f7
- ce526ea
- a58a982
- a26d15d
- ddf3dff
- 85ff5e5
- de97a29
- ca9f486
- 08ea36c
- a87990a
- 37a7850
- 0d0992e
- 6a22d2a
- 50964bd
96 files changed +12879−3335
+58−0
| @@ -0,0 +1,58 @@ | ||
| name: CI | ||
| on: | ||
| push: | ||
| pull_request: | ||
| schedule: | ||
| # Weekly, so new advisories against unchanged dependencies still surface. | ||
| - cron: "17 6 * * 1" | ||
| permissions: | ||
| contents: read | ||
| # Every action is pinned to a commit, not a tag a compromised upstream could move. To update | ||
| # one, look up the new release's commit (git ls-remote --tags https://github.com/<owner>/<repo>) | ||
| # and change the hash and its comment together. | ||
| env: | ||
| CARGO_TERM_COLOR: always | ||
| jobs: | ||
| check: | ||
| name: Format, lint and test | ||
| runs-on: ubuntu-latest | ||
| # The suite takes seconds; a hang should fail fast rather than run for GitHub's six hours. | ||
| timeout-minutes: 20 | ||
| if: github.event_name != 'schedule' | ||
| steps: | ||
| - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 | ||
| - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable branch | ||
| with: | ||
| # Pinned to a commit, the action can't read the toolchain from a branch name. | ||
| toolchain: stable | ||
| components: rustfmt, clippy | ||
| - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 | ||
| - run: cargo fmt --all --check | ||
| - run: cargo clippy --workspace --all-targets --locked -- -D warnings | ||
| # The integration tests drive real git, rsync, flock and mountpoint, all on the runner. | ||
| # The whole workspace at once: the web tests use the gitv binary too. | ||
| - run: cargo test --workspace --locked | ||
| audit: | ||
| name: Dependency advisories and licences | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 10 | ||
| steps: | ||
| - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 | ||
| - uses: taiki-e/install-action@fe3acb53a98b62c772db35de75ce0e4595e7ca8c # v2.90.8 | ||
| with: | ||
| # cargo-about is pinned so THIRD-PARTY-LICENSES only changes when dependencies do. | ||
| tool: cargo-audit,cargo-about@0.9.3 | ||
| - run: cargo audit | ||
| - name: THIRD-PARTY-LICENSES is current | ||
| run: | | ||
| scripts/third-party-licenses "$RUNNER_TEMP/THIRD-PARTY-LICENSES" | ||
| diff -u THIRD-PARTY-LICENSES "$RUNNER_TEMP/THIRD-PARTY-LICENSES" || { | ||
| echo "::error::THIRD-PARTY-LICENSES is out of date: run scripts/third-party-licenses and commit the result" | ||
| exit 1 | ||
| } | ||
CLAUDE.mdAdded
+141−0
| @@ -0,0 +1,141 @@ | ||
| # CLAUDE.md | ||
| This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. | ||
| GITv is self-hosted Git hosting: pushes over OpenSSH, a read-only web browser, and read-only HTTPS cloning of public repositories. It runs on one Fedora droplet (git.um9i.dev) behind Caddy. | ||
| ## Commands | ||
| Run everything from the workspace root. The web tests run the `gitv` binary, which only a workspace build produces. | ||
| ```sh | ||
| cargo build # both binaries | ||
| cargo fmt --all --check # CI: rustfmt.toml sets max_width 120 | ||
| cargo clippy --workspace --all-targets --locked -- -D warnings # CI treats warnings as errors | ||
| cargo test --workspace --locked # everything | ||
| # One test, by package and target: | ||
| cargo test -p gitv-core --lib <name> # core unit tests | ||
| cargo test -p gitv --test ssh <name> # SSH handler integration tests | ||
| cargo test -p gitv --test backup <name> # deploy/gitv-backup and gitv-restore | ||
| cargo test -p gitv-web --lib <name> # auth.rs and render.rs unit tests | ||
| cargo test -p gitv-web --bin gitv-web <name> # unit tests in the server's own modules | ||
| cargo test -p gitv-web --test web <name> # every page over HTTP | ||
| cargo test -p gitv-web --test auth <name> # sign-in, sessions, lockout | ||
| ``` | ||
| Run locally against a scratch tree (admin commands skip the root check when `GITV_REPOS` is set): | ||
| ```sh | ||
| export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys GITV_HOST=localhost GITV_WEB_AUTH=$PWD/dev/web-login | ||
| ./target/debug/gitv create um9i demo | ||
| ./target/debug/gitv-web setup && ./target/debug/gitv-web serve --port 8080 | ||
| GIT_SSH_VARIANT=simple GIT_SSH_COMMAND=$PWD/scripts/fake-ssh git push um9i@local:um9i/demo.git main # runs `gitv serve` as that owner's key | ||
| ``` | ||
| When dependencies change, run `scripts/third-party-licenses` (needs `cargo install cargo-about --locked --features cli`) and commit the regenerated `THIRD-PARTY-LICENSES`. CI fails if it is stale, and it also runs `cargo audit`. The GitHub Actions in `.github/workflows/ci.yml` are pinned to commit hashes with version comments; update the hash and comment together. | ||
| ## Architecture | ||
| Three crates. `gitv` depends only on `gitv-core` and a few small crates, so building it never compiles the web stack. | ||
| - **`gitv-core`**: everything both binaries share: | ||
| - configuration (`config.rs`) | ||
| - name rules (`valid_name`) | ||
| - working through directory handles | ||
| - running git with a deadline and an output cap | ||
| - `publish_file`, which writes a file atomically | ||
| - **`gitv`**: the SSH forced command (`gitv serve <owner>`) and the root admin CLI. | ||
| - **`gitv-web`**: the axum browser and the smart-HTTP clone service. Its library exposes only `auth` and `render` (for tests and the CLI). The router, views and everything else live in the binary (`main.rs` plus modules). | ||
| ### Invariants that span the codebase | ||
| - **Directory handles, never paths.** Repositories live at `<root>/<owner>/<name>.git`. | ||
| - Code that finds, creates, deletes or lists repositories opens directories with `O_NOFOLLOW` through `gitv_core` (`open_owner`, `repo_dir`/`repo_in`, `open_dir`/`open_dir_at`, `try_entries`, `remove_tree_at`, `renameat2` with `RENAME_NOREPLACE`). | ||
| - It keeps a `RepoDir`, and git runs inside that open directory (`fchdir` in `pre_exec`). | ||
| - `RepoDir.path` is for messages and cache keys only; never reopen it. | ||
| - Symlinked owner or repository folders are refused. | ||
| - **All git goes through core.** | ||
| - `git_command`/`git`/`git_capped` (or `configure` for `git-receive-pack`/`git-upload-pack` run directly) give a cleared environment with no user or system config and literal pathspecs. | ||
| - A watchdog kills any command past `GIT_TIMEOUT`. A page-wide deadline is set with `RepoDir::limit_until`. | ||
| - Web pages read git output through `Reader::git_bytes`, capped at `PAGE_OUTPUT_LIMIT` (8 MiB) because the service runs under `MemoryMax=640M`. | ||
| - **Paths and ref names are bytes.** | ||
| - Git allows any bytes but `/` and NUL in names. Query values decode to `Vec<u8>` (`urls::parse_query`), are checked with `clean_path`, and reach git as `OsStr`. | ||
| - Only display uses `lossy()`. | ||
| - Plain names that could be misread (40/64-hex, `refs/…`, `HEAD`) are linked as qualified refs (`Reader::branch_ref`/`tag_ref`). `Reader::resolve` looks ids up as objects only. | ||
| - **Visibility** is a `gitv-public` marker file in the repository directory. For a signed-out visitor, a private repository and a missing one give the same answer (`View::LoginRequired`), so existence never leaks. Smart HTTP serves public repositories only, read-only. The description is git's `description` file, read and replaced through the directory handle (`RepoDir::description`/`set_description`); git's `Unnamed repository` placeholder counts as none. | ||
| - **No scripts, anywhere.** | ||
| - Every HTML response sends `SECURITY` (CSP `default-src 'none'`, no `script-src`). | ||
| - Raw files get `RAW_SECURITY`, which adds `sandbox`. | ||
| - Templates are askama and auto-escape. `|safe` is only for HTML produced by the templates themselves or by `render.rs`, which escapes raw HTML in Markdown and rewrites links. | ||
| - Don't add JavaScript or inline styles to pages. | ||
| ### `gitv` (SSH and admin) | ||
| - **Access.** `gitv add-key` writes `restrict,command="<gitv> serve <owner>"` lines to `/etc/gitv/authorized_keys`. A key reaches only its owner's repositories, and `serve` parses `SSH_ORIGINAL_COMMAND`. `gitv keys` and `remove-key` list and revoke keys by SHA-256 fingerprint; every change to the keys file goes through `edit_keys` (the `keys.lock` flock, then `publish_file`, then `restorecon`). | ||
| - **Pushes.** | ||
| - Pushing to a missing name creates the repository. It is built in a private staging folder and published by rename. | ||
| - A push holds the repository's `flock` shared. The backup takes it exclusive. | ||
| - A push runs with `PUSH_CONFIG` (no hooks, reflogs on every ref, unreachable objects kept 30 days), and appends ref changes to `gitv-push.log`. A repository with a `gitv-protected` marker (`gitv protect`) also gets `PROTECTED_CONFIG` (no non-fast-forward or deleting branch updates; git applies neither to tags). | ||
| - **Deletion** moves a repository to `<owner>/.trash/<name>.<unix time>`. `gitv purge`, run daily by a timer, removes entries older than 30 days. After that, `gitv-restore <snapshot> DIR OWNER/NAME` copies one repository out of a backup, and `gitv import` publishes it through the same staging and no-replace rename as `create` (`Contents::CopyOf`). | ||
| - **Logging.** SSH users only ever see generic errors. Details go to syslog, or to `$GITV_LOG` when it is set. | ||
| ### `gitv-web` | ||
| - **Routing (`main.rs`).** The routes form four groups: | ||
| - **Public, exact paths:** the assets and `/login`. | ||
| - **Smart HTTP:** `info/refs` and `git-upload-pack`. | ||
| - **Browse:** the `login::browse` middleware puts an `Extension<bool>` "signed in" on each request. | ||
| - **Private:** behind `login::require_login`. | ||
| - **Rendering and capacity.** | ||
| - Pages render on the blocking pool via `blocking()`. Renders, downloads and transfers each draw on a `capacity::Pool`, which reserves slots for signed-in sessions and caps each anonymous client. | ||
| - The client is an IPv4 address or IPv6 /64, taken from `X-Forwarded-For` only on loopback connections (`throttle::Client`). | ||
| - **Views (`views/`).** Each returns a `View`. `Repo` holds a `Reader` (git queries, one ref listing per request) and builds URLs and shared fragments. | ||
| - **Cache (`cache.rs`).** An LRU keyed by immutable object ids (plus the repository, when the content contains links). Concurrent requests for a missing key make it once. | ||
| - **Sign-in.** One account file (`$GITV_WEB_AUTH`, default `/var/lib/gitv-web/login`) holds an Argon2id password hash and a TOTP secret. | ||
| - `auth.rs`: credentials, the record of used codes, and the trusted-device token. | ||
| - `login.rs`: handlers, in-memory sessions, throttling. | ||
| - `setup.rs`: the `setup` and `password` commands. | ||
| - Sessions remember the account's fingerprint, so changing the password ends every other session. | ||
| - The trusted-device cookie lets a browser bypass only the global cap of 60 failed sign-ins an hour (`throttle.rs`). | ||
| ### Configuration and environment | ||
| - `/etc/gitv/gitv.conf` (`$GITV_CONFIG`) holds `host` and `command`. Parsing is strict: an unknown key is an error, and both binaries load it at startup. | ||
| - Overrides used by local runs and tests: `GITV_REPOS`, `GITV_KEYS`, `GITV_WEB_AUTH`, `GITV_HOST`, `GITV_LOG`. | ||
| - The backup scripts also read `GITV_BACKUP_DIR`, `GITV_BACKUP_SSH_DIR`, `GITV_BACKUP_REQUIRE_MOUNT` and `GITV_BACKUP_LOCK_WAIT`. | ||
| ### Tests | ||
| - **Helpers:** `testing/host.rs` is shared by both packages' integration tests through `#[path]` includes in `tests/common/mod.rs`. It builds a scratch installation (`Host`) and a stand-in for ssh. `crates/gitv-web/tests/common/web.rs` starts a real `gitv-web` on port 0 and speaks raw HTTP/1.1. | ||
| - **Scratch folders:** integration tests write under `CARGO_TARGET_TMPDIR`. Unit tests use the system temporary folder. | ||
| ## Deployment | ||
| The files in `deploy/` are the source copies of the host's configuration: systemd units and timers, the Caddyfile, the sshd drop-in, `gitv.conf`, and the backup and restore scripts. README.md has where each one goes, plus the backup and disaster-recovery procedures. | ||
| Pushing `master` to `origin` (GitHub) and `gitv` (the server itself) publishes source only; deploying is a separate step, over SSH as `root@git.um9i.dev`. The `git@` account has a forced command and can't deploy. | ||
| 1. **Check access:** `ssh -o BatchMode=yes root@git.um9i.dev 'id -un && systemctl is-active gitv-web'` should print `root`, then `active`. | ||
| 2. **Build locally:** `cargo build --locked --release --bins`. | ||
| - The droplet has no Rust toolchain. | ||
| - Its glibc is older than this machine's, so check with `objdump -T target/release/<bin> | grep -o 'GLIBC_[0-9.]*' | sort -uV | tail -1`. | ||
| 3. **Stage the files:** | ||
| - Copy the binaries (and any changed `deploy/` files) to a staging folder on the droplet. | ||
| - Verify their checksums there. | ||
| - Keep the previous versions for rollback. | ||
| 4. **Replace atomically:** | ||
| - Write each file beside its target, then rename it over the target (`install -m 0755 … .name.new && mv -f`), so a push mid-deploy never finds `gitv` missing. | ||
| - Run `restorecon` on the replaced files. | ||
| 5. **Restart and verify:** | ||
| - Run `systemctl restart gitv-web`. | ||
| - Check that the HTTPS homepage loads, and that `git ls-remote gitv HEAD` matches `master`. | ||
| - A binary-only release needs no sshd restart. | ||
| - Restarting `gitv-web` signs everyone out, since sessions are held in memory. | ||
| If a release changes units, timers, backup scripts or the Caddyfile, install those explicitly too (and `systemctl daemon-reload` for units). | ||
| ## Conventions | ||
| - Commit messages: a plain imperative subject saying what changed for the user or operator, then a body explaining why. | ||
| - Code comments explain why, in plain sentences, especially for security- and race-related choices; keep that style. | ||
+45−2
| @@ -360,6 +360,16 @@ dependencies = [ | ||
| "ctutils", | ||
| ] | ||
| [[package]] | ||
| name = "errno" | ||
| version = "0.3.15" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" | ||
| dependencies = [ | ||
| "libc", | ||
| "windows-sys", | ||
| ] | ||
| [[package]] | ||
| name = "find-msvc-tools" | ||
| version = "0.1.15" | ||
| @@ -429,7 +439,26 @@ dependencies = [ | ||
| [[package]] | ||
| name = "gitv" | ||
| version = "0.1.0" | ||
| version = "0.3.0" | ||
| dependencies = [ | ||
| "base64", | ||
| "clap", | ||
| "gitv-core", | ||
| "nix", | ||
| "sha2", | ||
| "shlex", | ||
| ] | ||
| [[package]] | ||
| name = "gitv-core" | ||
| version = "0.3.0" | ||
| dependencies = [ | ||
| "nix", | ||
| ] | ||
| [[package]] | ||
| name = "gitv-web" | ||
| version = "0.3.0" | ||
| dependencies = [ | ||
| "argon2", | ||
| "askama", | ||
| @@ -437,7 +466,10 @@ dependencies = [ | ||
| "base64", | ||
| "clap", | ||
| "data-encoding", | ||
| "flate2", | ||
| "futures-util", | ||
| "getrandom", | ||
| "gitv-core", | ||
| "hmac", | ||
| "html-escape", | ||
| "nix", | ||
| @@ -447,7 +479,6 @@ dependencies = [ | ||
| "serde", | ||
| "sha1", | ||
| "sha2", | ||
| "shlex", | ||
| "subtle", | ||
| "syntect", | ||
| "thiserror", | ||
| @@ -901,6 +932,16 @@ version = "2.0.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" | ||
| [[package]] | ||
| name = "signal-hook-registry" | ||
| version = "1.4.8" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" | ||
| dependencies = [ | ||
| "errno", | ||
| "libc", | ||
| ] | ||
| [[package]] | ||
| name = "simd-adler32" | ||
| version = "0.3.10" | ||
| @@ -1002,9 +1043,11 @@ version = "1.54.1" | ||
| source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" | ||
| dependencies = [ | ||
| "bytes", | ||
| "libc", | ||
| "mio", | ||
| "pin-project-lite", | ||
| "signal-hook-registry", | ||
| "socket2", | ||
| "tokio-macros", | ||
| "windows-sys", | ||
+15−6
| @@ -1,19 +1,28 @@ | ||
| [package] | ||
| name = "gitv" | ||
| version = "0.1.0" | ||
| [workspace] | ||
| resolver = "3" | ||
| members = ["crates/gitv-core", "crates/gitv", "crates/gitv-web"] | ||
| [workspace.package] | ||
| version = "0.3.0" | ||
| edition = "2024" | ||
| license = "AGPL-3.0-or-later" | ||
| [dependencies] | ||
| # One version of each dependency for the whole workspace; each crate names only what it uses, | ||
| # so building the SSH tool never compiles the web server's dependencies. | ||
| [workspace.dependencies] | ||
| gitv-core = { path = "crates/gitv-core" } | ||
| 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" | ||
| flate2 = "1.1.11" | ||
| futures-util = { version = "0.3.34", default-features = false, features = ["std"] } | ||
| getrandom = "0.4.3" | ||
| hmac = "0.13.0" | ||
| html-escape = "0.3.1" | ||
| nix = { version = "0.32.0", features = ["user", "fs", "dir", "resource"] } | ||
| nix = { version = "0.32.0", features = ["user", "fs", "dir", "resource", "hostname", "process"] } | ||
| pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] } | ||
| qrcode = { version = "0.15.0", default-features = false } | ||
| rpassword = "7.5.5" | ||
| @@ -24,7 +33,7 @@ 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"] } | ||
| tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync", "io-util", "process", "time", "signal"] } | ||
| [profile.release] | ||
| lto = "thin" | ||
LICENSEAdded
+661−0
| @@ -0,0 +1,661 @@ | ||
| GNU AFFERO GENERAL PUBLIC LICENSE | ||
| Version 3, 19 November 2007 | ||
| Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> | ||
| Everyone is permitted to copy and distribute verbatim copies | ||
| of this license document, but changing it is not allowed. | ||
| Preamble | ||
| The GNU Affero General Public License is a free, copyleft license for | ||
| software and other kinds of works, specifically designed to ensure | ||
| cooperation with the community in the case of network server software. | ||
| The licenses for most software and other practical works are designed | ||
| to take away your freedom to share and change the works. By contrast, | ||
| our General Public Licenses are intended to guarantee your freedom to | ||
| share and change all versions of a program--to make sure it remains free | ||
| software for all its users. | ||
| When we speak of free software, we are referring to freedom, not | ||
| price. Our General Public Licenses are designed to make sure that you | ||
| have the freedom to distribute copies of free software (and charge for | ||
| them if you wish), that you receive source code or can get it if you | ||
| want it, that you can change the software or use pieces of it in new | ||
| free programs, and that you know you can do these things. | ||
| Developers that use our General Public Licenses protect your rights | ||
| with two steps: (1) assert copyright on the software, and (2) offer | ||
| you this License which gives you legal permission to copy, distribute | ||
| and/or modify the software. | ||
| A secondary benefit of defending all users' freedom is that | ||
| improvements made in alternate versions of the program, if they | ||
| receive widespread use, become available for other developers to | ||
| incorporate. Many developers of free software are heartened and | ||
| encouraged by the resulting cooperation. However, in the case of | ||
| software used on network servers, this result may fail to come about. | ||
| The GNU General Public License permits making a modified version and | ||
| letting the public access it on a server without ever releasing its | ||
| source code to the public. | ||
| The GNU Affero General Public License is designed specifically to | ||
| ensure that, in such cases, the modified source code becomes available | ||
| to the community. It requires the operator of a network server to | ||
| provide the source code of the modified version running there to the | ||
| users of that server. Therefore, public use of a modified version, on | ||
| a publicly accessible server, gives the public access to the source | ||
| code of the modified version. | ||
| An older license, called the Affero General Public License and | ||
| published by Affero, was designed to accomplish similar goals. This is | ||
| a different license, not a version of the Affero GPL, but Affero has | ||
| released a new version of the Affero GPL which permits relicensing under | ||
| this license. | ||
| The precise terms and conditions for copying, distribution and | ||
| modification follow. | ||
| TERMS AND CONDITIONS | ||
| 0. Definitions. | ||
| "This License" refers to version 3 of the GNU Affero General Public License. | ||
| "Copyright" also means copyright-like laws that apply to other kinds of | ||
| works, such as semiconductor masks. | ||
| "The Program" refers to any copyrightable work licensed under this | ||
| License. Each licensee is addressed as "you". "Licensees" and | ||
| "recipients" may be individuals or organizations. | ||
| To "modify" a work means to copy from or adapt all or part of the work | ||
| in a fashion requiring copyright permission, other than the making of an | ||
| exact copy. The resulting work is called a "modified version" of the | ||
| earlier work or a work "based on" the earlier work. | ||
| A "covered work" means either the unmodified Program or a work based | ||
| on the Program. | ||
| To "propagate" a work means to do anything with it that, without | ||
| permission, would make you directly or secondarily liable for | ||
| infringement under applicable copyright law, except executing it on a | ||
| computer or modifying a private copy. Propagation includes copying, | ||
| distribution (with or without modification), making available to the | ||
| public, and in some countries other activities as well. | ||
| To "convey" a work means any kind of propagation that enables other | ||
| parties to make or receive copies. Mere interaction with a user through | ||
| a computer network, with no transfer of a copy, is not conveying. | ||
| An interactive user interface displays "Appropriate Legal Notices" | ||
| to the extent that it includes a convenient and prominently visible | ||
| feature that (1) displays an appropriate copyright notice, and (2) | ||
| tells the user that there is no warranty for the work (except to the | ||
| extent that warranties are provided), that licensees may convey the | ||
| work under this License, and how to view a copy of this License. If | ||
| the interface presents a list of user commands or options, such as a | ||
| menu, a prominent item in the list meets this criterion. | ||
| 1. Source Code. | ||
| The "source code" for a work means the preferred form of the work | ||
| for making modifications to it. "Object code" means any non-source | ||
| form of a work. | ||
| A "Standard Interface" means an interface that either is an official | ||
| standard defined by a recognized standards body, or, in the case of | ||
| interfaces specified for a particular programming language, one that | ||
| is widely used among developers working in that language. | ||
| The "System Libraries" of an executable work include anything, other | ||
| than the work as a whole, that (a) is included in the normal form of | ||
| packaging a Major Component, but which is not part of that Major | ||
| Component, and (b) serves only to enable use of the work with that | ||
| Major Component, or to implement a Standard Interface for which an | ||
| implementation is available to the public in source code form. A | ||
| "Major Component", in this context, means a major essential component | ||
| (kernel, window system, and so on) of the specific operating system | ||
| (if any) on which the executable work runs, or a compiler used to | ||
| produce the work, or an object code interpreter used to run it. | ||
| The "Corresponding Source" for a work in object code form means all | ||
| the source code needed to generate, install, and (for an executable | ||
| work) run the object code and to modify the work, including scripts to | ||
| control those activities. However, it does not include the work's | ||
| System Libraries, or general-purpose tools or generally available free | ||
| programs which are used unmodified in performing those activities but | ||
| which are not part of the work. For example, Corresponding Source | ||
| includes interface definition files associated with source files for | ||
| the work, and the source code for shared libraries and dynamically | ||
| linked subprograms that the work is specifically designed to require, | ||
| such as by intimate data communication or control flow between those | ||
| subprograms and other parts of the work. | ||
| The Corresponding Source need not include anything that users | ||
| can regenerate automatically from other parts of the Corresponding | ||
| Source. | ||
| The Corresponding Source for a work in source code form is that | ||
| same work. | ||
| 2. Basic Permissions. | ||
| All rights granted under this License are granted for the term of | ||
| copyright on the Program, and are irrevocable provided the stated | ||
| conditions are met. This License explicitly affirms your unlimited | ||
| permission to run the unmodified Program. The output from running a | ||
| covered work is covered by this License only if the output, given its | ||
| content, constitutes a covered work. This License acknowledges your | ||
| rights of fair use or other equivalent, as provided by copyright law. | ||
| You may make, run and propagate covered works that you do not | ||
| convey, without conditions so long as your license otherwise remains | ||
| in force. You may convey covered works to others for the sole purpose | ||
| of having them make modifications exclusively for you, or provide you | ||
| with facilities for running those works, provided that you comply with | ||
| the terms of this License in conveying all material for which you do | ||
| not control copyright. Those thus making or running the covered works | ||
| for you must do so exclusively on your behalf, under your direction | ||
| and control, on terms that prohibit them from making any copies of | ||
| your copyrighted material outside their relationship with you. | ||
| Conveying under any other circumstances is permitted solely under | ||
| the conditions stated below. Sublicensing is not allowed; section 10 | ||
| makes it unnecessary. | ||
| 3. Protecting Users' Legal Rights From Anti-Circumvention Law. | ||
| No covered work shall be deemed part of an effective technological | ||
| measure under any applicable law fulfilling obligations under article | ||
| 11 of the WIPO copyright treaty adopted on 20 December 1996, or | ||
| similar laws prohibiting or restricting circumvention of such | ||
| measures. | ||
| When you convey a covered work, you waive any legal power to forbid | ||
| circumvention of technological measures to the extent such circumvention | ||
| is effected by exercising rights under this License with respect to | ||
| the covered work, and you disclaim any intention to limit operation or | ||
| modification of the work as a means of enforcing, against the work's | ||
| users, your or third parties' legal rights to forbid circumvention of | ||
| technological measures. | ||
| 4. Conveying Verbatim Copies. | ||
| You may convey verbatim copies of the Program's source code as you | ||
| receive it, in any medium, provided that you conspicuously and | ||
| appropriately publish on each copy an appropriate copyright notice; | ||
| keep intact all notices stating that this License and any | ||
| non-permissive terms added in accord with section 7 apply to the code; | ||
| keep intact all notices of the absence of any warranty; and give all | ||
| recipients a copy of this License along with the Program. | ||
| You may charge any price or no price for each copy that you convey, | ||
| and you may offer support or warranty protection for a fee. | ||
| 5. Conveying Modified Source Versions. | ||
| You may convey a work based on the Program, or the modifications to | ||
| produce it from the Program, in the form of source code under the | ||
| terms of section 4, provided that you also meet all of these conditions: | ||
| a) The work must carry prominent notices stating that you modified | ||
| it, and giving a relevant date. | ||
| b) The work must carry prominent notices stating that it is | ||
| released under this License and any conditions added under section | ||
| 7. This requirement modifies the requirement in section 4 to | ||
| "keep intact all notices". | ||
| c) You must license the entire work, as a whole, under this | ||
| License to anyone who comes into possession of a copy. This | ||
| License will therefore apply, along with any applicable section 7 | ||
| additional terms, to the whole of the work, and all its parts, | ||
| regardless of how they are packaged. This License gives no | ||
| permission to license the work in any other way, but it does not | ||
| invalidate such permission if you have separately received it. | ||
| d) If the work has interactive user interfaces, each must display | ||
| Appropriate Legal Notices; however, if the Program has interactive | ||
| interfaces that do not display Appropriate Legal Notices, your | ||
| work need not make them do so. | ||
| A compilation of a covered work with other separate and independent | ||
| works, which are not by their nature extensions of the covered work, | ||
| and which are not combined with it such as to form a larger program, | ||
| in or on a volume of a storage or distribution medium, is called an | ||
| "aggregate" if the compilation and its resulting copyright are not | ||
| used to limit the access or legal rights of the compilation's users | ||
| beyond what the individual works permit. Inclusion of a covered work | ||
| in an aggregate does not cause this License to apply to the other | ||
| parts of the aggregate. | ||
| 6. Conveying Non-Source Forms. | ||
| You may convey a covered work in object code form under the terms | ||
| of sections 4 and 5, provided that you also convey the | ||
| machine-readable Corresponding Source under the terms of this License, | ||
| in one of these ways: | ||
| a) Convey the object code in, or embodied in, a physical product | ||
| (including a physical distribution medium), accompanied by the | ||
| Corresponding Source fixed on a durable physical medium | ||
| customarily used for software interchange. | ||
| b) Convey the object code in, or embodied in, a physical product | ||
| (including a physical distribution medium), accompanied by a | ||
| written offer, valid for at least three years and valid for as | ||
| long as you offer spare parts or customer support for that product | ||
| model, to give anyone who possesses the object code either (1) a | ||
| copy of the Corresponding Source for all the software in the | ||
| product that is covered by this License, on a durable physical | ||
| medium customarily used for software interchange, for a price no | ||
| more than your reasonable cost of physically performing this | ||
| conveying of source, or (2) access to copy the | ||
| Corresponding Source from a network server at no charge. | ||
| c) Convey individual copies of the object code with a copy of the | ||
| written offer to provide the Corresponding Source. This | ||
| alternative is allowed only occasionally and noncommercially, and | ||
| only if you received the object code with such an offer, in accord | ||
| with subsection 6b. | ||
| d) Convey the object code by offering access from a designated | ||
| place (gratis or for a charge), and offer equivalent access to the | ||
| Corresponding Source in the same way through the same place at no | ||
| further charge. You need not require recipients to copy the | ||
| Corresponding Source along with the object code. If the place to | ||
| copy the object code is a network server, the Corresponding Source | ||
| may be on a different server (operated by you or a third party) | ||
| that supports equivalent copying facilities, provided you maintain | ||
| clear directions next to the object code saying where to find the | ||
| Corresponding Source. Regardless of what server hosts the | ||
| Corresponding Source, you remain obligated to ensure that it is | ||
| available for as long as needed to satisfy these requirements. | ||
| e) Convey the object code using peer-to-peer transmission, provided | ||
| you inform other peers where the object code and Corresponding | ||
| Source of the work are being offered to the general public at no | ||
| charge under subsection 6d. | ||
| A separable portion of the object code, whose source code is excluded | ||
| from the Corresponding Source as a System Library, need not be | ||
| included in conveying the object code work. | ||
| A "User Product" is either (1) a "consumer product", which means any | ||
| tangible personal property which is normally used for personal, family, | ||
| or household purposes, or (2) anything designed or sold for incorporation | ||
| into a dwelling. In determining whether a product is a consumer product, | ||
| doubtful cases shall be resolved in favor of coverage. For a particular | ||
| product received by a particular user, "normally used" refers to a | ||
| typical or common use of that class of product, regardless of the status | ||
| of the particular user or of the way in which the particular user | ||
| actually uses, or expects or is expected to use, the product. A product | ||
| is a consumer product regardless of whether the product has substantial | ||
| commercial, industrial or non-consumer uses, unless such uses represent | ||
| the only significant mode of use of the product. | ||
| "Installation Information" for a User Product means any methods, | ||
| procedures, authorization keys, or other information required to install | ||
| and execute modified versions of a covered work in that User Product from | ||
| a modified version of its Corresponding Source. The information must | ||
| suffice to ensure that the continued functioning of the modified object | ||
| code is in no case prevented or interfered with solely because | ||
| modification has been made. | ||
| If you convey an object code work under this section in, or with, or | ||
| specifically for use in, a User Product, and the conveying occurs as | ||
| part of a transaction in which the right of possession and use of the | ||
| User Product is transferred to the recipient in perpetuity or for a | ||
| fixed term (regardless of how the transaction is characterized), the | ||
| Corresponding Source conveyed under this section must be accompanied | ||
| by the Installation Information. But this requirement does not apply | ||
| if neither you nor any third party retains the ability to install | ||
| modified object code on the User Product (for example, the work has | ||
| been installed in ROM). | ||
| The requirement to provide Installation Information does not include a | ||
| requirement to continue to provide support service, warranty, or updates | ||
| for a work that has been modified or installed by the recipient, or for | ||
| the User Product in which it has been modified or installed. Access to a | ||
| network may be denied when the modification itself materially and | ||
| adversely affects the operation of the network or violates the rules and | ||
| protocols for communication across the network. | ||
| Corresponding Source conveyed, and Installation Information provided, | ||
| in accord with this section must be in a format that is publicly | ||
| documented (and with an implementation available to the public in | ||
| source code form), and must require no special password or key for | ||
| unpacking, reading or copying. | ||
| 7. Additional Terms. | ||
| "Additional permissions" are terms that supplement the terms of this | ||
| License by making exceptions from one or more of its conditions. | ||
| Additional permissions that are applicable to the entire Program shall | ||
| be treated as though they were included in this License, to the extent | ||
| that they are valid under applicable law. If additional permissions | ||
| apply only to part of the Program, that part may be used separately | ||
| under those permissions, but the entire Program remains governed by | ||
| this License without regard to the additional permissions. | ||
| When you convey a copy of a covered work, you may at your option | ||
| remove any additional permissions from that copy, or from any part of | ||
| it. (Additional permissions may be written to require their own | ||
| removal in certain cases when you modify the work.) You may place | ||
| additional permissions on material, added by you to a covered work, | ||
| for which you have or can give appropriate copyright permission. | ||
| Notwithstanding any other provision of this License, for material you | ||
| add to a covered work, you may (if authorized by the copyright holders of | ||
| that material) supplement the terms of this License with terms: | ||
| a) Disclaiming warranty or limiting liability differently from the | ||
| terms of sections 15 and 16 of this License; or | ||
| b) Requiring preservation of specified reasonable legal notices or | ||
| author attributions in that material or in the Appropriate Legal | ||
| Notices displayed by works containing it; or | ||
| c) Prohibiting misrepresentation of the origin of that material, or | ||
| requiring that modified versions of such material be marked in | ||
| reasonable ways as different from the original version; or | ||
| d) Limiting the use for publicity purposes of names of licensors or | ||
| authors of the material; or | ||
| e) Declining to grant rights under trademark law for use of some | ||
| trade names, trademarks, or service marks; or | ||
| f) Requiring indemnification of licensors and authors of that | ||
| material by anyone who conveys the material (or modified versions of | ||
| it) with contractual assumptions of liability to the recipient, for | ||
| any liability that these contractual assumptions directly impose on | ||
| those licensors and authors. | ||
| All other non-permissive additional terms are considered "further | ||
| restrictions" within the meaning of section 10. If the Program as you | ||
| received it, or any part of it, contains a notice stating that it is | ||
| governed by this License along with a term that is a further | ||
| restriction, you may remove that term. If a license document contains | ||
| a further restriction but permits relicensing or conveying under this | ||
| License, you may add to a covered work material governed by the terms | ||
| of that license document, provided that the further restriction does | ||
| not survive such relicensing or conveying. | ||
| If you add terms to a covered work in accord with this section, you | ||
| must place, in the relevant source files, a statement of the | ||
| additional terms that apply to those files, or a notice indicating | ||
| where to find the applicable terms. | ||
| Additional terms, permissive or non-permissive, may be stated in the | ||
| form of a separately written license, or stated as exceptions; | ||
| the above requirements apply either way. | ||
| 8. Termination. | ||
| You may not propagate or modify a covered work except as expressly | ||
| provided under this License. Any attempt otherwise to propagate or | ||
| modify it is void, and will automatically terminate your rights under | ||
| this License (including any patent licenses granted under the third | ||
| paragraph of section 11). | ||
| However, if you cease all violation of this License, then your | ||
| license from a particular copyright holder is reinstated (a) | ||
| provisionally, unless and until the copyright holder explicitly and | ||
| finally terminates your license, and (b) permanently, if the copyright | ||
| holder fails to notify you of the violation by some reasonable means | ||
| prior to 60 days after the cessation. | ||
| Moreover, your license from a particular copyright holder is | ||
| reinstated permanently if the copyright holder notifies you of the | ||
| violation by some reasonable means, this is the first time you have | ||
| received notice of violation of this License (for any work) from that | ||
| copyright holder, and you cure the violation prior to 30 days after | ||
| your receipt of the notice. | ||
| Termination of your rights under this section does not terminate the | ||
| licenses of parties who have received copies or rights from you under | ||
| this License. If your rights have been terminated and not permanently | ||
| reinstated, you do not qualify to receive new licenses for the same | ||
| material under section 10. | ||
| 9. Acceptance Not Required for Having Copies. | ||
| You are not required to accept this License in order to receive or | ||
| run a copy of the Program. Ancillary propagation of a covered work | ||
| occurring solely as a consequence of using peer-to-peer transmission | ||
| to receive a copy likewise does not require acceptance. However, | ||
| nothing other than this License grants you permission to propagate or | ||
| modify any covered work. These actions infringe copyright if you do | ||
| not accept this License. Therefore, by modifying or propagating a | ||
| covered work, you indicate your acceptance of this License to do so. | ||
| 10. Automatic Licensing of Downstream Recipients. | ||
| Each time you convey a covered work, the recipient automatically | ||
| receives a license from the original licensors, to run, modify and | ||
| propagate that work, subject to this License. You are not responsible | ||
| for enforcing compliance by third parties with this License. | ||
| An "entity transaction" is a transaction transferring control of an | ||
| organization, or substantially all assets of one, or subdividing an | ||
| organization, or merging organizations. If propagation of a covered | ||
| work results from an entity transaction, each party to that | ||
| transaction who receives a copy of the work also receives whatever | ||
| licenses to the work the party's predecessor in interest had or could | ||
| give under the previous paragraph, plus a right to possession of the | ||
| Corresponding Source of the work from the predecessor in interest, if | ||
| the predecessor has it or can get it with reasonable efforts. | ||
| You may not impose any further restrictions on the exercise of the | ||
| rights granted or affirmed under this License. For example, you may | ||
| not impose a license fee, royalty, or other charge for exercise of | ||
| rights granted under this License, and you may not initiate litigation | ||
| (including a cross-claim or counterclaim in a lawsuit) alleging that | ||
| any patent claim is infringed by making, using, selling, offering for | ||
| sale, or importing the Program or any portion of it. | ||
| 11. Patents. | ||
| A "contributor" is a copyright holder who authorizes use under this | ||
| License of the Program or a work on which the Program is based. The | ||
| work thus licensed is called the contributor's "contributor version". | ||
| A contributor's "essential patent claims" are all patent claims | ||
| owned or controlled by the contributor, whether already acquired or | ||
| hereafter acquired, that would be infringed by some manner, permitted | ||
| by this License, of making, using, or selling its contributor version, | ||
| but do not include claims that would be infringed only as a | ||
| consequence of further modification of the contributor version. For | ||
| purposes of this definition, "control" includes the right to grant | ||
| patent sublicenses in a manner consistent with the requirements of | ||
| this License. | ||
| Each contributor grants you a non-exclusive, worldwide, royalty-free | ||
| patent license under the contributor's essential patent claims, to | ||
| make, use, sell, offer for sale, import and otherwise run, modify and | ||
| propagate the contents of its contributor version. | ||
| In the following three paragraphs, a "patent license" is any express | ||
| agreement or commitment, however denominated, not to enforce a patent | ||
| (such as an express permission to practice a patent or covenant not to | ||
| sue for patent infringement). To "grant" such a patent license to a | ||
| party means to make such an agreement or commitment not to enforce a | ||
| patent against the party. | ||
| If you convey a covered work, knowingly relying on a patent license, | ||
| and the Corresponding Source of the work is not available for anyone | ||
| to copy, free of charge and under the terms of this License, through a | ||
| publicly available network server or other readily accessible means, | ||
| then you must either (1) cause the Corresponding Source to be so | ||
| available, or (2) arrange to deprive yourself of the benefit of the | ||
| patent license for this particular work, or (3) arrange, in a manner | ||
| consistent with the requirements of this License, to extend the patent | ||
| license to downstream recipients. "Knowingly relying" means you have | ||
| actual knowledge that, but for the patent license, your conveying the | ||
| covered work in a country, or your recipient's use of the covered work | ||
| in a country, would infringe one or more identifiable patents in that | ||
| country that you have reason to believe are valid. | ||
| If, pursuant to or in connection with a single transaction or | ||
| arrangement, you convey, or propagate by procuring conveyance of, a | ||
| covered work, and grant a patent license to some of the parties | ||
| receiving the covered work authorizing them to use, propagate, modify | ||
| or convey a specific copy of the covered work, then the patent license | ||
| you grant is automatically extended to all recipients of the covered | ||
| work and works based on it. | ||
| A patent license is "discriminatory" if it does not include within | ||
| the scope of its coverage, prohibits the exercise of, or is | ||
| conditioned on the non-exercise of one or more of the rights that are | ||
| specifically granted under this License. You may not convey a covered | ||
| work if you are a party to an arrangement with a third party that is | ||
| in the business of distributing software, under which you make payment | ||
| to the third party based on the extent of your activity of conveying | ||
| the work, and under which the third party grants, to any of the | ||
| parties who would receive the covered work from you, a discriminatory | ||
| patent license (a) in connection with copies of the covered work | ||
| conveyed by you (or copies made from those copies), or (b) primarily | ||
| for and in connection with specific products or compilations that | ||
| contain the covered work, unless you entered into that arrangement, | ||
| or that patent license was granted, prior to 28 March 2007. | ||
| Nothing in this License shall be construed as excluding or limiting | ||
| any implied license or other defenses to infringement that may | ||
| otherwise be available to you under applicable patent law. | ||
| 12. No Surrender of Others' Freedom. | ||
| If conditions are imposed on you (whether by court order, agreement or | ||
| otherwise) that contradict the conditions of this License, they do not | ||
| excuse you from the conditions of this License. If you cannot convey a | ||
| covered work so as to satisfy simultaneously your obligations under this | ||
| License and any other pertinent obligations, then as a consequence you may | ||
| not convey it at all. For example, if you agree to terms that obligate you | ||
| to collect a royalty for further conveying from those to whom you convey | ||
| the Program, the only way you could satisfy both those terms and this | ||
| License would be to refrain entirely from conveying the Program. | ||
| 13. Remote Network Interaction; Use with the GNU General Public License. | ||
| Notwithstanding any other provision of this License, if you modify the | ||
| Program, your modified version must prominently offer all users | ||
| interacting with it remotely through a computer network (if your version | ||
| supports such interaction) an opportunity to receive the Corresponding | ||
| Source of your version by providing access to the Corresponding Source | ||
| from a network server at no charge, through some standard or customary | ||
| means of facilitating copying of software. This Corresponding Source | ||
| shall include the Corresponding Source for any work covered by version 3 | ||
| of the GNU General Public License that is incorporated pursuant to the | ||
| following paragraph. | ||
| Notwithstanding any other provision of this License, you have | ||
| permission to link or combine any covered work with a work licensed | ||
| under version 3 of the GNU General Public License into a single | ||
| combined work, and to convey the resulting work. The terms of this | ||
| License will continue to apply to the part which is the covered work, | ||
| but the work with which it is combined will remain governed by version | ||
| 3 of the GNU General Public License. | ||
| 14. Revised Versions of this License. | ||
| The Free Software Foundation may publish revised and/or new versions of | ||
| the GNU Affero General Public License from time to time. Such new versions | ||
| will be similar in spirit to the present version, but may differ in detail to | ||
| address new problems or concerns. | ||
| Each version is given a distinguishing version number. If the | ||
| Program specifies that a certain numbered version of the GNU Affero General | ||
| Public License "or any later version" applies to it, you have the | ||
| option of following the terms and conditions either of that numbered | ||
| version or of any later version published by the Free Software | ||
| Foundation. If the Program does not specify a version number of the | ||
| GNU Affero General Public License, you may choose any version ever published | ||
| by the Free Software Foundation. | ||
| If the Program specifies that a proxy can decide which future | ||
| versions of the GNU Affero General Public License can be used, that proxy's | ||
| public statement of acceptance of a version permanently authorizes you | ||
| to choose that version for the Program. | ||
| Later license versions may give you additional or different | ||
| permissions. However, no additional obligations are imposed on any | ||
| author or copyright holder as a result of your choosing to follow a | ||
| later version. | ||
| 15. Disclaimer of Warranty. | ||
| THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | ||
| APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | ||
| HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | ||
| OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | ||
| THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||
| PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | ||
| IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | ||
| ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | ||
| 16. Limitation of Liability. | ||
| IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | ||
| WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | ||
| THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | ||
| GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | ||
| USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | ||
| DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | ||
| PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | ||
| EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | ||
| SUCH DAMAGES. | ||
| 17. Interpretation of Sections 15 and 16. | ||
| If the disclaimer of warranty and limitation of liability provided | ||
| above cannot be given local legal effect according to their terms, | ||
| reviewing courts shall apply local law that most closely approximates | ||
| an absolute waiver of all civil liability in connection with the | ||
| Program, unless a warranty or assumption of liability accompanies a | ||
| copy of the Program in return for a fee. | ||
| END OF TERMS AND CONDITIONS | ||
| How to Apply These Terms to Your New Programs | ||
| If you develop a new program, and you want it to be of the greatest | ||
| possible use to the public, the best way to achieve this is to make it | ||
| free software which everyone can redistribute and change under these terms. | ||
| To do so, attach the following notices to the program. It is safest | ||
| to attach them to the start of each source file to most effectively | ||
| state the exclusion of warranty; and each file should have at least | ||
| the "copyright" line and a pointer to where the full notice is found. | ||
| <one line to give the program's name and a brief idea of what it does.> | ||
| Copyright (C) <year> <name of author> | ||
| This program is free software: you can redistribute it and/or modify | ||
| it under the terms of the GNU Affero General Public License as published by | ||
| the Free Software Foundation, either version 3 of the License, or | ||
| (at your option) any later version. | ||
| This program is distributed in the hope that it will be useful, | ||
| but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| GNU Affero General Public License for more details. | ||
| You should have received a copy of the GNU Affero General Public License | ||
| along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
| Also add information on how to contact you by electronic and paper mail. | ||
| If your software can interact with users remotely through a computer | ||
| network, you should also make sure that it provides a way for users to | ||
| get its source. For example, if your program is a web application, its | ||
| interface could display a "Source" link that leads users to an archive | ||
| of the code. There are many ways you could offer source, and different | ||
| solutions will be better for different programs; see section 13 for the | ||
| specific requirements. | ||
| You should also get your employer (if you work as a programmer) or school, | ||
| if any, to sign a "copyright disclaimer" for the program, if necessary. | ||
| For more information on this, and how to apply and follow the GNU AGPL, see | ||
| <https://www.gnu.org/licenses/>. | ||
MILESTONE.mdAdded
+19−0
| @@ -0,0 +1,19 @@ | ||
| # GITv v0.3.0 | ||
| v0.3.0 makes GITv nicer to live in for its one operator: manage keys without editing files by hand, browse and link history precisely, compare revisions, set repository details, download tagged releases, and restore a single repository from backup. Tick each item once its acceptance criteria are verified by a test. | ||
| ## Scope | ||
| GITv stays a single-operator host. The web browser stays read-only and script-free: every new page is a GET, every change to a repository is an SSH or admin command, and nothing new needs its own storage or backups beyond what git and the repository directory already hold. Each item ships and closes on its own. | ||
| Deferred until a second person pushes to the server: individual accounts and repository permissions, issues, pull requests and approvals, fork-based pull requests, release asset uploads, and upstream sync. Each would add a writable web path (forms, CSRF, permission checks on every write) and project data outside git that the backups would have to cover. | ||
| ## Items, in order | ||
| - [x] **SSH key list and revoke.** `gitv keys [owner]` lists every active key with its owner, SHA-256 fingerprint (as `ssh-keygen -l` prints it) and label. `gitv add-key --label <text>` records a label for a new key. `gitv remove-key <fingerprint>` removes exactly that key, atomically and under the same lock as `add-key`. Verify that a revoked key no longer reaches anything, that a second key for the same owner still works, that an unknown fingerprint changes nothing, and that hand-written lines (options, comments, tabs) survive a removal. | ||
| - [x] **File history and line links.** A file's page links to the commits that changed it (`log` limited to that path, paged like branch history). Source lines carry `#L<n>` anchors, and a "Permalink" link pins the current file to its commit id, so a copied link opens the same lines after the branch moves. A range (`?lines=10-20`) is highlighted by the server, with no JavaScript. | ||
| - [x] **Compare revisions.** `/<owner>/<name>/compare?from=<rev>&to=<rev>` shows the commits in `from..to`, the changed files, and the diff against the merge base. It reuses the commit page's diff rendering, output caps and cache. Cover a release-to-release comparison and a feature branch that has diverged from its target, and the access rules for private repositories. | ||
| - [x] **Description, default branch and index filter.** Over SSH (and as root): `description <name> <text>` writes git's `description` file, and `default-branch <name> <branch>` points `HEAD` at an existing branch. The index shows descriptions and can be filtered by name with a plain GET form (`?q=`). The repository header shows its visibility to the signed-in operator. | ||
| - [x] **Tagged source archives.** The tags page links a `.tar.gz` of each tag, made by `git archive` and served through the download pool, under the repository's access rules. Tag annotations remain the release notes. Verify with a tagged GITv release that the archive matches `git archive` run locally. | ||
| - [x] **Single-repository restore from backup.** Document restoring one repository from a retained snapshot after its trash entry was purged, and test it in `tests/backup.rs`: branches, tags, default branch and visibility come back, it can be restored under a new name, and a repository that has since taken the name is never overwritten. | ||
| - [x] **Optional: protect a repository from history rewrites.** `protect <name> on|off` sets `receive.denyNonFastForwards` and `receive.denyDeletes` for that repository's pushes (git applies both to branches only). Verify that force-pushes and branch deletion are refused while ordinary pushes still work, and that the operator's push log and reflogs are unaffected. | ||
+196−11
| @@ -1,22 +1,78 @@ | ||
| # GITv | ||
| Private Git hosting over OpenSSH, plus a read-only web browser. | ||
| Git hosting with SSH pushes, public and private repository browsing, and read-only HTTPS cloning for public repositories. | ||
| - `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`) | ||
| - `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `visibility`, `protect`, `description`, `default-branch`, `delete`, `add-key`, `keys`, `remove-key`, `trash`, `restore`, `purge`, `import`) | ||
| - `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, compare, tags, archive), with Markdown rendering and syntax highlighting (`crates/gitv-web/src/render.rs`) | ||
| **Linking to code.** A file's History lists the commits that changed it, and a folder's History does the same for everything inside. Permalink opens the file at the commit you're looking at, so the link keeps showing the same content after the branch moves. Click a line number to link that line (`#L12`). To link a range, add `lines=` to the address, for example `…&lines=12-20#L12`; the server marks those lines, and Permalink keeps the range. | ||
| **Comparing revisions.** `/<owner>/<name>/compare?from=v0.1.0&to=main` lists the commits `to` has that `from` lacks and the changes they make. A branch that has diverged is compared from where the two split, so the other branch's newer work isn't shown as undone. Any branch, tag or commit id works on either side, `to` defaults to the default branch, and the address can be shared. Each tag links to the changes since the previous tag in its history, and a branch's commit list links to its comparison with the default branch. | ||
| **Source archives.** Each tag on the tags page has a Source (.tar.gz) download, made by `git archive` from the tagged commit as it's requested, with every file under a `<repository>-<tag>/` folder. `/<owner>/<name>/archive?ref=<branch, tag or commit>` works for any revision. The same revision always gives the same files and times. Downloads follow the repository's visibility, and share the raw-download limits below. Tag annotations serve as release notes; there are no uploaded release assets. | ||
| **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. | ||
| Existing and newly created repositories default to private. Publish one as its SSH owner or as the server administrator: | ||
| ```sh | ||
| ssh git@git.um9i.dev visibility my-project public | ||
| # Equivalent command on the server | ||
| gitv visibility um9i my-project public | ||
| ``` | ||
| Anyone can now find it on the repository index, browse its files and history, and run `git clone https://git.um9i.dev/um9i/my-project`. Use the same visibility command with `private` to require sign-in again and disable HTTPS fetches. Copies already downloaded remain with their recipients. Pushes use SSH. | ||
| **Description and default branch.** A one-line description shows under the repository's name and on the index, where it can be searched along with names. The default branch is the one the web shows first and that clones check out. Without a value, each command prints the current one: | ||
| ```sh | ||
| ssh git@git.um9i.dev description my-project A small toolbox # "" removes it | ||
| ssh git@git.um9i.dev default-branch my-project release # must be an existing branch | ||
| # Equivalent commands on the server | ||
| gitv description um9i my-project "A small toolbox" | ||
| gitv default-branch um9i my-project release | ||
| ``` | ||
| **Protecting history.** `ssh git@git.um9i.dev protect my-project on` (or `gitv protect um9i my-project on`) makes pushes refuse to force-update or delete any branch; new branches and ordinary pushes still work, and `off` lifts it. Git applies this to branches only: tags can still be moved or deleted, and the push log records it when they are. It's kept as a `gitv-protected` file in the repository, like visibility, so backups carry it, and the repository header shows it when you're signed in. | ||
| The description lives in git's own `description` file in the repository. Signed in, the repository header also shows whether it's public, and for a public repository both its HTTPS and SSH addresses. | ||
| **Limits.** The web server runs at most 16 page renders, 6 raw or archive downloads and 4 HTTPS clones at once. Some render and download slots are kept for signed-in sessions, so anonymous visitors can't crowd out the owner. Each anonymous client (an IPv4 address or IPv6 /64, as Caddy reports it) may hold at most 4 renders, 2 downloads and 2 clones at a time. Past these limits a request gets 503 at once rather than queueing. | ||
| **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 and purging move and remove 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. | ||
| **Deleting and recovering.** `delete` (over SSH or as root) never removes anything: it moves the repository to `<owner>/.trash/<name>.<unix time>`, where it stops being served. The operator manages the trash: | ||
| ```sh | ||
| gitv trash # what's waiting, and for how long | ||
| gitv restore um9i my-project.1763800000 # back under its old name (or --as other-name) | ||
| gitv purge # remove entries deleted 30+ days ago (--older-than-days N) | ||
| ``` | ||
| `deploy/gitv-purge.timer` runs `gitv purge` daily, so deleted repositories can be restored for 30 days. | ||
| 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. | ||
| History overwritten by a push can be recovered for the same 30 days. Every push records a reflog entry for each ref it changes, and keeps unreachable objects as long as those entries; for example, `git -C <repo> rev-parse main@{1}` finds where `main` pointed before a force-push. Git drops a branch's reflog when the branch is deleted, so each push also appends its ref changes to `gitv-push.log` in the repository (`<unix time> <old> <new> <ref>`, `-` for none). To bring back a deleted branch, find its last commit there and run `git -C <repo> branch <name> <commit>`. | ||
| **SSH keys.** Each key in `/etc/gitv/authorized_keys` reaches only its owner's repositories. Give each device its own key and a label, so a lost one can be revoked alone: | ||
| ```sh | ||
| gitv add-key um9i laptop.pub --label "laptop" # Ed25519 only; the key file's own comment isn't kept | ||
| gitv keys # owner, SHA-256 fingerprint (as ssh-keygen -l shows it), label | ||
| gitv keys um9i # one owner's keys | ||
| gitv add-key um9i laptop.pub --label "work" # a key um9i already has: renames it in place | ||
| gitv remove-key SHA256:gNSIRW+2Iyiuvsdp/bgjy38bvWHw6wQm3tuoXrl3WjQ | ||
| ``` | ||
| Adding a key the owner already has, with a label, only renames it: its line keeps its options, and the key never stops working. A key registered to another owner is refused. `remove-key` rewrites the file atomically under the same lock as `add-key` and keeps every other line as it was, including hand-written ones (listed with `-` as the owner when they aren't a `gitv serve` command). sshd reads the file on each connection, so the key stops working at once, but a connection already open finishes what it is doing. | ||
| The browser follows the system's light or dark setting. Its stylesheet (`crates/gitv-web/assets/style.css`) and the Red Hat Display, Text and Mono fonts (`crates/gitv-web/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 | ||
| gitv-web setup # account admin; --user NAME for another; --force to replace it (keeping its name) | ||
| ``` | ||
| 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. | ||
| @@ -24,10 +80,20 @@ It prints a generated password (20 random characters, shown only this once), the | ||
| - **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. | ||
| - Sessions last up to 12 hours, including across browser restarts. Sign out to end a session on a shared device. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`). | ||
| - Failed attempts are counted per client: an IPv4 address, or an IPv6 /64. After five, that client is locked out for a minute, doubling with each further failure up to 15 minutes. A client's count is forgotten after an hour without a failure. Someone guessing from elsewhere therefore can't lock you out. Across all clients together, at most 60 failures an hour are judged, which caps a distributed attack. While that cap is full, only browsers that have signed in before can try: a successful sign-in also sets a trusted-device cookie for 90 days, kept across sign-outs, so an attack spread over many addresses can't lock you out of a browser you've used. `gitv-web setup --force` (a new authenticator secret) forgets every such browser. The client's address comes from Caddy's `X-Forwarded-For`, which gitv-web trusts only on loopback connections. A code works once. | ||
| Until the account exists, pages requiring sign-in show setup instructions. Public repositories can already be browsed and cloned. | ||
| ## Layout | ||
| The repository is a Cargo workspace of three crates: | ||
| - `crates/gitv-core`: what both programs share: configuration, name rules, working through directory handles, and running git with a deadline and an output cap | ||
| - `crates/gitv`: the SSH command handler and administrator CLI | ||
| - `crates/gitv-web`: the web browser and HTTPS clone service, with its templates and assets | ||
| Until the account exists, the browser answers every page with instructions to run `gitv-web setup`. | ||
| `gitv` depends only on `gitv-core` and a few small crates, so building it (`cargo build -p gitv`) never compiles the web server's dependencies. | ||
| ## Run locally | ||
| @@ -35,7 +101,7 @@ Set `GITV_REPOS` (and optionally `GITV_KEYS`) to point at a local tree. When `GI | ||
| ```sh | ||
| cargo build | ||
| export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys | ||
| export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys GITV_HOST=localhost | ||
| mkdir -p dev/repos | ||
| ./target/debug/gitv create um9i demo | ||
| export GITV_WEB_AUTH=$PWD/dev/web-login | ||
| @@ -57,4 +123,123 @@ 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, 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`. | ||
| Run them from the workspace root, so both binaries are built: the web tests use `gitv` to set up their repositories. `crates/gitv/tests/ssh.rs` runs `gitv serve` the way a key does over SSH, pushing and cloning real repositories through a stand-in for ssh, and `crates/gitv/tests/backup.rs` runs the backup and restore scripts. `crates/gitv-web/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. `crates/gitv-web/tests/auth.rs` covers signing in, two-factor codes, lockout, sessions and changing the password. None needs an SSH server or network access. The integration tests write only to `target/tmp`; the unit tests use the system's temporary folder, since Cargo names `target/tmp` only to integration tests. Helpers both packages use are in `testing/host.rs`. | ||
| `.github/workflows/ci.yml` runs the same checks on every push and pull request (`cargo fmt --check`, clippy with warnings as errors, `cargo test`), plus `cargo audit` against the RustSec advisory database, also weekly so new advisories surface without a push. | ||
| ## Configuration | ||
| Settings that differ between installations live in `/etc/gitv/gitv.conf` (`deploy/gitv.conf` is this server's copy; `$GITV_CONFIG` points elsewhere): | ||
| ```sh | ||
| host = git.um9i.dev # in clone addresses and help; default: $GITV_HOST, then the machine's hostname | ||
| command = /usr/local/bin/gitv # what add-key writes into each key's forced command (this is the default) | ||
| ``` | ||
| It must be readable by the `git` and `gitv-web` accounts (mode 0644). Both binaries check it at startup and refuse to run with an unknown setting or a bad value. Over SSH, a key holder is told only that the server is misconfigured, and the details go to the operator log. `gitv-web serve` prints the host it uses and where that came from. | ||
| ## Production configuration | ||
| The deployment files are the source copies for the Fedora host. Caddy uses | ||
| `deploy/Caddyfile` at `/etc/caddy/Caddyfile`. The web service runs with | ||
| `deploy/gitv-web.service` at `/etc/systemd/system/gitv-web.service`, alongside | ||
| Fedora's distribution-provided systemd defaults. OpenSSH uses | ||
| `deploy/sshd-gitv.conf` at `/etc/ssh/sshd_config.d/90-gitv.conf`. GITV's own settings are | ||
| `deploy/gitv.conf` at `/etc/gitv/gitv.conf`. The trash purge runs from | ||
| `deploy/gitv-purge.service` and `deploy/gitv-purge.timer` in `/etc/systemd/system`, enabled with | ||
| `systemctl enable --now gitv-purge.timer`. | ||
| **Logs.** Caddy sends HSTS (a year, so browsers never fall back to plain HTTP) and writes one JSON line per request to `/var/log/caddy/gitv-access.log`. The log rotates at 50 MiB and keeps 30 days; Caddy leaves cookie and authorization values out of it. Create the folder for Caddy once with `install -d -o caddy -g caddy -m 0750 /var/log/caddy`. Before reloading, validate as the `caddy` user: `sudo -u caddy caddy validate --config /etc/caddy/Caddyfile`. Validating as root opens the log file too, leaving it owned by root, and the reload then fails with `permission denied` until that file is removed or handed to `caddy`. | ||
| gitv-web logs every judged sign-in and password change to the journal, with the client's address (or IPv6 /64) and whether the password or the code was wrong: | ||
| ```sh | ||
| journalctl -u gitv-web -g 'sign-in|password change' | ||
| ``` | ||
| `right password, wrong code` means someone knows the password: change it. Attempts refused while a client is locked out aren't logged, so a flood can't fill the journal. | ||
| ## Backups | ||
| `deploy/gitv-backup` snapshots everything the server can't rebuild: the repositories (with their trash, reflogs, push logs and visibility markers), `/etc/gitv` (the SSH keys), `/var/lib/gitv-web` (the web sign-in) and the server's SSH host keys (`/etc/ssh/ssh_host_*`), so a rebuilt server is one clients already trust. Each snapshot is a plain copy in `/mnt/gitv-backup/gitv/snapshots/<UTC time>/`. Files unchanged since the previous snapshot are hard links to it, so a day's snapshot costs only what changed. Each repository is copied under a lock that pushes also take, so no copy catches a push half way. A repository a push holds for more than 15 minutes keeps its copy from the previous snapshot (noted in the snapshot's `MANIFEST`), so the rest are still backed up, and the run then fails so you hear about it. Every copy is then checked with `git fsck`, and only a snapshot that passes becomes `latest`. Snapshots are kept for 30 days. | ||
| The backup holds the authenticator secret, the password hash and the SSH host keys' private halves, so it is private to root (mode 0700). | ||
| **The volume.** Create a DigitalOcean block storage volume in the droplet's region (ext4), attach it, and mount it at `/mnt/gitv-backup`: | ||
| ```sh | ||
| # /etc/fstab (use the volume's own /dev/disk/by-id name) | ||
| /dev/disk/by-id/scsi-0DO_Volume_gitv-backup /mnt/gitv-backup ext4 defaults,nofail,discard,noatime 0 2 | ||
| ``` | ||
| The script refuses to run unless that directory is a mounted volume, so a missing mount can't fill the droplet's own disk. | ||
| A volume survives the droplet being destroyed or its disk failing, and the snapshots cover mistakes for 30 days. It doesn't survive a regional outage or the loss of the DigitalOcean account. Take an occasional DigitalOcean snapshot of the volume, and add an off-site copy when that matters. | ||
| **Install.** | ||
| ```sh | ||
| install -m 0755 deploy/gitv-backup deploy/gitv-restore /usr/local/sbin/ | ||
| cp deploy/gitv-backup.{service,timer} deploy/gitv-restore-check.{service,timer} /etc/systemd/system/ | ||
| systemctl daemon-reload | ||
| systemctl enable --now gitv-backup.timer gitv-restore-check.timer | ||
| systemctl start gitv-backup # a first snapshot now | ||
| ``` | ||
| The backup runs daily at about 02:30. Every Sunday, `gitv-restore check` copies the latest snapshot out, runs a full `git fsck` on every repository, and deletes the copy, proving the backups restore. That copy is a full one on the backup volume, so keep free space there for at least one more whole snapshot (`du -sh /mnt/gitv-backup/gitv/latest/`), or the check can fill the volume and break the next backup. A failure of either shows in `systemctl --failed` and `journalctl -u gitv-backup`. | ||
| ## Disaster recovery | ||
| **A deleted repository.** For 30 days it waits in the trash: `gitv trash`, then `gitv restore` (see Storage). After that, bring it back from a snapshot: | ||
| ```sh | ||
| gitv-restore find um9i/my-project # the snapshots holding it, newest last | ||
| gitv-restore 2026-11-20T023000Z /srv/gitv-restore um9i/my-project | ||
| gitv import um9i my-project /srv/gitv-restore/my-project.git | ||
| rm -rf /srv/gitv-restore | ||
| ``` | ||
| `gitv-restore` copies just that repository out of the snapshot and checks it with `git fsck`, without touching the live tree. `gitv import` copies it into place, checks it again, and gives it to the `git` account. It comes back as it was in the snapshot: branches, tags, default branch, visibility, description, reflogs and push log. Import never replaces anything: if the name has been taken since, it refuses, and you can import under another name instead (`gitv import um9i my-project-restored …`). Pushes made after that snapshot are lost from the server, but every clone still has them. | ||
| **One file, or an older state.** Snapshots are plain folders, so copy what you need straight out of `/mnt/gitv-backup/gitv/snapshots/<time>/repos/<owner>/<name>.git`. For history overwritten in the last 30 days, the reflog and push log (see Storage) are quicker. | ||
| **The whole server.** On a fresh Fedora droplet: | ||
| 1. Detach the volume from the old droplet (if it still exists), attach it to the new one, and mount it at `/mnt/gitv-backup` as above. | ||
| 2. Install git and Caddy. Create the `git` account with an ordinary shell such as `/bin/bash`. sshd runs each key's forced command through it, so `git-shell` would refuse `gitv serve`, and keys can't run anything else. Also create the `gitv-web` system account in the `git` group. Build and install `gitv` and `gitv-web` to `/usr/local/bin`, and the deployment files as described under Production configuration and Backups. | ||
| 3. Restore the latest snapshot to a staging folder. This also verifies every repository: | ||
| ```sh | ||
| gitv-restore list | ||
| gitv-restore latest /srv/gitv-restore | ||
| ``` | ||
| 4. Move it into place. rsync run as root keeps owners by name, so the new accounts take over their files: | ||
| ```sh | ||
| mkdir -p /srv/gitv /etc/gitv /var/lib/gitv-web | ||
| rsync -a /srv/gitv-restore/repos/ /srv/gitv/repos/ | ||
| rsync -a /srv/gitv-restore/etc-gitv/ /etc/gitv/ | ||
| rsync -a /srv/gitv-restore/gitv-web/ /var/lib/gitv-web/ | ||
| cp -p /srv/gitv-restore/ssh-host-keys/ssh_host_* /etc/ssh/ | ||
| # Copied files carry their folder's default SELinux label, not the one the policy names | ||
| # (sshd reads authorized_keys only as ssh_home_t); restorecon gives each its own. | ||
| restorecon -R /srv/gitv /etc/gitv /var/lib/gitv-web /etc/ssh | ||
| rm -rf /srv/gitv-restore | ||
| ``` | ||
| 5. Restart `sshd` (it now presents the old host keys), start `gitv-web` and `caddy`, and enable the timers: `systemctl enable --now gitv-purge.timer gitv-backup.timer gitv-restore-check.timer`. Point DNS at the new droplet. Check a clone over SSH and over HTTPS, and sign in to the web browser. | ||
| Pushes made after the last snapshot are lost from the server, but every clone still has them: pushing again restores them. | ||
| ## Licence | ||
| Copyright (C) 2026 Um9i | ||
| GITv is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See [`LICENSE`](LICENSE) for the full terms. | ||
| The AGPL extends the GPL to software used over a network: if you run a modified GITv that others reach through the web browser or over SSH, you must offer those users the source of your modified version (section 13). | ||
| The binaries also contain other people's software, each under its own permissive licence: the Rust crates GITv depends on, the Oniguruma regular-expression library, the Red Hat Display, Text and Mono fonts (SIL Open Font License), and Sublime Text's syntax definitions. `THIRD-PARTY-LICENSES` reproduces all of their notices, and those licences require it to accompany any copy of the binaries, so every release archive must include both `LICENSE` and `THIRD-PARTY-LICENSES`. | ||
| `scripts/third-party-licenses` regenerates the file with [cargo-about](https://github.com/EmbarkStudios/cargo-about) (`cargo install cargo-about --locked --features cli`); its configuration is in `licenses/`. Run it whenever dependencies change: CI fails while the committed file is out of date. | ||
THIRD-PARTY-LICENSESAdded
+2649−0
| @@ -0,0 +1,2649 @@ | ||
| Third-party software in GITv | ||
| ============================ | ||
| GITv itself is licensed under the GNU Affero General Public License, version 3 or later (see | ||
| LICENSE). The gitv and gitv-web binaries also contain the software below, each under its own | ||
| licence, reproduced here as those licences require. Generated by scripts/third-party-licenses. | ||
| ================================================================================ | ||
| Apache License 2.0 (Apache-2.0) | ||
| Used by: | ||
| - rpassword 7.5.5 <https://github.com/conradkleinespel/rpassword> | ||
| - rtoolbox 0.0.6 <https://github.com/conradkleinespel/rtoolbox> | ||
| - ryu 1.0.23 <https://github.com/dtolnay/ryu> | ||
| - sync_wrapper 1.0.2 <https://github.com/Actyx/sync_wrapper> | ||
| Apache License | ||
| Version 2.0, January 2004 | ||
| http://www.apache.org/licenses/ | ||
| TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION | ||
| 1. Definitions. | ||
| "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. | ||
| "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. | ||
| "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. | ||
| "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. | ||
| "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. | ||
| "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. | ||
| "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). | ||
| "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. | ||
| "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." | ||
| "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. | ||
| 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. | ||
| 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. | ||
| 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: | ||
| (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices stating that You changed the files; and | ||
| (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and | ||
| (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. | ||
| You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. | ||
| 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. | ||
| 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. | ||
| 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. | ||
| 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. | ||
| 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. | ||
| END OF TERMS AND CONDITIONS | ||
| APPENDIX: How to apply the Apache License to your work. | ||
| To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. | ||
| Copyright [yyyy] [name of copyright owner] | ||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| ================================================================================ | ||
| BSD 2-Clause "Simplified" License (BSD-2-Clause) | ||
| Used by: | ||
| - onig_sys 69.9.3 <https://github.com/rust-onig/rust-onig> | ||
| Oniguruma LICENSE | ||
| ----------------- | ||
| Copyright (c) 2002-2021 K.Kosako <kkosako0@gmail.com> | ||
| All rights reserved. | ||
| Redistribution and use in source and binary forms, with or without | ||
| modification, are permitted provided that the following conditions | ||
| are met: | ||
| 1. Redistributions of source code must retain the above copyright | ||
| notice, this list of conditions and the following disclaimer. | ||
| 2. Redistributions in binary form must reproduce the above copyright | ||
| notice, this list of conditions and the following disclaimer in the | ||
| documentation and/or other materials provided with the distribution. | ||
| THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND | ||
| ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | ||
| ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE | ||
| FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS | ||
| OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | ||
| HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | ||
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | ||
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF | ||
| SUCH DAMAGE. | ||
| ================================================================================ | ||
| BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) | ||
| Used by: | ||
| - matchit 0.8.4 <https://github.com/ibraheemdev/matchit> | ||
| BSD 3-Clause License | ||
| Copyright (c) 2013, Julien Schmidt | ||
| All rights reserved. | ||
| Redistribution and use in source and binary forms, with or without | ||
| modification, are permitted provided that the following conditions are met: | ||
| 1. Redistributions of source code must retain the above copyright notice, this | ||
| list of conditions and the following disclaimer. | ||
| 2. Redistributions in binary form must reproduce the above copyright notice, | ||
| this list of conditions and the following disclaimer in the documentation | ||
| and/or other materials provided with the distribution. | ||
| 3. Neither the name of the copyright holder nor the names of its | ||
| contributors may be used to endorse or promote products derived from | ||
| this software without specific prior written permission. | ||
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
| FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
| OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| ================================================================================ | ||
| BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) | ||
| Used by: | ||
| - subtle 2.6.1 <https://github.com/dalek-cryptography/subtle> | ||
| Copyright (c) 2016-2017 Isis Agora Lovecruft, Henry de Valence. All rights reserved. | ||
| Copyright (c) 2016-2024 Isis Agora Lovecruft. All rights reserved. | ||
| Redistribution and use in source and binary forms, with or without | ||
| modification, are permitted provided that the following conditions are | ||
| met: | ||
| 1. Redistributions of source code must retain the above copyright | ||
| notice, this list of conditions and the following disclaimer. | ||
| 2. Redistributions in binary form must reproduce the above copyright | ||
| notice, this list of conditions and the following disclaimer in the | ||
| documentation and/or other materials provided with the distribution. | ||
| 3. Neither the name of the copyright holder nor the names of its | ||
| contributors may be used to endorse or promote products derived from | ||
| this software without specific prior written permission. | ||
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | ||
| IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | ||
| TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A | ||
| PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
| HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
| SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED | ||
| TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | ||
| PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | ||
| LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | ||
| NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
| SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - onig_sys 69.9.3 <https://github.com/rust-onig/rust-onig> | ||
| # Rust-Onig is Open Source! | ||
| All source code in this repository is distributed under the terms of | ||
| the *MIT License* unless otherwise stated. The Oniguruma source code | ||
| remains the property of the original authors and is re-distributed | ||
| under the original license, see [COPYING](oniguruma/COPYING) for more | ||
| information. | ||
| > The MIT License (MIT) | ||
| > | ||
| > Copyright (c) 2015 Will Speak <will@willspeak.me>, Ivan Ivashchenko | ||
| > <defuz@me.com>, and contributors. | ||
| > | ||
| > Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| > of this software and associated documentation files (the "Software"), to deal | ||
| > in the Software without restriction, including without limitation the rights | ||
| > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| > copies of the Software, and to permit persons to whom the Software is | ||
| > furnished to do so, subject to the following conditions: | ||
| > | ||
| > The above copyright notice and this permission notice shall be included in all | ||
| > copies or substantial portions of the Software. | ||
| > | ||
| > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| > SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - onig 6.5.3 <https://github.com/iwillspeak/rust-onig> | ||
| # Rust-Onig is Open Source! | ||
| All source code in this repository is distributed under the terms of | ||
| the *MIT License* unless otherwise stated. The Oniguruma source code | ||
| remains the property of the original authors and is re-distributed | ||
| under the original license. | ||
| > The MIT License (MIT) | ||
| > | ||
| > Copyright (c) 2015 Will Speak <will@willspeak.me>, Ivan Ivashchenko | ||
| > <defuz@me.com>, and contributors. | ||
| > | ||
| > Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| > of this software and associated documentation files (the "Software"), to deal | ||
| > in the Software without restriction, including without limitation the rights | ||
| > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| > copies of the Software, and to permit persons to whom the Software is | ||
| > furnished to do so, subject to the following conditions: | ||
| > | ||
| > The above copyright notice and this permission notice shall be included in all | ||
| > copies or substantial portions of the Software. | ||
| > | ||
| > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| > SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - atomic-waker 1.1.2 <https://github.com/smol-rs/atomic-waker> | ||
| =============================================================================== | ||
| Copyright (c) 2016 Alex Crichton | ||
| Copyright (c) 2017 The Tokio Authors | ||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| =============================================================================== | ||
| Copyright (c) 2016 Alex Crichton | ||
| Copyright (c) 2017 The Tokio Authors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - form_urlencoded 1.2.3 <https://github.com/servo/rust-url> | ||
| Copyright (c) 2013-2016 The rust-url developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - percent-encoding 2.3.2 <https://github.com/servo/rust-url/> | ||
| Copyright (c) 2013-2025 The rust-url developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - cfg-if 1.0.5 <https://github.com/rust-lang/cfg-if> | ||
| - socket2 0.6.5 <https://github.com/rust-lang/socket2> | ||
| Copyright (c) 2014 Alex Crichton | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - mio 1.2.5 <https://github.com/tokio-rs/mio> | ||
| Copyright (c) 2014 Carl Lerche and other MIO contributors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - errno 0.3.15 <https://github.com/lambda-fairy/rust-errno> | ||
| Copyright (c) 2014 Chris Wong | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - mime 0.3.18 <https://github.com/hyperium/mime> | ||
| Copyright (c) 2014 Sean McArthur | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - base64ct 1.8.3 <https://github.com/RustCrypto/formats> | ||
| Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) | ||
| Copyright (c) 2021-2025 The RustCrypto Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - bitflags 2.13.2 <https://github.com/bitflags/bitflags> | ||
| - log 0.4.35 <https://github.com/rust-lang/log> | ||
| - regex-syntax 0.8.12 <https://github.com/rust-lang/regex> | ||
| Copyright (c) 2014 The Rust Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - flate2 1.1.11 <https://github.com/rust-lang/flate2-rs> | ||
| Copyright (c) 2014-2026 Alex Crichton | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - hyper 1.12.0 <https://github.com/hyperium/hyper> | ||
| Copyright (c) 2014-2026 Sean McArthur | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - unicase 2.10.0 <https://github.com/seanmonstar/unicase> | ||
| Copyright (c) 2014-2026 Sean McArthur | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - heck 0.5.0 <https://github.com/withoutboats/heck> | ||
| Copyright (c) 2015 The Rust Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - httparse 1.10.1 <https://github.com/seanmonstar/httparse> | ||
| Copyright (c) 2015-2025 Sean McArthur | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - futures-core 0.3.34 <https://github.com/rust-lang/futures-rs> | ||
| - futures-task 0.3.34 <https://github.com/rust-lang/futures-rs> | ||
| - futures-util 0.3.34 <https://github.com/rust-lang/futures-rs> | ||
| Copyright (c) 2016 Alex Crichton | ||
| Copyright (c) 2017 The Tokio Authors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - serde_urlencoded 0.7.1 <https://github.com/nox/serde_urlencoded> | ||
| Copyright (c) 2016 Anthony Ramine | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - utf8parse 0.2.2 <https://github.com/alacritty/vte> | ||
| Copyright (c) 2016 Joe Wilm | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - httpdate 1.0.3 <https://github.com/pyfisch/httpdate> | ||
| Copyright (c) 2016 Pyfisch | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - qrcode 0.15.0 <https://github.com/kennytm/qrcode-rust> | ||
| Copyright (c) 2016 kennytm | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy of | ||
| this software and associated documentation files (the "Software"), to deal in | ||
| the Software without restriction, including without limitation the rights to | ||
| use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software is furnished to do so, | ||
| subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | ||
| FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
| COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | ||
| IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | ||
| CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - sha1 0.11.0 <https://github.com/RustCrypto/hashes> | ||
| - sha2 0.11.1 <https://github.com/RustCrypto/hashes> | ||
| Copyright (c) 2016-2026 The RustCrypto Project Developers | ||
| Copyright (c) 2016 Artyom Pavlov | ||
| Copyright (c) 2009-2013 Mozilla Foundation | ||
| Copyright (c) 2006-2009 Graydon Hoare | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - hmac 0.13.0 <https://github.com/RustCrypto/MACs> | ||
| Copyright (c) 2017 Artyom Pavlov | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - fnv 1.0.7 <https://github.com/servo/rust-fnv> | ||
| Copyright (c) 2017 Contributors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - http 1.5.0 <https://github.com/hyperium/http> | ||
| Copyright (c) 2017 http-rs authors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - signal-hook-registry 1.4.8 <https://github.com/vorner/signal-hook> | ||
| Copyright (c) 2017 tokio-jsonrpc developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - askama 0.16.1 <https://github.com/askama-rs/askama> | ||
| - askama_derive 0.16.1 <https://github.com/askama-rs/askama> | ||
| - askama_macros 0.16.1 <https://github.com/askama-rs/askama> | ||
| - askama_parser 0.16.1 <https://github.com/askama-rs/askama> | ||
| Copyright (c) 2017-2020 Dirkjan Ochtman | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - digest 0.11.3 <https://github.com/RustCrypto/traits> | ||
| Copyright (c) 2017-2025 RustCrypto Developers | ||
| Copyright (c) 2017 Artyom Pavlov | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - blake2 0.11.0 <https://github.com/RustCrypto/hashes> | ||
| Copyright (c) 2017-2026 The RustCrypto Project Developers | ||
| Copyright (c) 2017 Artyom Pavlov | ||
| Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - bytes 1.12.2 <https://github.com/tokio-rs/bytes> | ||
| Copyright (c) 2018 Carl Lerche | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - smallvec 1.16.6 <https://github.com/smallvec/smallvec> | ||
| Copyright (c) 2018 The Servo Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - block-buffer 0.12.1 <https://github.com/RustCrypto/utils> | ||
| Copyright (c) 2018-2025 The RustCrypto Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - getrandom 0.4.3 <https://github.com/rust-random/getrandom> | ||
| Copyright (c) 2018-2026 The rust-random Project Developers | ||
| Copyright (c) 2014 The Rust Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - slab 0.4.12 <https://github.com/tokio-rs/slab> | ||
| Copyright (c) 2019 Carl Lerche | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - tracing-core 0.1.36 <https://github.com/tokio-rs/tracing> | ||
| - tracing 0.1.44 <https://github.com/tokio-rs/tracing> | ||
| Copyright (c) 2019 Tokio Contributors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - tower-layer 0.3.3 <https://github.com/tower-rs/tower> | ||
| - tower-service 0.3.3 <https://github.com/tower-rs/tower> | ||
| - tower 0.5.3 <https://github.com/tower-rs/tower> | ||
| Copyright (c) 2019 Tower Contributors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - axum 0.8.9 <https://github.com/tokio-rs/axum> | ||
| Copyright (c) 2019 axum Contributors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - http-body-util 0.1.5 <https://github.com/hyperium/http-body> | ||
| - http-body 1.1.0 <https://github.com/hyperium/http-body> | ||
| Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - password-hash 0.6.1 <https://github.com/RustCrypto/traits> | ||
| Copyright (c) 2020-2026 RustCrypto Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - const-oid 0.10.3 <https://github.com/RustCrypto/formats> | ||
| - cpufeatures 0.3.1 <https://github.com/RustCrypto/utils> | ||
| Copyright (c) 2020-2026 The RustCrypto Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - crypto-common 0.2.2 <https://github.com/RustCrypto/traits> | ||
| Copyright (c) 2021-2026 RustCrypto Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - argon2 0.6.0 <https://github.com/RustCrypto/password-hashes> | ||
| - phc 0.6.1 <https://github.com/RustCrypto/formats> | ||
| Copyright (c) 2021-2026 The RustCrypto Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - cmov 0.5.4 <https://github.com/RustCrypto/utils> | ||
| - hybrid-array 0.4.15 <https://github.com/RustCrypto/hybrid-array> | ||
| Copyright (c) 2022-2026 The RustCrypto Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - hyper-util 0.1.21 <https://github.com/hyperium/hyper-util> | ||
| Copyright (c) 2023-2025 Sean McArthur | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - ctutils 0.4.8 <https://github.com/RustCrypto/utils> | ||
| Copyright (c) 2025-2026 The RustCrypto Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - anstream 1.0.0 <https://github.com/rust-cli/anstyle.git> | ||
| - anstyle-parse 1.0.0 <https://github.com/rust-cli/anstyle.git> | ||
| - anstyle-query 1.1.5 <https://github.com/rust-cli/anstyle.git> | ||
| - anstyle 1.0.14 <https://github.com/rust-cli/anstyle.git> | ||
| - clap 4.6.9 <https://github.com/clap-rs/clap> | ||
| - clap_builder 4.6.7 <https://github.com/clap-rs/clap> | ||
| - clap_derive 4.6.9 <https://github.com/clap-rs/clap> | ||
| - clap_lex 1.1.2 <https://github.com/clap-rs/clap> | ||
| - colorchoice 1.0.5 <https://github.com/rust-cli/anstyle.git> | ||
| - is_terminal_polyfill 1.70.2 <https://github.com/polyfill-rs/is_terminal_polyfill> | ||
| Copyright (c) Individual contributors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - libc 0.2.191 <https://github.com/rust-lang/libc> | ||
| Copyright (c) The Rust Project Developers | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - syntect 5.3.0 <https://github.com/trishume/syntect> | ||
| MIT License | ||
| Copyright (c) 2017 Tristan Hume, Keith Hall, Google Inc and other contributors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - crc32fast 1.5.5 <https://github.com/srijs/rust-crc32fast> | ||
| MIT License | ||
| Copyright (c) 2018 Sam Rijs, Alex Crichton and contributors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - tokio-macros 2.7.2 <https://github.com/tokio-rs/tokio> | ||
| MIT License | ||
| Copyright (c) 2019 Yoshua Wuyts | ||
| Copyright (c) Tokio Contributors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - axum-core 0.5.6 <https://github.com/tokio-rs/axum> | ||
| MIT License | ||
| Copyright (c) 2019–2025 axum Contributors | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - html-escape 0.3.1 <https://github.com/magiclen/html-escape> | ||
| MIT License | ||
| Copyright (c) 2020 magiclen.org (Ron Li) | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - matchit 0.8.4 <https://github.com/ibraheemdev/matchit> | ||
| MIT License | ||
| Copyright (c) 2022 Ibraheem Ahmed | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - tokio 1.54.1 <https://github.com/tokio-rs/tokio> | ||
| MIT License | ||
| Copyright (c) Tokio Contributors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - simd-adler32 0.3.10 <https://github.com/mcountryman/simd-adler32> | ||
| MIT License | ||
| Copyright (c) [2021] [Marvin Countryman] | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - miniz_oxide 0.9.1 <https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide> | ||
| MIT License | ||
| Copyright 2013-2014 RAD Game Tools and Valve Software | ||
| Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC | ||
| Copyright (c) 2017 Frommi | ||
| Copyright (c) 2017-2024 oyvindln | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - miniz_oxide 0.9.1 <https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide> | ||
| MIT License | ||
| Copyright 2013-2014 RAD Game Tools and Valve Software | ||
| Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC | ||
| Copyright (c) 2017 Frommi | ||
| Copyright (c) 2017-2024 oyvindln | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - rustc-hash 2.1.3 <https://github.com/rust-lang/rustc-hash> | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - adler2 2.0.1 <https://github.com/oyvindln/adler2> | ||
| - atomic-waker 1.1.2 <https://github.com/smol-rs/atomic-waker> | ||
| - itoa 1.0.19 <https://github.com/dtolnay/itoa> | ||
| - once_cell 1.21.4 <https://github.com/matklad/once_cell> | ||
| - pin-project-lite 0.2.18 <https://github.com/taiki-e/pin-project-lite> | ||
| - proc-macro2 1.0.107 <https://github.com/dtolnay/proc-macro2> | ||
| - quote 1.0.47 <https://github.com/dtolnay/quote> | ||
| - serde 1.0.229 <https://github.com/serde-rs/serde> | ||
| - serde_core 1.0.229 <https://github.com/serde-rs/serde> | ||
| - serde_derive 1.0.229 <https://github.com/serde-rs/serde> | ||
| - serde_json 1.0.154 <https://github.com/serde-rs/json> | ||
| - serde_path_to_error 0.1.20 <https://github.com/dtolnay/path-to-error> | ||
| - syn 3.0.10 <https://github.com/dtolnay/syn> | ||
| - thiserror-impl 2.0.21 <https://github.com/dtolnay/thiserror> | ||
| - thiserror 2.0.21 <https://github.com/dtolnay/thiserror> | ||
| - unicode-ident 1.0.27 <https://github.com/dtolnay/unicode-ident> | ||
| - zmij 1.0.23 <https://github.com/dtolnay/zmij> | ||
| Permission is hereby granted, free of charge, to any | ||
| person obtaining a copy of this software and associated | ||
| documentation files (the "Software"), to deal in the | ||
| Software without restriction, including without | ||
| limitation the rights to use, copy, modify, merge, | ||
| publish, distribute, sublicense, and/or sell copies of | ||
| the Software, and to permit persons to whom the Software | ||
| is furnished to do so, subject to the following | ||
| conditions: | ||
| The above copyright notice and this permission notice | ||
| shall be included in all copies or substantial portions | ||
| of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF | ||
| ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED | ||
| TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT | ||
| SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
| CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR | ||
| IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - winnow 1.0.5 <https://github.com/winnow-rs/winnow> | ||
| Permission is hereby granted, free of charge, to any person obtaining | ||
| a copy of this software and associated documentation files (the | ||
| "Software"), to deal in the Software without restriction, including | ||
| without limitation the rights to use, copy, modify, merge, publish, | ||
| distribute, sublicense, and/or sell copies of the Software, and to | ||
| permit persons to whom the Software is furnished to do so, subject to | ||
| the following conditions: | ||
| The above copyright notice and this permission notice shall be | ||
| included in all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
| NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | ||
| LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | ||
| WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - pulldown-cmark-escape 0.11.0 <https://github.com/raphlinus/pulldown-cmark> | ||
| - pulldown-cmark 0.13.6 <https://github.com/raphlinus/pulldown-cmark> | ||
| The MIT License | ||
| Copyright 2015 Google Inc. All rights reserved. | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - tracing-core 0.1.36 <https://github.com/tokio-rs/tracing> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2014 Mathijs van de Nes | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - typenum 1.20.1 <https://github.com/paholg/typenum> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2014 Paho Lurie-Gregg | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - memchr 2.8.3 <https://github.com/BurntSushi/memchr> | ||
| - walkdir 2.5.1 <https://github.com/BurntSushi/walkdir> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2015 Andrew Gallant | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - nix 0.32.0 <https://github.com/nix-rust/nix> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2015 Carl Lerche + nix-rust Authors | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - strsim 0.11.1 <https://github.com/rapidfuzz/strsim-rs> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2015 Danny Guo | ||
| Copyright (c) 2016 Titus Wormer <tituswormer@gmail.com> | ||
| Copyright (c) 2018 Akash Kurdekar | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - shlex 2.0.1 <https://github.com/comex/rust-shlex> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2015 Nicholas Allegra (comex). | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - data-encoding 2.11.1 <https://github.com/ia0/data-encoding> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2015-2020 Julien Cretin | ||
| Copyright (c) 2017-2020 Google Inc. | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - same-file 1.0.6 <https://github.com/BurntSushi/same-file> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2017 Andrew Gallant | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - base64 0.23.1 <https://github.com/marshallpierce/rust-base64> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2025 Alice Maz, Marshall Pierce | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| ================================================================================ | ||
| MIT License (MIT) | ||
| Used by: | ||
| - bincode 1.3.3 <https://github.com/servo/bincode> | ||
| The MIT License (MIT) | ||
| Copyright (c) 2014 Ty Overby | ||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| ================================================================================ | ||
| Unicode License v3 (Unicode-3.0) | ||
| Used by: | ||
| - unicode-ident 1.0.27 <https://github.com/dtolnay/unicode-ident> | ||
| UNICODE LICENSE V3 | ||
| COPYRIGHT AND PERMISSION NOTICE | ||
| Copyright © 1991-2023 Unicode, Inc. | ||
| NOTICE TO USER: Carefully read the following legal agreement. BY | ||
| DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR | ||
| SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE | ||
| TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT | ||
| DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. | ||
| Permission is hereby granted, free of charge, to any person obtaining a | ||
| copy of data files and any associated documentation (the "Data Files") or | ||
| software and any associated documentation (the "Software") to deal in the | ||
| Data Files or Software without restriction, including without limitation | ||
| the rights to use, copy, modify, merge, publish, distribute, and/or sell | ||
| copies of the Data Files or Software, and to permit persons to whom the | ||
| Data Files or Software are furnished to do so, provided that either (a) | ||
| this copyright and permission notice appear with all copies of the Data | ||
| Files or Software, or (b) this copyright and permission notice appear in | ||
| associated Documentation. | ||
| THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY | ||
| KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF | ||
| THIRD PARTY RIGHTS. | ||
| IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE | ||
| BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, | ||
| OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, | ||
| WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, | ||
| ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA | ||
| FILES OR SOFTWARE. | ||
| Except as contained in this notice, the name of a copyright holder shall | ||
| not be used in advertising or otherwise to promote the sale, use or other | ||
| dealings in these Data Files or Software without prior written | ||
| authorization of the copyright holder. | ||
| ================================================================================ | ||
| Red Hat Display, Red Hat Text and Red Hat Mono fonts (OFL-1.1) | ||
| Built into gitv-web, from crates/gitv-web/assets/fonts. | ||
| Copyright 2024 The Red Hat Project Authors (https://github.com/RedHatOfficial/RedHatFont) | ||
| This Font Software is licensed under the SIL Open Font License, Version 1.1. | ||
| This license is copied below, and is also available with a FAQ at: | ||
| https://scripts.sil.org/OFL | ||
| ----------------------------------------------------------- | ||
| SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 | ||
| ----------------------------------------------------------- | ||
| PREAMBLE | ||
| The goals of the Open Font License (OFL) are to stimulate worldwide | ||
| development of collaborative font projects, to support the font creation | ||
| efforts of academic and linguistic communities, and to provide a free and | ||
| open framework in which fonts may be shared and improved in partnership | ||
| with others. | ||
| The OFL allows the licensed fonts to be used, studied, modified and | ||
| redistributed freely as long as they are not sold by themselves. The | ||
| fonts, including any derivative works, can be bundled, embedded, | ||
| redistributed and/or sold with any software provided that any reserved | ||
| names are not used by derivative works. The fonts and derivatives, | ||
| however, cannot be released under any other type of license. The | ||
| requirement for fonts to remain under this license does not apply | ||
| to any document created using the fonts or their derivatives. | ||
| DEFINITIONS | ||
| "Font Software" refers to the set of files released by the Copyright | ||
| Holder(s) under this license and clearly marked as such. This may | ||
| include source files, build scripts and documentation. | ||
| "Reserved Font Name" refers to any names specified as such after the | ||
| copyright statement(s). | ||
| "Original Version" refers to the collection of Font Software components as | ||
| distributed by the Copyright Holder(s). | ||
| "Modified Version" refers to any derivative made by adding to, deleting, | ||
| or substituting -- in part or in whole -- any of the components of the | ||
| Original Version, by changing formats or by porting the Font Software to a | ||
| new environment. | ||
| "Author" refers to any designer, engineer, programmer, technical | ||
| writer or other person who contributed to the Font Software. | ||
| PERMISSION & CONDITIONS | ||
| Permission is hereby granted, free of charge, to any person obtaining | ||
| a copy of the Font Software, to use, study, copy, merge, embed, modify, | ||
| redistribute, and sell modified and unmodified copies of the Font | ||
| Software, subject to the following conditions: | ||
| 1) Neither the Font Software nor any of its individual components, | ||
| in Original or Modified Versions, may be sold by itself. | ||
| 2) Original or Modified Versions of the Font Software may be bundled, | ||
| redistributed and/or sold with any software, provided that each copy | ||
| contains the above copyright notice and this license. These can be | ||
| included either as stand-alone text files, human-readable headers or | ||
| in the appropriate machine-readable metadata fields within text or | ||
| binary files as long as those fields can be easily viewed by the user. | ||
| 3) No Modified Version of the Font Software may use the Reserved Font | ||
| Name(s) unless explicit written permission is granted by the corresponding | ||
| Copyright Holder. This restriction only applies to the primary font name as | ||
| presented to the users. | ||
| 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font | ||
| Software shall not be used to promote, endorse or advertise any | ||
| Modified Version, except to acknowledge the contribution(s) of the | ||
| Copyright Holder(s) and the Author(s) or with their explicit written | ||
| permission. | ||
| 5) The Font Software, modified or unmodified, in part or in whole, | ||
| must be distributed entirely under this license, and must not be | ||
| distributed under any other license. The requirement for fonts to | ||
| remain under this license does not apply to any document created | ||
| using the Font Software. | ||
| TERMINATION | ||
| This license becomes null and void if any of the above conditions are | ||
| not met. | ||
| DISCLAIMER | ||
| THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF | ||
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT | ||
| OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE | ||
| COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | ||
| INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL | ||
| DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
| FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM | ||
| OTHER DEALINGS IN THE FONT SOFTWARE. | ||
| ================================================================================ | ||
| Syntax definitions from Sublime Text's Packages | ||
| Built into gitv-web through syntect's default syntax set, from | ||
| https://github.com/sublimehq/Packages. Unless a file there says otherwise: | ||
| Permission to copy, use, modify, sell and distribute this | ||
| software is granted. This software is provided "as is" without | ||
| express or implied warranty, and with no claim as to its | ||
| suitability for any purpose. | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| [package] | ||
| name = "gitv-core" | ||
| description = "Shared pieces of GITv: configuration, name rules, directory handles and bounded git commands" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| license.workspace = true | ||
| publish = false | ||
| [dependencies] | ||
| nix.workspace = true | ||
+158−0
| @@ -0,0 +1,158 @@ | ||
| //! Settings that differ between installations, read once from `/etc/gitv/gitv.conf` | ||
| //! (`$GITV_CONFIG` to use another file): | ||
| //! | ||
| //! ```text | ||
| //! # The name people reach this server by, in clone addresses and help. | ||
| //! host = git.example.com | ||
| //! # Where gitv is installed: what each key's forced command runs. | ||
| //! command = /usr/local/bin/gitv | ||
| //! ``` | ||
| //! | ||
| //! Both are optional. `host` defaults to `$GITV_HOST`, then the machine's hostname; `command` | ||
| //! defaults to `/usr/local/bin/gitv`. A missing file means all defaults; an unknown key or a bad | ||
| //! value is an error, so a typo can't silently change nothing. Each binary calls [`load`] at | ||
| //! startup, so a problem stops it with a clear message before it serves anything. | ||
| use std::path::{Path, PathBuf}; | ||
| use std::sync::LazyLock; | ||
| pub struct Config { | ||
| /// The server's public hostname, lowercase. | ||
| pub host: String, | ||
| /// The absolute path of the `gitv` binary, for forced commands. | ||
| pub command: String, | ||
| /// Where `host` came from, for startup messages. | ||
| pub host_source: &'static str, | ||
| } | ||
| static CONFIG: LazyLock<Result<Config, String>> = | ||
| LazyLock::new(|| read(&config_path(), std::env::var("GITV_HOST").ok())); | ||
| /// Where the configuration file is: `$GITV_CONFIG`, or `/etc/gitv/gitv.conf`. | ||
| pub fn config_path() -> PathBuf { | ||
| std::env::var_os("GITV_CONFIG").map_or_else(|| PathBuf::from("/etc/gitv/gitv.conf"), PathBuf::from) | ||
| } | ||
| /// Read and check the configuration. | ||
| /// | ||
| /// # Errors | ||
| /// A message naming the file and the problem. | ||
| pub fn load() -> Result<&'static Config, String> { | ||
| CONFIG.as_ref().map_err(Clone::clone) | ||
| } | ||
| /// The server's public hostname. Binaries [`load`] the configuration first; should it be | ||
| /// broken anyway, `localhost` stands in rather than a wrong real name. | ||
| pub fn host() -> &'static str { | ||
| CONFIG.as_ref().map_or("localhost", |c| c.host.as_str()) | ||
| } | ||
| /// The command each key's forced command runs. | ||
| pub fn command() -> &'static str { | ||
| CONFIG.as_ref().map_or("/usr/local/bin/gitv", |c| c.command.as_str()) | ||
| } | ||
| fn read(path: &Path, host_override: Option<String>) -> Result<Config, String> { | ||
| let text = match std::fs::read_to_string(path) { | ||
| Ok(text) => text, | ||
| Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), | ||
| Err(e) => return Err(format!("couldn't read {}: {e}", path.display())), | ||
| }; | ||
| parse(&text, host_override).map_err(|e| format!("{}: {e}", path.display())) | ||
| } | ||
| fn parse(text: &str, host_override: Option<String>) -> Result<Config, String> { | ||
| let (mut host, mut command) = (None, None); | ||
| for (number, line) in text.lines().enumerate() { | ||
| let line = line.trim(); | ||
| if line.is_empty() || line.starts_with('#') { | ||
| continue; | ||
| } | ||
| let (key, value) = | ||
| line.split_once('=').ok_or_else(|| format!("line {}: expected `key = value`", number + 1))?; | ||
| let value = value.trim().to_string(); | ||
| match key.trim() { | ||
| "host" => host = Some(value), | ||
| "command" => command = Some(value), | ||
| other => return Err(format!("line {}: unknown setting `{other}` (known: host, command)", number + 1)), | ||
| } | ||
| } | ||
| // Every value given is checked, even one GITV_HOST overrides: a broken file is still broken. | ||
| let checked = |host: String, source: &'static str| { | ||
| let host = host.to_ascii_lowercase(); | ||
| if valid_host(&host) { Ok((host, source)) } else { Err(format!("`{host}` (from {source}) isn't a hostname")) } | ||
| }; | ||
| let from_file = host.map(|host| checked(host, "the configuration file")).transpose()?; | ||
| let (host, host_source) = match (host_override, from_file) { | ||
| (Some(host), _) => checked(host, "GITV_HOST")?, | ||
| (None, Some(found)) => found, | ||
| (None, None) => { | ||
| let name = nix::unistd::gethostname().map_err(|e| format!("no host set and no hostname: {e}"))?; | ||
| checked(name.to_string_lossy().into_owned(), "the machine's hostname")? | ||
| } | ||
| }; | ||
| let command = command.unwrap_or_else(|| "/usr/local/bin/gitv".into()); | ||
| // It goes inside command="..." in authorized_keys, so nothing that could end or escape that. | ||
| if !command.starts_with('/') || command.bytes().any(|b| b.is_ascii_whitespace() || b"\"\\'".contains(&b)) { | ||
| return Err(format!("command `{command}` must be an absolute path without spaces or quotes")); | ||
| } | ||
| Ok(Config { host, command, host_source }) | ||
| } | ||
| /// A DNS name: dot-separated labels of letters, digits and inner hyphens, 253 characters at most. | ||
| fn valid_host(host: &str) -> bool { | ||
| host.len() <= 253 | ||
| && host.split('.').all(|label| { | ||
| (1..=63).contains(&label.len()) | ||
| && label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') | ||
| && !label.starts_with('-') | ||
| && !label.ends_with('-') | ||
| }) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn settings_come_from_the_file_with_the_environment_first() { | ||
| let file = "# comment\nhost = Git.Example.COM\n\ncommand = /opt/gitv/bin/gitv\n"; | ||
| let config = parse(file, None).unwrap(); | ||
| assert_eq!((config.host.as_str(), config.command.as_str()), ("git.example.com", "/opt/gitv/bin/gitv")); | ||
| assert_eq!(config.host_source, "the configuration file"); | ||
| let config = parse(file, Some("other.example".into())).unwrap(); | ||
| assert_eq!((config.host.as_str(), config.host_source), ("other.example", "GITV_HOST")); | ||
| } | ||
| #[test] | ||
| fn defaults_fill_in_what_is_missing() { | ||
| let config = parse("", None).unwrap(); | ||
| assert_eq!(config.command, "/usr/local/bin/gitv"); | ||
| assert_eq!(config.host_source, "the machine's hostname"); | ||
| assert!(valid_host(&config.host)); | ||
| } | ||
| #[test] | ||
| fn mistakes_are_refused_with_the_line() { | ||
| for (text, expected) in [ | ||
| ("hots = x.example", "line 1: unknown setting `hots`"), | ||
| ("\nhost", "line 2: expected `key = value`"), | ||
| ("host = git.example.com/repos", "isn't a hostname"), | ||
| ("host = -bad.example", "isn't a hostname"), | ||
| ("host = a..b", "isn't a hostname"), | ||
| ("command = gitv", "must be an absolute path"), | ||
| ("command = /usr/bin/gitv\" evil", "must be an absolute path"), | ||
| ] { | ||
| let error = parse(text, Some("ok.example".into())).err().unwrap_or_default(); | ||
| assert!(error.contains(expected), "{text:?}: {error}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn a_missing_file_means_defaults_and_an_unreadable_one_is_an_error() { | ||
| let missing = std::env::temp_dir().join(format!("gitv-no-config-{}", std::process::id())); | ||
| assert!(read(&missing, Some("x.example".into())).is_ok()); | ||
| let error = read(&std::env::temp_dir(), None).err().unwrap_or_default(); | ||
| assert!(error.contains("couldn't read"), "{error}"); | ||
| } | ||
| } | ||
crates/gitv-core/src/lib.rsRenamed
+377−27
| @@ -1,7 +1,6 @@ | ||
| //! Shared pieces of GITv: configuration, name rules and read-only git access. | ||
| pub mod auth; | ||
| pub mod render; | ||
| pub mod config; | ||
| use std::ffi::{OsStr, OsString}; | ||
| use std::io::Read; | ||
| @@ -18,10 +17,9 @@ use std::time::{Duration, Instant}; | ||
| use nix::dir::Dir; | ||
| use nix::fcntl::{AtFlags, OFlag, open, openat}; | ||
| use nix::sys::stat::{Mode, SFlag, fstatat}; | ||
| use nix::sys::wait::{Id, WaitPidFlag, waitid}; | ||
| use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, unlinkat}; | ||
| pub const HOST: &str = "git.um9i.dev"; | ||
| /// Where bare repositories live: `<root>/<owner>/<name>.git`. `GITV_REPOS` overrides it for local runs. | ||
| pub fn repos_root() -> PathBuf { | ||
| std::env::var_os("GITV_REPOS").map_or_else(|| PathBuf::from("/srv/gitv/repos"), PathBuf::from) | ||
| @@ -61,7 +59,10 @@ pub fn git_base() -> Command { | ||
| command | ||
| } | ||
| fn configure(command: &mut Command) { | ||
| /// Give any git program (`git`, or `git-receive-pack` run directly) the same clean environment | ||
| /// as [`git_base`]: no inherited variables, no user or system config, stdin closed until the | ||
| /// caller says otherwise. | ||
| pub fn configure(command: &mut Command) { | ||
| command | ||
| .env_clear() | ||
| .env("PATH", "/usr/bin:/bin") | ||
| @@ -75,10 +76,16 @@ fn configure(command: &mut Command) { | ||
| /// An open repository directory. Holding the directory itself, not its path, means a symlink | ||
| /// swapped in after the checks can't redirect anything: git runs inside this exact directory. | ||
| /// Git's file for a repository's one-line description, in the repository directory. | ||
| const DESCRIPTION: &str = "description"; | ||
| /// The longest description, in characters. | ||
| pub const DESCRIPTION_LIMIT: usize = 160; | ||
| pub struct RepoDir { | ||
| /// Where it was found, for messages and cache keys only; never reopened. | ||
| pub path: PathBuf, | ||
| fd: OwnedFd, | ||
| deadline: Option<Instant>, | ||
| } | ||
| impl RepoDir { | ||
| @@ -86,7 +93,11 @@ impl RepoDir { | ||
| /// code finds repositories through [`repo_dir`] or [`repo_in`]. | ||
| pub fn at(path: &Path) -> Option<RepoDir> { | ||
| let fd = open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW, Mode::empty()).ok()?; | ||
| Some(RepoDir { path: path.to_path_buf(), fd }) | ||
| Some(RepoDir { path: path.to_path_buf(), fd, deadline: None }) | ||
| } | ||
| pub fn limit_until(&mut self, deadline: Instant) { | ||
| self.deadline = Some(deadline); | ||
| } | ||
| /// A command that starts inside this directory, whatever happens to its path meanwhile. | ||
| @@ -94,10 +105,110 @@ impl RepoDir { | ||
| command_in(&self.fd, program) | ||
| } | ||
| pub fn is_public(&self) -> bool { | ||
| self.has_marker("gitv-public") | ||
| } | ||
| pub fn set_public(&self, public: bool) -> nix::Result<()> { | ||
| self.set_marker("gitv-public", public) | ||
| } | ||
| /// Whether pushes may only move branches forwards and never delete them (`gitv protect`). | ||
| pub fn is_protected(&self) -> bool { | ||
| self.has_marker("gitv-protected") | ||
| } | ||
| pub fn set_protected(&self, protected: bool) -> nix::Result<()> { | ||
| self.set_marker("gitv-protected", protected) | ||
| } | ||
| /// A setting kept as an empty file in the repository directory: present (and a regular | ||
| /// file) means on. Backups and restores carry it with the repository. | ||
| fn has_marker(&self, marker: &str) -> bool { | ||
| matches!(try_kind_at(&self.fd, OsStr::new(marker)), Ok(Some(SFlag::S_IFREG))) | ||
| } | ||
| fn set_marker(&self, marker: &str, on: bool) -> nix::Result<()> { | ||
| if on { | ||
| match openat( | ||
| &self.fd, | ||
| marker, | ||
| OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_CLOEXEC, | ||
| Mode::S_IRUSR, | ||
| ) { | ||
| Ok(_) => Ok(()), | ||
| Err(nix::errno::Errno::EEXIST) if self.has_marker(marker) => Ok(()), | ||
| Err(error) => Err(error), | ||
| } | ||
| } else { | ||
| match unlinkat(&self.fd, marker, UnlinkatFlags::NoRemoveDir) { | ||
| Err(nix::errno::Errno::ENOENT) => Ok(()), | ||
| result => result, | ||
| } | ||
| } | ||
| } | ||
| /// The open directory, for reading it by handle. | ||
| /// The repository's one-line description from git's `description` file, or `None` when | ||
| /// there's none or it still holds the placeholder `git init` writes. | ||
| pub fn description(&self) -> Option<String> { | ||
| // Non-blocking, so a FIFO planted at the name can't hang the reader; then only a | ||
| // regular file is read, and only its first kilobyte. | ||
| let flags = OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC; | ||
| let fd = openat(&self.fd, DESCRIPTION, flags, Mode::empty()).ok()?; | ||
| let meta = nix::sys::stat::fstat(&fd).ok()?; | ||
| if SFlag::from_bits_truncate(meta.st_mode) & SFlag::S_IFMT != SFlag::S_IFREG { | ||
| return None; | ||
| } | ||
| let mut bytes = Vec::new(); | ||
| std::fs::File::from(fd).take(DESCRIPTION_LIMIT as u64 * 4).read_to_end(&mut bytes).ok()?; | ||
| let text = String::from_utf8_lossy(&bytes); | ||
| let line = text.lines().next().unwrap_or_default().trim(); | ||
| let placeholder = line.starts_with("Unnamed repository"); | ||
| (!line.is_empty() && !placeholder).then(|| line.chars().filter(|c| !c.is_control()).collect()) | ||
| } | ||
| /// Replace the description, or remove it with `None`. The new file is written beside the old | ||
| /// one and renamed over it inside this open directory, so a reader sees one or the other. | ||
| pub fn set_description(&self, text: Option<&str>) -> nix::Result<()> { | ||
| use std::io::Write as _; | ||
| let Some(text) = text else { | ||
| return match unlinkat(&self.fd, DESCRIPTION, UnlinkatFlags::NoRemoveDir) { | ||
| Err(nix::errno::Errno::ENOENT) => Ok(()), | ||
| result => result, | ||
| }; | ||
| }; | ||
| let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); | ||
| let temporary = format!(".{DESCRIPTION}.tmp-{}-{nanos}", std::process::id()); | ||
| let flags = OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC; | ||
| let fd = openat(&self.fd, temporary.as_str(), flags, Mode::from_bits_truncate(0o644))?; | ||
| let written = (|| { | ||
| // Created with the umask applied; readers (the web service) need it world-readable. | ||
| nix::sys::stat::fchmod(&fd, Mode::from_bits_truncate(0o644))?; | ||
| let mut file = std::fs::File::from(fd); | ||
| let io = |e: std::io::Error| e.raw_os_error().map_or(nix::errno::Errno::EIO, nix::errno::Errno::from_raw); | ||
| file.write_all(format!("{text}\n").as_bytes()).map_err(io)?; | ||
| file.sync_all().map_err(io)?; | ||
| nix::fcntl::renameat(&self.fd, temporary.as_str(), &self.fd, DESCRIPTION) | ||
| })(); | ||
| if written.is_err() { | ||
| let _ = unlinkat(&self.fd, temporary.as_str(), UnlinkatFlags::NoRemoveDir); | ||
| } | ||
| written | ||
| } | ||
| pub fn handle(&self) -> BorrowedFd<'_> { | ||
| self.fd.as_fd() | ||
| } | ||
| /// Lock the repository directory itself, waiting for any conflicting holder. Pushes hold it | ||
| /// shared; a backup holds it exclusive (`flock -x <repo>`) so it never copies a push half | ||
| /// written. Released when the returned lock is dropped. | ||
| pub fn lock(&self, exclusive: bool) -> nix::Result<nix::fcntl::Flock<OwnedFd>> { | ||
| let fd = self.fd.try_clone().map_err(|e| nix::errno::Errno::from_raw(e.raw_os_error().unwrap_or(0)))?; | ||
| let kind = if exclusive { nix::fcntl::FlockArg::LockExclusive } else { nix::fcntl::FlockArg::LockShared }; | ||
| nix::fcntl::Flock::lock(fd, kind).map_err(|(_, e)| e) | ||
| } | ||
| } | ||
| /// A command that starts inside the open directory `dir`. The command owns its own duplicate | ||
| @@ -144,16 +255,61 @@ pub fn git<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S]) -> Result<Vec<u8>, St | ||
| } | ||
| } | ||
| /// Like [`git`], with `input` written to the command's stdin, as for `cat-file --batch-check`. | ||
| pub fn git_with_input<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], input: &[u8]) -> Result<Vec<u8>, String> { | ||
| match run_git(git_dir, args, Some(input), GIT_OUTPUT_LIMIT, GIT_TIMEOUT)? { | ||
| (output, false) => Ok(output), | ||
| (_, true) => Err("git output too large".into()), | ||
| } | ||
| } | ||
| /// Like [`git`], but output beyond `cap` bytes stops the command and comes back truncated, with | ||
| /// `true` to say so, rather than as an error. | ||
| pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> Result<(Vec<u8>, bool), String> { | ||
| let mut child = git_command(git_dir) | ||
| .args(args) | ||
| .stdout(Stdio::piped()) | ||
| .stderr(Stdio::null()) | ||
| .spawn() | ||
| .map_err(|e| format!("cannot run git: {e}"))?; | ||
| git_capped_for(git_dir, args, cap, GIT_TIMEOUT) | ||
| } | ||
| /// Apply a shorter budget to optional work while respecting the overall page deadline. | ||
| pub fn git_capped_for<S: AsRef<OsStr>>( | ||
| git_dir: &RepoDir, | ||
| args: &[S], | ||
| cap: usize, | ||
| timeout: Duration, | ||
| ) -> Result<(Vec<u8>, bool), String> { | ||
| run_git(git_dir, args, None, cap, timeout) | ||
| } | ||
| fn run_git<S: AsRef<OsStr>>( | ||
| git_dir: &RepoDir, | ||
| args: &[S], | ||
| input: Option<&[u8]>, | ||
| cap: usize, | ||
| timeout: Duration, | ||
| ) -> Result<(Vec<u8>, bool), String> { | ||
| let deadline = Instant::now() + timeout.min(GIT_TIMEOUT); | ||
| let deadline = git_dir.deadline.map_or(deadline, |limit| limit.min(deadline)); | ||
| if Instant::now() >= deadline { | ||
| return Err("page time budget exhausted".into()); | ||
| } | ||
| let mut command = git_command(git_dir); | ||
| command.args(args).stdout(Stdio::piped()).stderr(Stdio::null()); | ||
| if input.is_some() { | ||
| command.stdin(Stdio::piped()); | ||
| } | ||
| let mut child = command.spawn().map_err(|e| format!("cannot run git: {e}"))?; | ||
| let mut stdout = child.stdout.take().ok_or("git has no stdout")?; | ||
| // Written from its own thread, so git can't block on a full stdout while we block on a full | ||
| // stdin. A killed git fails the write (SIGPIPE is ignored in Rust programs), ending the thread. | ||
| let writer = match (input, child.stdin.take()) { | ||
| (Some(input), Some(mut stdin)) => { | ||
| let input = input.to_vec(); | ||
| Some(thread::spawn(move || { | ||
| let _ = std::io::Write::write_all(&mut stdin, &input); | ||
| })) | ||
| } | ||
| _ => None, | ||
| }; | ||
| let pid = nix::unistd::Pid::from_raw(i32::try_from(child.id()).map_err(|_| "git has no pid")?); | ||
| let child = Arc::new(Mutex::new(child)); | ||
| let kill = |child: &Mutex<Child>| { | ||
| // The child is never reaped while the lock is held, so this can't hit a reused pid. | ||
| @@ -161,13 +317,14 @@ pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> | ||
| let _ = child.kill(); | ||
| } | ||
| }; | ||
| let deadline = Instant::now() + GIT_TIMEOUT; | ||
| // The watchdog covers a read that blocks; nobody holds the lock while blocked. | ||
| let (finished, wait) = mpsc::channel::<()>(); | ||
| let watchdog = { | ||
| let child = Arc::clone(&child); | ||
| thread::spawn(move || { | ||
| if let Err(RecvTimeoutError::Timeout) = wait.recv_timeout(GIT_TIMEOUT) { | ||
| if let Err(RecvTimeoutError::Timeout) = | ||
| wait.recv_timeout(deadline.saturating_duration_since(Instant::now())) | ||
| { | ||
| kill(&child); | ||
| } | ||
| }) | ||
| @@ -180,19 +337,23 @@ pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> | ||
| kill(&child); | ||
| } | ||
| drop(stdout); | ||
| // Poll rather than block in wait(), taking the lock only briefly, so a kill can always | ||
| // get in, here or from the watchdog, even if git closed its output but kept running. | ||
| // Wait for git to exit without reaping it (WNOWAIT), holding no lock, so the watchdog can | ||
| // still kill it if it closed its output but kept running. Until it is reaped its pid can't | ||
| // be reused, so that kill can never reach another process. Then reap it at once. | ||
| let status = loop { | ||
| let polled = child.lock().map_err(|_| "git watchdog failed")?.try_wait(); | ||
| match polled { | ||
| Ok(Some(status)) => break Ok(status), | ||
| Ok(None) if Instant::now() >= deadline => kill(&child), | ||
| Ok(None) => thread::sleep(Duration::from_millis(2)), | ||
| match waitid(Id::Pid(pid), WaitPidFlag::WEXITED | WaitPidFlag::WNOWAIT) { | ||
| Ok(_) => { | ||
| break child.lock().map_err(|_| "git watchdog failed")?.wait().map_err(|e| format!("git failed: {e}")); | ||
| } | ||
| Err(nix::errno::Errno::EINTR) => continue, | ||
| Err(e) => break Err(format!("git failed: {e}")), | ||
| } | ||
| }; | ||
| let _ = finished.send(()); | ||
| let _ = watchdog.join(); | ||
| if let Some(writer) = writer { | ||
| let _ = writer.join(); | ||
| } | ||
| read.map_err(|e| format!("cannot read git output: {e}"))?; | ||
| let status = status?; | ||
| if overflow { | ||
| @@ -204,6 +365,96 @@ pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> | ||
| } | ||
| } | ||
| /// A client's requested git protocol (`version=2`, say), when it is well formed, to pass on as | ||
| /// `GIT_PROTOCOL`, as sshd and `git http-backend` do. Anything else is ignored. | ||
| pub fn git_protocol(value: &str) -> Option<&str> { | ||
| (value.len() <= 64 && value.bytes().all(|b| b.is_ascii_alphanumeric() || b"=:.".contains(&b))).then_some(value) | ||
| } | ||
| /// Seconds since the Unix epoch, or 0 if the clock is set before it. | ||
| pub fn unix_now() -> u64 { | ||
| std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) | ||
| } | ||
| /// Make a rename or new file in `path`'s directory durable: until the directory itself is | ||
| /// synced, a crash can leave the old name, or none, in place of what was just published. | ||
| pub fn sync_directory_of(path: &Path) -> std::io::Result<()> { | ||
| let directory = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); | ||
| std::fs::File::open(directory)?.sync_all() | ||
| } | ||
| /// Why [`publish_file`] failed. Nothing was published in any case but a failed final sync. | ||
| #[derive(Debug)] | ||
| pub enum PublishError<E> { | ||
| /// Asked not to replace, and something is already at the path. | ||
| Exists, | ||
| /// Writing, renaming or syncing failed. | ||
| Io(std::io::Error), | ||
| /// The caller's `prepare` step failed. | ||
| Prepare(E), | ||
| } | ||
| impl<E: std::fmt::Display> std::fmt::Display for PublishError<E> { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| match self { | ||
| PublishError::Exists => write!(f, "it already exists"), | ||
| PublishError::Io(e) => write!(f, "{e}"), | ||
| PublishError::Prepare(e) => write!(f, "{e}"), | ||
| } | ||
| } | ||
| } | ||
| /// Publish `contents` at `path` in one step, so readers see the old file or the new one, never | ||
| /// part of either, and a crash leaves one of them in place. | ||
| /// | ||
| /// The contents go to a fresh hidden file beside `path`, under a name no other writer uses, | ||
| /// created exclusively (never an existing file opened and truncated) with permissions `mode` | ||
| /// (applied after creation, so the umask doesn't narrow them). `prepare` then sees the | ||
| /// finished file, to change its ownership say, before it is synced and renamed into place, | ||
| /// replacing what's there only if `replace` is set. The directory is synced last, so the | ||
| /// rename survives a crash. On any failure before the rename the hidden file is removed. | ||
| /// | ||
| /// # Errors | ||
| /// [`PublishError::Exists`] if `replace` is unset and `path` exists; [`PublishError::Prepare`] | ||
| /// with `prepare`'s own error; otherwise [`PublishError::Io`]. | ||
| pub fn publish_file<E>( | ||
| path: &Path, | ||
| contents: &[u8], | ||
| mode: u32, | ||
| replace: bool, | ||
| prepare: impl FnOnce(&std::fs::File) -> Result<(), E>, | ||
| ) -> Result<(), PublishError<E>> { | ||
| use std::io::Write as _; | ||
| use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; | ||
| use std::sync::atomic::{AtomicU64, Ordering}; | ||
| static WRITES: AtomicU64 = AtomicU64::new(0); | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); | ||
| let serial = WRITES.fetch_add(1, Ordering::Relaxed); | ||
| let temporary = path.with_file_name(format!(".{name}.tmp-{}-{nanos}-{serial}", std::process::id())); | ||
| let mut file = | ||
| std::fs::File::options().write(true).create_new(true).mode(mode).open(&temporary).map_err(PublishError::Io)?; | ||
| let published = (|| { | ||
| file.write_all(contents).map_err(PublishError::Io)?; | ||
| file.set_permissions(std::fs::Permissions::from_mode(mode)).map_err(PublishError::Io)?; | ||
| prepare(&file).map_err(PublishError::Prepare)?; | ||
| file.sync_all().map_err(PublishError::Io)?; | ||
| let flags = if replace { nix::fcntl::RenameFlags::empty() } else { 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 => PublishError::Exists, | ||
| e => PublishError::Io(e.into()), | ||
| }, | ||
| ) | ||
| })(); | ||
| if published.is_err() { | ||
| let _ = std::fs::remove_file(&temporary); | ||
| return published; | ||
| } | ||
| sync_directory_of(path).map_err(PublishError::Io) | ||
| } | ||
| /// Decode `%XX` escapes to raw bytes, as in a URL path or a Markdown link destination. `+` | ||
| /// stays a plus (only query strings use it for a space). A malformed escape is kept as written. | ||
| pub fn percent_decode(text: &str) -> Vec<u8> { | ||
| @@ -241,6 +492,15 @@ pub fn open_root() -> Option<OwnedFd> { | ||
| open(&repos_root(), OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).ok() | ||
| } | ||
| /// The directory at `path`, refused if its last part is a symlink or not a directory, to work | ||
| /// inside by handle. | ||
| /// | ||
| /// # Errors | ||
| /// The open's failure: `ELOOP` for a symlink, `ENOTDIR` for anything else that isn't a folder. | ||
| pub fn open_dir(path: &Path) -> std::io::Result<OwnedFd> { | ||
| Ok(open(path, DIR_FLAGS, Mode::empty())?) | ||
| } | ||
| /// The directory `name` inside `dir`; refused if it is a symlink or not a directory. | ||
| pub fn open_dir_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<OwnedFd> { | ||
| openat(dir, name, DIR_FLAGS, Mode::empty()) | ||
| @@ -274,14 +534,32 @@ pub fn entries(dir: &impl AsFd) -> Vec<OsString> { | ||
| /// The names in an open directory, or the error that stopped the listing part way. | ||
| pub fn try_entries(dir: &impl AsFd) -> nix::Result<Vec<OsString>> { | ||
| list_entries(dir, false) | ||
| } | ||
| /// List only child directories, using directory-entry types when the filesystem supplies them. | ||
| pub fn try_subdirs(dir: &impl AsFd) -> nix::Result<Vec<OsString>> { | ||
| list_entries(dir, true) | ||
| } | ||
| fn list_entries(dir: &impl AsFd, directories_only: bool) -> nix::Result<Vec<OsString>> { | ||
| let fresh = openat(dir, ".", OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty())?; | ||
| let mut listing = Dir::from_fd(fresh)?; | ||
| let mut names = Vec::new(); | ||
| for entry in listing.iter() { | ||
| let name = OsStr::from_bytes(entry?.file_name().to_bytes()).to_os_string(); | ||
| if name != "." && name != ".." { | ||
| names.push(name); | ||
| let entry = entry?; | ||
| let name = OsStr::from_bytes(entry.file_name().to_bytes()); | ||
| if name == "." || name == ".." { | ||
| continue; | ||
| } | ||
| if directories_only { | ||
| match entry.file_type() { | ||
| Some(nix::dir::Type::Directory) => {} | ||
| None if try_kind_at(dir, name)? == Some(SFlag::S_IFDIR) => {} | ||
| _ => continue, | ||
| } | ||
| } | ||
| names.push(name.to_owned()); | ||
| } | ||
| Ok(names) | ||
| } | ||
| @@ -335,7 +613,7 @@ pub fn repo_in(owner_dir: &impl AsFd, owner: &str, name: &str) -> Option<RepoDir | ||
| if kind_at(&fd, OsStr::new("HEAD")) != Some(SFlag::S_IFREG) { | ||
| return None; | ||
| } | ||
| Some(RepoDir { path: repos_root().join(owner).join(file), fd }) | ||
| Some(RepoDir { path: repos_root().join(owner).join(file), fd, deadline: None }) | ||
| } | ||
| /// [`repo_in`], opening the owner's directory first. | ||
| @@ -350,8 +628,7 @@ mod tests { | ||
| /// A bare repository holding one blob of `size` bytes, and the blob's id. | ||
| fn repo_with_blob(name: &str, size: usize) -> (RepoDir, String) { | ||
| let dir = std::env::temp_dir().join(format!("gitv-lib-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| let dir = scratch(name); | ||
| assert!(git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| let dir = RepoDir::at(&dir).unwrap(); | ||
| let mut child = git_command(&dir) | ||
| @@ -365,6 +642,57 @@ mod tests { | ||
| (dir, oid) | ||
| } | ||
| #[test] | ||
| fn git_commands_share_the_page_deadline_even_while_blocked_on_io() { | ||
| let (mut dir, oid) = repo_with_blob("deadline", 10); | ||
| let pipe = dir.path.join("pending-config"); | ||
| nix::unistd::mkfifo(&pipe, Mode::S_IRUSR | Mode::S_IWUSR).unwrap(); | ||
| // Holding both ends open keeps Git waiting for more bytes until its watchdog fires. | ||
| let _writer = fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap(); | ||
| let deadline = Instant::now() + Duration::from_millis(250); | ||
| dir.limit_until(deadline); | ||
| let result = git(&dir, &["config", "--file", "pending-config", "--list"]); | ||
| let finished = Instant::now(); | ||
| assert!(result.unwrap_err().contains("SIGKILL"), "the watchdog must kill the running Git command"); | ||
| assert!(finished >= deadline); | ||
| assert!(finished.duration_since(deadline) < Duration::from_secs(5), "used the per-command timeout"); | ||
| // Even a fast command must be refused once the same page has spent its budget. | ||
| assert_eq!(git(&dir, &["cat-file", "-s", &oid]).unwrap_err(), "page time budget exhausted"); | ||
| fs::remove_dir_all(&dir.path).unwrap(); | ||
| } | ||
| #[test] | ||
| fn published_files_replace_whole_or_not_at_all() { | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let dir = scratch("publish"); | ||
| let path = dir.join("keys"); | ||
| let none = |_: &fs::File| Ok::<(), String>(()); | ||
| publish_file(&path, b"one\n", 0o644, true, none).unwrap(); | ||
| publish_file(&path, b"two\n", 0o644, true, none).unwrap(); | ||
| assert_eq!(fs::read(&path).unwrap(), b"two\n"); | ||
| assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644, "the umask didn't narrow it"); | ||
| // Not replacing: the existing file stays. | ||
| assert!(matches!(publish_file(&path, b"three\n", 0o600, false, none), Err(PublishError::Exists))); | ||
| // A failed preparation publishes nothing and says why. | ||
| let refuse = |_: &fs::File| Err("not today".to_string()); | ||
| assert!( | ||
| matches!(publish_file(&path, b"four\n", 0o600, true, refuse), Err(PublishError::Prepare(e)) if e == "not today") | ||
| ); | ||
| assert_eq!(fs::read(&path).unwrap(), b"two\n"); | ||
| let names: Vec<_> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect(); | ||
| assert_eq!(names, ["keys"], "no hidden file was left behind"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn only_well_formed_protocol_requests_pass() { | ||
| assert_eq!(git_protocol("version=2"), Some("version=2")); | ||
| assert_eq!(git_protocol("version=2:value=1"), Some("version=2:value=1")); | ||
| for bad in ["version=2\n", "a b", "x;rm", &"v".repeat(65)] { | ||
| assert_eq!(git_protocol(bad), None, "{bad:?}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn capped_output_stops_early_and_says_so() { | ||
| let (dir, oid) = repo_with_blob("capped", 1 << 20); | ||
| @@ -378,6 +706,16 @@ mod tests { | ||
| let _ = fs::remove_dir_all(&dir.path); | ||
| } | ||
| #[test] | ||
| fn input_reaches_git_even_when_it_outgrows_a_pipe() { | ||
| let (dir, oid) = repo_with_blob("input", 10); | ||
| // Far more queries than a pipe buffers, so writing and reading must overlap. | ||
| let queries = format!("{oid}\n").repeat(20_000); | ||
| let out = git_with_input(&dir, &["cat-file", "--batch-check"], queries.as_bytes()).unwrap(); | ||
| assert_eq!(out, format!("{oid} blob 10\n").repeat(20_000).into_bytes()); | ||
| let _ = fs::remove_dir_all(&dir.path); | ||
| } | ||
| #[test] | ||
| fn an_open_repository_stays_bound_to_its_directory() { | ||
| // Open one repository, then swap another into its path: git must still see the first. | ||
| @@ -423,6 +761,18 @@ mod tests { | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_directory_opened_by_path_is_never_a_symlink() { | ||
| let dir = scratch("open-dir"); | ||
| std::fs::create_dir(dir.join("real")).unwrap(); | ||
| std::fs::write(dir.join("file"), "").unwrap(); | ||
| std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap(); | ||
| assert!(open_dir(&dir.join("real")).is_ok()); | ||
| assert!(open_dir(&dir.join("link")).is_err(), "a symlinked folder is refused"); | ||
| assert!(open_dir(&dir.join("file")).is_err(), "a file is refused"); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn removing_a_tree_never_follows_symlinks() { | ||
| let dir = scratch("remove"); | ||
+35−0
| @@ -0,0 +1,35 @@ | ||
| [package] | ||
| name = "gitv-web" | ||
| description = "GITv's repository browser and read-only HTTPS clone service" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| license.workspace = true | ||
| publish = false | ||
| [dependencies] | ||
| gitv-core.workspace = true | ||
| argon2.workspace = true | ||
| askama.workspace = true | ||
| axum.workspace = true | ||
| clap.workspace = true | ||
| data-encoding.workspace = true | ||
| flate2.workspace = true | ||
| futures-util.workspace = true | ||
| getrandom.workspace = true | ||
| hmac.workspace = true | ||
| html-escape.workspace = true | ||
| nix.workspace = true | ||
| pulldown-cmark.workspace = true | ||
| qrcode.workspace = true | ||
| rpassword.workspace = true | ||
| serde.workspace = true | ||
| sha1.workspace = true | ||
| sha2.workspace = true | ||
| subtle.workspace = true | ||
| syntect.workspace = true | ||
| thiserror.workspace = true | ||
| tokio.workspace = true | ||
| [dev-dependencies] | ||
| # The shared test helpers build SSH keys for their fixtures. | ||
| base64.workspace = true | ||
+3−3
| @@ -1,8 +1,8 @@ | ||
| Google Inc. | ||
| Copyright 2024 The Red Hat Project Authors (https://github.com/RedHatOfficial/RedHatFont) | ||
| This Font Software is licensed under the SIL Open Font License, Version 1.1. | ||
| This license is copied below, and is also available with a FAQ at: | ||
| http://scripts.sil.org/OFL | ||
| https://scripts.sil.org/OFL | ||
| ----------------------------------------------------------- | ||
| @@ -18,7 +18,7 @@ with others. | ||
| The OFL allows the licensed fonts to be used, studied, modified and | ||
| redistributed freely as long as they are not sold by themselves. The | ||
| fonts, including any derivative works, can be bundled, embedded, | ||
| fonts, including any derivative works, can be bundled, embedded, | ||
| redistributed and/or sold with any software provided that any reserved | ||
| names are not used by derivative works. The fonts and derivatives, | ||
| however, cannot be released under any other type of license. The | ||
+0−0
No content changes.
+0−0
No content changes.
+0−0
No content changes.
+0−0
Binary file changed.
+0−0
Binary file changed.
Binary file changed.
Binary file changed.
+73−16
| @@ -55,7 +55,12 @@ main{max-width:1080px;margin:0 auto;padding:32px 24px 72px} | ||
| .reponame a{color:var(--ink)} | ||
| .reponame .own{font-weight:400;color:var(--ink-2)} | ||
| .reponame .sep{font-weight:300;color:var(--ink-2);opacity:.5} | ||
| .clone{display:flex;align-items:stretch;flex:0 1 380px;min-width:0} | ||
| .repoid{display:grid;gap:6px;min-width:0;flex:1 1 20em} | ||
| .repoline{display:flex;align-items:center;gap:8px 12px;flex-wrap:wrap} | ||
| .vis{padding:2px 9px;font-size:12px;font-weight:600;color:var(--ink-2);border:1px solid var(--rule);border-radius:99px} | ||
| .repodesc{margin:0;max-width:64ch;color:var(--ink-2);overflow-wrap:anywhere} | ||
| .clones{display:grid;gap:8px;flex:0 1 380px;min-width:0} | ||
| .clone{display:flex;align-items:stretch;min-width:0} | ||
| .clone span{display:flex;align-items:center;padding:0 10px;font-size:12px;font-weight:600;color:var(--ink-2); | ||
| background:var(--rule-2);border:1px solid var(--rule);border-right:0;border-radius:8px 0 0 8px} | ||
| .clone input{width:100%;min-width:0;min-height:36px;padding:0 10px;font:13px var(--f-mono);color:var(--ink); | ||
| @@ -93,7 +98,7 @@ main{max-width:1080px;margin:0 auto;padding:32px 24px 72px} | ||
| .panel{background:var(--surface);border:1px solid var(--rule);border-radius:10px;overflow:hidden;margin:0 0 24px} | ||
| .panel-head{display:flex;align-items:center;justify-content:space-between;gap:8px 16px;flex-wrap:wrap;min-height:48px; | ||
| padding:8px 16px;font-size:14px;background:var(--sunk);border-bottom:1px solid var(--rule)} | ||
| .panel-head .lead{display:flex;align-items:center;gap:10px;min-width:0;flex:1} | ||
| .panel-head .lead{display:flex;align-items:center;gap:10px;min-width:0;flex:1 1 12em} | ||
| .panel-head .lead b{font-weight:600;overflow-wrap:anywhere} | ||
| .panel-head .who{white-space:nowrap} | ||
| .panel-head .side{display:flex;align-items:center;gap:12px;color:var(--ink-2);font-size:13px;white-space:nowrap} | ||
| @@ -112,13 +117,44 @@ a.entry:hover .name{color:var(--accent)} | ||
| color:var(--accent);background:var(--accent-wash)} | ||
| .sha:hover{text-decoration:none;box-shadow:inset 0 0 0 1px var(--accent)} | ||
| .repo-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:2px 20px;align-items:center;padding:14px 18px;color:var(--ink)} | ||
| .repo-row:hover{background:var(--sunk);text-decoration:none} | ||
| .repo-row:hover .rname{color:var(--accent)} | ||
| .rname{font:700 18px/1.3 var(--f-display);letter-spacing:-.01em;overflow-wrap:anywhere} | ||
| /* Repository index */ | ||
| .index-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:12px 0 24px} | ||
| .index-head .title{font-size:clamp(32px,5vw,44px);letter-spacing:-.035em} | ||
| .index-head .count,.index-columns,.rwhen,.ridentity small{font-size:14px;color:var(--ink-2)} | ||
| .index-columns,.repo-row{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr) 8rem;gap:20px;align-items:center;padding:16px 20px} | ||
| .index-columns{padding-block:10px;background:var(--sunk);border-bottom:1px solid var(--rule);font-weight:600} | ||
| .index-columns span:last-child,.rwhen{text-align:right} | ||
| .repo-row{min-height:68px;color:var(--ink)} | ||
| .repo-row:is(:hover,:focus-visible,:active){background:var(--sunk);text-decoration:none} | ||
| .repo-row:focus-visible{outline-offset:-3px} | ||
| .repo-row:is(:hover,:focus-visible) .rname{color:var(--accent);text-decoration:underline} | ||
| .ridentity{display:grid;gap:2px} | ||
| .rname{font:700 19px/1.3 var(--f-display);overflow-wrap:anywhere} | ||
| .rname span{font-weight:400;color:var(--ink-2)} | ||
| .rlast{grid-column:1;font-size:14px;color:var(--ink-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| .rwhen{grid-row:1 / span 2;grid-column:2;font-size:13px;color:var(--ink-2);white-space:nowrap} | ||
| .rlast{font-size:15px;line-height:1.4;overflow-wrap:anywhere} | ||
| .rdesc{font-size:14px;line-height:1.4;color:var(--ink-2);overflow-wrap:anywhere} | ||
| .index-filter{display:flex;gap:8px;flex-wrap:wrap;margin:-8px 0 20px} | ||
| .index-filter input{flex:1 1 10em;min-width:0;min-height:38px;padding:0 12px;font:400 15px var(--f-text);color:var(--ink); | ||
| background:var(--surface);border:1px solid var(--rule);border-radius:8px} | ||
| .index-filter .button{min-height:38px} | ||
| .index-filter input:hover{border-color:var(--ink-2)} | ||
| .index-filter input:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-color:var(--accent)} | ||
| .rwhen{font-variant-numeric:tabular-nums} | ||
| .index-empty{text-align:center;padding:clamp(40px,8vw,88px) 20px} | ||
| .index-mark{display:inline-grid;place-items:center;background:var(--accent-wash);color:var(--accent);width:60px;height:60px;border-radius:16px} | ||
| .index-mark .ic{width:36px;height:36px} | ||
| .index-empty h2{font:700 clamp(22px,4vw,28px)/1.25 var(--f-display);margin:18px 0} | ||
| .index-empty p{color:var(--ink-2)} | ||
| .index-empty code{overflow-wrap:anywhere} | ||
| .index-empty .button{min-height:44px;white-space:normal} | ||
| @media(max-width:720px){ | ||
| .index-columns{display:none} | ||
| .index-list .repo-row{grid-template-columns:minmax(0,1fr);gap:5px;padding:16px} | ||
| .ridentity{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 12px} | ||
| .rdesc{flex-basis:100%} | ||
| .rwhen{text-align:left} | ||
| .rwhen:empty{display:none} | ||
| } | ||
| .commit-row{display:flex;align-items:center;gap:14px;min-height:58px;padding:10px 16px} | ||
| .commit-row .cmain{flex:1;min-width:0} | ||
| @@ -135,7 +171,7 @@ a.entry:hover .name{color:var(--accent)} | ||
| .tag-row .tname{font:700 19px/1.25 var(--f-display);letter-spacing:-.01em;color:var(--ink);overflow-wrap:anywhere} | ||
| .tag-row .tnote,.tag-row .tmeta{grid-column:1;font-size:14px;color:var(--ink-2);overflow-wrap:anywhere} | ||
| .tag-row .tmeta{font-size:13px;display:flex;align-items:center;gap:6px 12px;flex-wrap:wrap} | ||
| .tag-row .tacts{grid-row:1 / span 3;grid-column:2;display:flex;gap:8px} | ||
| .tag-row .tacts{grid-row:1 / span 3;grid-column:2;display:flex;flex-wrap:wrap;justify-content:flex-end;gap:8px} | ||
| /* Buttons */ | ||
| .button{display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 12px;font:500 14px var(--f-text); | ||
| @@ -148,10 +184,19 @@ a.entry:hover .name{color:var(--accent)} | ||
| .segmented a[aria-current]{color:var(--accent);background:var(--accent-wash)} | ||
| /* Code */ | ||
| .code-view{display:grid;grid-template-columns:auto minmax(0,1fr);font:13.5px/1.6 var(--f-mono);tab-size:4} | ||
| .code-view{display:grid;grid-template-columns:auto minmax(0,1fr);font:13.5px/1.6 var(--f-mono);tab-size:4; | ||
| position:relative;isolation:isolate} | ||
| .code-view pre{margin:0;padding:12px 0;font:inherit} | ||
| .code-view .gutter{padding:12px 14px 12px 18px;text-align:right;color:var(--ink-2);opacity:.7;user-select:none; | ||
| .code-view .gutter{padding:12px 14px 12px 18px;text-align:right;color:var(--ink-2);user-select:none; | ||
| border-right:1px solid var(--rule-2);background:var(--sunk)} | ||
| .code-view .gutter a{color:inherit} | ||
| .code-view .gutter a:hover{color:var(--accent);text-decoration:none} | ||
| /* A linked line (#L12) or range (lines=12-20) is banded across the code. The band sits in the | ||
| line's own place in the gutter's flow and stretches to the whole view, under the text. */ | ||
| .code-view .gutter a:target,.code-view .gutter a.sel{color:var(--ink);font-weight:600} | ||
| .code-view .gutter a:target::after,.code-view .gutter a.sel::after{content:"";position:absolute;left:0;right:0; | ||
| height:1.6em;margin-top:0;background:var(--target);z-index:-1;pointer-events:none} | ||
| .code-view .gutter a:target{scroll-margin-top:30vh} | ||
| .code-view .code{padding-left:18px;padding-right:24px;overflow-x:auto;white-space:pre} | ||
| .note{padding:28px 20px;text-align:center;color:var(--ink-2)} | ||
| @@ -228,6 +273,15 @@ a.entry:hover .name{color:var(--accent)} | ||
| font-weight:600;cursor:pointer} | ||
| .button.primary:hover{filter:brightness(1.08)} | ||
| button.button{cursor:pointer} | ||
| /* Comparing revisions */ | ||
| .compare-form{flex-direction:row;flex-wrap:wrap;align-items:flex-end;padding:16px 20px} | ||
| .compare-form label{flex:1 1 14em} | ||
| .compare-form input{font:400 15px var(--f-mono)} | ||
| .compare-summary{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:0 0 16px} | ||
| .compare-summary p{margin:0;max-width:72ch} | ||
| .locator-bar{display:flex;align-items:flex-start;justify-content:space-between;gap:0 12px;flex-wrap:wrap} | ||
| .actions{display:flex;gap:8px;margin:0 0 12px} | ||
| .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)} | ||
| @@ -244,25 +298,28 @@ button.button{cursor:pointer} | ||
| .bar{padding:0 16px} | ||
| main{padding:20px 16px 56px} | ||
| .reponame{font-size:27px} | ||
| .clone{flex-basis:100%} | ||
| .clones{flex-basis:100%} | ||
| .markdown{padding:4px 18px 18px} | ||
| .cmsg{padding:18px}.facts{padding:14px 18px;gap:12px 24px} | ||
| .repo-row,.tag-row{grid-template-columns:minmax(0,1fr)} | ||
| .rwhen,.tag-row .tacts{grid-row:auto;grid-column:1} | ||
| .tag-row{grid-template-columns:minmax(0,1fr)} | ||
| .tag-row .tacts{grid-row:auto;grid-column:1;justify-content:flex-start} | ||
| .panel-head .who{display:none} | ||
| } | ||
| @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-list{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr) max-content;column-gap:12px} | ||
| .tree-list>li{grid-column:1/-1} | ||
| .tree-row{display:grid;grid-template-columns:subgrid;align-items:center} | ||
| .tree-row time{margin-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-list{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} | ||
| } | ||
crates/gitv-web/src/auth.rsRenamed
+170−78
| @@ -4,7 +4,7 @@ | ||
| //! The account lives in one small file (see [`auth_path`]), readable only by its owner: | ||
| //! | ||
| //! ```text | ||
| //! user=Um9i | ||
| //! user=admin | ||
| //! password=$argon2id$v=19$m=19456,t=2,p=1$... | ||
| //! totp=JBSWY3DPEHPK3PXP... | ||
| //! ``` | ||
| @@ -12,8 +12,6 @@ | ||
| //! [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; | ||
| @@ -25,8 +23,8 @@ 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"; | ||
| /// The account name a first `gitv-web setup` uses unless told otherwise. | ||
| pub const DEFAULT_USER: &str = "admin"; | ||
| /// How authenticator apps label the account. | ||
| pub const ISSUER: &str = "GITv"; | ||
| /// Shortest password accepted, in characters. | ||
| @@ -71,6 +69,11 @@ pub enum AuthError { | ||
| Ownership { path: PathBuf, source: nix::errno::Errno }, | ||
| } | ||
| /// How long a browser that signed in stays trusted, in seconds: 90 days. A trusted browser | ||
| /// isn't held back by the cap on failed sign-ins from every client together, so an attack | ||
| /// spread over many addresses can't lock the owner out (see the `throttle` module). | ||
| pub const DEVICE_LIFETIME: u64 = 90 * 24 * 60 * 60; | ||
| /// Longest account name accepted, in characters. | ||
| pub const MAX_USER: usize = 64; | ||
| @@ -116,13 +119,6 @@ enum Publish { | ||
| 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. | ||
| @@ -136,16 +132,35 @@ pub struct WriteLock { | ||
| /// # 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)?; | ||
| use nix::fcntl::{OFlag, openat}; | ||
| use nix::sys::stat::Mode; | ||
| use std::os::unix::fs::MetadataExt; | ||
| let lock_path = sibling(path, "lock"); | ||
| let write_error = |source| AuthError::Write { path: lock_path.clone(), source }; | ||
| let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); | ||
| let directory = gitv_core::open_dir(parent).map_err(write_error)?; | ||
| let name = lock_path.file_name().expect("sibling has a file name"); | ||
| let flags = OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC | OFlag::O_NONBLOCK | OFlag::O_WRONLY; | ||
| let private = Mode::S_IRUSR | Mode::S_IWUSR; | ||
| let (fd, created) = match openat(&directory, name, flags | OFlag::O_CREAT | OFlag::O_EXCL, private) { | ||
| Ok(fd) => (fd, true), | ||
| Err(nix::errno::Errno::EEXIST) => { | ||
| (openat(&directory, name, flags, Mode::empty()).map_err(|e| write_error(e.into()))?, false) | ||
| } | ||
| Err(error) => return Err(write_error(error.into())), | ||
| }; | ||
| let file = fs::File::from(fd); | ||
| let meta = file.metadata().map_err(write_error)?; | ||
| let expected = | ||
| if created { nix::unistd::geteuid() } else { owner.map_or_else(nix::unistd::geteuid, |(service, _)| service) }; | ||
| if !meta.is_file() || meta.nlink() != 1 || meta.mode() & 0o077 != 0 || meta.uid() != expected.as_raw() { | ||
| return Err(write_error(std::io::Error::other("unsafe account lock file"))); | ||
| } | ||
| // Only change ownership of an inode this open created exclusively. | ||
| if created { | ||
| 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 }) | ||
| @@ -186,14 +201,21 @@ pub fn change_password( | ||
| /// 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)?; | ||
| if Credentials::load(path)?.fingerprint() != credentials.fingerprint() { | ||
| return Ok(false); | ||
| } | ||
| 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), | ||
| Ok(text) => { | ||
| let malformed = || AuthError::Malformed { path: record.clone(), reason: "invalid replay record" }; | ||
| let (id, step) = text.trim_end_matches('\n').split_once(' ').ok_or_else(malformed)?; | ||
| if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { | ||
| return Err(malformed()); | ||
| } | ||
| let step = step.parse::<u64>().map_err(|_| malformed())?; | ||
| if id == secret_id { step } else { 0 } | ||
| } | ||
| Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, | ||
| Err(source) => return Err(AuthError::Read { path: record, source }), | ||
| }; | ||
| @@ -217,32 +239,13 @@ fn write_replacing(path: &Path, contents: &[u8], owner: Owner) -> Result<(), Aut | ||
| /// 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 | ||
| let replace = matches!(mode, Publish::Replace); | ||
| gitv_core::publish_file(path, contents, 0o600, replace, |file| hand_over(file, path, owner)).map_err(|e| match e { | ||
| // One atomic step that fails if the name exists, so two first setups can't both win. | ||
| gitv_core::PublishError::Exists => AuthError::AlreadySetUp(path.to_path_buf()), | ||
| gitv_core::PublishError::Io(source) => AuthError::Write { path: path.to_path_buf(), source }, | ||
| gitv_core::PublishError::Prepare(error) => error, | ||
| }) | ||
| } | ||
| /// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`. | ||
| @@ -458,6 +461,35 @@ impl Credentials { | ||
| }) | ||
| } | ||
| /// A token marking a browser that has signed in, good for [`DEVICE_LIFETIME`] from | ||
| /// `unix_seconds`: the expiry, then an HMAC of it under a key derived from the authenticator | ||
| /// secret. Nothing is stored, so it outlives restarts; a new secret (`gitv-web setup | ||
| /// --force`) voids every one. | ||
| pub fn device_token(&self, unix_seconds: u64) -> String { | ||
| let expires = unix_seconds.saturating_add(DEVICE_LIFETIME).to_be_bytes(); | ||
| let mut token = expires.to_vec(); | ||
| token.extend_from_slice(&self.device_mac(&expires)); | ||
| data_encoding::BASE64URL_NOPAD.encode(&token) | ||
| } | ||
| /// Whether `token` is one [`Credentials::device_token`] made for this account and it hasn't | ||
| /// expired at `unix_seconds`. Compared in constant time. | ||
| pub fn trusts_device(&self, token: &str, unix_seconds: u64) -> bool { | ||
| let Ok(token) = data_encoding::BASE64URL_NOPAD.decode(token.as_bytes()) else { return false }; | ||
| let Some((expires, tag)) = token.split_first_chunk::<8>() else { return false }; | ||
| u64::from_be_bytes(*expires) > unix_seconds && bool::from(self.device_mac(expires).as_slice().ct_eq(tag)) | ||
| } | ||
| fn device_mac(&self, expires: &[u8; 8]) -> [u8; 32] { | ||
| // A key of its own, derived from the secret, so device tokens and codes never share one. | ||
| let mut derive = Hmac::<Sha256>::new_from_slice(&self.totp_secret).expect("HMAC takes any key length"); | ||
| derive.update(b"gitv-web trusted device v1"); | ||
| let key = derive.finalize().into_bytes(); | ||
| let mut mac = Hmac::<Sha256>::new_from_slice(&key).expect("HMAC takes any key length"); | ||
| mac.update(expires); | ||
| mac.finalize().into_bytes().into() | ||
| } | ||
| /// 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] { | ||
| @@ -486,12 +518,20 @@ fn url_component(value: &str) -> String { | ||
| mod tests { | ||
| use super::*; | ||
| /// A fresh, empty directory for one test. | ||
| 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 | ||
| } | ||
| /// 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(), | ||
| user: "Um9i".into(), | ||
| password_hash: hash_password("correct horse battery").unwrap(), | ||
| totp_secret: RFC_SECRET.to_vec(), | ||
| } | ||
| @@ -623,13 +663,6 @@ mod tests { | ||
| 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"); | ||
| @@ -678,13 +711,6 @@ mod tests { | ||
| 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"); | ||
| @@ -773,21 +799,45 @@ mod tests { | ||
| 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 lock_requires_a_private_regular_file_with_one_link() { | ||
| use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; | ||
| let dir = scratch("lock-links"); | ||
| let path = dir.join("login"); | ||
| let sentinel = dir.join("sentinel"); | ||
| fs::write(&sentinel, b"untouched").unwrap(); | ||
| fs::set_permissions(&sentinel, fs::Permissions::from_mode(0o600)).unwrap(); | ||
| let before = fs::metadata(&sentinel).unwrap().uid(); | ||
| let owner = nix::unistd::geteuid() | ||
| .is_root() | ||
| .then(|| (nix::unistd::Uid::from_raw(65534), nix::unistd::Gid::from_raw(65534))); | ||
| let lock = sibling(&path, "lock"); | ||
| symlink(&sentinel, &lock).unwrap(); | ||
| assert!(lock_for_writing(&path, owner).is_err()); | ||
| fs::remove_file(&lock).unwrap(); | ||
| fs::hard_link(&sentinel, &lock).unwrap(); | ||
| assert!(lock_for_writing(&path, owner).is_err()); | ||
| assert_eq!(fs::metadata(&sentinel).unwrap().uid(), before); | ||
| assert_eq!(fs::read(&sentinel).unwrap(), b"untouched"); | ||
| fs::remove_file(&lock).unwrap(); | ||
| drop(lock_for_writing(&path, owner).unwrap()); | ||
| if let Some((uid, gid)) = owner { | ||
| let handed_over = fs::metadata(&lock).unwrap(); | ||
| assert_eq!((handed_over.uid(), handed_over.gid()), (uid.as_raw(), gid.as_raw())); | ||
| drop(lock_for_writing(&path, owner).unwrap()); | ||
| } | ||
| fs::remove_dir_all(dir).unwrap(); | ||
| } | ||
| #[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()); | ||
| let original = account(); | ||
| original.save(&path, None).unwrap(); | ||
| assert!(consume_code(&path, &original, "287082", 59).unwrap()); | ||
| // Nothing in memory carries over: the record on disk refuses it. | ||
| assert!(!consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| assert!(!consume_code(&path, &original, "287082", 59).unwrap()); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| @@ -795,16 +845,58 @@ mod tests { | ||
| 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 original = account(); | ||
| original.save(&path, None).unwrap(); | ||
| assert!(consume_code(&path, &original, "287082", 59).unwrap()); | ||
| let mut replaced = account(); | ||
| replaced.totp_secret = b"another secret of twenty".to_vec(); | ||
| replaced.save(&path, None).unwrap(); | ||
| 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"); | ||
| assert!(!consume_code(&path, &original, "287082", 59).unwrap()); | ||
| assert!(!consume_code(&path, &replaced, &code, 59).unwrap()); | ||
| fs::write(sibling(&path, "used"), "corrupt").unwrap(); | ||
| assert!(consume_code(&path, &replaced, &code, 59).is_err()); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
| mod device_tokens { | ||
| use super::*; | ||
| #[test] | ||
| fn are_trusted_until_they_expire() { | ||
| let token = account().device_token(1_000); | ||
| assert!(account().trusts_device(&token, 1_000)); | ||
| assert!(account().trusts_device(&token, 1_000 + DEVICE_LIFETIME - 1)); | ||
| assert!(!account().trusts_device(&token, 1_000 + DEVICE_LIFETIME)); | ||
| } | ||
| #[test] | ||
| fn are_refused_when_forged_altered_or_from_another_secret() { | ||
| let token = account().device_token(1_000); | ||
| let mut bytes = data_encoding::BASE64URL_NOPAD.decode(token.as_bytes()).unwrap(); | ||
| bytes[0] ^= 1; // A later expiry, which the tag no longer matches. | ||
| let altered = data_encoding::BASE64URL_NOPAD.encode(&bytes); | ||
| let mut other = account(); | ||
| other.totp_secret = b"another secret of twenty".to_vec(); | ||
| for forged in ["", "x", &altered, &other.device_token(1_000), &token[..token.len() - 2]] { | ||
| assert!(!account().trusts_device(forged, 1_000), "{forged:?}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn survive_a_password_change() { | ||
| let mut credentials = account(); | ||
| let token = credentials.device_token(1_000); | ||
| credentials.set_password("a whole new password").unwrap(); | ||
| assert!( | ||
| credentials.trusts_device(&token, 1_000), | ||
| "devices are tied to the authenticator, not the password" | ||
| ); | ||
| } | ||
| } | ||
| mod otpauth_uri { | ||
| use super::*; | ||
+231−0
| @@ -0,0 +1,231 @@ | ||
| //! Rendered HTML and git answers kept in memory, keyed by immutable object ids. | ||
| use std::collections::{BTreeMap, HashMap}; | ||
| use std::sync::{Arc, Condvar, LazyLock, Mutex}; | ||
| /// Rendered HTML and git answers keyed by immutable object ids, so repeat views skip the | ||
| /// expensive work. Keys for anything that contains links include the repository, since the | ||
| /// same content in two repositories links differently. When full, the entries used least | ||
| /// recently make room, so pages people keep viewing stay cached. | ||
| pub(crate) struct Cache { | ||
| budget: usize, | ||
| /// Each key's value and when it was last used. | ||
| entries: HashMap<String, (Arc<str>, u64)>, | ||
| /// Keys by when they were last used, oldest first. | ||
| by_use: BTreeMap<u64, String>, | ||
| clock: u64, | ||
| bytes: usize, | ||
| } | ||
| pub(crate) static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(|| Mutex::new(Cache::new(CACHE_BUDGET))); | ||
| pub(crate) const CACHE_BUDGET: usize = 32 << 20; | ||
| impl Cache { | ||
| pub(crate) fn new(budget: usize) -> Cache { | ||
| Cache { budget, entries: HashMap::new(), by_use: BTreeMap::new(), clock: 0, bytes: 0 } | ||
| } | ||
| fn tick(&mut self) -> u64 { | ||
| self.clock += 1; | ||
| self.clock | ||
| } | ||
| /// The value for `key`, which now counts as just used. | ||
| pub(crate) fn get(&mut self, key: &str) -> Option<Arc<str>> { | ||
| let now = self.tick(); | ||
| let (value, used) = self.entries.get_mut(key)?; | ||
| let key = self.by_use.remove(used).unwrap_or_else(|| key.to_string()); | ||
| *used = now; | ||
| let value = Arc::clone(value); | ||
| self.by_use.insert(now, key); | ||
| Some(value) | ||
| } | ||
| /// Keep `value` under `key`, making room by dropping the least recently used entries. | ||
| /// Anything over a quarter of the budget would push out much of everything else, so it | ||
| /// isn't kept. | ||
| pub(crate) fn insert(&mut self, key: String, value: Arc<str>) { | ||
| let size = key.len() + value.len(); | ||
| if size > self.budget / 4 { | ||
| return; | ||
| } | ||
| // Two requests can render the same key at once; the second replaces the first. | ||
| self.remove(&key); | ||
| while self.bytes + size > self.budget { | ||
| let Some((_, oldest)) = self.by_use.pop_first() else { break }; | ||
| if let Some((old, _)) = self.entries.remove(&oldest) { | ||
| self.bytes -= oldest.len() + old.len(); | ||
| } | ||
| } | ||
| let now = self.tick(); | ||
| self.by_use.insert(now, key.clone()); | ||
| self.entries.insert(key, (value, now)); | ||
| self.bytes += size; | ||
| } | ||
| fn remove(&mut self, key: &str) { | ||
| if let Some((old, used)) = self.entries.remove(key) { | ||
| self.by_use.remove(&used); | ||
| self.bytes -= key.len() + old.len(); | ||
| } | ||
| } | ||
| } | ||
| /// The cached value for `key`, or `make`'s. A failure (`None`) is never cached, so a git | ||
| /// command that timed out is retried next time instead of leaving a blank forever. | ||
| /// | ||
| /// Only one request makes a missing value at a time: others asking for the same key meanwhile | ||
| /// wait for its answer (failure included) instead of running the same git work alongside it. | ||
| /// They wait at most [`gitv_core::GIT_TIMEOUT`], the longest the first can take. | ||
| pub(crate) fn cached(key: String, make: impl FnOnce() -> Option<String>) -> Option<Arc<str>> { | ||
| if let Some(hit) = lock(&CACHE).get(&key) { | ||
| return Some(hit); | ||
| } | ||
| let flight = { | ||
| let mut pending = lock(&PENDING); | ||
| match pending.get(&key) { | ||
| Some(flight) => Err(Arc::clone(flight)), | ||
| None => { | ||
| let flight = Arc::new(Flight::default()); | ||
| pending.insert(key.clone(), Arc::clone(&flight)); | ||
| Ok(flight) | ||
| } | ||
| } | ||
| }; | ||
| let mut landing = match flight { | ||
| Err(flight) => return flight.wait(), | ||
| Ok(flight) => Landing { key, flight, value: None }, | ||
| }; | ||
| // Another request may have made it between the first look and joining the pending list. | ||
| // (Bound first, so the cache's lock is released before any git work starts.) | ||
| let made_meanwhile = lock(&CACHE).get(&landing.key); | ||
| landing.value = made_meanwhile.or_else(|| { | ||
| let value: Arc<str> = make()?.into(); | ||
| lock(&CACHE).insert(landing.key.clone(), Arc::clone(&value)); | ||
| Some(value) | ||
| }); | ||
| landing.value.clone() | ||
| } | ||
| /// Keys being made now, and how their waiters hear the answer. | ||
| static PENDING: LazyLock<Mutex<HashMap<String, Arc<Flight>>>> = LazyLock::new(Mutex::default); | ||
| /// One value being made: `None` until it is done, then its answer. | ||
| #[derive(Default)] | ||
| struct Flight { | ||
| answer: Mutex<Option<Option<Arc<str>>>>, | ||
| done: Condvar, | ||
| } | ||
| impl Flight { | ||
| fn wait(&self) -> Option<Arc<str>> { | ||
| let answer = lock(&self.answer); | ||
| let (answer, _) = self | ||
| .done | ||
| .wait_timeout_while(answer, gitv_core::GIT_TIMEOUT, |a| a.is_none()) | ||
| .unwrap_or_else(|e| e.into_inner()); | ||
| answer.clone().flatten() | ||
| } | ||
| } | ||
| /// The request making a value. Dropping it, whether the value was made or `make` panicked, | ||
| /// answers every waiter and clears the key from [`PENDING`], so nobody waits forever. | ||
| struct Landing { | ||
| key: String, | ||
| flight: Arc<Flight>, | ||
| value: Option<Arc<str>>, | ||
| } | ||
| impl Drop for Landing { | ||
| fn drop(&mut self) { | ||
| lock(&PENDING).remove(&self.key); | ||
| *lock(&self.flight.answer) = Some(self.value.take()); | ||
| self.flight.done.notify_all(); | ||
| } | ||
| } | ||
| /// A lock that a panic elsewhere doesn't disable: the cache holds no invariant a panic | ||
| /// could break half way, so carrying on is safe. | ||
| fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { | ||
| mutex.lock().unwrap_or_else(|e| e.into_inner()) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| fn value(text: &str) -> Arc<str> { | ||
| text.into() | ||
| } | ||
| #[test] | ||
| fn requests_for_one_missing_value_make_it_once() { | ||
| use std::sync::atomic::{AtomicUsize, Ordering}; | ||
| static MADE: AtomicUsize = AtomicUsize::new(0); | ||
| let key = format!("test-single-flight:{}", std::process::id()); | ||
| let threads: Vec<_> = (0..8) | ||
| .map(|_| { | ||
| let key = key.clone(); | ||
| std::thread::spawn(move || { | ||
| cached(key, || { | ||
| MADE.fetch_add(1, Ordering::SeqCst); | ||
| std::thread::sleep(std::time::Duration::from_millis(200)); | ||
| Some("made".into()) | ||
| }) | ||
| }) | ||
| }) | ||
| .collect(); | ||
| for thread in threads { | ||
| assert_eq!(thread.join().unwrap().as_deref(), Some("made")); | ||
| } | ||
| assert_eq!(MADE.load(Ordering::SeqCst), 1, "the value was made more than once"); | ||
| } | ||
| #[test] | ||
| fn a_maker_that_panics_leaves_nobody_waiting() { | ||
| let key = format!("test-panic:{}", std::process::id()); | ||
| let maker = { | ||
| let key = key.clone(); | ||
| std::thread::spawn(move || { | ||
| cached(key, || { | ||
| std::thread::sleep(std::time::Duration::from_millis(200)); | ||
| panic!("render failed") | ||
| }) | ||
| }) | ||
| }; | ||
| std::thread::sleep(std::time::Duration::from_millis(50)); | ||
| let started = std::time::Instant::now(); | ||
| assert_eq!(cached(key.clone(), || Some("unused".into())), None, "the waiter hears the failure"); | ||
| assert!(started.elapsed() < std::time::Duration::from_secs(5), "the waiter wasn't released"); | ||
| assert!(maker.join().is_err()); | ||
| assert_eq!(cached(key, || Some("retried".into())).as_deref(), Some("retried"), "a failure isn't cached"); | ||
| } | ||
| #[test] | ||
| fn the_least_recently_used_entries_make_room() { | ||
| // Room for four entries of 2 bytes of key and 8 of value. | ||
| let mut cache = Cache::new(40); | ||
| for key in ["k1", "k2", "k3", "k4"] { | ||
| cache.insert(key.into(), value("12345678")); | ||
| } | ||
| assert!(cache.get("k1").is_some(), "k1 is used again, so k2 is now the oldest"); | ||
| cache.insert("k5".into(), value("12345678")); | ||
| assert!(cache.get("k2").is_none(), "the least recently used went"); | ||
| for key in ["k1", "k3", "k4", "k5"] { | ||
| assert!(cache.get(key).is_some(), "{key} stays"); | ||
| } | ||
| assert_eq!(cache.bytes, 40); | ||
| } | ||
| #[test] | ||
| fn replacing_a_key_counts_it_once_and_big_values_are_not_kept() { | ||
| let mut cache = Cache::new(40); | ||
| cache.insert("k1".into(), value("1234")); | ||
| cache.insert("k1".into(), value("12345678")); | ||
| assert_eq!(cache.bytes, 10); | ||
| assert_eq!(cache.entries.len(), cache.by_use.len()); | ||
| cache.insert("big".into(), value("12345678901")); | ||
| assert!(cache.get("big").is_none(), "over a quarter of the budget"); | ||
| assert_eq!(&*cache.get("k1").unwrap(), "12345678"); | ||
| } | ||
| } | ||
+133−0
| @@ -0,0 +1,133 @@ | ||
| //! How many expensive requests (page renders, raw downloads, clones) may run at once, and who | ||
| //! may use the slots, so anonymous traffic can never crowd out the signed-in owner. | ||
| //! | ||
| //! A [`Pool`] has open slots, which anyone may use, and reserved slots, which only signed-in | ||
| //! sessions may use (they take an open slot when the reserved ones are busy). An anonymous | ||
| //! client may also hold only a few slots at once, so one address can't take them all; clients | ||
| //! are identified as in sign-in throttling (an IPv4 address or IPv6 /64). | ||
| use std::collections::HashMap; | ||
| use std::sync::{Arc, Mutex}; | ||
| use tokio::sync::{OwnedSemaphorePermit, Semaphore}; | ||
| use super::throttle::Client; | ||
| /// How many slots each anonymous client holds, shared between a pool and its slots. | ||
| type Held = Arc<Mutex<HashMap<Client, usize>>>; | ||
| /// Who is asking for a slot. | ||
| #[derive(Clone, Copy, Debug)] | ||
| pub struct Visitor { | ||
| pub client: Client, | ||
| pub signed_in: bool, | ||
| } | ||
| pub struct Pool { | ||
| open: Arc<Semaphore>, | ||
| reserved: Arc<Semaphore>, | ||
| per_client: usize, | ||
| held: Held, | ||
| } | ||
| /// A slot in a [`Pool`], given back when dropped. | ||
| pub struct Slot { | ||
| _permit: OwnedSemaphorePermit, | ||
| /// The anonymous client this slot counts against. | ||
| counted: Option<(Held, Client)>, | ||
| } | ||
| impl Drop for Slot { | ||
| fn drop(&mut self) { | ||
| if let Some((held, client)) = &self.counted { | ||
| let mut held = held.lock().unwrap_or_else(|e| e.into_inner()); | ||
| if let Some(count) = held.get_mut(client) { | ||
| *count -= 1; | ||
| if *count == 0 { | ||
| held.remove(client); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| impl Pool { | ||
| pub fn new(open: usize, reserved: usize, per_client: usize) -> Pool { | ||
| Pool { | ||
| open: Arc::new(Semaphore::new(open)), | ||
| reserved: Arc::new(Semaphore::new(reserved)), | ||
| per_client, | ||
| held: Arc::default(), | ||
| } | ||
| } | ||
| /// A slot for `visitor` now, or `None` if none is free to them: the caller answers busy. | ||
| pub fn try_acquire(&self, visitor: Visitor) -> Option<Slot> { | ||
| if visitor.signed_in { | ||
| let permit = | ||
| Arc::clone(&self.reserved).try_acquire_owned().or_else(|_| Arc::clone(&self.open).try_acquire_owned()); | ||
| return permit.ok().map(|permit| Slot { _permit: permit, counted: None }); | ||
| } | ||
| let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner()); | ||
| let count = held.entry(visitor.client).or_insert(0); | ||
| let permit = (*count < self.per_client).then(|| Arc::clone(&self.open).try_acquire_owned().ok()).flatten(); | ||
| match permit { | ||
| Some(permit) => { | ||
| *count += 1; | ||
| Some(Slot { _permit: permit, counted: Some((Arc::clone(&self.held), visitor.client)) }) | ||
| } | ||
| None => { | ||
| if *count == 0 { | ||
| held.remove(&visitor.client); | ||
| } | ||
| None | ||
| } | ||
| } | ||
| } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| fn anonymous(address: &str) -> Visitor { | ||
| Visitor { client: Client::new(address.parse().unwrap()), signed_in: false } | ||
| } | ||
| fn owner() -> Visitor { | ||
| Visitor { signed_in: true, ..anonymous("198.51.100.1") } | ||
| } | ||
| #[test] | ||
| fn anonymous_traffic_cannot_take_the_reserved_slots() { | ||
| let pool = Pool::new(4, 2, 1); | ||
| let taken: Vec<Slot> = | ||
| (0..4).map(|i| pool.try_acquire(anonymous(&format!("203.0.113.{i}"))).unwrap()).collect(); | ||
| assert!(pool.try_acquire(anonymous("203.0.113.99")).is_none(), "the open slots are full"); | ||
| let first = pool.try_acquire(owner()).expect("the owner gets a reserved slot"); | ||
| let second = pool.try_acquire(owner()).expect("and another"); | ||
| assert!(pool.try_acquire(owner()).is_none(), "all slots are busy"); | ||
| drop(taken); | ||
| assert!(pool.try_acquire(owner()).is_some(), "the owner may also use open slots"); | ||
| drop((first, second)); | ||
| } | ||
| #[test] | ||
| fn one_anonymous_client_holds_only_its_share() { | ||
| let pool = Pool::new(8, 0, 2); | ||
| let a = anonymous("203.0.113.7"); | ||
| let held = [pool.try_acquire(a).unwrap(), pool.try_acquire(a).unwrap()]; | ||
| assert!(pool.try_acquire(a).is_none(), "a third slot for the same client"); | ||
| assert!(pool.try_acquire(anonymous("2001:db8::1")).is_some(), "another client still gets one"); | ||
| drop(held); | ||
| assert!(pool.try_acquire(a).is_some(), "slots come back when dropped"); | ||
| assert!(pool.held.lock().unwrap().is_empty(), "no client is remembered once it holds nothing"); | ||
| } | ||
| #[test] | ||
| fn signed_in_sessions_have_no_per_client_cap() { | ||
| let pool = Pool::new(4, 0, 1); | ||
| let held: Vec<Slot> = (0..4).map(|_| pool.try_acquire(owner()).unwrap()).collect(); | ||
| assert_eq!(held.len(), 4); | ||
| } | ||
| } | ||
+111−0
| @@ -0,0 +1,111 @@ | ||
| //! Bounded, backpressured output from a pinned Git process. | ||
| use axum::body::{Body, Bytes}; | ||
| use futures_util::{StreamExt, stream}; | ||
| use std::{io, process::Stdio, time::Duration}; | ||
| #[cfg(test)] | ||
| use tokio::sync::Semaphore; | ||
| use tokio::{ | ||
| io::{AsyncReadExt, AsyncWriteExt}, | ||
| process::Command, | ||
| sync::{mpsc, oneshot}, | ||
| }; | ||
| pub struct Output { | ||
| child: tokio::process::Child, | ||
| stdout: tokio::process::ChildStdout, | ||
| } | ||
| impl Output { | ||
| pub fn start(mut command: Command) -> io::Result<Self> { | ||
| let mut child = command.kill_on_drop(true).stdout(Stdio::piped()).spawn()?; | ||
| let stdout = child.stdout.take().ok_or_else(|| io::Error::other("missing Git stdout"))?; | ||
| Ok(Self { child, stdout }) | ||
| } | ||
| pub async fn prefix(&mut self, len: usize) -> io::Result<Bytes> { | ||
| let mut bytes = vec![0; len]; | ||
| tokio::time::timeout(gitv_core::GIT_TIMEOUT, self.stdout.read_exact(&mut bytes)).await??; | ||
| Ok(bytes.into()) | ||
| } | ||
| pub fn body(mut self, prefix: Bytes, input: Option<Bytes>, permit: impl Send + 'static, timeout: Duration) -> Body { | ||
| let (tx, rx) = mpsc::channel::<Bytes>(2); | ||
| let (finished, status) = oneshot::channel(); | ||
| let (body_guard, dropped) = oneshot::channel::<()>(); | ||
| tokio::spawn(async move { | ||
| let _permit = permit; | ||
| let deadline = tokio::time::Instant::now() + timeout; | ||
| let mut stdin = self.child.stdin.take(); | ||
| let write = async move { | ||
| if let Some(input) = input { | ||
| stdin.as_mut().ok_or_else(|| io::Error::other("missing Git stdin"))?.write_all(&input).await?; | ||
| } | ||
| drop(stdin); | ||
| Ok::<_, io::Error>(()) | ||
| }; | ||
| let read = async { | ||
| let mut buf = vec![0; 65536]; | ||
| loop { | ||
| let count = self.stdout.read(&mut buf).await?; | ||
| if count == 0 { | ||
| break; | ||
| } | ||
| tx.send(Bytes::copy_from_slice(&buf[..count])).await.map_err(|_| io::ErrorKind::BrokenPipe)?; | ||
| } | ||
| if !self.child.wait().await?.success() { | ||
| return Err(io::Error::other("Git transfer failed")); | ||
| } | ||
| Ok(()) | ||
| }; | ||
| let outcome = tokio::select! { | ||
| _ = tx.closed() => return, | ||
| result = tokio::time::timeout_at(deadline, async { tokio::try_join!(write, read).map(|_| ()) }) => | ||
| result.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())), | ||
| }; | ||
| drop(self); | ||
| drop(tx); | ||
| let _ = finished.send(outcome); | ||
| // Hold the slot through buffered delivery, but never beyond the transfer deadline. | ||
| let _ = tokio::time::timeout_at(deadline, dropped).await; | ||
| }); | ||
| // The worker's terminal status has its own channel (a oneshot), so a full | ||
| // byte queue cannot turn a failed transfer into successful EOF. | ||
| let chunks = stream::unfold(rx, |mut rx| async { Some((rx.recv().await?, rx)) }).map(Ok); | ||
| let end = stream::once(async move { | ||
| let _guard = body_guard; | ||
| status.await.map_err(io::Error::other)??; | ||
| Ok::<_, io::Error>(Bytes::new()) | ||
| }); | ||
| Body::from_stream(stream::iter((!prefix.is_empty()).then_some(Ok(prefix))).chain(chunks).chain(end)) | ||
| } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[tokio::test] | ||
| async fn dropping_a_transfer_body_releases_its_slot() { | ||
| static SLOT: Semaphore = Semaphore::const_new(1); | ||
| let mut command = Command::new("head"); | ||
| command.args(["-c", "1048576", "/dev/zero"]); | ||
| let output = Output::start(command).unwrap(); | ||
| let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_secs(300)); | ||
| drop(body); | ||
| let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap(); | ||
| drop(permit); | ||
| } | ||
| #[tokio::test] | ||
| async fn stalled_body_times_out_and_reports_the_error_after_buffered_bytes() { | ||
| static SLOT: Semaphore = Semaphore::const_new(1); | ||
| let mut command = Command::new("head"); | ||
| command.args(["-c", "1048576", "/dev/zero"]); | ||
| let output = Output::start(command).unwrap(); | ||
| let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_millis(50)); | ||
| assert!(SLOT.try_acquire().is_err()); | ||
| let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap(); | ||
| assert!(axum::body::to_bytes(body, 1 << 20).await.is_err()); | ||
| drop(permit); | ||
| } | ||
| } | ||
+81−0
| @@ -0,0 +1,81 @@ | ||
| //! Small pieces of HTML shared by every page: icons, dates, sizes and the page layout. | ||
| use crate::templates; | ||
| pub(crate) fn icon(name: &str) -> String { | ||
| let path = match name { | ||
| "dir" => r#"<path d="M2 4.5c0-.6.4-1 1-1h3.2l1.4 1.5H13c.6 0 1 .4 1 1v6.5c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1z"/>"#, | ||
| "file" => r#"<path d="M4 1.8h5.3L12.5 5v9.2H4z"/><path d="M9 1.8v3.5h3.5"/>"#, | ||
| "branch" => { | ||
| r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"# | ||
| } | ||
| "tag" => r#"<path d="M2 2.5h5.3l6.2 6.2-4.8 4.8-6.7-6.7z"/><circle cx="5" cy="5.5" r="1"/>"#, | ||
| "book" => { | ||
| r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"# | ||
| } | ||
| "code" => r#"<path d="M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5"/>"#, | ||
| "commits" => r#"<circle cx="8" cy="8" r="2.4"/><path d="M1.5 8h4.1M10.4 8h4.1"/>"#, | ||
| "chevron" => r#"<path d="M4.5 6.5 8 10l3.5-3.5"/>"#, | ||
| "up" => r#"<path d="M8 13V3.5M4 7.5l4-4 4 4"/>"#, | ||
| "module" => r#"<rect x="2.5" y="2.5" width="11" height="11" rx="2"/><path d="M5.5 8h5M8 5.5v5"/>"#, | ||
| _ => "", | ||
| }; | ||
| format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#) | ||
| } | ||
| /// "3 hours ago" for recent times, the calendar date (as git printed it) after a month. | ||
| pub(crate) fn ago(stamp: &str, date: &str) -> String { | ||
| let Ok(then) = stamp.parse::<u64>() else { return date.to_string() }; | ||
| let span = gitv_core::unix_now().saturating_sub(then); | ||
| let unit = |n: u64, word: &str| format!("{n} {word}{} ago", if n == 1 { "" } else { "s" }); | ||
| match span { | ||
| 0..60 => "just now".into(), | ||
| 60..3600 => unit(span / 60, "minute"), | ||
| 3600..86400 => unit(span / 3600, "hour"), | ||
| 86400..2_592_000 => unit(span / 86400, "day"), | ||
| _ => date.to_string(), | ||
| } | ||
| } | ||
| /// A commit subject for display; an empty one would leave an invisible link. | ||
| pub(crate) fn subject_or_placeholder(subject: &str) -> &str { | ||
| if subject.trim().is_empty() { "(no message)" } else { subject } | ||
| } | ||
| pub(crate) fn plural(count: usize, one: &str, many: &str) -> String { | ||
| format!("{count} {}", if count == 1 { one } else { many }) | ||
| } | ||
| pub(crate) fn size(bytes: usize) -> String { | ||
| match bytes { | ||
| 0..1024 => plural(bytes, "byte", "bytes"), | ||
| 1024..1_048_576 => format!("{:.1} KB", bytes as f64 / 1024.0), | ||
| _ => format!("{:.1} MB", bytes as f64 / 1_048_576.0), | ||
| } | ||
| } | ||
| /// The page for a render that failed on the server's side: a bug, not a bad link. | ||
| pub(crate) fn view_failed(signed_in: bool) -> String { | ||
| templates::Notice { | ||
| title: "Something went wrong", | ||
| signed_in, | ||
| heading: "This page couldn’t be shown", | ||
| message: "Something went wrong on the server. Try again; if it keeps happening, the operator can see why in the log.", | ||
| code: None, | ||
| link: Some(("/", "Back to repositories")), | ||
| } | ||
| .to_string() | ||
| } | ||
| /// The page for anything that isn't there, or a malformed link. | ||
| pub(crate) fn view_missing(signed_in: bool) -> String { | ||
| templates::Notice { | ||
| title: "Not found", | ||
| signed_in, | ||
| heading: "Nothing here", | ||
| message: "That repository, branch, file or commit doesn’t exist, or the link is malformed.", | ||
| code: None, | ||
| link: Some(("/", "Back to repositories")), | ||
| } | ||
| .to_string() | ||
| } | ||
+5−0
| @@ -0,0 +1,5 @@ | ||
| //! The parts of gitv-web its tests use directly: sign-in credentials and Markdown and code | ||
| //! rendering. The server itself is the `gitv-web` binary. | ||
| pub mod auth; | ||
| pub mod render; | ||
crates/gitv-web/src/login.rsRenamed
+169−277
| @@ -2,15 +2,16 @@ | ||
| //! | ||
| //! 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 | ||
| //! account's [fingerprint](gitv_web::auth::Credentials::fingerprint), so changing the password, here | ||
| //! or with `gitv-web password`, ends every other session. | ||
| //! | ||
| //! The command-line account commands (`setup`, `password`) are in `setup.rs`. | ||
| 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::os::unix::fs::MetadataExt; | ||
| use std::path::PathBuf; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | ||
| use std::time::{Duration, Instant}; | ||
| use axum::Extension; | ||
| use axum::extract::{Form, FromRequest, RawQuery, Request, State}; | ||
| @@ -18,25 +19,23 @@ 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 gitv_core::{percent_decode, unix_now}; | ||
| use gitv_web::auth::{AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, random_bytes}; | ||
| use serde::Deserialize; | ||
| use sha2::{Digest, Sha256}; | ||
| use subtle::ConstantTimeEq; | ||
| use super::{SECURITY, layout, page, percent_decode}; | ||
| use super::throttle::{Client, Throttle}; | ||
| use super::{SECURITY, html}; | ||
| /// 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"; | ||
| /// Marks a browser that has signed in, so the cap on everyone's failures together never locks | ||
| /// it out (see [`gitv_web::auth::Credentials::device_token`]). Kept across sign-outs. | ||
| const DEVICE_COOKIE: &str = "__Host-gitv-device"; | ||
| /// 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 { | ||
| @@ -44,7 +43,8 @@ pub struct Login { | ||
| 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>, | ||
| /// Failed attempts, by client (see [`Throttle`]). | ||
| throttle: Mutex<Throttle>, | ||
| /// 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>, | ||
| @@ -69,7 +69,7 @@ const CONCURRENT_CHECKS: usize = 2; | ||
| enum Checked { | ||
| Right, | ||
| Wrong, | ||
| /// Sign-in was locked by the time this attempt's turn came. | ||
| /// This client was locked out 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, | ||
| @@ -88,12 +88,12 @@ struct Session { | ||
| 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>, | ||
| /// Who is making a sign-in attempt: their client, and whether their browser has signed in | ||
| /// before (see [`Login::trusted`]). | ||
| #[derive(Clone, Copy)] | ||
| struct Asker { | ||
| client: Client, | ||
| trusted: bool, | ||
| } | ||
| /// What [`require_login`] hands a signed-in request. | ||
| @@ -114,7 +114,7 @@ impl Login { | ||
| path, | ||
| loaded: Mutex::new(None), | ||
| sessions: Mutex::new(HashMap::new()), | ||
| guard: Mutex::new(Guard::default()), | ||
| throttle: Mutex::new(Throttle::default()), | ||
| hashing: Arc::new(tokio::sync::Semaphore::new(CONCURRENT_CHECKS)), | ||
| admission: Arc::new(tokio::sync::Semaphore::new(ADMITTED_ATTEMPTS)), | ||
| #[cfg(test)] | ||
| @@ -166,41 +166,38 @@ impl Login { | ||
| )) | ||
| } | ||
| /// How long sign-in stays locked, if it is. | ||
| fn locked_for(&self) -> Option<Duration> { | ||
| let guard = self.guard.lock().unwrap_or_else(|e| e.into_inner()); | ||
| guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now())) | ||
| fn throttle(&self) -> std::sync::MutexGuard<'_, Throttle> { | ||
| self.throttle.lock().unwrap_or_else(|e| e.into_inner()) | ||
| } | ||
| #[cfg(test)] | ||
| fn record_failure(&self) { | ||
| Self::fail(&mut self.guard.lock().unwrap_or_else(|e| e.into_inner())); | ||
| /// How long `client` must wait to try again, if it must; see [`Throttle::locked_for`]. | ||
| fn locked_for(&self, Asker { client, trusted }: Asker) -> Option<Duration> { | ||
| self.throttle().locked_for(client, Instant::now(), trusted) | ||
| } | ||
| 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); | ||
| } | ||
| /// Whether the request comes from a browser that has signed in to this account before. | ||
| fn trusted(&self, headers: &HeaderMap) -> bool { | ||
| let Some(token) = cookie_value(headers, DEVICE_COOKIE) else { return false }; | ||
| self.credentials().is_ok_and(|c| c.trusts_device(token, unix_now())) | ||
| } | ||
| /// 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 | ||
| /// failures may have locked this client out 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>, | ||
| purpose: &'static str, | ||
| credentials: &Arc<Credentials>, | ||
| asker: Asker, | ||
| 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() { | ||
| if let Some(wait) = self.locked_for(asker) { | ||
| return Checked::Locked(wait); | ||
| } | ||
| #[cfg(test)] | ||
| @@ -210,7 +207,7 @@ impl Login { | ||
| let _permit = permit; | ||
| let user_ok = user.is_none_or(|u| creds.user_matches(&u)); | ||
| let password_ok = creds.verify_password(&password) && user_ok; | ||
| login.settle(&creds, password_ok, &code) | ||
| login.settle(purpose, &creds, asker, password_ok, &code) | ||
| }) | ||
| .await | ||
| .unwrap_or(Checked::Wrong) | ||
| @@ -219,44 +216,64 @@ impl Login { | ||
| /// Record a check's result. The code is checked and used up in one step, under the account | ||
| /// file's lock and recorded on disk, so it works once: across simultaneous requests, | ||
| /// restarts and processes alike. | ||
| fn settle(&self, credentials: &Credentials, password_ok: bool, code: &str) -> Checked { | ||
| let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner()); | ||
| /// | ||
| /// Every judged attempt goes to the log (the journal, under systemd) with the client, and | ||
| /// whether the password or the code was wrong. Visitors only ever hear that something was; | ||
| /// the operator can see a right password with a wrong code, which means the password is known. | ||
| fn settle( | ||
| &self, | ||
| purpose: &'static str, | ||
| credentials: &Credentials, | ||
| Asker { client, trusted }: Asker, | ||
| password_ok: bool, | ||
| code: &str, | ||
| ) -> Checked { | ||
| let code_ok = password_ok | ||
| && match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) { | ||
| && match gitv_web::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; | ||
| } | ||
| }; | ||
| let mut throttle = self.throttle(); | ||
| if code_ok { | ||
| guard.failures = 0; | ||
| guard.locked_until = None; | ||
| throttle.succeed(client); | ||
| eprintln!("gitv-web: {purpose} succeeded from {client}"); | ||
| 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, | ||
| let now = Instant::now(); | ||
| throttle.fail(client, now); | ||
| let wrong = if password_ok { "right password, wrong code" } else { "wrong password" }; | ||
| match throttle.locked_for(client, now, trusted) { | ||
| Some(wait) => { | ||
| eprintln!("gitv-web: {purpose} failed from {client} ({wrong}); locked out for {}s", wait.as_secs()); | ||
| Checked::Locked(wait) | ||
| } | ||
| None => { | ||
| eprintln!("gitv-web: {purpose} failed from {client} ({wrong})"); | ||
| Checked::Wrong | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| /// The SHA-256 of the session token in a request's cookie. | ||
| fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> { | ||
| let token = headers | ||
| /// The value of the cookie called `name`, from any of a request's `Cookie` headers. | ||
| fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { | ||
| 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()) | ||
| .find_map(|pair| pair.trim().strip_prefix(name)?.strip_prefix('=')) | ||
| } | ||
| fn unix_now() -> u64 { | ||
| SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) | ||
| /// The SHA-256 of the session token in a request's cookie. | ||
| fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> { | ||
| let token = cookie_value(headers, COOKIE)?; | ||
| let token = BASE64URL_NOPAD.decode(token.as_bytes()).ok().filter(|t| t.len() == 32)?; | ||
| Some(Sha256::digest(token).into()) | ||
| } | ||
| /// Where to go after signing in: a path on this site, never another site (`//evil.example`). | ||
| @@ -265,17 +282,13 @@ fn safe_next(next: &str) -> &str { | ||
| 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 { | ||
| fn redirect(to: &str, cookies: &[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); | ||
| for cookie in cookies.iter().filter_map(|c| HeaderValue::from_str(c).ok()) { | ||
| response.headers_mut().append(header::SET_COOKIE, cookie); | ||
| } | ||
| response | ||
| } | ||
| @@ -283,11 +296,12 @@ fn redirect(to: &str, cookie: Option<String>) -> Response { | ||
| fn not_set_up() -> Response { | ||
| html( | ||
| StatusCode::SERVICE_UNAVAILABLE, | ||
| layout( | ||
| notice( | ||
| "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, | ||
| "Sign-in isn’t set up", | ||
| "Create the account on the server, then reload this page:", | ||
| Some("gitv-web setup"), | ||
| ), | ||
| ) | ||
| } | ||
| @@ -296,23 +310,39 @@ fn not_set_up() -> Response { | ||
| /// 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) => { | ||
| let credentials = login.credentials(); | ||
| if let Ok(creds) = &credentials | ||
| && let Some(session) = login.session(request.headers(), creds) | ||
| { | ||
| request.extensions_mut().insert(session); | ||
| return next.run(request).await; | ||
| } | ||
| challenge(credentials.err(), request.uri()) | ||
| } | ||
| pub async fn browse(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response { | ||
| let credentials = login.credentials(); | ||
| let signed_in = credentials.as_ref().ok().and_then(|c| login.session(request.headers(), c)).is_some(); | ||
| request.extensions_mut().insert(signed_in); | ||
| let uri = request.uri().clone(); | ||
| let response = next.run(request).await; | ||
| if response.status() == StatusCode::UNAUTHORIZED { challenge(credentials.err(), &uri) } else { response } | ||
| } | ||
| fn challenge(error: Option<AuthError>, uri: &axum::http::Uri) -> Response { | ||
| match error { | ||
| Some(AuthError::NotSetUp(_)) => return not_set_up(), | ||
| Some(error) => { | ||
| eprintln!("gitv-web: {error}"); | ||
| return html( | ||
| StatusCode::SERVICE_UNAVAILABLE, | ||
| layout("Unavailable", "<p class=\"note\">Sign-in is unavailable.</p>", false), | ||
| notice("Unavailable", false, "Unavailable", "Sign-in is unavailable.", None), | ||
| ); | ||
| } | ||
| }; | ||
| if let Some(signed_in) = login.session(request.headers(), &credentials) { | ||
| request.extensions_mut().insert(signed_in); | ||
| return next.run(request).await; | ||
| None => {} | ||
| } | ||
| let wanted = request.uri().path_and_query().map_or("/", |p| p.as_str()); | ||
| redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), None) | ||
| let wanted = uri.path_and_query().map_or("/", |p| p.as_str()); | ||
| redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), &[]) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| @@ -334,14 +364,14 @@ fn sign_in_page(status: StatusCode, next: &str, message: &str) -> Response { | ||
| ) | ||
| } | ||
| fn locked_page(wait: Duration) -> Response { | ||
| /// "Try again in 3 minutes." | ||
| fn try_again(wait: Duration) -> String { | ||
| 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}."), | ||
| ) | ||
| format!("Try again in {minutes} minute{}.", if minutes == 1 { "" } else { "s" }) | ||
| } | ||
| fn locked_page(wait: Duration) -> Response { | ||
| sign_in_page(StatusCode::TOO_MANY_REQUESTS, "/", &format!("Too many failed sign-ins. {}", try_again(wait))) | ||
| } | ||
| pub async fn sign_in_form(State(login): State<Arc<Login>>, headers: HeaderMap, RawQuery(query): RawQuery) -> Response { | ||
| @@ -354,7 +384,7 @@ pub async fn sign_in_form(State(login): State<Arc<Login>>, headers: HeaderMap, R | ||
| if let Ok(credentials) = login.credentials() | ||
| && login.session(&headers, &credentials).is_some() | ||
| { | ||
| return redirect(safe_next(&next), None); | ||
| return redirect(safe_next(&next), &[]); | ||
| } | ||
| sign_in_page(StatusCode::OK, &next, "") | ||
| } | ||
| @@ -364,7 +394,9 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo | ||
| 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() { | ||
| let client = Client::of(request.headers(), request.extensions()); | ||
| let asker = Asker { client, trusted: login.trusted(request.headers()) }; | ||
| if let Some(wait) = login.locked_for(asker) { | ||
| return locked_page(wait); | ||
| } | ||
| // Too large (over FORM_LIMIT) or malformed: refused with the rejection's own status. | ||
| @@ -382,7 +414,7 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo | ||
| return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now."); | ||
| } | ||
| }; | ||
| match login.check(&credentials, Some(form.user), form.password, &form.code).await { | ||
| match login.check("sign-in", &credentials, asker, Some(form.user), form.password, &form.code).await { | ||
| Checked::Right => {} | ||
| Checked::Locked(wait) => return locked_page(wait), | ||
| Checked::Unavailable => { | ||
| @@ -394,7 +426,14 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo | ||
| } | ||
| } | ||
| match login.start_session(credentials.fingerprint()) { | ||
| Ok(cookie) => redirect(safe_next(&form.next), Some(cookie)), | ||
| Ok(cookie) => { | ||
| let device = format!( | ||
| "{DEVICE_COOKIE}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}", | ||
| credentials.device_token(unix_now()), | ||
| gitv_web::auth::DEVICE_LIFETIME | ||
| ); | ||
| redirect(safe_next(&form.next), &[cookie, device]) | ||
| } | ||
| Err(error) => { | ||
| eprintln!("gitv-web: {error}"); | ||
| sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.") | ||
| @@ -420,12 +459,13 @@ pub async fn sign_out( | ||
| 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>"#), | ||
| notice("Not allowed", true, "Not allowed", "That form has expired. Go back and try again.", None), | ||
| ); | ||
| } | ||
| 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)) | ||
| // The device cookie stays: signing out doesn't make this browser a stranger. | ||
| redirect("/login", &[clear]) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| @@ -441,33 +481,22 @@ pub struct ChangePasswordForm { | ||
| } | ||
| 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 page = super::templates::Account { | ||
| title: "Account", | ||
| signed_in: true, | ||
| user, | ||
| message, | ||
| ok, | ||
| csrf: &signed_in.csrf, | ||
| min_password: MIN_PASSWORD, | ||
| }; | ||
| 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) | ||
| ), | ||
| ), | ||
| ) | ||
| html(status, page.to_string()) | ||
| } | ||
| /// A page with a heading, a sentence and perhaps a command to copy. | ||
| fn notice(title: &str, signed_in: bool, heading: &str, message: &str, code: Option<&str>) -> String { | ||
| super::templates::Notice { title, signed_in, heading, message, code: code.map(str::to_string), link: None } | ||
| .to_string() | ||
| } | ||
| pub async fn account(State(login): State<Arc<Login>>, Extension(signed_in): Extension<SignedIn>) -> Response { | ||
| @@ -480,20 +509,19 @@ pub async fn account(State(login): State<Arc<Login>>, Extension(signed_in): Exte | ||
| pub async fn change_password( | ||
| State(login): State<Arc<Login>>, | ||
| Extension(signed_in): Extension<SignedIn>, | ||
| client: Client, | ||
| headers: HeaderMap, | ||
| Form(form): Form<ChangePasswordForm>, | ||
| ) -> Response { | ||
| let asker = Asker { client, trusted: login.trusted(&headers) }; | ||
| 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 let Some(wait) = login.locked_for(asker) { | ||
| return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait))); | ||
| } | ||
| if form.new != form.repeat { | ||
| return refuse(StatusCode::BAD_REQUEST, "The new passwords don’t match."); | ||
| @@ -501,14 +529,10 @@ pub async fn change_password( | ||
| if let Err(error) = check_new_password(&form.new) { | ||
| return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}.")); | ||
| } | ||
| match login.check(&credentials, None, form.current, &form.code).await { | ||
| match login.check("password change", &credentials, asker, 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."), | ||
| ); | ||
| return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait))); | ||
| } | ||
| Checked::Wrong => return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right."), | ||
| Checked::Unavailable => { | ||
| @@ -518,7 +542,8 @@ pub async fn change_password( | ||
| // 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 saved = | ||
| tokio::task::spawn_blocking(move || gitv_web::auth::change_password(&path, authorized, &new, None)).await; | ||
| let fingerprint = match saved { | ||
| Ok(Ok(fingerprint)) => fingerprint, | ||
| Ok(Err(AuthError::Changed)) => { | ||
| @@ -547,117 +572,6 @@ pub async fn change_password( | ||
| 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::*; | ||
| @@ -685,6 +599,11 @@ mod tests { | ||
| Login::at(PathBuf::new()) | ||
| } | ||
| /// The client a request without connection details counts as. | ||
| fn unknown() -> Client { | ||
| Client::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)) | ||
| } | ||
| #[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()); | ||
| @@ -692,7 +611,10 @@ mod tests { | ||
| 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 }) | ||
| tokio::spawn(async move { | ||
| let asker = Asker { client: unknown(), trusted: false }; | ||
| login.check("sign-in", &credentials, asker, None, "a wrong guess".into(), "123456").await | ||
| }) | ||
| }) | ||
| .collect(); | ||
| for guess in guesses { | ||
| @@ -701,7 +623,10 @@ mod tests { | ||
| // 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"); | ||
| assert!( | ||
| started <= crate::throttle::FREE_FAILURES as usize + CONCURRENT_CHECKS, | ||
| "{started} password checks ran" | ||
| ); | ||
| } | ||
| #[tokio::test] | ||
| @@ -722,41 +647,8 @@ mod tests { | ||
| .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"); | ||
| assert_eq!(login.throttle().failures(unknown()), 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()); | ||
| } | ||
| } | ||
| } | ||
+385−0
| @@ -0,0 +1,385 @@ | ||
| //! Repository browser and read-only HTTP clone service. Anonymous visitors can access public repositories. | ||
| //! A session grants the shared web account access to private repositories. | ||
| mod cache; | ||
| mod capacity; | ||
| mod git_stream; | ||
| mod html; | ||
| mod login; | ||
| mod repository; | ||
| mod setup; | ||
| mod smart_http; | ||
| mod templates; | ||
| mod throttle; | ||
| mod urls; | ||
| mod views; | ||
| use std::sync::{Arc, LazyLock}; | ||
| use std::time::Instant; | ||
| use axum::extract::{DefaultBodyLimit, Path, RawQuery}; | ||
| use axum::http::{StatusCode, header}; | ||
| use axum::response::{IntoResponse, Redirect, Response}; | ||
| use axum::routing::{get, post}; | ||
| use axum::{Extension, Router}; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv_core::repos_root; | ||
| use gitv_web::render; | ||
| use crate::html::{view_failed, view_missing}; | ||
| use crate::urls::{encode, lossy, parse_query}; | ||
| use crate::views::{route, view_index}; | ||
| use capacity::{Pool, Visitor}; | ||
| use throttle::Client; | ||
| 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 ICON_192: &[u8] = include_bytes!("../assets/icons/192.png"); | ||
| const ICON_512: &[u8] = include_bytes!("../assets/icons/512.png"); | ||
| const ICON_MASKABLE: &[u8] = include_bytes!("../assets/icons/maskable.png"); | ||
| const ICON_APPLE: &[u8] = include_bytes!("../assets/icons/apple-touch.png"); | ||
| /// Lets browsers install GITv as an app that opens in its own window. | ||
| const MANIFEST: &str = r##"{"id":"/","name":"GITv","short_name":"GITv","start_url":"/","scope":"/","display":"standalone","background_color":"#f6f7f9","theme_color":"#ffffff","icons":[{"src":"/favicon.svg","sizes":"any","type":"image/svg+xml"},{"src":"/icons/192.png","sizes":"192x192","type":"image/png"},{"src":"/icons/512.png","sizes":"512x512","type":"image/png"},{"src":"/icons/maskable.png","sizes":"512x512","type":"image/png","purpose":"maskable"}]}"##; | ||
| 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 files the pages need, by path, with their media types. Anyone may load them. | ||
| const ASSETS: [(&str, &str, &[u8]); 9] = [ | ||
| ("/favicon.svg", "image/svg+xml", FAVICON.as_bytes()), | ||
| ("/manifest.webmanifest", "application/manifest+json", MANIFEST.as_bytes()), | ||
| ("/icons/192.png", "image/png", ICON_192), | ||
| ("/icons/512.png", "image/png", ICON_512), | ||
| ("/icons/maskable.png", "image/png", ICON_MASKABLE), | ||
| ("/apple-touch-icon.png", "image/png", ICON_APPLE), | ||
| ("/fonts/display.woff2", "font/woff2", FONT_DISPLAY), | ||
| ("/fonts/text.woff2", "font/woff2", FONT_TEXT), | ||
| ("/fonts/mono.woff2", "font/woff2", FONT_MONO), | ||
| ]; | ||
| /// The stylesheet's URL carries a hash of its contents, so browsers can cache it for good and | ||
| /// still pick up every change. | ||
| static STYLE_URL: LazyLock<String> = LazyLock::new(|| { | ||
| use std::hash::{Hash, Hasher}; | ||
| let mut hasher = std::hash::DefaultHasher::new(); | ||
| STYLESHEET.hash(&mut hasher); | ||
| format!("/style.css?v={:012x}", hasher.finish() & 0xffff_ffff_ffff) | ||
| }); | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Responses | ||
| #[derive(Parser)] | ||
| #[command(about = "Read-only web browser for GITv repositories")] | ||
| struct Cli { | ||
| #[command(subcommand)] | ||
| action: Action, | ||
| } | ||
| #[derive(Subcommand)] | ||
| enum Action { | ||
| /// Serve the browser on localhost | ||
| Serve { | ||
| #[arg(long, default_value_t = 8080)] | ||
| port: u16, | ||
| }, | ||
| /// Create the web account: a generated password and an authenticator (2FA) secret | ||
| Setup { | ||
| /// The account name [default: the current account's with --force, otherwise admin] | ||
| #[arg(long)] | ||
| user: Option<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 { | ||
| LoginRequired, | ||
| Html(String), | ||
| /// Pinned cat-file command, expected size and original download name. | ||
| Raw(Box<std::process::Command>, usize, Vec<u8>), | ||
| /// Pinned `git archive` command, and the download's file name. | ||
| Archive(Box<std::process::Command>, String), | ||
| Busy, | ||
| Redirect(String), | ||
| Missing(bool), | ||
| } | ||
| const SECURITY: [(header::HeaderName, &str); 4] = [ | ||
| ( | ||
| header::CONTENT_SECURITY_POLICY, | ||
| "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self'; manifest-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", | ||
| ), | ||
| (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), | ||
| (header::REFERRER_POLICY, "no-referrer"), | ||
| (header::CACHE_CONTROL, "no-store"), | ||
| ]; | ||
| /// Headers for a raw file, which is repository content served from this site's own origin. | ||
| /// The sandbox makes a file opened directly (an SVG, say) a unique origin with no scripts, so | ||
| /// even a policy mistake can't let it act as the signed-in visitor. Inline styles are allowed | ||
| /// so SVGs draw as their authors meant; nothing may load from anywhere. | ||
| const RAW_SECURITY: [(header::HeaderName, &str); 4] = [ | ||
| (header::CONTENT_SECURITY_POLICY, "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:"), | ||
| (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), | ||
| (header::REFERRER_POLICY, "no-referrer"), | ||
| (header::CACHE_CONTROL, "no-store"), | ||
| ]; | ||
| impl View { | ||
| /// The response for `visitor`, who may need a download slot for a raw file. | ||
| async fn response(self, visitor: Visitor) -> Response { | ||
| match self { | ||
| View::LoginRequired => StatusCode::UNAUTHORIZED.into_response(), | ||
| View::Html(body) => html(StatusCode::OK, body), | ||
| View::Raw(cmd, size, name) => raw_response(visitor, *cmd, size, name).await, | ||
| View::Archive(cmd, name) => archive_response(visitor, *cmd, name).await, | ||
| View::Busy => StatusCode::SERVICE_UNAVAILABLE.into_response(), | ||
| View::Redirect(to) => Redirect::to(&to).into_response(), | ||
| View::Missing(signed_in) => missing(signed_in), | ||
| } | ||
| } | ||
| } | ||
| fn missing(signed_in: bool) -> Response { | ||
| html(StatusCode::NOT_FOUND, view_missing(signed_in)) | ||
| } | ||
| /// An HTML page, with the security headers every page sends. | ||
| fn html(status: StatusCode, body: String) -> Response { | ||
| (status, SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response() | ||
| } | ||
| fn static_file(kind: &'static str, data: &'static [u8]) -> Response { | ||
| ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "max-age=86400")], data).into_response() | ||
| } | ||
| fn stylesheet() -> Response { | ||
| let headers = | ||
| [(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")]; | ||
| (headers, STYLESHEET).into_response() | ||
| } | ||
| /// Pages rendering at once: 12 for anyone, 4 more kept for signed-in sessions, and at most 4 | ||
| /// for any one anonymous client. Excess requests are refused before any blocking work queues. | ||
| static RENDERS: LazyLock<Pool> = LazyLock::new(|| Pool::new(12, 4, 4)); | ||
| /// Raw downloads streaming at once: 4 for anyone, 2 kept for signed-in sessions, 2 per | ||
| /// anonymous client. | ||
| static DOWNLOADS: LazyLock<Pool> = LazyLock::new(|| Pool::new(4, 2, 2)); | ||
| async fn raw_response(visitor: Visitor, command: std::process::Command, size: usize, name: Vec<u8>) -> Response { | ||
| let Some(permit) = DOWNLOADS.try_acquire(visitor) else { | ||
| return StatusCode::SERVICE_UNAVAILABLE.into_response(); | ||
| }; | ||
| let Ok(mut output) = git_stream::Output::start(command.into()) else { | ||
| return StatusCode::INTERNAL_SERVER_ERROR.into_response(); | ||
| }; | ||
| let Ok(prefix) = output.prefix(size.min(8000)).await else { | ||
| return StatusCode::INTERNAL_SERVER_ERROR.into_response(); | ||
| }; | ||
| let binary = prefix.contains(&0); | ||
| let filename = lossy(&name); | ||
| let kind = match filename.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() { | ||
| Some("png") => "image/png", | ||
| Some("jpg" | "jpeg") => "image/jpeg", | ||
| Some("gif") => "image/gif", | ||
| Some("webp") => "image/webp", | ||
| // Safe to serve as an image: the sandbox (see RAW_SECURITY) blocks any script inside it. | ||
| Some("svg") => "image/svg+xml", | ||
| _ if binary => "application/octet-stream", | ||
| _ => "text/plain; charset=utf-8", | ||
| }; | ||
| let body = output.body(prefix, None, permit, std::time::Duration::from_secs(300)); | ||
| let mut response = (RAW_SECURITY, [(header::CONTENT_TYPE, kind)], body).into_response(); | ||
| response.headers_mut().insert(header::CONTENT_LENGTH, size.into()); | ||
| if kind == "application/octet-stream" | ||
| && let Ok(value) = format!("attachment; filename*=UTF-8''{}", encode(&name)).parse() | ||
| { | ||
| response.headers_mut().insert(header::CONTENT_DISPOSITION, value); | ||
| } | ||
| response | ||
| } | ||
| /// A source archive, streamed from `git archive` as it's made, in a download slot. Its size | ||
| /// isn't known until it's done, so it goes out chunked. | ||
| async fn archive_response(visitor: Visitor, command: std::process::Command, name: String) -> Response { | ||
| let Some(permit) = DOWNLOADS.try_acquire(visitor) else { | ||
| return StatusCode::SERVICE_UNAVAILABLE.into_response(); | ||
| }; | ||
| let Ok(mut output) = git_stream::Output::start(command.into()) else { | ||
| return StatusCode::INTERNAL_SERVER_ERROR.into_response(); | ||
| }; | ||
| // Every gzip stream starts with a 10-byte header. Waiting for it means a git that fails at | ||
| // once (an unreadable object, say) is an error response, not a cut-off download. | ||
| let Ok(prefix) = output.prefix(10).await else { | ||
| return StatusCode::INTERNAL_SERVER_ERROR.into_response(); | ||
| }; | ||
| let body = output.body(prefix, None, permit, std::time::Duration::from_secs(300)); | ||
| let disposition = format!("attachment; filename=\"{name}\""); | ||
| ( | ||
| RAW_SECURITY, | ||
| [(header::CONTENT_TYPE, "application/gzip"), (header::CONTENT_DISPOSITION, disposition.as_str())], | ||
| body, | ||
| ) | ||
| .into_response() | ||
| } | ||
| /// Git calls block, so every page renders on the blocking pool. The permit moves into the | ||
| /// blocking work itself: if the request is cancelled while rendering, the slot stays taken | ||
| /// until the work actually ends. | ||
| async fn blocking(visitor: Visitor, f: impl FnOnce() -> View + Send + 'static) -> Response { | ||
| let Some(permit) = RENDERS.try_acquire(visitor) else { | ||
| return StatusCode::SERVICE_UNAVAILABLE.into_response(); | ||
| }; | ||
| let work = move || { | ||
| let _permit = permit; | ||
| let started = Instant::now(); | ||
| let view = f(); | ||
| if started.elapsed() >= gitv_core::GIT_TIMEOUT { View::Busy } else { view } | ||
| }; | ||
| match tokio::task::spawn_blocking(work).await { | ||
| Ok(view) => view.response(visitor).await, | ||
| Err(error) => { | ||
| eprintln!("gitv-web: a page failed to render: {error}"); | ||
| html(StatusCode::INTERNAL_SERVER_ERROR, view_failed(visitor.signed_in)) | ||
| } | ||
| } | ||
| } | ||
| /// A repository page: `/{owner}/{name}` (which redirects to its files) or | ||
| /// `/{owner}/{name}/{view}`. | ||
| async fn repository_page( | ||
| Path(mut segments): Path<std::collections::HashMap<String, String>>, | ||
| RawQuery(query): RawQuery, | ||
| Extension(signed_in): Extension<bool>, | ||
| client: Client, | ||
| ) -> Response { | ||
| let owner = segments.remove("owner").unwrap_or_default(); | ||
| let name = segments.remove("name").unwrap_or_default(); | ||
| let view = segments.remove("view"); | ||
| blocking(Visitor { client, signed_in }, move || { | ||
| route(&owner, &name, view.as_deref(), &parse_query(query.as_deref()), signed_in) | ||
| }) | ||
| .await | ||
| } | ||
| fn main() -> std::process::ExitCode { | ||
| let outcome = match Cli::parse().action { | ||
| Action::Serve { port } => serve(port), | ||
| Action::Setup { user, force } => setup::setup(user.as_deref(), force).map_err(|e| e.to_string()), | ||
| Action::Password => setup::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 config = gitv_core::config::load()?; | ||
| 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 mut public = Router::new().route("/style.css", get(|| async { stylesheet() })); | ||
| for (path, kind, data) in ASSETS { | ||
| public = public.route(path, get(move || async move { static_file(kind, data) })); | ||
| } | ||
| let public = public.route( | ||
| "/login", | ||
| get(login::sign_in_form).post(login::sign_in).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), | ||
| ); | ||
| // Account actions and unmatched paths require a session. | ||
| let private = Router::new() | ||
| .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)), | ||
| ) | ||
| .fallback(|| async { missing(true) }) | ||
| .layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login)); | ||
| let browse = Router::new() | ||
| .route( | ||
| "/", | ||
| get(|Extension(user): Extension<bool>, client: Client, RawQuery(query): RawQuery| { | ||
| blocking(Visitor { client, signed_in: user }, move || { | ||
| view_index(user, &parse_query(query.as_deref())) | ||
| }) | ||
| }), | ||
| ) | ||
| .route("/{owner}/{name}", get(repository_page)) | ||
| .route("/{owner}/{name}/{view}", get(repository_page)) | ||
| .layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::browse)); | ||
| let app = public | ||
| .route("/{owner}/{name}/info/refs", get(smart_http::refs)) | ||
| .route("/{owner}/{name}/git-upload-pack", post(smart_http::pack)) | ||
| .merge(browse) | ||
| .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: {}; host {} from {})", | ||
| repos_root().display(), | ||
| config.host, | ||
| config.host_source | ||
| ); | ||
| // Connection details let sign-in throttle each client separately. | ||
| let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>(); | ||
| axum::serve(listener, app).with_graceful_shutdown(shutdown_requested()).await.map_err(|e| e.to_string())?; | ||
| eprintln!("gitv-web: stopped"); | ||
| Ok(()) | ||
| }) | ||
| } | ||
| /// Resolves when systemd (SIGTERM) or a terminal (Ctrl-C) asks the server to stop. From then | ||
| /// on it takes no new connections, and stops once the requests in progress (clones and | ||
| /// downloads included) have finished, or systemd's stop timeout runs out. | ||
| async fn shutdown_requested() { | ||
| let terminate = async { | ||
| match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { | ||
| Ok(mut signal) => { | ||
| signal.recv().await; | ||
| } | ||
| Err(error) => { | ||
| eprintln!("gitv-web: can't watch for SIGTERM, so it will stop at once: {error}"); | ||
| std::future::pending::<()>().await; | ||
| } | ||
| } | ||
| }; | ||
| tokio::select! { | ||
| () = terminate => {} | ||
| _ = tokio::signal::ctrl_c() => {} | ||
| } | ||
| eprintln!("gitv-web: stopping; finishing requests in progress"); | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[tokio::test] | ||
| async fn a_client_over_its_share_is_busy_without_starting_work() { | ||
| let visitor = Visitor { client: Client::new("203.0.113.250".parse().unwrap()), signed_in: false }; | ||
| let held: Vec<_> = std::iter::from_fn(|| RENDERS.try_acquire(visitor)).collect(); | ||
| assert!(!held.is_empty()); | ||
| let response = blocking(visitor, || panic!("excess render was admitted")).await; | ||
| assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); | ||
| drop(held); | ||
| // A render that fails is a server error, not a missing page. | ||
| let failed = blocking(visitor, || panic!("a render bug")).await; | ||
| assert_eq!(failed.status(), StatusCode::INTERNAL_SERVER_ERROR); | ||
| assert_eq!(blocking(visitor, || View::Html(String::new())).await.status(), StatusCode::OK); | ||
| } | ||
| } | ||
+103−9
| @@ -4,6 +4,7 @@ | ||
| //! inline styles, so the page's `style-src 'self'` policy holds; the site stylesheet colours them. | ||
| use std::sync::LazyLock; | ||
| use std::time::{Duration, Instant}; | ||
| use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd}; | ||
| use syntect::html::{ClassStyle, ClassedHTMLGenerator}; | ||
| @@ -13,6 +14,9 @@ use syntect::util::LinesWithEndings; | ||
| /// Files larger than this are shown as plain escaped text. | ||
| pub const HIGHLIGHT_LIMIT: usize = 512 << 10; | ||
| /// The most time one file or code block may spend being highlighted. | ||
| const HIGHLIGHT_BUDGET: Duration = Duration::from_secs(2); | ||
| const CLASSES: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" }; | ||
| static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines); | ||
| @@ -42,13 +46,20 @@ fn syntax_for_fence(lang: &str) -> Option<&'static SyntaxReference> { | ||
| } | ||
| fn highlight_with(code: &str, syntax: Option<&'static SyntaxReference>) -> String { | ||
| let Some(syntax) = syntax.filter(|_| code.len() <= HIGHLIGHT_LIMIT) else { | ||
| return html_escape::encode_text(code).into_owned(); | ||
| }; | ||
| highlight_within(code, syntax, HIGHLIGHT_BUDGET) | ||
| } | ||
| /// Highlight, or give up and show plain text once `budget` is spent. Some grammars are slow on | ||
| /// some input, and nothing else bounds this work: it runs outside git's deadlines and holds a | ||
| /// render slot until it ends. | ||
| fn highlight_within(code: &str, syntax: Option<&'static SyntaxReference>, budget: Duration) -> String { | ||
| let plain = || html_escape::encode_text(code).into_owned(); | ||
| let Some(syntax) = syntax.filter(|_| code.len() <= HIGHLIGHT_LIMIT) else { return plain() }; | ||
| let deadline = Instant::now() + budget; | ||
| let mut generator = ClassedHTMLGenerator::new_with_class_style(syntax, &SYNTAXES, CLASSES); | ||
| for line in LinesWithEndings::from(code) { | ||
| if generator.parse_html_for_line_which_includes_newline(line).is_err() { | ||
| return html_escape::encode_text(code).into_owned(); | ||
| if Instant::now() >= deadline || generator.parse_html_for_line_which_includes_newline(line).is_err() { | ||
| return plain(); | ||
| } | ||
| } | ||
| generator.finalize() | ||
| @@ -98,7 +109,7 @@ pub fn resolve_link(dir: &[u8], target: &str) -> Target { | ||
| dir.split(|b| *b == b'/').filter(|p| !p.is_empty()).map(<[u8]>::to_vec).collect() | ||
| }; | ||
| for raw in path.split('/') { | ||
| let part = crate::percent_decode(raw); | ||
| let part = gitv_core::percent_decode(raw); | ||
| match part.as_slice() { | ||
| b"" | b"." => {} | ||
| b".." => { | ||
| @@ -122,8 +133,19 @@ pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], bool) -> String) | ||
| Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES; | ||
| let rewrite = |dest: CowStr<'_>, image: bool| -> CowStr<'static> { | ||
| match resolve_link(dir, &dest) { | ||
| Target::External(url) if url.starts_with('#') => format!("#md-{}", &url[1..]).into(), | ||
| Target::External(url) => url.into(), | ||
| Target::Repo(path) => link(&path, image).into(), | ||
| Target::Repo(path) => { | ||
| let mut url = link(&path, image); | ||
| if let Some((_, fragment)) = dest.split_once('#') { | ||
| url.push('#'); | ||
| if !image && is_markdown(&String::from_utf8_lossy(&path)) { | ||
| url.push_str("md-"); | ||
| } | ||
| url.push_str(fragment); | ||
| } | ||
| url.into() | ||
| } | ||
| Target::Blocked => "#".into(), | ||
| } | ||
| }; | ||
| @@ -163,6 +185,49 @@ pub fn markdown(source: &str, dir: &[u8], link: &dyn Fn(&[u8], bool) -> String) | ||
| other => other, | ||
| }); | ||
| } | ||
| // Derive anchors from visible heading text. Prefix them so document headings cannot | ||
| // shadow page navigation. Duplicate headings get stable suffixes. | ||
| let mut used = std::collections::HashSet::new(); | ||
| let mut suffixes = std::collections::HashMap::new(); | ||
| let mut heading = None; | ||
| for index in 0..events.len() { | ||
| match &events[index] { | ||
| Event::Start(Tag::Heading { .. }) => heading = Some((index, String::new())), | ||
| Event::Text(text) | Event::Code(text) => { | ||
| if let Some((_, title)) = &mut heading { | ||
| title.push_str(text); | ||
| } | ||
| } | ||
| Event::End(TagEnd::Heading(_)) => { | ||
| if let Some((start, title)) = heading.take() { | ||
| let base: String = title | ||
| .to_lowercase() | ||
| .chars() | ||
| .filter_map(|c| { | ||
| if c.is_whitespace() { | ||
| Some('-') | ||
| } else if c.is_alphanumeric() || matches!(c, '-' | '_') { | ||
| Some(c) | ||
| } else { | ||
| None | ||
| } | ||
| }) | ||
| .collect(); | ||
| let base = format!("md-{base}"); | ||
| let mut id = base.clone(); | ||
| let suffix = suffixes.entry(base.clone()).or_insert(0usize); | ||
| while !used.insert(id.clone()) { | ||
| *suffix += 1; | ||
| id = format!("{base}-{suffix}"); | ||
| } | ||
| if let Event::Start(Tag::Heading { id: target, .. }) = &mut events[start] { | ||
| *target = Some(id.into()); | ||
| } | ||
| } | ||
| } | ||
| _ => {} | ||
| } | ||
| } | ||
| let mut out = String::new(); | ||
| pulldown_cmark::html::push_html(&mut out, events.into_iter()); | ||
| out | ||
| @@ -183,11 +248,33 @@ mod tests { | ||
| assert!(!html.contains("<div"), "{html}"); | ||
| } | ||
| #[test] | ||
| fn links_match_unique_heading_ids() { | ||
| let html = markdown( | ||
| "# Install *Git* | ||
| # Install Git | ||
| [second](#install-git-1) [guide](guide.md#install-git)", | ||
| b"", | ||
| &link, | ||
| ); | ||
| for fragment in [ | ||
| "id=\"md-install-git\"", | ||
| "id=\"md-install-git-1\"", | ||
| "href=\"#md-install-git-1\"", | ||
| "href=\"/blob?path=guide.md#md-install-git\"", | ||
| ] { | ||
| assert!(html.contains(fragment), "{html}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn ignores_heading_attributes() { | ||
| let html = markdown("# Title {onclick=alert(1) #main .skip style=x}", b"", &link); | ||
| // The braces stay as heading text instead of becoming attributes. | ||
| assert_eq!(html.trim(), "<h1>Title {onclick=alert(1) #main .skip style=x}</h1>"); | ||
| assert!(html.contains(">Title {onclick=alert(1) #main .skip style=x}</h1>")); | ||
| assert!(!html.contains(" onclick=")); | ||
| } | ||
| #[test] | ||
| @@ -201,7 +288,7 @@ mod tests { | ||
| fn rewrites_relative_links_and_images() { | ||
| let html = | ||
| markdown("[a](guide.md#top) [b](/src/lib.rs)  [d](https://x.dev)", b"docs", &link); | ||
| assert!(html.contains("href=\"/blob?path=docs/guide.md\""), "{html}"); | ||
| assert!(html.contains("href=\"/blob?path=docs/guide.md#md-top\""), "{html}"); | ||
| assert!(html.contains("href=\"/blob?path=src/lib.rs\""), "{html}"); | ||
| assert!(html.contains("src=\"/raw?path=img/logo.png\""), "{html}"); | ||
| assert!(html.contains("href=\"https://x.dev\""), "{html}"); | ||
| @@ -222,6 +309,13 @@ mod tests { | ||
| assert_eq!(repo(b"", "a%00b"), None); | ||
| } | ||
| #[test] | ||
| fn highlighting_past_its_budget_falls_back_to_plain_text() { | ||
| let syntax = syntax_for("x.rs", ""); | ||
| assert!(highlight_within("fn main() {}\n", syntax, Duration::from_secs(60)).contains("hl-")); | ||
| assert_eq!(highlight_within("fn <b>\n", syntax, Duration::ZERO), "fn <b>\n"); | ||
| } | ||
| #[test] | ||
| fn highlights_fenced_code_and_files() { | ||
| let html = markdown("```rust\nfn main() {}\n```", b"", &link); | ||
+538−0
| @@ -0,0 +1,538 @@ | ||
| //! Git queries on an already-open repository. Ref and path identities remain byte strings. | ||
| use std::{sync::Arc, time::Duration}; | ||
| use gitv_core::{RepoDir, git_capped, git_with_input}; | ||
| use crate::cache::cached; | ||
| use crate::urls::{encode, join, lossy}; | ||
| /// The most output any one git command run for a page may produce. Pages render 16 at a time | ||
| /// in a service capped at 640 MiB, so this keeps a huge folder or ref list in a public | ||
| /// repository from running the server out of memory; past it, the page is "not found". It | ||
| /// fits about 80,000 folder entries or 60,000 refs, and files shown are capped far lower. | ||
| pub(crate) const PAGE_OUTPUT_LIMIT: usize = 8 << 20; | ||
| /// Objects an abbreviated id may match before it counts as too ambiguous to look up. | ||
| const MAX_CANDIDATES: usize = 1000; | ||
| const ENTRY_FORMAT: &str = "%H%x00%ct%x00%cI%x00%cd%x00%s%x00%B"; | ||
| const ENTRY_DATE: &str = "--date=format:%-d %b %Y, %H:%M:%S %z"; | ||
| use std::{cell::OnceCell, collections::HashMap, ffi::OsStr, os::unix::ffi::OsStrExt}; | ||
| pub(super) struct Reader { | ||
| pub(super) dir: RepoDir, | ||
| refs: OnceCell<Refs>, | ||
| } | ||
| /// The newest commit on a ref: full hash, subject, author, unix time, short date. | ||
| pub(super) struct Head { | ||
| pub(super) oid: String, | ||
| pub(super) subject: String, | ||
| pub(super) author: String, | ||
| pub(super) stamp: String, | ||
| pub(super) date: String, | ||
| } | ||
| impl Head { | ||
| pub(super) const FORMAT: &'static str = "--format=%H%x00%an%x00%ct%x00%cd%x00%s"; | ||
| pub(super) fn parse(out: &str) -> Option<Head> { | ||
| let f: Vec<&str> = out.trim_end_matches('\n').splitn(5, '\0').collect(); | ||
| let [oid, author, stamp, date, subject] = <[&str; 5]>::try_from(f).ok()?; | ||
| Some(Head { | ||
| oid: oid.into(), | ||
| subject: subject.into(), | ||
| author: author.into(), | ||
| stamp: stamp.into(), | ||
| date: date.into(), | ||
| }) | ||
| } | ||
| } | ||
| /// The branches and tags, from one `git for-each-ref`. | ||
| #[derive(Default)] | ||
| struct Refs { | ||
| /// Branch names, without `refs/heads/`, in git's order. | ||
| heads: Vec<Vec<u8>>, | ||
| /// Tag names, without `refs/tags/`, in git's order. | ||
| tags: Vec<Vec<u8>>, | ||
| /// The commit each full ref name names, for those that name one directly or through one | ||
| /// annotated tag. | ||
| commits: HashMap<Vec<u8>, String>, | ||
| /// Each tag and the object it ends at after one peel, as history labels use it. | ||
| tag_targets: Vec<(Vec<u8>, String)>, | ||
| } | ||
| impl Refs { | ||
| /// Parse `refname NUL objectname NUL objecttype NUL *objectname NUL *objecttype` lines. A ref | ||
| /// name can hold neither a NUL nor a newline. | ||
| fn parse(out: &[u8]) -> Refs { | ||
| let mut refs = Refs::default(); | ||
| for line in out.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { | ||
| let Ok([name, oid, kind, peeled, peeled_kind]) = | ||
| <[&[u8]; 5]>::try_from(line.split(|b| *b == 0).collect::<Vec<_>>()) | ||
| else { | ||
| continue; | ||
| }; | ||
| let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned(); | ||
| let commit = match (kind, peeled_kind) { | ||
| (b"commit", _) => Some(oid), | ||
| (b"tag", b"commit") => Some(peeled), | ||
| _ => None, | ||
| }; | ||
| if let Some(commit) = commit { | ||
| refs.commits.insert(name.to_vec(), text(commit)); | ||
| } | ||
| if let Some(branch) = name.strip_prefix(b"refs/heads/") { | ||
| refs.heads.push(branch.to_vec()); | ||
| } else if let Some(tag) = name.strip_prefix(b"refs/tags/") { | ||
| refs.tags.push(tag.to_vec()); | ||
| let target = if peeled.is_empty() { oid } else { peeled }; | ||
| refs.tag_targets.push((tag.to_vec(), text(target))); | ||
| } | ||
| } | ||
| refs | ||
| } | ||
| } | ||
| impl Reader { | ||
| pub(super) fn new(dir: RepoDir) -> Self { | ||
| Self { dir, refs: OnceCell::new() } | ||
| } | ||
| /// A git command's output, or `None` if it fails or passes [`PAGE_OUTPUT_LIMIT`]. | ||
| pub(super) fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> { | ||
| match git_capped(&self.dir, args, PAGE_OUTPUT_LIMIT) { | ||
| Ok((output, false)) => Some(output), | ||
| _ => None, | ||
| } | ||
| } | ||
| pub(super) fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> { | ||
| self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned()) | ||
| } | ||
| /// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch. | ||
| pub(super) fn default_ref(&self) -> Vec<u8> { | ||
| let head = self.git_bytes(&["symbolic-ref", "HEAD"]).unwrap_or_default(); | ||
| let heads = self.heads(); | ||
| let target = head.strip_suffix(b"\n").and_then(|h| h.strip_prefix(b"refs/heads/")); | ||
| let choice = target | ||
| .into_iter() | ||
| .chain([b"main".as_slice(), b"master"]) | ||
| .find(|name| heads.iter().any(|h| h == name)) | ||
| .or_else(|| heads.first().map(Vec::as_slice)); | ||
| choice.map_or_else(|| b"HEAD".to_vec(), |name| self.branch_ref(name)) | ||
| } | ||
| /// Every branch and tag, read with one git command the first time any is needed. | ||
| fn refs(&self) -> &Refs { | ||
| self.refs.get_or_init(|| { | ||
| let format = "--format=%(refname)%00%(objectname)%00%(objecttype)%00%(*objectname)%00%(*objecttype)"; | ||
| Refs::parse(&self.git_bytes(&["for-each-ref", format, "refs/heads", "refs/tags"]).unwrap_or_default()) | ||
| }) | ||
| } | ||
| pub(super) fn heads(&self) -> &[Vec<u8>] { | ||
| &self.refs().heads | ||
| } | ||
| pub(super) fn tags(&self) -> &[Vec<u8>] { | ||
| &self.refs().tags | ||
| } | ||
| /// The commit a reference names, in this order: | ||
| /// | ||
| /// - `refs/heads/NAME` or `refs/tags/NAME` for an existing branch or tag: the form links | ||
| /// use whenever a plain name could be misread (see [`Reader::branch_ref`]); | ||
| /// - a full commit id, always as an object, whatever refs are named; | ||
| /// - a branch, then a tag, by exact name, so any name git allows works and none is read as | ||
| /// revision syntax; | ||
| /// - `HEAD`, then an abbreviated commit id, again only as an object. | ||
| pub(super) fn resolve(&self, reference: &[u8]) -> Option<String> { | ||
| let is_head = |n: &[u8]| self.heads().iter().any(|h| h == n); | ||
| let is_tag = |n: &[u8]| self.tags().iter().any(|h| h == n); | ||
| let hex = reference.iter().all(u8::is_ascii_hexdigit); | ||
| let full = if reference.strip_prefix(b"refs/heads/").is_some_and(is_head) | ||
| || reference.strip_prefix(b"refs/tags/").is_some_and(is_tag) | ||
| { | ||
| reference.to_vec() | ||
| } else if hex && matches!(reference.len(), 40 | 64) { | ||
| return self.commit_object(std::str::from_utf8(reference).ok()?); | ||
| } else if is_head(reference) { | ||
| [b"refs/heads/".as_slice(), reference].concat() | ||
| } else if is_tag(reference) { | ||
| [b"refs/tags/".as_slice(), reference].concat() | ||
| } else if reference == b"HEAD" { | ||
| reference.to_vec() | ||
| } else if hex && reference.len() >= 4 { | ||
| return self.commit_object(std::str::from_utf8(reference).ok()?); | ||
| } else { | ||
| return None; | ||
| }; | ||
| // Branches and tags that name a commit (directly, or through one annotated tag) were | ||
| // answered by the ref listing; anything else is peeled by git as before. | ||
| if let Some(commit) = self.refs().commits.get(&full) { | ||
| return Some(commit.clone()); | ||
| } | ||
| let spec = [full.as_slice(), b"^{commit}"].concat(); | ||
| let args = ["rev-parse", "--verify", "--quiet", "--end-of-options"].map(OsStr::new); | ||
| self.git(&[args.as_slice(), &[OsStr::from_bytes(&spec)]].concat()).map(|s| s.trim().into()) | ||
| } | ||
| /// The commit whose id is or starts with `id`, looked up among objects only: a branch or | ||
| /// tag that happens to be named like an id can't redirect it. Annotated tag objects peel to | ||
| /// their commit. An abbreviation that fits more than one commit finds nothing. | ||
| /// | ||
| /// At most two git commands, however many objects share the prefix: one lists them (skipped | ||
| /// for a full id) and one peels them all. Both are given full ids, which git always reads as | ||
| /// objects, never as ref names. | ||
| pub(super) fn commit_object(&self, id: &str) -> Option<String> { | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) { | ||
| return None; | ||
| } | ||
| let id = id.to_ascii_lowercase(); | ||
| let candidates = if matches!(id.len(), 40 | 64) { | ||
| id.clone() | ||
| } else { | ||
| self.git(&["rev-parse", &format!("--disambiguate={id}")])? | ||
| }; | ||
| let queries: String = | ||
| candidates.lines().take(MAX_CANDIDATES + 1).map(|oid| format!("{oid}^{{commit}}\n")).collect(); | ||
| if queries.is_empty() || queries.lines().count() > MAX_CANDIDATES { | ||
| return None; | ||
| } | ||
| let peeled = | ||
| git_with_input(&self.dir, &["cat-file", "--batch-check=%(objectname) %(objecttype)"], queries.as_bytes()) | ||
| .ok()?; | ||
| // Anything that isn't a commit-ish answers "<query> missing"; a tag and the commit it | ||
| // points at peel to the same commit, which counts once. | ||
| let commits: std::collections::BTreeSet<&[u8]> = | ||
| peeled.split(|b| *b == b'\n').filter_map(|line| line.strip_suffix(b" commit")).collect(); | ||
| match commits.into_iter().collect::<Vec<_>>().as_slice() { | ||
| [one] => Some(String::from_utf8_lossy(one).into_owned()), | ||
| _ => None, | ||
| } | ||
| } | ||
| /// Whether a plain name in a link would resolve to itself: it mustn't look like a full | ||
| /// commit id or a qualified ref, which [`Reader::resolve`] reads first. | ||
| fn plain_is_safe(name: &[u8]) -> bool { | ||
| let full_id = matches!(name.len(), 40 | 64) && name.iter().all(u8::is_ascii_hexdigit); | ||
| !full_id && !name.starts_with(b"refs/") && name != b"HEAD" | ||
| } | ||
| pub(super) fn branch_ref(&self, name: &[u8]) -> Vec<u8> { | ||
| if Self::plain_is_safe(name) { name.to_vec() } else { [b"refs/heads/".as_slice(), name].concat() } | ||
| } | ||
| pub(super) fn tag_ref(&self, name: &[u8]) -> Vec<u8> { | ||
| if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) { | ||
| name.to_vec() | ||
| } else { | ||
| [b"refs/tags/".as_slice(), name].concat() | ||
| } | ||
| } | ||
| /// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking | ||
| /// history for a path can be slow, so answers for a fixed commit are cached. | ||
| pub(super) fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> { | ||
| Head::parse(&self.latest_raw(rev, path)?) | ||
| } | ||
| /// [`Reader::latest`] as git printed it, for callers that cache it themselves. | ||
| pub(super) fn latest_raw(&self, rev: &str, path: &[u8]) -> Option<String> { | ||
| let lookup = || { | ||
| let mut args: Vec<&OsStr> = | ||
| ["log", "-1", "--date=format:%-d %b %Y", Head::FORMAT, rev, "--"].map(OsStr::new).to_vec(); | ||
| if !path.is_empty() { | ||
| args.push(OsStr::from_bytes(path)); | ||
| } | ||
| self.git(&args).filter(|out| !out.trim().is_empty()) | ||
| }; | ||
| let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()); | ||
| if is_oid { | ||
| Some(cached(format!("latest:{}:{rev}:{}", self.dir.path.display(), encode(path)), lookup)?.to_string()) | ||
| } else { | ||
| lookup() | ||
| } | ||
| } | ||
| /// Resolve just the displayed entries. A warm page needs no history query. On a cold | ||
| /// page one bounded linear walk handles recent changes, with Git's path-specific | ||
| /// history simplification retained for anything older or behind a merge. | ||
| pub(super) fn entry_histories(&self, commit: &str, dir: &[u8], names: &[&[u8]]) -> Vec<Option<Arc<str>>> { | ||
| let recent = OnceCell::new(); | ||
| names | ||
| .iter() | ||
| .map(|&name| { | ||
| let path = join(dir, name); | ||
| let key = format!("entry-commit:{}:{commit}:{}", self.dir.path.display(), encode(&path)); | ||
| cached(key, || { | ||
| if names.len() > 1 { | ||
| let matches = recent.get_or_init(|| self.recent_entry_histories(commit, dir, names)); | ||
| if let Some(record) = matches.as_ref().and_then(|m| m.get(name)) { | ||
| return Some(record.to_string()); | ||
| } | ||
| } | ||
| let format = format!("--format={ENTRY_FORMAT}"); | ||
| let args = ["log", "-1", ENTRY_DATE, &format, commit, "--"].map(OsStr::new); | ||
| self.git(&[args.as_slice(), &[OsStr::from_bytes(&path)]].concat()).filter(|out| !out.is_empty()) | ||
| }) | ||
| }) | ||
| .collect() | ||
| } | ||
| fn recent_entry_histories<'a>( | ||
| &self, | ||
| commit: &str, | ||
| dir: &[u8], | ||
| names: &[&'a [u8]], | ||
| ) -> Option<HashMap<&'a [u8], Arc<str>>> { | ||
| let format = format!("--format=%x00%P%x00{ENTRY_FORMAT}"); | ||
| let window = format!("-{RECENT_WINDOW}"); | ||
| let args = [ | ||
| "log", | ||
| &window, | ||
| "--first-parent", | ||
| "--diff-merges=off", | ||
| "--root", | ||
| "--no-renames", | ||
| "--name-only", | ||
| "-z", | ||
| ENTRY_DATE, | ||
| &format, | ||
| commit, | ||
| "--", | ||
| ]; | ||
| // Output past the cap is cut off; what came before it is still exact, and anything not | ||
| // found in it is looked up on its own. | ||
| let (bytes, _) = gitv_core::git_capped_for(&self.dir, &args, RECENT_BYTES, Duration::from_secs(1)).ok()?; | ||
| Some(recent_changes(&bytes, dir, names)) | ||
| } | ||
| /// Commits reachable from `commit`. A commit's history never changes, so the count is cached. | ||
| pub(super) fn commit_count(&self, commit: &str) -> usize { | ||
| let key = format!("count:{}:{commit}", self.dir.path.display()); | ||
| cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string())) | ||
| .and_then(|count| count.parse().ok()) | ||
| .unwrap_or(0) | ||
| } | ||
| /// Tag names grouped by the commit (or other object) they point at, for labelling history. | ||
| pub(super) fn tags_by_commit(&self) -> HashMap<String, Vec<Vec<u8>>> { | ||
| let mut found: HashMap<String, Vec<Vec<u8>>> = HashMap::new(); | ||
| for (name, target) in &self.refs().tag_targets { | ||
| found.entry(target.clone()).or_default().push(name.clone()); | ||
| } | ||
| found | ||
| } | ||
| } | ||
| /// Linear history a cold folder listing reads in one walk, newest first, before looking up | ||
| /// whatever it didn't find one entry at a time. | ||
| const RECENT_WINDOW: usize = 1000; | ||
| /// The most of that walk's output read; a cut-off walk still answers for what it covered. | ||
| const RECENT_BYTES: usize = 4 << 20; | ||
| /// A record begins with an empty NUL field (impossible as a pathname), followed by | ||
| /// parents, six metadata fields, then Git's newline and NUL-terminated changed paths. | ||
| /// | ||
| /// Records are newest first, so the first record naming an entry is its latest change. The | ||
| /// walk ends at the first merge, past which first-parent order and Git's per-path history can | ||
| /// disagree. Output cut off part way (at the byte cap) ends the walk where it was cut: every | ||
| /// field is NUL-terminated, so a partial one is never read as a shorter name. | ||
| fn recent_changes<'a>(mut data: &[u8], dir: &[u8], names: &[&'a [u8]]) -> HashMap<&'a [u8], Arc<str>> { | ||
| fn field<'b>(data: &mut &'b [u8]) -> Option<&'b [u8]> { | ||
| let end = data.iter().position(|&b| b == 0)?; | ||
| let value = &data[..end]; | ||
| *data = &data[end + 1..]; | ||
| Some(value) | ||
| } | ||
| let mut pending: std::collections::HashSet<_> = names.iter().copied().collect(); | ||
| let mut found = HashMap::new(); | ||
| let mut walk = || -> Option<()> { | ||
| while !data.is_empty() && !pending.is_empty() { | ||
| data = data.strip_prefix(b"\0")?; | ||
| if field(&mut data)?.contains(&b' ') { | ||
| break; | ||
| } | ||
| let start = data; | ||
| for _ in 0..6 { | ||
| field(&mut data)?; | ||
| } | ||
| let metadata = &start[..start.len() - data.len() - 1]; | ||
| let record = OnceCell::new(); | ||
| if let Some(paths) = data.strip_prefix(b"\n") { | ||
| data = paths; | ||
| while !data.is_empty() && data[0] != 0 { | ||
| let path = field(&mut data)?; | ||
| let relative = if dir.is_empty() { | ||
| path | ||
| } else { | ||
| let Some(rest) = path.strip_prefix(dir).and_then(|r| r.strip_prefix(b"/")) else { continue }; | ||
| rest | ||
| }; | ||
| let name = relative.split(|&b| b == b'/').next()?; | ||
| if let Some(name) = pending.take(name) { | ||
| let value = record.get_or_init(|| Arc::<str>::from(lossy(metadata))); | ||
| found.insert(name, Arc::clone(value)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Some(()) | ||
| }; | ||
| let _ = walk(); | ||
| found | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn batch_uses_newest_change_and_stops_at_the_first_merge() { | ||
| let input = b"\0parent\0tip\0time\0iso\0date\0subject\0full\nmessage\0\nother/file\0docs/\xff/new\0docs/\nfile\0\0older\0previous\0time\0iso\0date\0subject\0message\0\ndocs/\xff/old\0\0one two\0merge\0time\0iso\0date\0subject\0message\0\ndocs/side\0"; | ||
| let names = [b"\xff".as_slice(), b"\nfile", b"side", b"file"]; | ||
| let result = recent_changes(input, b"docs", &names); | ||
| assert_eq!(result.len(), 2); | ||
| for name in &names[..2] { | ||
| assert_eq!(&*result[name], "tip\0time\0iso\0date\0subject\0full\nmessage"); | ||
| } | ||
| } | ||
| /// A bare repository built from a `git fast-import` stream, and its folder. | ||
| fn imported(name: &str, stream: &str) -> (Reader, std::path::PathBuf) { | ||
| use std::io::Write as _; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-{name}-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| assert!(gitv_core::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| let mut import = gitv_core::git_base() | ||
| .arg("--git-dir") | ||
| .arg(&dir) | ||
| .args(["fast-import", "--quiet"]) | ||
| .stdin(std::process::Stdio::piped()) | ||
| .spawn() | ||
| .unwrap(); | ||
| import.stdin.take().unwrap().write_all(stream.as_bytes()).unwrap(); | ||
| assert!(import.wait().unwrap().success()); | ||
| (Reader::new(RepoDir::at(&dir).unwrap()), dir) | ||
| } | ||
| /// A bare repository with 1000 commits on main, 3000 blobs and an annotated tag on the tip, | ||
| /// enough that 4-digit prefixes collide: commit with blob, and commit with commit. | ||
| fn crowded_repository() -> (Reader, std::path::PathBuf) { | ||
| let mut stream = String::new(); | ||
| for i in 0..3000 { | ||
| let data = format!("blob {i}\n"); | ||
| stream += &format!("blob\ndata {}\n{data}", data.len()); | ||
| } | ||
| for i in 0..1000 { | ||
| let message = format!("commit {i}\n"); | ||
| stream += &format!( | ||
| "commit refs/heads/main\ncommitter A <a@example.com> {} +0000\ndata {}\n{message}\n", | ||
| 1_700_000_000 + i, | ||
| message.len() | ||
| ); | ||
| } | ||
| stream += "tag v1\nfrom refs/heads/main\ntagger A <a@example.com> 1800000000 +0000\ndata 3\nv1\n"; | ||
| imported("crowded", &stream) | ||
| } | ||
| #[test] | ||
| fn abbreviated_ids_find_commits_among_other_objects() { | ||
| let (reader, dir) = crowded_repository(); | ||
| let listing = | ||
| reader.git(&["cat-file", "--batch-all-objects", "--batch-check=%(objectname) %(objecttype)"]).unwrap(); | ||
| let mut by_prefix: HashMap<&str, Vec<(&str, &str)>> = HashMap::new(); | ||
| for line in listing.lines() { | ||
| let (oid, kind) = line.split_once(' ').unwrap(); | ||
| by_prefix.entry(&oid[..4]).or_default().push((oid, kind)); | ||
| } | ||
| let commits = |group: &[(&str, &str)]| group.iter().filter(|(_, k)| *k == "commit").count(); | ||
| // One commit sharing its prefix with a blob: the commit is found. | ||
| let (prefix, group) = by_prefix | ||
| .iter() | ||
| .find(|(_, g)| commits(g) == 1 && g.iter().any(|(_, k)| *k == "blob")) | ||
| .expect("a commit and a blob share a prefix"); | ||
| let commit = group.iter().find(|(_, k)| *k == "commit").unwrap().0; | ||
| assert_eq!(reader.commit_object(prefix).as_deref(), Some(commit)); | ||
| assert_eq!(reader.commit_object(&prefix.to_uppercase()).as_deref(), Some(commit), "case doesn't matter"); | ||
| // Two commits sharing a prefix: ambiguous, so nothing. | ||
| let (prefix, _) = by_prefix.iter().find(|(_, g)| commits(g) >= 2).expect("two commits share a prefix"); | ||
| assert_eq!(reader.commit_object(prefix), None); | ||
| // A blob alone is no commit; a full id is looked up directly. | ||
| let (blob, _) = by_prefix.values().flatten().find(|(_, k)| *k == "blob").unwrap(); | ||
| assert_eq!(reader.commit_object(blob), None); | ||
| assert_eq!(reader.commit_object(commit).as_deref(), Some(commit)); | ||
| // An annotated tag peels to its commit, by full or abbreviated id. | ||
| let tip = reader.git(&["rev-parse", "main"]).unwrap().trim().to_string(); | ||
| let tag = reader.git(&["rev-parse", "v1"]).unwrap().trim().to_string(); | ||
| assert_ne!(tag, tip); | ||
| assert_eq!(reader.commit_object(&tag).as_deref(), Some(tip.as_str())); | ||
| assert_eq!(reader.commit_object(&tag[..12]).as_deref(), Some(tip.as_str())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn one_walk_finds_entries_changed_long_ago() { | ||
| // old.txt is written once, then busy.txt changes in each of 30 later commits. | ||
| let mut stream = String::from( | ||
| "commit refs/heads/main\ncommitter A <a@example.com> 1700000000 +0000\ndata 6\nfirst\nM 644 inline old.txt\ndata 4\nold\n\n", | ||
| ); | ||
| for i in 1..=30 { | ||
| let message = format!("change {i}\n"); | ||
| let content = format!("{i}\n"); | ||
| stream += &format!( | ||
| "commit refs/heads/main\ncommitter A <a@example.com> {} +0000\ndata {}\n{message}M 644 inline busy.txt\ndata {}\n{content}\n", | ||
| 1_700_000_000 + i, | ||
| message.len(), | ||
| content.len() | ||
| ); | ||
| } | ||
| let (reader, dir) = imported("walk", &stream); | ||
| let tip = reader.git(&["rev-parse", "main"]).unwrap().trim().to_string(); | ||
| let first = reader.git(&["rev-list", "--max-parents=0", "main"]).unwrap().trim().to_string(); | ||
| let names = [b"old.txt".as_slice(), b"busy.txt"]; | ||
| let found = reader.recent_entry_histories(&tip, b"", &names).unwrap(); | ||
| assert!(found[b"old.txt".as_slice()].starts_with(&first), "found in the one walk"); | ||
| assert!(found[b"busy.txt".as_slice()].starts_with(&tip)); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_walk_cut_off_part_way_keeps_what_it_read() { | ||
| let input = b"\0p\0tip\0t\0i\0d\0s\0m\0\na.txt\0b.txt\0\0p\0older\0t\0i\0d\0s\0m\0\nc.t"; | ||
| let names = [b"a.txt".as_slice(), b"b.txt", b"c.txt", b"c.t"]; | ||
| let result = recent_changes(input, b"", &names); | ||
| assert_eq!(result.len(), 2, "a and b from the whole record; nothing from the cut-off name"); | ||
| assert!(result[b"a.txt".as_slice()].starts_with("tip")); | ||
| } | ||
| #[test] | ||
| fn one_ref_listing_resolves_what_it_can_and_leaves_the_rest_to_git() { | ||
| let out = b"refs/heads/main\0c1\0commit\0\0\n\ | ||
| refs/heads/odd-\xff\0c2\0commit\0\0\n\ | ||
| refs/tags/v1\0t1\0tag\0c1\0commit\n\ | ||
| refs/tags/nested\0t2\0tag\0t1\0tag\n\ | ||
| refs/tags/tree\0r1\0tree\0\0\n"; | ||
| let refs = Refs::parse(out); | ||
| assert_eq!(refs.heads, [b"main".to_vec(), b"odd-\xff".to_vec()]); | ||
| assert_eq!(refs.tags, [b"v1".to_vec(), b"nested".to_vec(), b"tree".to_vec()]); | ||
| assert_eq!(refs.commits[b"refs/heads/odd-\xff".as_slice()], "c2"); | ||
| assert_eq!(refs.commits[b"refs/tags/v1".as_slice()], "c1", "an annotated tag peels to its commit"); | ||
| assert!(!refs.commits.contains_key(b"refs/tags/nested".as_slice()), "a tag of a tag is left to git"); | ||
| assert!(!refs.commits.contains_key(b"refs/tags/tree".as_slice()), "a tag of a tree is no commit"); | ||
| assert_eq!(refs.tag_targets[0], (b"v1".to_vec(), "c1".to_string())); | ||
| } | ||
| #[test] | ||
| fn control_characters_in_git_names_do_not_shift_fields() { | ||
| let head = Head::parse("commit\0First\x1fLast\0timestamp\0date\0subject\x1fmore").unwrap(); | ||
| assert_eq!(head.author, "First\x1fLast"); | ||
| assert_eq!(head.stamp, "timestamp"); | ||
| assert_eq!(head.subject, "subject\x1fmore"); | ||
| } | ||
| } | ||
+116−0
| @@ -0,0 +1,116 @@ | ||
| //! The command line's account commands: `gitv-web setup` creates the web account, and | ||
| //! `gitv-web password` changes its password. Neither touches the running server, which | ||
| //! re-reads the account file whenever it changes. | ||
| use std::os::unix::fs::DirBuilderExt; | ||
| use std::os::unix::process::CommandExt; | ||
| use std::path::Path; | ||
| use gitv_web::auth::{AuthError, Credentials, auth_path, check_new_password, generate_password}; | ||
| /// `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: Option<&str>, force: bool) -> Result<(), AuthError> { | ||
| let path = auth_path(); | ||
| // Replacing an account keeps its name unless told otherwise. | ||
| let existing = if force { Credentials::load(&path).ok().map(|c| c.user().to_string()) } else { None }; | ||
| let user = user.or(existing.as_deref()).unwrap_or(gitv_web::auth::DEFAULT_USER); | ||
| // A bad name is refused before anything is made, so --force can't swap a working account | ||
| // for one that won't load. | ||
| gitv_web::auth::check_user(user)?; | ||
| // 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_web::auth::service_owner()?; | ||
| prepare_directory(&path, owner)?; | ||
| let _lock = gitv_web::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_web::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv_web::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_web::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 = gitv_core::open_dir(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(()) | ||
| } | ||
+123−0
| @@ -0,0 +1,123 @@ | ||
| //! Read-only Git smart HTTP, using upload-pack's stateless protocol. | ||
| use super::capacity::{Pool, Visitor}; | ||
| use super::git_stream::Output; | ||
| use super::throttle::Client; | ||
| use axum::{ | ||
| body::Bytes, | ||
| extract::{Path, RawQuery, Request}, | ||
| http::{HeaderMap, StatusCode, header}, | ||
| response::{IntoResponse, Response}, | ||
| }; | ||
| use gitv_core::{git_command, repo_dir}; | ||
| use std::sync::LazyLock; | ||
| use std::{process::Stdio, time::Duration}; | ||
| use tokio::process::Command; | ||
| /// Clones and fetches at once. Git clients send no session cookie, so every transfer is | ||
| /// anonymous; each client may run two, so no single address can take them all. | ||
| static TRANSFERS: LazyLock<Pool> = LazyLock::new(|| Pool::new(4, 0, 2)); | ||
| pub async fn refs( | ||
| Path(path): Path<(String, String)>, | ||
| RawQuery(query): RawQuery, | ||
| client: Client, | ||
| headers: HeaderMap, | ||
| ) -> Response { | ||
| if query.as_deref() != Some("service=git-upload-pack") { | ||
| return StatusCode::NOT_FOUND.into_response(); | ||
| } | ||
| transfer(path, client, protocol(&headers), None).await | ||
| } | ||
| /// The protocol the client asked for in its `Git-Protocol` header (`version=2`, say), when it | ||
| /// is well formed, to hand to upload-pack as `GIT_PROTOCOL`, as `git http-backend` does. | ||
| fn protocol(headers: &HeaderMap) -> Option<String> { | ||
| gitv_core::git_protocol(headers.get("git-protocol")?.to_str().ok()?).map(str::to_string) | ||
| } | ||
| pub async fn pack(Path(path): Path<(String, String)>, client: Client, request: Request) -> Response { | ||
| if request.headers().get(header::CONTENT_TYPE).map(|h| h.as_bytes()) | ||
| != Some(b"application/x-git-upload-pack-request") | ||
| { | ||
| return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response(); | ||
| } | ||
| let protocol = protocol(request.headers()); | ||
| transfer(path, client, protocol, Some(request)).await | ||
| } | ||
| async fn transfer( | ||
| (owner, name): (String, String), | ||
| client: Client, | ||
| protocol: Option<String>, | ||
| request: Option<Request>, | ||
| ) -> Response { | ||
| // `https://host/owner/name.git` works as well as the address the pages show. | ||
| let name = name.strip_suffix(".git").unwrap_or(&name); | ||
| let Some(dir) = repo_dir(&owner, name).filter(|dir| dir.is_public()) else { | ||
| return StatusCode::NOT_FOUND.into_response(); | ||
| }; | ||
| // Taken before the body is read, so memory for bodies stays bounded by the slots; the | ||
| // per-client cap keeps one slow sender from holding them all. | ||
| let Some(permit) = TRANSFERS.try_acquire(Visitor { client, signed_in: false }) else { | ||
| return StatusCode::SERVICE_UNAVAILABLE.into_response(); | ||
| }; | ||
| const MAX_REQUEST: usize = 2 << 20; | ||
| let input = if let Some(request) = request { | ||
| let gzip = match request.headers().get(header::CONTENT_ENCODING).map(|h| h.as_bytes()) { | ||
| None | Some(b"identity") => false, | ||
| Some(b"gzip") => true, | ||
| _ => return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response(), | ||
| }; | ||
| let bytes = | ||
| match tokio::time::timeout(Duration::from_secs(10), axum::body::to_bytes(request.into_body(), MAX_REQUEST)) | ||
| .await | ||
| { | ||
| Err(_) => return StatusCode::REQUEST_TIMEOUT.into_response(), | ||
| Ok(Err(_)) => return StatusCode::PAYLOAD_TOO_LARGE.into_response(), | ||
| Ok(Ok(bytes)) => bytes, | ||
| }; | ||
| if gzip { | ||
| use std::io::Read; | ||
| let mut decoded = Vec::new(); | ||
| if flate2::read::GzDecoder::new(bytes.as_ref()) | ||
| .take(MAX_REQUEST as u64 + 1) | ||
| .read_to_end(&mut decoded) | ||
| .is_err() | ||
| { | ||
| return StatusCode::BAD_REQUEST.into_response(); | ||
| } | ||
| if decoded.len() > MAX_REQUEST { | ||
| return StatusCode::PAYLOAD_TOO_LARGE.into_response(); | ||
| } | ||
| Some(Bytes::from(decoded)) | ||
| } else { | ||
| Some(bytes) | ||
| } | ||
| } else { | ||
| None | ||
| }; | ||
| if !dir.is_public() { | ||
| return StatusCode::NOT_FOUND.into_response(); | ||
| } | ||
| let advertise = input.is_none(); | ||
| let mut cmd = Command::from(git_command(&dir)); | ||
| cmd.args(["upload-pack", "--stateless-rpc"]); | ||
| if advertise { | ||
| cmd.arg("--advertise-refs"); | ||
| } | ||
| cmd.arg(".").stdin(Stdio::piped()); | ||
| // Protocol v2 lets a client ask only for the refs it wants instead of hearing every one. | ||
| let v2 = protocol.as_deref().is_some_and(|p| p.split(':').any(|item| item == "version=2")); | ||
| if let Some(protocol) = &protocol { | ||
| cmd.env("GIT_PROTOCOL", protocol); | ||
| } | ||
| let Ok(output) = Output::start(cmd) else { return StatusCode::INTERNAL_SERVER_ERROR.into_response() }; | ||
| // Version 2's capability advertisement stands alone; earlier versions start with the | ||
| // service line (git http-backend does the same). | ||
| let prefix = | ||
| if advertise && !v2 { Bytes::from_static(b"001e# service=git-upload-pack\n0000") } else { Bytes::new() }; | ||
| let body = output.body(prefix, input, permit, Duration::from_secs(300)); | ||
| let kind = | ||
| if advertise { "application/x-git-upload-pack-advertisement" } else { "application/x-git-upload-pack-result" }; | ||
| ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "no-store")], body).into_response() | ||
| } | ||
+325−0
| @@ -0,0 +1,325 @@ | ||
| //! Every page and repeated fragment, as askama templates, which escape everything they are | ||
| //! given unless it is marked `|safe`. Only HTML these templates or the Markdown and | ||
| //! highlighting renderers produced is ever passed as safe. | ||
| use askama::Template; | ||
| /// A page with a heading, a sentence, and optionally a command to copy and a button. | ||
| #[derive(Template)] | ||
| #[template(path = "notice.html")] | ||
| pub(crate) struct Notice<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub heading: &'a str, | ||
| pub message: &'a str, | ||
| pub code: Option<String>, | ||
| pub link: Option<(&'a str, &'a str)>, | ||
| } | ||
| /// A repository's name, clone address and tabs. | ||
| #[derive(Template)] | ||
| #[template(path = "masthead.html")] | ||
| pub(crate) struct Masthead<'a> { | ||
| pub owner: &'a str, | ||
| pub name: &'a str, | ||
| pub home: String, | ||
| /// "Public" or "Private", shown only when signed in. | ||
| pub visibility: Option<&'static str>, | ||
| /// Whether pushes are held to fast-forwards, shown only when signed in. | ||
| pub protected: bool, | ||
| pub description: Option<String>, | ||
| /// Each way to clone it: protocol and address. | ||
| pub addresses: Vec<(&'static str, String)>, | ||
| pub tabs: Vec<Tab>, | ||
| } | ||
| pub(crate) struct Tab { | ||
| pub href: String, | ||
| pub current: bool, | ||
| pub icon: String, | ||
| pub label: &'static str, | ||
| pub count: Option<usize>, | ||
| } | ||
| /// The branch and tag menu, then the path as breadcrumbs. | ||
| #[derive(Template)] | ||
| #[template(path = "locator.html")] | ||
| pub(crate) struct Locator<'a> { | ||
| pub branch_icon: String, | ||
| pub chevron_icon: String, | ||
| /// The reference as people see it. | ||
| pub current: std::borrow::Cow<'a, str>, | ||
| pub branches: Vec<MenuItem<'a>>, | ||
| pub tags: Vec<MenuItem<'a>>, | ||
| /// The repository root's link, when there is a path to show. | ||
| pub root: Option<String>, | ||
| pub repo_name: &'a str, | ||
| pub crumbs: Vec<Crumb<'a>>, | ||
| } | ||
| pub(crate) struct MenuItem<'a> { | ||
| pub href: String, | ||
| pub current: bool, | ||
| pub name: std::borrow::Cow<'a, str>, | ||
| } | ||
| /// One part of a path; the last has no link. | ||
| pub(crate) struct Crumb<'a> { | ||
| pub href: Option<String>, | ||
| pub name: std::borrow::Cow<'a, str>, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "sha-link.html")] | ||
| pub(crate) struct ShaLink<'a> { | ||
| pub href: String, | ||
| pub short: &'a str, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "empty.html")] | ||
| pub(crate) struct Empty<'a> { | ||
| pub title: String, | ||
| pub signed_in: bool, | ||
| pub masthead: String, | ||
| pub host: &'a str, | ||
| pub owner: &'a str, | ||
| pub name: &'a str, | ||
| } | ||
| /// Highlighted source with a gutter of line numbers. Each number is an anchor that links to | ||
| /// itself (`#L<n>`), and the `selected` lines are marked, so the stylesheet can highlight a | ||
| /// linked line or range without any script. | ||
| #[derive(Template)] | ||
| #[template(path = "code.html")] | ||
| pub(crate) struct Code<'a> { | ||
| pub lines: usize, | ||
| pub selected: Option<(usize, usize)>, | ||
| pub code: &'a str, | ||
| } | ||
| impl Code<'_> { | ||
| fn is_selected(&self, n: &usize) -> bool { | ||
| self.selected.is_some_and(|(from, to)| (from..=to).contains(n)) | ||
| } | ||
| } | ||
| /// Preview and Code links for a Markdown file. | ||
| pub(crate) struct Views { | ||
| pub preview: String, | ||
| pub code: String, | ||
| pub as_code: bool, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "blob.html")] | ||
| pub(crate) struct Blob<'a> { | ||
| pub title: String, | ||
| pub signed_in: bool, | ||
| pub masthead: String, | ||
| pub locator: String, | ||
| pub file_icon: String, | ||
| pub name: &'a str, | ||
| pub facts: &'a str, | ||
| pub views: Option<Views>, | ||
| pub history: String, | ||
| pub permalink: String, | ||
| pub raw: String, | ||
| pub content: &'a str, | ||
| } | ||
| pub(crate) struct TagRow<'a> { | ||
| pub name: std::borrow::Cow<'a, str>, | ||
| pub note: Option<std::borrow::Cow<'a, str>>, | ||
| pub sha_link: String, | ||
| pub when: String, | ||
| pub browse: String, | ||
| /// The tagged files as a `.tar.gz`. | ||
| pub archive: String, | ||
| /// A comparison with the previous tag, and its label. | ||
| pub compare: Option<(String, String)>, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "tags.html")] | ||
| pub(crate) struct Tags<'a> { | ||
| pub title: String, | ||
| pub signed_in: bool, | ||
| pub masthead: String, | ||
| pub rows: Vec<TagRow<'a>>, | ||
| } | ||
| /// One file of a commit's diff: its name and link, and its lines when they were read. | ||
| pub(crate) struct DiffFile<'a> { | ||
| pub href: String, | ||
| pub path: std::borrow::Cow<'a, str>, | ||
| pub status: &'static str, | ||
| pub diff: Option<&'a super::views::FileDiff>, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "diff.html")] | ||
| pub(crate) struct Diff<'a> { | ||
| pub file_count: String, | ||
| pub totals: Option<(usize, usize)>, | ||
| pub too_big: bool, | ||
| /// What the changes are, for the note when they're too large: "This commit’s changes". | ||
| pub what: &'static str, | ||
| pub file_icon: String, | ||
| pub files: Vec<DiffFile<'a>>, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "account.html")] | ||
| pub(crate) struct Account<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub user: &'a str, | ||
| pub message: &'a str, | ||
| pub ok: bool, | ||
| pub csrf: &'a str, | ||
| pub min_password: usize, | ||
| } | ||
| #[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: std::borrow::Cow<'a, str>, | ||
| pub url: String, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "compare.html")] | ||
| pub(super) struct Compare<'a> { | ||
| pub title: String, | ||
| pub signed_in: bool, | ||
| pub masthead: String, | ||
| pub action: String, | ||
| pub from: String, | ||
| pub to: String, | ||
| /// Branch and tag names the form suggests. | ||
| pub refs: Vec<String>, | ||
| pub message: Option<String>, | ||
| pub summary: Option<String>, | ||
| pub swap: Option<String>, | ||
| pub rows: Vec<CommitRow<'a>>, | ||
| pub more: Option<String>, | ||
| // Rendered by `Diff`, which escapes repository data. | ||
| pub diff: Option<String>, | ||
| pub tag_icon: 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>>, | ||
| /// A link comparing a branch with the default one, and its label. | ||
| pub compare: Option<(String, String)>, | ||
| 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, | ||
| pub full_date: 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>, | ||
| } | ||
| pub(super) struct RepositoryRow { | ||
| pub owner: String, | ||
| pub name: String, | ||
| pub public: bool, | ||
| pub description: Option<String>, | ||
| pub subject: String, | ||
| pub when: String, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "repositories.html")] | ||
| pub(super) struct Repositories<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub count: String, | ||
| /// The filter as typed, and how many repositories there are to filter. | ||
| pub filter: String, | ||
| pub total: usize, | ||
| pub rows: Vec<RepositoryRow>, | ||
| pub branch: String, | ||
| pub host: &'a str, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "commit.html")] | ||
| pub(super) struct Commit<'a> { | ||
| pub title: &'a str, | ||
| pub signed_in: bool, | ||
| pub masthead: String, | ||
| pub browse: String, | ||
| pub message: &'a str, | ||
| pub author: &'a str, | ||
| pub email: &'a str, | ||
| pub date: &'a str, | ||
| pub short_id: &'a str, | ||
| pub parent_links: String, | ||
| pub diff: &'a str, | ||
| } | ||
| pub(super) struct TreeHead { | ||
| pub author: String, | ||
| pub subject: String, | ||
| pub url: String, | ||
| pub sha_link: String, | ||
| pub when: String, | ||
| pub history: String, | ||
| } | ||
| #[derive(Template)] | ||
| #[template(path = "tree.html")] | ||
| pub(super) struct Tree<'a> { | ||
| pub title: String, | ||
| pub signed_in: bool, | ||
| pub masthead: String, | ||
| pub locator: String, | ||
| pub head: Option<TreeHead>, | ||
| pub up: Option<String>, | ||
| pub rows: Vec<TreeRow<'a>>, | ||
| pub previous: Option<String>, | ||
| pub next: Option<String>, | ||
| pub readme: Option<(String, String)>, | ||
| } | ||
+292−0
| @@ -0,0 +1,292 @@ | ||
| //! Brute-force protection for sign-in, by client, so one attacker can't lock the owner out. | ||
| //! | ||
| //! Each client (an IPv4 address, or an IPv6 /64, which one machine usually controls whole) gets | ||
| //! [`FREE_FAILURES`] failed attempts; each one after that locks that client out for longer, | ||
| //! from a minute up to [`LONGEST_LOCK`]. A client's failures are forgotten after | ||
| //! [`FORGET_AFTER`] without one, so an old attack never turns a later typo into a long lock. | ||
| //! | ||
| //! On top of that, every client together may fail at most [`GLOBAL_PER_HOUR`] times an hour. | ||
| //! That caps how fast a distributed attack can guess. One client, held back by its own lock, | ||
| //! can never reach it alone. Browsers that have signed in before carry a trusted-device token | ||
| //! (see `gitv_web::auth::Credentials::device_token`) and aren't held to this cap, so many | ||
| //! addresses together can't lock the owner out; their own per-client lock still applies. | ||
| //! | ||
| //! Every method takes the current time, so the rules can be tested without waiting. | ||
| use std::collections::{HashMap, VecDeque}; | ||
| use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; | ||
| use std::time::{Duration, Instant}; | ||
| use axum::extract::{ConnectInfo, FromRequestParts}; | ||
| use axum::http::request::Parts; | ||
| use axum::http::{Extensions, HeaderMap}; | ||
| /// Failed attempts a client may make before it is locked out. | ||
| pub const FREE_FAILURES: u32 = 5; | ||
| /// The longest a client's lock lasts; it starts at a minute and doubles with each failure. | ||
| pub const LONGEST_LOCK: Duration = Duration::from_secs(15 * 60); | ||
| /// How long without a failure before a client's count starts again. | ||
| pub const FORGET_AFTER: Duration = Duration::from_secs(60 * 60); | ||
| /// Failures allowed per hour from every client together. | ||
| pub const GLOBAL_PER_HOUR: usize = 60; | ||
| /// Clients remembered at once. Past this, the one quiet longest is forgotten first. | ||
| const MAX_CLIENTS: usize = 4096; | ||
| const HOUR: Duration = Duration::from_secs(60 * 60); | ||
| /// Who is signing in, as far as throttling is concerned: their address, or their IPv6 /64. | ||
| #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
| pub struct Client(IpAddr); | ||
| impl Client { | ||
| pub fn new(address: IpAddr) -> Client { | ||
| Client(match address { | ||
| IpAddr::V6(v6) => match v6.to_ipv4_mapped() { | ||
| Some(v4) => IpAddr::V4(v4), | ||
| None => { | ||
| let prefix = u128::from(v6) & !((1u128 << 64) - 1); | ||
| IpAddr::V6(Ipv6Addr::from(prefix)) | ||
| } | ||
| }, | ||
| v4 => v4, | ||
| }) | ||
| } | ||
| /// The client a request came from. gitv-web listens on loopback behind Caddy, which puts | ||
| /// the real client's address last in `X-Forwarded-For`; that header is believed only from | ||
| /// a loopback peer, since anyone else could write anything there. Without connection | ||
| /// details (as in unit tests) every request is one unknown client. | ||
| pub fn of(headers: &HeaderMap, extensions: &Extensions) -> Client { | ||
| let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|ConnectInfo(addr)| addr.ip()); | ||
| let forwarded = || { | ||
| let header = headers.get_all("x-forwarded-for").iter().next_back()?.to_str().ok()?; | ||
| header.rsplit(',').next()?.trim().parse::<IpAddr>().ok() | ||
| }; | ||
| let address = match peer { | ||
| Some(peer) if peer.is_loopback() => forwarded().unwrap_or(peer), | ||
| Some(peer) => peer, | ||
| None => IpAddr::V4(Ipv4Addr::UNSPECIFIED), | ||
| }; | ||
| Client::new(address) | ||
| } | ||
| } | ||
| /// The address, or the /64 for IPv6, as the logs show it. | ||
| impl std::fmt::Display for Client { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| match self.0 { | ||
| IpAddr::V4(v4) => write!(f, "{v4}"), | ||
| IpAddr::V6(v6) => write!(f, "{v6}/64"), | ||
| } | ||
| } | ||
| } | ||
| impl<S: Send + Sync> FromRequestParts<S> for Client { | ||
| type Rejection = std::convert::Infallible; | ||
| async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Client, Self::Rejection> { | ||
| Ok(Client::of(&parts.headers, &parts.extensions)) | ||
| } | ||
| } | ||
| /// One client's record. | ||
| #[derive(Default)] | ||
| struct Record { | ||
| failures: u32, | ||
| last_failure: Option<Instant>, | ||
| locked_until: Option<Instant>, | ||
| } | ||
| impl Record { | ||
| fn locked_for(&self, now: Instant) -> Option<Duration> { | ||
| self.locked_until.and_then(|until| until.checked_duration_since(now)).filter(|d| !d.is_zero()) | ||
| } | ||
| fn forgotten(&self, now: Instant) -> bool { | ||
| self.locked_for(now).is_none() && self.last_failure.is_none_or(|t| now.duration_since(t) >= FORGET_AFTER) | ||
| } | ||
| fn fail(&mut self, now: Instant) { | ||
| if self.forgotten(now) { | ||
| self.failures = 0; | ||
| } | ||
| self.failures += 1; | ||
| self.last_failure = Some(now); | ||
| if let Some(over) = self.failures.checked_sub(FREE_FAILURES + 1) { | ||
| let lock = Duration::from_secs(60).saturating_mul(1 << over.min(10)).min(LONGEST_LOCK); | ||
| self.locked_until = Some(now + lock); | ||
| } | ||
| } | ||
| } | ||
| #[derive(Default)] | ||
| pub struct Throttle { | ||
| clients: HashMap<Client, Record>, | ||
| /// When the failures of the last hour happened, oldest first, at most [`GLOBAL_PER_HOUR`]. | ||
| recent: VecDeque<Instant>, | ||
| } | ||
| impl Throttle { | ||
| /// How long `client` must wait before trying again, if at all. A `trusted` browser (one that | ||
| /// has signed in before) waits only for its own lock, never the global cap. | ||
| pub fn locked_for(&self, client: Client, now: Instant, trusted: bool) -> Option<Duration> { | ||
| let own = self.clients.get(&client).and_then(|r| r.locked_for(now)); | ||
| let global = (!trusted && self.recent.len() >= GLOBAL_PER_HOUR) | ||
| .then(|| self.recent.front().and_then(|first| (*first + HOUR).checked_duration_since(now))) | ||
| .flatten() | ||
| .filter(|d| !d.is_zero()); | ||
| own.max(global) | ||
| } | ||
| /// Count a failed attempt by `client`. | ||
| pub fn fail(&mut self, client: Client, now: Instant) { | ||
| while self.recent.front().is_some_and(|t| now.duration_since(*t) >= HOUR) { | ||
| self.recent.pop_front(); | ||
| } | ||
| if self.recent.len() >= GLOBAL_PER_HOUR { | ||
| self.recent.pop_front(); | ||
| } | ||
| self.recent.push_back(now); | ||
| self.clients.retain(|_, record| !record.forgotten(now)); | ||
| if self.clients.len() >= MAX_CLIENTS && !self.clients.contains_key(&client) { | ||
| let quietest = self.clients.iter().min_by_key(|(_, r)| r.last_failure).map(|(c, _)| *c); | ||
| if let Some(quietest) = quietest { | ||
| self.clients.remove(&quietest); | ||
| } | ||
| } | ||
| self.clients.entry(client).or_default().fail(now); | ||
| } | ||
| /// `client` got everything right: its own record is cleared. Other clients' are not, and | ||
| /// neither is the global count, which other clients' failures still make up. | ||
| pub fn succeed(&mut self, client: Client) { | ||
| self.clients.remove(&client); | ||
| } | ||
| #[cfg(test)] | ||
| pub fn failures(&self, client: Client) -> u32 { | ||
| self.clients.get(&client).map_or(0, |r| r.failures) | ||
| } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| fn ip(text: &str) -> Client { | ||
| Client::new(text.parse().unwrap()) | ||
| } | ||
| #[test] | ||
| fn a_client_is_locked_after_its_free_failures_and_longer_each_time() { | ||
| let (mut throttle, now, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7")); | ||
| (0..FREE_FAILURES).for_each(|_| throttle.fail(a, now)); | ||
| assert_eq!(throttle.locked_for(a, now, false), None); | ||
| throttle.fail(a, now); | ||
| assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(60))); | ||
| throttle.fail(a, now); | ||
| assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(120))); | ||
| (0..20).for_each(|_| throttle.fail(a, now)); | ||
| assert_eq!(throttle.locked_for(a, now, false), Some(LONGEST_LOCK)); | ||
| } | ||
| #[test] | ||
| fn one_clients_lock_leaves_the_others_alone() { | ||
| let (mut throttle, now) = (Throttle::default(), Instant::now()); | ||
| (0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now)); | ||
| assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some()); | ||
| assert_eq!(throttle.locked_for(ip("198.51.100.1"), now, false), None, "the owner elsewhere isn't locked"); | ||
| } | ||
| #[test] | ||
| fn failures_are_forgotten_after_a_quiet_hour() { | ||
| let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7")); | ||
| (0..12).for_each(|_| throttle.fail(a, start)); | ||
| // Long after the lock ran out and an hour after the last failure, one typo is free. | ||
| let later = start + LONGEST_LOCK + FORGET_AFTER; | ||
| throttle.fail(a, later); | ||
| assert_eq!(throttle.locked_for(a, later, false), None); | ||
| assert_eq!(throttle.failures(a), 1); | ||
| } | ||
| #[test] | ||
| fn failures_inside_the_hour_still_count() { | ||
| let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7")); | ||
| (0..=FREE_FAILURES).for_each(|_| throttle.fail(a, start)); | ||
| // The minute's lock is over, but the next failure comes well inside the hour. | ||
| let later = start + Duration::from_secs(120); | ||
| assert_eq!(throttle.locked_for(a, later, false), None); | ||
| throttle.fail(a, later); | ||
| assert_eq!(throttle.locked_for(a, later, false), Some(Duration::from_secs(120))); | ||
| } | ||
| #[test] | ||
| fn success_clears_only_that_client() { | ||
| let (mut throttle, now) = (Throttle::default(), Instant::now()); | ||
| (0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now)); | ||
| (0..3).for_each(|_| throttle.fail(ip("198.51.100.1"), now)); | ||
| throttle.succeed(ip("198.51.100.1")); | ||
| assert_eq!(throttle.failures(ip("198.51.100.1")), 0); | ||
| assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some(), "the attacker stays locked"); | ||
| } | ||
| #[test] | ||
| fn many_clients_together_are_held_to_the_hourly_rate() { | ||
| let (mut throttle, start) = (Throttle::default(), Instant::now()); | ||
| let owner = ip("198.51.100.1"); | ||
| // Each attacker address stays within its own free failures. | ||
| for i in 0..GLOBAL_PER_HOUR { | ||
| let at = start + Duration::from_secs(i as u64); | ||
| throttle.fail(Client::new(IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i as u32))), at); | ||
| } | ||
| let now = start + Duration::from_secs(GLOBAL_PER_HOUR as u64); | ||
| let wait = throttle.locked_for(owner, now, false).expect("the hourly budget is spent"); | ||
| assert!(wait <= HOUR && wait > HOUR - Duration::from_secs(61), "{wait:?}"); | ||
| assert_eq!(throttle.locked_for(owner, now, true), None, "a browser that signed in before isn't held"); | ||
| // As the oldest failures age out of the hour, attempts are allowed again. | ||
| assert_eq!(throttle.locked_for(owner, start + HOUR, false), None); | ||
| } | ||
| #[test] | ||
| fn a_trusted_browser_is_still_held_by_its_own_lock() { | ||
| let (mut throttle, now, typist) = (Throttle::default(), Instant::now(), ip("198.51.100.2")); | ||
| (0..=FREE_FAILURES).for_each(|_| throttle.fail(typist, now)); | ||
| assert!(throttle.locked_for(typist, now, true).is_some()); | ||
| } | ||
| #[test] | ||
| fn ipv6_clients_are_grouped_by_their_64_and_mapped_ipv4_is_ipv4() { | ||
| assert_eq!(ip("2001:db8:1:2:aaaa::1"), ip("2001:db8:1:2:ffff::9")); | ||
| assert_ne!(ip("2001:db8:1:2::1"), ip("2001:db8:1:3::1")); | ||
| assert_eq!(ip("::ffff:203.0.113.7"), ip("203.0.113.7")); | ||
| } | ||
| #[test] | ||
| fn clients_show_as_their_address_or_64() { | ||
| assert_eq!(ip("203.0.113.7").to_string(), "203.0.113.7"); | ||
| assert_eq!(ip("2001:db8:1:2:aaaa::1").to_string(), "2001:db8:1:2::/64"); | ||
| } | ||
| #[test] | ||
| fn forwarded_addresses_are_believed_only_from_loopback() { | ||
| let parts = |peer: &str, forwarded: Option<&str>| { | ||
| let mut request = axum::http::Request::builder(); | ||
| if let Some(value) = forwarded { | ||
| request = request.header("x-forwarded-for", value); | ||
| } | ||
| let (mut parts, ()) = request.body(()).unwrap().into_parts(); | ||
| parts.extensions.insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap())); | ||
| parts | ||
| }; | ||
| let of = |peer, forwarded| { | ||
| let parts = parts(peer, forwarded); | ||
| Client::of(&parts.headers, &parts.extensions) | ||
| }; | ||
| assert_eq!(of("127.0.0.1:5000", Some("203.0.113.7")), ip("203.0.113.7"), "Caddy's word is taken"); | ||
| assert_eq!(of("127.0.0.1:5000", Some("1.2.3.4, 203.0.113.7")), ip("203.0.113.7"), "the last hop is Caddy's"); | ||
| assert_eq!(of("127.0.0.1:5000", Some("not an address")), ip("127.0.0.1")); | ||
| assert_eq!(of("127.0.0.1:5000", None), ip("127.0.0.1")); | ||
| assert_eq!(of("[::1]:5000", Some("2001:db8::1")), ip("2001:db8::1")); | ||
| assert_eq!(of("192.0.2.5:5000", Some("203.0.113.7")), ip("192.0.2.5"), "nobody else's is"); | ||
| } | ||
| } | ||
+114−0
| @@ -0,0 +1,114 @@ | ||
| //! Query strings, repository paths and URL encoding. | ||
| use std::borrow::Cow; | ||
| use std::collections::HashMap; | ||
| use std::ffi::OsString; | ||
| use std::fmt::Write as _; | ||
| use std::os::unix::ffi::OsStringExt; | ||
| use gitv_core::percent_decode; | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Query strings and paths | ||
| // | ||
| // File paths are bytes, not text: git allows any bytes but `/` and NUL in a name, so a path | ||
| // is decoded from the URL, checked and handed to git without ever passing through UTF-8. | ||
| /// Query parameters with their values percent-decoded to raw bytes. The first of a repeated | ||
| /// key wins. | ||
| pub(crate) type Q = HashMap<String, Vec<u8>>; | ||
| pub(crate) fn parse_query(raw: Option<&str>) -> Q { | ||
| let mut query = Q::new(); | ||
| for pair in raw.unwrap_or("").split('&').filter(|p| !p.is_empty()) { | ||
| let (key, value) = pair.split_once('=').unwrap_or((pair, "")); | ||
| // In a query string `+` is a space; an encoded plus (`%2B`) stays a plus. | ||
| let (key, value) = (key.replace('+', " "), value.replace('+', " ")); | ||
| if let Ok(key) = String::from_utf8(percent_decode(&key)) { | ||
| query.entry(key).or_insert_with(|| percent_decode(&value)); | ||
| } | ||
| } | ||
| query | ||
| } | ||
| /// A text parameter; one that isn't valid UTF-8 counts as absent. | ||
| pub(crate) fn param(q: &Q, key: &str) -> Option<String> { | ||
| q.get(key).and_then(|v| String::from_utf8(v.clone()).ok()) | ||
| } | ||
| pub(crate) fn encode(value: &[u8]) -> String { | ||
| let mut out = String::with_capacity(value.len()); | ||
| for &b in value { | ||
| match b { | ||
| b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char), | ||
| _ => { | ||
| let _ = write!(out, "%{b:02X}"); | ||
| } | ||
| } | ||
| } | ||
| out | ||
| } | ||
| /// A repository-relative path with no `.`, `..`, empty or absolute parts and no NUL. | ||
| pub(crate) fn clean_path(value: &[u8]) -> Option<Vec<u8>> { | ||
| let parts: Vec<&[u8]> = value.split(|b| *b == b'/').filter(|p| !p.is_empty()).collect(); | ||
| if parts.iter().any(|p| *p == b"." || *p == b".." || p.contains(&0)) { | ||
| return None; | ||
| } | ||
| Some(parts.join(&b'/')) | ||
| } | ||
| pub(crate) fn parent_of(path: &[u8]) -> &[u8] { | ||
| path.iter().rposition(|b| *b == b'/').map_or(&[], |i| &path[..i]) | ||
| } | ||
| pub(crate) fn file_name(path: &[u8]) -> &[u8] { | ||
| path.iter().rposition(|b| *b == b'/').map_or(path, |i| &path[i + 1..]) | ||
| } | ||
| pub(crate) fn join(dir: &[u8], name: &[u8]) -> Vec<u8> { | ||
| if dir.is_empty() { name.to_vec() } else { [dir, b"/", name].concat() } | ||
| } | ||
| /// Bytes for display. Names that aren't UTF-8 show replacement characters, but links keep | ||
| /// the real bytes. | ||
| pub(crate) fn lossy(bytes: &[u8]) -> Cow<'_, str> { | ||
| String::from_utf8_lossy(bytes) | ||
| } | ||
| /// `<commit>:<path>` for git, path bytes intact. | ||
| pub(crate) fn spec(commit: &str, path: &[u8]) -> OsString { | ||
| let mut spec = format!("{commit}:").into_bytes(); | ||
| spec.extend_from_slice(path); | ||
| OsString::from_vec(spec) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn percent_decoding_keeps_raw_bytes() { | ||
| assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings"); | ||
| assert_eq!(parse_query(Some("p=a+b%2Bc"))["p"], b"a b+c"); | ||
| assert_eq!(percent_decode("caf%C3%A9"), "café".as_bytes()); | ||
| assert_eq!(percent_decode("%FF%00"), [0xff, 0]); | ||
| assert_eq!(percent_decode("100%"), b"100%"); | ||
| assert_eq!(percent_decode("%zz%4"), b"%zz%4"); | ||
| } | ||
| #[test] | ||
| fn query_first_value_wins() { | ||
| let q = parse_query(Some("path=a&path=b&ref=main&flag")); | ||
| assert_eq!(q["path"], b"a"); | ||
| assert_eq!(param(&q, "ref").as_deref(), Some("main")); | ||
| assert_eq!(q["flag"], b""); | ||
| } | ||
| #[test] | ||
| fn paths_are_cleaned_as_bytes() { | ||
| assert_eq!(clean_path(b"/a//b/"), Some(b"a/b".to_vec())); | ||
| assert_eq!(clean_path(b"a/../b"), None); | ||
| assert_eq!(clean_path(b"./a"), None); | ||
| assert_eq!(clean_path(b"a\0b"), None); | ||
| assert_eq!(clean_path(&[0xff, b'/', b'x']), Some(vec![0xff, b'/', b'x'])); | ||
| assert_eq!(encode(&[b'a', b' ', 0xff, b'/']), "a%20%FF/"); | ||
| } | ||
| } | ||
+48−0
| @@ -0,0 +1,48 @@ | ||
| //! A revision's files as a `.tar.gz`, made by `git archive`. | ||
| use super::Repo; | ||
| use crate::View; | ||
| use crate::urls::Q; | ||
| pub(crate) fn view_archive(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = q.get("ref")?; | ||
| let commit = repo.reader.resolve(reference)?; | ||
| let base = format!("{}-{}", repo.name, archive_label(reference, &commit)); | ||
| let prefix = format!("--prefix={base}/"); | ||
| let mut command = gitv_core::git_command(&repo.reader.dir); | ||
| // The commit id, not the name: what's archived is exactly what was resolved, and the | ||
| // archive's file times are that commit's time, so the same revision always gives the | ||
| // same bytes. | ||
| command.args(["archive", "--format=tar.gz", &prefix, &commit, "--"]); | ||
| Some(View::Archive(Box::new(command), format!("{base}.tar.gz"))) | ||
| } | ||
| /// The revision's part of the archive's name: a branch or tag name with `refs/…` dropped, or a | ||
| /// short id for a commit id. Only letters, digits and `.`, `_`, `+`, `-` are kept, so the name | ||
| /// is safe as a file name and inside a quoted header. | ||
| pub(crate) fn archive_label(reference: &[u8], commit: &str) -> String { | ||
| let name = | ||
| reference.strip_prefix(b"refs/tags/").or_else(|| reference.strip_prefix(b"refs/heads/")).unwrap_or(reference); | ||
| if name.eq_ignore_ascii_case(commit.as_bytes()) { | ||
| return commit[..12].to_string(); | ||
| } | ||
| let label: String = | ||
| name.iter().map(|&b| if b.is_ascii_alphanumeric() || b"._+-".contains(&b) { b as char } else { '-' }).collect(); | ||
| let label = label.trim_matches(['-', '.']); | ||
| if label.is_empty() { commit[..12].to_string() } else { label.to_string() } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn archive_names_are_plain_file_names() { | ||
| let id = "0123456789abcdef0123456789abcdef01234567"; | ||
| assert_eq!(archive_label(b"refs/tags/v1.2.0", id), "v1.2.0"); | ||
| assert_eq!(archive_label(b"release/2.0", id), "release-2.0"); | ||
| assert_eq!(archive_label(b"caf\xc3\xa9 \"quoted\"", id), "caf----quoted"); | ||
| assert_eq!(archive_label(b"..", id), "0123456789ab"); | ||
| assert_eq!(archive_label(id.to_uppercase().as_bytes(), id), "0123456789ab"); | ||
| } | ||
| } | ||
+125−0
| @@ -0,0 +1,125 @@ | ||
| //! A file, highlighted or rendered, and its raw download. | ||
| use gitv_web::render; | ||
| use super::tree::{Rendered, render_file}; | ||
| use super::{RAW_LIMIT, Repo, SHOW_LIMIT, entry}; | ||
| use crate::html::{icon, size}; | ||
| use crate::urls::{Q, clean_path, file_name, lossy, param, parent_of}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| let reference = repo.reference(q); | ||
| let path = clean_path(q.get("path")?)?; | ||
| let commit = repo.reader.resolve(&reference)?; | ||
| let item = entry(repo, &commit, &path)?; | ||
| match item.kind.as_str() { | ||
| "blob" => {} | ||
| // Markdown links can't tell files from folders, so a file link to a folder lands here. | ||
| "tree" => return Some(View::Redirect(repo.url_at("tree", &reference, &path, ""))), | ||
| _ => return None, | ||
| } | ||
| let name = lossy(file_name(&path)).into_owned(); | ||
| if raw { | ||
| if item.size > RAW_LIMIT { | ||
| let message = format!("{name} is {}. Clone the repository to get it.", size(item.size)); | ||
| return Some(View::Html( | ||
| templates::Notice { | ||
| title: "File too large", | ||
| signed_in: repo.signed_in, | ||
| heading: "This file is too large to download here", | ||
| message: &message, | ||
| code: Some(format!("git clone {}", repo.clone_address().1)), | ||
| link: None, | ||
| } | ||
| .to_string(), | ||
| )); | ||
| } | ||
| let mut command = gitv_core::git_command(&repo.reader.dir); | ||
| command.args(["cat-file", "blob", &item.oid]); | ||
| return Some(View::Raw(Box::new(command), item.size, file_name(&path).to_vec())); | ||
| } | ||
| let too_big = item.size > SHOW_LIMIT; | ||
| let markdown = !too_big && render::is_markdown(&name); | ||
| let as_code = !markdown || param(q, "view").as_deref() == Some("code"); | ||
| let selected = param(q, "lines").and_then(|value| line_range(&value)); | ||
| let rendered = if too_big { | ||
| Rendered { | ||
| facts: size(item.size), | ||
| html: r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"#.into(), | ||
| } | ||
| } else { | ||
| render_file(repo, &item.oid, item.size, &name, parent_of(&path), &reference, as_code, selected)? | ||
| }; | ||
| let views = markdown.then(|| templates::Views { | ||
| preview: repo.url_at("blob", &reference, &path, ""), | ||
| code: repo.url_at("blob", &reference, &path, "view=code"), | ||
| as_code, | ||
| }); | ||
| Some(View::Html( | ||
| templates::Blob { | ||
| title: format!("{} at {}", lossy(&path), lossy(&reference)), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("tree", &reference, Some(&commit)), | ||
| locator: repo.locator("blob", &reference, &path), | ||
| file_icon: icon("file"), | ||
| name: &name, | ||
| facts: &rendered.facts, | ||
| views, | ||
| history: repo.url_at("log", &reference, &path, ""), | ||
| permalink: repo.url_at("blob", commit.as_bytes(), &path, &pinned_extra(markdown && as_code, selected)), | ||
| raw: repo.url_at("raw", &reference, &path, ""), | ||
| content: &rendered.html, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// The lines a `lines` parameter selects: `12` or `12-20`, counted from 1. A range given | ||
| /// backwards is read forwards. Anything else selects nothing rather than failing the page. | ||
| fn line_range(value: &str) -> Option<(usize, usize)> { | ||
| let (from, to) = value.split_once('-').unwrap_or((value, value)); | ||
| let (from, to): (usize, usize) = (from.parse().ok()?, to.parse().ok()?); | ||
| (from > 0 && to > 0).then(|| (from.min(to), from.max(to))) | ||
| } | ||
| /// What a permalink keeps of this view: the Code view of a Markdown file, and the selected | ||
| /// lines, scrolled to the first of them. | ||
| fn pinned_extra(code_view: bool, selected: Option<(usize, usize)>) -> String { | ||
| let mut extra = Vec::new(); | ||
| if code_view { | ||
| extra.push("view=code".to_string()); | ||
| } | ||
| if let Some((from, to)) = selected { | ||
| extra.push(if from == to { format!("lines={from}") } else { format!("lines={from}-{to}") }); | ||
| } | ||
| let mut extra = extra.join("&"); | ||
| if let Some((from, _)) = selected { | ||
| extra.push_str(&format!("#L{from}")); | ||
| } | ||
| extra | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn line_ranges_are_read_leniently() { | ||
| assert_eq!(line_range("12"), Some((12, 12))); | ||
| assert_eq!(line_range("12-20"), Some((12, 20))); | ||
| assert_eq!(line_range("20-12"), Some((12, 20))); | ||
| for bad in ["", "0", "0-3", "a", "3-", "-3", "1-2-3", "99999999999999999999999"] { | ||
| assert_eq!(line_range(bad), None, "{bad}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn permalinks_keep_the_view_and_the_lines() { | ||
| assert_eq!(pinned_extra(false, None), ""); | ||
| assert_eq!(pinned_extra(true, Some((4, 4))), "view=code&lines=4#L4"); | ||
| assert_eq!(pinned_extra(false, Some((4, 9))), "lines=4-9#L4"); | ||
| } | ||
| } | ||
+232−0
| @@ -0,0 +1,232 @@ | ||
| //! One commit and its changes. | ||
| use gitv_core::git_capped; | ||
| use super::{DIFF_LIMIT, Repo}; | ||
| use crate::cache::cached; | ||
| use crate::html::{icon, plural, subject_or_placeholder}; | ||
| use crate::urls::{Q, lossy, param}; | ||
| use crate::{View, templates}; | ||
| /// One changed file: how git names it (raw bytes, from NUL-delimited output) and its status. | ||
| pub(crate) struct Change { | ||
| pub(crate) status: &'static str, | ||
| pub(crate) path: Vec<u8>, | ||
| } | ||
| /// Parse `git show -z --name-status`: a status (`M`, `A`, `D`, `R100`, ...) then one path, or | ||
| /// two (old and new) for renames and copies. | ||
| pub(crate) fn parse_changes(out: &[u8]) -> Vec<Change> { | ||
| let mut fields = out.split(|b| *b == 0).filter(|f| !f.is_empty()); | ||
| let mut changes = Vec::new(); | ||
| while let Some(code) = fields.next() { | ||
| let (status, paths) = match code.first() { | ||
| Some(b'A') => ("Added", 1), | ||
| Some(b'D') => ("Deleted", 1), | ||
| Some(b'R') => ("Renamed", 2), | ||
| Some(b'C') => ("Copied", 2), | ||
| _ => ("", 1), | ||
| }; | ||
| let mut path = None; | ||
| for _ in 0..paths { | ||
| path = fields.next(); | ||
| } | ||
| let Some(path) = path else { break }; | ||
| changes.push(Change { status, path: path.to_vec() }); | ||
| } | ||
| changes | ||
| } | ||
| /// One line of a diff: `hunk`, `add`, `del` or `ctx`, its old and new line numbers (empty | ||
| /// where it has none), and its text. | ||
| pub(crate) struct DiffLine { | ||
| pub(crate) class: &'static str, | ||
| pub(crate) old: String, | ||
| pub(crate) new: String, | ||
| pub(crate) text: String, | ||
| } | ||
| impl DiffLine { | ||
| fn new(class: &'static str, old: String, new: String, text: &str) -> DiffLine { | ||
| DiffLine { class, old, new, text: text.to_string() } | ||
| } | ||
| /// The mark the page shows before the line. | ||
| pub(crate) fn sign(&self) -> &'static str { | ||
| match self.class { | ||
| "add" => "+", | ||
| "del" => "-", | ||
| _ => " ", | ||
| } | ||
| } | ||
| } | ||
| /// The lines of one file's diff: (class, old number, new number, text). | ||
| pub(crate) struct FileDiff { | ||
| pub(crate) rows: Vec<DiffLine>, | ||
| pub(crate) added: usize, | ||
| pub(crate) removed: usize, | ||
| pub(crate) binary: bool, | ||
| } | ||
| /// Split `git show` patch output into one entry per `diff --git` section, in order. Names come | ||
| /// from [`parse_changes`], not from these human-readable headers, which quote or misplace odd names. | ||
| pub(crate) fn parse_diff(text: &str) -> Vec<FileDiff> { | ||
| let mut files: Vec<FileDiff> = Vec::new(); | ||
| let (mut old, mut new) = (0usize, 0usize); | ||
| for line in text.lines() { | ||
| if line.starts_with("diff --git ") { | ||
| files.push(FileDiff { rows: Vec::new(), added: 0, removed: 0, binary: false }); | ||
| continue; | ||
| } | ||
| let Some(file) = files.last_mut() else { continue }; | ||
| let in_hunk = !file.rows.is_empty(); | ||
| if !in_hunk && line.starts_with("Binary files ") { | ||
| file.binary = true; | ||
| } else if line.starts_with("@@") { | ||
| let nums: Vec<usize> = line | ||
| .split_whitespace() | ||
| .skip(1) | ||
| .take(2) | ||
| .map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0)) | ||
| .collect(); | ||
| (old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0)); | ||
| file.rows.push(DiffLine::new("hunk", String::new(), String::new(), line)); | ||
| } else if !in_hunk { | ||
| continue; | ||
| } else if let Some(t) = line.strip_prefix('+') { | ||
| file.rows.push(DiffLine::new("add", String::new(), new.to_string(), t)); | ||
| new += 1; | ||
| file.added += 1; | ||
| } else if let Some(t) = line.strip_prefix('-') { | ||
| file.rows.push(DiffLine::new("del", old.to_string(), String::new(), t)); | ||
| old += 1; | ||
| file.removed += 1; | ||
| } else if let Some(t) = line.strip_prefix(' ') { | ||
| file.rows.push(DiffLine::new("ctx", old.to_string(), new.to_string(), t)); | ||
| old += 1; | ||
| new += 1; | ||
| } | ||
| } | ||
| files | ||
| } | ||
| pub(crate) fn view_commit(repo: &Repo, q: &Q) -> Option<View> { | ||
| let id = param(q, "id")?; | ||
| // Any case: ids are hex, and the lookup reads them in lower case. | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) { | ||
| return None; | ||
| } | ||
| // Looked up as an object only: a branch named like this id can't redirect the page. | ||
| let commit = repo.reader.commit_object(&id)?; | ||
| // NUL between fields: a commit message can't contain one, so the subject and body can hold | ||
| // any other byte, the separator git output elsewhere uses included. | ||
| let meta = repo.reader.git(&[ | ||
| "show", | ||
| "-s", | ||
| "--date=format:%-d %b %Y, %H:%M", | ||
| "--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b", | ||
| &commit, | ||
| ])?; | ||
| let f: Vec<&str> = meta.splitn(7, '\0').collect(); | ||
| let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; | ||
| let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" "); | ||
| // A commit's diff never changes, so its rendering is cached. If git can't produce it, the | ||
| // page still shows the commit, with a note. | ||
| let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents)) | ||
| .unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into()); | ||
| Some(View::Html( | ||
| templates::Commit { | ||
| title: subject_or_placeholder(subject), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("log", &repo.reader.default_ref(), None), | ||
| browse: repo.url("tree", &[("ref", oid)]), | ||
| message: message.trim(), | ||
| author, | ||
| email, | ||
| date, | ||
| short_id: oid.get(..12)?, | ||
| parent_links, | ||
| diff: &diff, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// A commit's changes as one panel per file. | ||
| pub(crate) fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> { | ||
| // A merge shows what it brought in relative to its first parent. | ||
| let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"]; | ||
| let names = [&["show", "-z", "--name-status"][..], &options, &[oid]].concat(); | ||
| let patch = [&["show", "--patch"][..], &options, &[oid]].concat(); | ||
| // A deleted file still exists in the parent commit. | ||
| let parent = parents.split_whitespace().next().unwrap_or(oid); | ||
| render_changes(repo, &names, &patch, parent, oid, "This commit’s changes") | ||
| } | ||
| /// The changes from commit `old` to commit `new` as one panel per file, for a comparison. | ||
| pub(crate) fn render_diff_between(repo: &Repo, old: &str, new: &str) -> Option<String> { | ||
| let options = ["--no-color", "-M", old, new, "--"]; | ||
| let names = [&["diff", "-z", "--name-status"][..], &options].concat(); | ||
| let patch = [&["diff", "--patch"][..], &options].concat(); | ||
| render_changes(repo, &names, &patch, old, new, "These changes") | ||
| } | ||
| /// Changes as one panel per file, from git's `names` (NUL-delimited `--name-status`) and | ||
| /// `patch` listings of the same diff. Files link to `new`, or to `old` when deleted. Only | ||
| /// [`DIFF_LIMIT`] bytes of patch are read; past that the files are listed without their lines. | ||
| fn render_changes( | ||
| repo: &Repo, | ||
| names: &[&str], | ||
| patch: &[&str], | ||
| old: &str, | ||
| new: &str, | ||
| what: &'static str, | ||
| ) -> Option<String> { | ||
| let names = repo.reader.git_bytes(names)?; | ||
| let changes = parse_changes(&names); | ||
| let (patch, too_big) = git_capped(&repo.reader.dir, patch, DIFF_LIMIT).ok()?; | ||
| let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) }; | ||
| // The two listings come from the same diff, in the same order; if they ever disagree, show | ||
| // names only rather than pair lines with the wrong file. | ||
| let paired = files.len() == changes.len(); | ||
| let panels: Vec<templates::DiffFile> = changes | ||
| .iter() | ||
| .enumerate() | ||
| .map(|(i, change)| { | ||
| let at = if change.status == "Deleted" { old } else { new }; | ||
| templates::DiffFile { | ||
| href: repo.url_at("blob", at.as_bytes(), &change.path, ""), | ||
| path: lossy(&change.path), | ||
| status: change.status, | ||
| diff: files.get(i).filter(|_| paired), | ||
| } | ||
| }) | ||
| .collect(); | ||
| let totals = paired.then(|| files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed))); | ||
| let diff = templates::Diff { | ||
| file_count: plural(changes.len(), "file", "files"), | ||
| totals, | ||
| too_big, | ||
| what, | ||
| file_icon: icon("file"), | ||
| files: panels, | ||
| }; | ||
| Some(diff.to_string()) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn name_status_parsing() { | ||
| let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0"; | ||
| let changes = parse_changes(out); | ||
| let got: Vec<(&str, &[u8])> = changes.iter().map(|c| (c.status, c.path.as_slice())).collect(); | ||
| assert_eq!( | ||
| got, | ||
| [("", &b"src/a b.rs"[..]), ("Renamed", b"new\tname"), ("Deleted", b"gone"), ("Added", b"\xffbin")] | ||
| ); | ||
| } | ||
| } | ||
+101−0
| @@ -0,0 +1,101 @@ | ||
| //! Two revisions compared: the commits one has that the other lacks, and what changed. | ||
| use super::Repo; | ||
| use super::commit::render_diff_between; | ||
| use super::log::commit_rows; | ||
| use crate::cache::cached; | ||
| use crate::html::{icon, plural}; | ||
| use crate::repository::Head; | ||
| use crate::urls::{Q, lossy}; | ||
| use crate::{View, templates}; | ||
| /// The most commits a comparison lists; the diff still covers all of them. | ||
| const COMPARE_COMMITS: usize = 250; | ||
| pub(crate) fn view_compare(repo: &Repo, q: &Q) -> Option<View> { | ||
| let given = |key| q.get(key).filter(|v| !v.is_empty()).cloned(); | ||
| let from = given("from"); | ||
| // Only `from` is needed: comparing against the default branch is the common case. | ||
| let to = given("to").or_else(|| from.as_ref().map(|_| repo.reader.default_ref())); | ||
| // A branch and a tag may share a name; suggest it once. | ||
| let mut seen = std::collections::HashSet::new(); | ||
| let refs: Vec<String> = repo | ||
| .reader | ||
| .heads() | ||
| .iter() | ||
| .chain(repo.reader.tags()) | ||
| .map(|name| lossy(name).into_owned()) | ||
| .filter(|name| seen.insert(name.clone())) | ||
| .collect(); | ||
| let mut page = templates::Compare { | ||
| title: "Compare revisions".into(), | ||
| signed_in: repo.signed_in, | ||
| masthead: String::new(), | ||
| action: repo.url("compare", &[]), | ||
| from: from.as_deref().map(lossy).unwrap_or_default().into_owned(), | ||
| to: to.as_deref().map(lossy).unwrap_or_default().into_owned(), | ||
| refs, | ||
| message: None, | ||
| summary: None, | ||
| swap: None, | ||
| rows: Vec::new(), | ||
| more: None, | ||
| diff: None, | ||
| tag_icon: icon("tag"), | ||
| }; | ||
| let (Some(from), Some(to)) = (from, to) else { | ||
| page.masthead = repo.masthead("log", &repo.reader.default_ref(), None); | ||
| return Some(View::Html(page.to_string())); | ||
| }; | ||
| let resolved = (repo.reader.resolve(&from), repo.reader.resolve(&to)); | ||
| let (Some(old), Some(new)) = resolved else { | ||
| let missing = if resolved.0.is_none() { &from } else { &to }; | ||
| page.masthead = repo.masthead("log", &repo.reader.default_ref(), None); | ||
| page.message = Some(format!("There’s no branch, tag or commit named {}.", lossy(missing))); | ||
| return Some(View::Html(page.to_string())); | ||
| }; | ||
| let (from_name, to_name) = (page.from.clone(), page.to.clone()); | ||
| page.title = format!("Comparing {from_name}...{to_name}"); | ||
| page.masthead = repo.masthead("log", &to, Some(&new)); | ||
| page.swap = Some(repo.compare_url(&to, &from)); | ||
| // Both ids are commits, so these results never change and are cached by them. | ||
| let span = format!("{old}...{new}"); | ||
| let counts = cached(repo.key("ahead", &span, ""), || { | ||
| repo.reader.git(&["rev-list", "--left-right", "--count", &span, "--"]).map(|out| out.trim().to_string()) | ||
| })?; | ||
| let (behind, ahead) = counts.split_once('\t')?; | ||
| let (behind, ahead): (usize, usize) = (behind.parse().ok()?, ahead.parse().ok()?); | ||
| // Unrelated histories have no merge base; their trees are then compared directly. | ||
| let base = | ||
| cached(repo.key("base", &span, ""), || repo.reader.git(&["merge-base", &old, &new]).map(|o| o.trim().into())); | ||
| let commits = plural(ahead, "commit", "commits"); | ||
| page.summary = Some(match (&base, ahead, behind) { | ||
| _ if old == new => format!("{from_name} and {to_name} are the same commit."), | ||
| (None, ..) => format!( | ||
| "{to_name} and {from_name} share no history. The {commits} below are all of {to_name}’s, \ | ||
| and the changes compare the two directly." | ||
| ), | ||
| (_, 0, _) => format!("{to_name} has no commits that {from_name} lacks."), | ||
| (_, _, 0) => format!("{to_name} is {commits} ahead of {from_name}."), | ||
| (_, _, behind) => format!( | ||
| "{to_name} is {commits} ahead of {from_name} and {} behind it. The changes are {to_name}’s since \ | ||
| the two diverged.", | ||
| plural(behind, "commit", "commits") | ||
| ), | ||
| }); | ||
| if ahead == 0 { | ||
| return Some(View::Html(page.to_string())); | ||
| } | ||
| let range = format!("{old}..{new}"); | ||
| let count = format!("-n{COMPARE_COMMITS}"); | ||
| let log = repo.reader.git(&["log", &count, "--date=format:%-d %b %Y", Head::FORMAT, &range, "--"])?; | ||
| page.rows = commit_rows(repo, &log, COMPARE_COMMITS); | ||
| page.more = (ahead > COMPARE_COMMITS).then(|| format!("Showing the newest {COMPARE_COMMITS} of {ahead} commits.")); | ||
| let start = base.as_deref().map_or(old.as_str(), |b| b); | ||
| let diff = cached(repo.key("compare", &format!("{start}..{new}"), ""), || render_diff_between(repo, start, &new)) | ||
| .map_or_else(|| r#"<p class="note">These changes couldn’t be read.</p>"#.to_string(), |d| d.to_string()); | ||
| page.diff = Some(diff); | ||
| Some(View::Html(page.to_string())) | ||
| } | ||
+219−0
| @@ -0,0 +1,219 @@ | ||
| //! The repository index. | ||
| use std::cmp::Reverse; | ||
| use std::ffi::OsStr; | ||
| use std::fmt::Write as _; | ||
| use std::os::fd::{AsFd, OwnedFd}; | ||
| use std::sync::Arc; | ||
| use std::time::{Instant, SystemTime, UNIX_EPOCH}; | ||
| use gitv_core::{RepoDir, config, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs}; | ||
| use super::Repo; | ||
| use crate::cache::cached; | ||
| use crate::html::{ago, icon, plural, subject_or_placeholder}; | ||
| use crate::repository::Head; | ||
| use crate::urls::{Q, param}; | ||
| use crate::{View, templates}; | ||
| /// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8 | ||
| /// (no valid owner or repository name is). | ||
| pub(crate) fn sorted_names(dir: &impl AsFd) -> Vec<String> { | ||
| let mut names: Vec<String> = | ||
| entries(dir).into_iter().filter_map(|n| n.into_string().ok()).filter(|n| !n.starts_with('.')).collect(); | ||
| names.sort(); | ||
| names | ||
| } | ||
| /// A fingerprint of a repository's branches, for caching its row on the index. Git updates a | ||
| /// ref by renaming a file into place (a loose ref under `refs/heads`, or `packed-refs` and | ||
| /// `HEAD` in the repository directory, or a table under `reftable`), and a rename changes the | ||
| /// directory's modification time. So the times of those directories change whenever a branch | ||
| /// or HEAD does. It reads them through the repository's open handle, the same directory git | ||
| /// reads, never through a path. The current minute is included too, which bounds staleness | ||
| /// should two pushes land within the filesystem's timestamp granularity. | ||
| pub(crate) fn refs_fingerprint(repo: &RepoDir) -> Option<String> { | ||
| /// Append a directory's modification time. | ||
| pub(crate) fn note(stamp: &mut String, dir: &impl AsFd) -> Option<()> { | ||
| let meta = nix::sys::stat::fstat(dir.as_fd()).ok()?; | ||
| let _ = write!(stamp, ":{}.{}", meta.st_mtime, meta.st_mtime_nsec); | ||
| Some(()) | ||
| } | ||
| /// Note `dir` and every directory under it, depth first, holding open only the directories | ||
| /// on the current path, never all the siblings at once. Any directory that can't be read | ||
| /// makes the whole fingerprint `None`, so a partial one is never trusted. | ||
| pub(crate) fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> { | ||
| note(stamp, dir)?; | ||
| let mut names = try_subdirs(dir).ok()?; | ||
| names.sort(); | ||
| // Ref files (and entries deleted since the listing) are covered by their directory's | ||
| // time; only subdirectories need visiting. | ||
| for name in names { | ||
| stamp.push('/'); | ||
| walk(stamp, &open_dir_at(dir, &name).ok()?)?; | ||
| } | ||
| Some(()) | ||
| } | ||
| /// A directory that may legitimately be absent: absent is a fact, unreadable is not. | ||
| pub(crate) fn optional(parent: &impl AsFd, name: &str) -> Option<Option<OwnedFd>> { | ||
| match open_dir_at(parent, OsStr::new(name)) { | ||
| Ok(dir) => Some(Some(dir)), | ||
| Err(nix::errno::Errno::ENOENT) => Some(None), | ||
| Err(_) => None, | ||
| } | ||
| } | ||
| let minute = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() / 60; | ||
| let mut stamp = format!("{minute}"); | ||
| note(&mut stamp, &repo.handle())?; | ||
| let refs = optional(&repo.handle(), "refs")?; | ||
| for dir in [refs.as_ref(), optional(&repo.handle(), "reftable")?.as_ref()] { | ||
| match dir { | ||
| Some(dir) => note(&mut stamp, dir)?, | ||
| None => stamp.push_str(":-"), | ||
| } | ||
| } | ||
| if let Some(refs) = refs.as_ref() | ||
| && let Some(heads) = optional(refs, "heads")? | ||
| { | ||
| walk(&mut stamp, &heads)?; | ||
| } | ||
| Some(stamp) | ||
| } | ||
| /// One row of the index: everything it shows, and no open repository handle, so a large | ||
| /// installation holds one handle at a time however many repositories it lists. | ||
| pub(crate) struct Row { | ||
| pub(crate) public: bool, | ||
| pub(crate) owner: String, | ||
| pub(crate) name: String, | ||
| pub(crate) description: Option<String>, | ||
| pub(crate) head: Option<Head>, | ||
| } | ||
| /// Whether a repository matches a filter: every word of it appears, ignoring case, in the | ||
| /// repository's `owner/name` or its description. | ||
| fn matches(words: &[String], owner: &str, name: &str, description: Option<&str>) -> bool { | ||
| let haystack = format!("{owner}/{name} {}", description.unwrap_or_default()).to_lowercase(); | ||
| words.iter().all(|word| haystack.contains(word.as_str())) | ||
| } | ||
| pub(crate) fn view_index(signed_in: bool, q: &Q) -> View { | ||
| let deadline = Instant::now() + gitv_core::GIT_TIMEOUT; | ||
| let filter = param(q, "q").unwrap_or_default(); | ||
| let words: Vec<String> = filter.split_whitespace().map(str::to_lowercase).collect(); | ||
| let mut total = 0; | ||
| let mut rows = Vec::new(); | ||
| let root = open_root(); | ||
| for owner in root.as_ref().map(sorted_names).unwrap_or_default() { | ||
| // Read through the owner's open directory: a symlinked owner isn't followed or listed. | ||
| let Some(owner_dir) = open_owner(&owner) else { continue }; | ||
| for entry in sorted_names(&owner_dir) { | ||
| let Some(name) = entry.strip_suffix(".git") else { continue }; | ||
| if Instant::now() >= deadline { | ||
| return View::Busy; | ||
| } | ||
| let Some(mut dir) = repo_in(&owner_dir, &owner, name) else { continue }; | ||
| let public = dir.is_public(); | ||
| if !signed_in && !public { | ||
| continue; | ||
| } | ||
| total += 1; | ||
| // Filtered before any git runs, so a narrow filter is cheap however many there are. | ||
| let description = dir.description(); | ||
| if !matches(&words, &owner, name, description.as_deref()) { | ||
| continue; | ||
| } | ||
| dir.limit_until(deadline); | ||
| let repo = Repo::from_dir(&owner, name, dir); | ||
| // HEAD usually names a real branch; only look further when it doesn't. An empty | ||
| // repository caches as an empty answer. | ||
| let lookup = || { | ||
| let latest = repo.reader.latest_raw("HEAD", b"").or_else(|| { | ||
| repo.reader.resolve(&repo.reader.default_ref()).and_then(|id| repo.reader.latest_raw(&id, b"")) | ||
| }); | ||
| (Instant::now() < deadline).then(|| latest.unwrap_or_default()) | ||
| }; | ||
| let raw = match refs_fingerprint(&repo.reader.dir) { | ||
| Some(stamp) => cached(format!("index:{}:{stamp}", repo.reader.dir.path.display()), lookup), | ||
| None => lookup().map(Arc::from), | ||
| }; | ||
| let head = raw.as_deref().and_then(Head::parse); | ||
| // `repo`, and with it the directory handle, is dropped here. | ||
| rows.push(Row { public, owner: owner.clone(), name: name.to_string(), description, head }); | ||
| } | ||
| } | ||
| rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0))); | ||
| let count = if words.is_empty() { | ||
| plural(rows.len(), "repository", "repositories") | ||
| } else { | ||
| format!("{} of {total}", rows.len()) | ||
| }; | ||
| let rows = rows | ||
| .into_iter() | ||
| .map(|row| { | ||
| let (subject, when) = row.head.map_or_else( | ||
| || ("No commits yet".into(), String::new()), | ||
| |h| (subject_or_placeholder(&h.subject).into(), ago(&h.stamp, &h.date)), | ||
| ); | ||
| templates::RepositoryRow { | ||
| owner: row.owner, | ||
| name: row.name, | ||
| public: row.public, | ||
| description: row.description, | ||
| subject, | ||
| when, | ||
| } | ||
| }) | ||
| .collect(); | ||
| View::Html( | ||
| templates::Repositories { | ||
| title: "Repositories", | ||
| signed_in, | ||
| count, | ||
| filter: filter.trim().to_string(), | ||
| total, | ||
| rows, | ||
| branch: icon("branch"), | ||
| host: config::host(), | ||
| } | ||
| .to_string(), | ||
| ) | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn filters_match_every_word_in_the_name_or_description() { | ||
| let words = |q: &str| q.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>(); | ||
| assert!(matches(&words(""), "ada", "tools", None)); | ||
| assert!(matches(&words("TOOL"), "ada", "tools", None)); | ||
| assert!(matches(&words("ada/to"), "ada", "tools", None)); | ||
| assert!(matches(&words("small box"), "ada", "tools", Some("A small toolbox"))); | ||
| assert!(!matches(&words("small crate"), "ada", "tools", Some("A small toolbox"))); | ||
| assert!(!matches(&words("bob"), "ada", "tools", None)); | ||
| } | ||
| #[test] | ||
| fn an_incomplete_fingerprint_is_never_trusted() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; // Root reads anything, so the unreadable folder below can't be made. | ||
| } | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-fingerprint-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| for folder in ["refs/heads/open", "refs/heads/locked/inner"] { | ||
| std::fs::create_dir_all(dir.join(folder)).unwrap(); | ||
| } | ||
| let repo = RepoDir::at(&dir).unwrap(); | ||
| assert!(refs_fingerprint(&repo).is_some()); | ||
| // A branch folder that can't be read: its refs could change unseen. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o000)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint missing a folder was trusted"); | ||
| // Names readable but not searchable: the folder's children can't be inspected. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o444)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint with an uninspectable folder was trusted"); | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o755)).unwrap(); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
+83−0
| @@ -0,0 +1,83 @@ | ||
| //! A branch or tag's history, or the history of one file or folder on it. | ||
| use std::ffi::OsStr; | ||
| use std::os::unix::ffi::OsStrExt; | ||
| use super::{PAGE, Repo}; | ||
| use crate::html::{ago, icon, subject_or_placeholder}; | ||
| use crate::repository::Head; | ||
| use crate::urls::{Q, clean_path, lossy, param}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = repo.reference(q); | ||
| let number: usize = param(q, "page").and_then(|p| p.parse().ok()).unwrap_or(0); | ||
| let skip = number.checked_mul(PAGE)?; | ||
| let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; | ||
| let commit = repo.reader.resolve(&reference)?; | ||
| let (count, skip) = (format!("-n{}", PAGE + 1), format!("--skip={skip}")); | ||
| // The path reaches git as bytes after `--`, and git's pathspecs are literal here, so a | ||
| // name like `star*.txt` means only that file. | ||
| let mut args: Vec<&OsStr> = | ||
| [OsStr::new("log"), count.as_ref(), skip.as_ref(), "--date=format:%-d %b %Y".as_ref(), Head::FORMAT.as_ref()] | ||
| .to_vec(); | ||
| args.extend([OsStr::new(&commit), OsStr::new("--")]); | ||
| if !path.is_empty() { | ||
| args.push(OsStr::from_bytes(&path)); | ||
| } | ||
| let out = repo.reader.git(&args)?; | ||
| let lines: Vec<&str> = out.lines().collect(); | ||
| let rows = commit_rows(repo, &out, PAGE); | ||
| let page_url = |n: usize| repo.url_at("log", &reference, &path, &format!("page={n}")); | ||
| let default = repo.reader.default_ref(); | ||
| let compare = (path.is_empty() && repo.reader.resolve(&default).is_some_and(|d| d != commit)).then(|| { | ||
| let shown = default.strip_prefix(b"refs/heads/").unwrap_or(&default); | ||
| (repo.compare_url(&default, &reference), format!("Compare with {}", lossy(shown))) | ||
| }); | ||
| let title = if path.is_empty() { | ||
| format!("Commits on {}", lossy(&reference)) | ||
| } else { | ||
| format!("History of {} on {}", lossy(&path), lossy(&reference)) | ||
| }; | ||
| Some(View::Html( | ||
| templates::History { | ||
| title, | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("log", &reference, Some(&commit)), | ||
| locator: repo.locator("log", &reference, &path), | ||
| rows, | ||
| compare, | ||
| newer: number.checked_sub(1).map(page_url), | ||
| older: (lines.len() > PAGE).then(|| page_url(number + 1)), | ||
| tag_icon: icon("tag"), | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// Rows for up to `limit` commits of `git log` output in [`Head::FORMAT`], each labelled with | ||
| /// the tags that point at it. | ||
| pub(crate) fn commit_rows<'a>(repo: &'a Repo, out: &str, limit: usize) -> Vec<templates::CommitRow<'a>> { | ||
| let tags = repo.reader.tags_by_commit(); | ||
| let mut rows = Vec::new(); | ||
| for head in out.lines().take(limit).filter_map(Head::parse) { | ||
| let labels = tags | ||
| .get(&head.oid) | ||
| .into_iter() | ||
| .flatten() | ||
| .map(|name| templates::TagLink { | ||
| name: lossy(name).into_owned().into(), | ||
| url: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""), | ||
| }) | ||
| .collect(); | ||
| 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, | ||
| }); | ||
| } | ||
| rows | ||
| } | ||
+281−0
| @@ -0,0 +1,281 @@ | ||
| //! The repository pages. Each view reads one open repository and returns a [`View`]. | ||
| mod archive; | ||
| mod blob; | ||
| mod commit; | ||
| mod compare; | ||
| mod index; | ||
| mod log; | ||
| mod tags; | ||
| mod tree; | ||
| use std::ffi::OsStr; | ||
| use std::fmt::Write as _; | ||
| use std::os::unix::ffi::OsStrExt; | ||
| use std::time::Instant; | ||
| use gitv_core::{RepoDir, config, repo_dir}; | ||
| use gitv_web::render; | ||
| use crate::html::{ago, icon, subject_or_placeholder}; | ||
| use crate::repository::Reader; | ||
| use crate::urls::{Q, encode, lossy}; | ||
| use crate::{View, templates}; | ||
| use archive::view_archive; | ||
| use blob::view_blob; | ||
| use commit::view_commit; | ||
| use compare::view_compare; | ||
| use log::view_log; | ||
| use tags::view_tags; | ||
| use tree::view_tree; | ||
| pub(crate) use commit::FileDiff; | ||
| pub(crate) use index::view_index; | ||
| pub(crate) const PAGE: usize = 50; | ||
| /// Largest file the Raw view serves; bigger files are for `git clone`. | ||
| pub(crate) const RAW_LIMIT: usize = 50 << 20; | ||
| /// Largest file shown on a page; bigger files offer Raw instead. | ||
| pub(crate) const SHOW_LIMIT: usize = 1 << 20; | ||
| /// Largest patch shown on a commit page; only this much is ever read. | ||
| pub(crate) const DIFF_LIMIT: usize = 2 << 20; | ||
| pub(crate) struct Repo { | ||
| pub(crate) signed_in: bool, | ||
| pub(crate) owner: String, | ||
| pub(crate) name: String, | ||
| pub(crate) reader: Reader, | ||
| } | ||
| impl Repo { | ||
| /// A repository opened through its owner and repository directories with symlinks refused; | ||
| /// every git command then runs inside that open directory. | ||
| pub(crate) fn open(owner: &str, name: &str) -> Option<Repo> { | ||
| let mut dir = repo_dir(owner, name)?; | ||
| dir.limit_until(Instant::now() + gitv_core::GIT_TIMEOUT); | ||
| Some(Repo::from_dir(owner, name, dir)) | ||
| } | ||
| pub(crate) fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo { | ||
| Repo { signed_in: false, reader: Reader::new(dir), owner: owner.into(), name: name.into() } | ||
| } | ||
| pub(crate) fn clone_address(&self) -> (&'static str, String) { | ||
| if self.reader.dir.is_public() { | ||
| ("HTTPS", format!("https://{}/{}/{}", config::host(), self.owner, self.name)) | ||
| } else { | ||
| ("SSH", format!("git@{}:{}/{}.git", config::host(), self.owner, self.name)) | ||
| } | ||
| } | ||
| pub(crate) fn url(&self, view: &str, query: &[(&str, &str)]) -> String { | ||
| let query: Vec<String> = | ||
| query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v.as_bytes()))).collect(); | ||
| let base = format!("/{}/{}/{view}", self.owner, self.name); | ||
| if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) } | ||
| } | ||
| /// The reference a page's `ref` parameter names, or the default branch. | ||
| pub(crate) fn reference(&self, q: &Q) -> Vec<u8> { | ||
| q.get("ref").cloned().unwrap_or_else(|| self.reader.default_ref()) | ||
| } | ||
| /// A tree, blob or raw link for a path, which may not be UTF-8. | ||
| pub(crate) fn url_at(&self, view: &str, reference: &[u8], path: &[u8], extra: &str) -> String { | ||
| let mut url = self.url(view, &[]); | ||
| if !reference.is_empty() { | ||
| let _ = write!(url, "?ref={}", encode(reference)); | ||
| } | ||
| if !path.is_empty() { | ||
| url.push(if url.contains('?') { '&' } else { '?' }); | ||
| let _ = write!(url, "path={}", encode(path)); | ||
| } | ||
| if !extra.is_empty() { | ||
| url.push(if url.contains('?') { '&' } else { '?' }); | ||
| url.push_str(extra); | ||
| } | ||
| url | ||
| } | ||
| /// 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. | ||
| pub(crate) fn entry_commit(&self, record: &str) -> Option<templates::EntryCommit> { | ||
| let mut fields = record.splitn(6, '\0'); | ||
| let oid = fields.next()?; | ||
| let stamp = fields.next()?; | ||
| let datetime = fields.next()?; | ||
| let full_date = 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, full_date.split(',').next().unwrap_or(full_date)), | ||
| full_date: full_date.into(), | ||
| datetime: datetime.into(), | ||
| }) | ||
| } | ||
| /// A cache key for rendered content of `oid` that links within this repository. | ||
| pub(crate) fn key(&self, kind: &str, oid: &str, extra: &str) -> String { | ||
| format!("{kind}:{}/{}:{oid}:{extra}", self.owner, self.name) | ||
| } | ||
| /// Render a Markdown file from directory `dir`, linking repository paths at `reference`. | ||
| pub(crate) fn markdown(&self, source: &str, dir: &[u8], reference: &[u8]) -> String { | ||
| render::markdown(source, dir, &|path, image| { | ||
| if image { | ||
| self.url_at("raw", reference, path, "") | ||
| } else if path.is_empty() { | ||
| self.url_at("tree", reference, b"", "") | ||
| } else { | ||
| self.url_at("blob", reference, path, "") | ||
| } | ||
| }) | ||
| } | ||
| /// Name, clone address and tabs, shared by every repository page. `commit` is `reference` | ||
| /// already resolved, when the caller has it. | ||
| pub(crate) fn masthead(&self, active: &str, reference: &[u8], commit: Option<&str>) -> String { | ||
| let commit = commit.map(str::to_string).or_else(|| self.reader.resolve(reference)); | ||
| let commits = commit.map_or(0, |c| self.reader.commit_count(&c)); | ||
| let tab = |view: &str, glyph: &str, label: &'static str, count: Option<usize>| templates::Tab { | ||
| href: self.url_at(view, if view == "tags" { b"" } else { reference }, b"", ""), | ||
| current: view == active, | ||
| icon: icon(glyph), | ||
| label, | ||
| count, | ||
| }; | ||
| let public = self.reader.dir.is_public(); | ||
| // Anyone may clone a public repository over HTTPS; the signed-in operator also pushes | ||
| // over SSH, so sees that address too, and whether the repository is public. | ||
| let ssh = ("SSH", format!("git@{}:{}/{}.git", config::host(), self.owner, self.name)); | ||
| let addresses = match (public, self.signed_in) { | ||
| (true, true) => vec![self.clone_address(), ssh], | ||
| _ => vec![self.clone_address()], | ||
| }; | ||
| templates::Masthead { | ||
| owner: &self.owner, | ||
| name: &self.name, | ||
| home: self.url("tree", &[]), | ||
| visibility: self.signed_in.then_some(if public { "Public" } else { "Private" }), | ||
| protected: self.signed_in && self.reader.dir.is_protected(), | ||
| description: self.reader.dir.description(), | ||
| addresses, | ||
| tabs: vec![ | ||
| tab("tree", "code", "Code", None), | ||
| tab("log", "commits", "Commits", Some(commits)), | ||
| tab("tags", "tag", "Tags", Some(self.reader.tags().len())), | ||
| ], | ||
| } | ||
| .to_string() | ||
| } | ||
| /// Branch and tag menu, then the path as breadcrumbs. | ||
| pub(crate) fn locator(&self, view: &str, reference: &[u8], path: &[u8]) -> String { | ||
| // `link` is what the URL carries; `name` is what people see. | ||
| let item = |link: Vec<u8>, name: &'_ [u8]| templates::MenuItem { | ||
| href: self.url_at(view, &link, path, ""), | ||
| current: link == reference, | ||
| name: lossy(name).into_owned().into(), | ||
| }; | ||
| let parts: Vec<&[u8]> = if path.is_empty() { Vec::new() } else { path.split(|b| *b == b'/').collect() }; | ||
| let crumbs = parts | ||
| .iter() | ||
| .enumerate() | ||
| .map(|(i, part)| templates::Crumb { | ||
| href: (i + 1 < parts.len()).then(|| self.url_at("tree", reference, &parts[..=i].join(&b'/'), "")), | ||
| name: lossy(part), | ||
| }) | ||
| .collect(); | ||
| let shown = reference | ||
| .strip_prefix(b"refs/heads/") | ||
| .or_else(|| reference.strip_prefix(b"refs/tags/")) | ||
| .unwrap_or(reference); | ||
| // A permalink pins a full commit id; its first twelve digits say enough. | ||
| let pinned = matches!(shown.len(), 40 | 64) && shown.iter().all(u8::is_ascii_hexdigit); | ||
| let shown = if pinned { &shown[..12] } else { shown }; | ||
| templates::Locator { | ||
| branch_icon: icon("branch"), | ||
| chevron_icon: icon("chevron"), | ||
| current: lossy(shown), | ||
| branches: self.reader.heads().iter().map(|b| item(self.reader.branch_ref(b), b)).collect(), | ||
| tags: self.reader.tags().iter().map(|t| item(self.reader.tag_ref(t), t)).collect(), | ||
| root: (!path.is_empty()).then(|| self.url_at("tree", reference, b"", "")), | ||
| repo_name: &self.name, | ||
| crumbs, | ||
| } | ||
| .to_string() | ||
| } | ||
| /// A comparison of two revisions, named as the URL should carry them. | ||
| pub(crate) fn compare_url(&self, from: &[u8], to: &[u8]) -> String { | ||
| format!("{}?from={}&to={}", self.url("compare", &[]), encode(from), encode(to)) | ||
| } | ||
| pub(crate) fn sha_link(&self, oid: &str) -> String { | ||
| templates::ShaLink { href: self.url("commit", &[("id", oid)]), short: &oid[..oid.len().min(7)] }.to_string() | ||
| } | ||
| } | ||
| /// One entry of a tree listing: `blob`, `tree` or `commit` (a submodule), its object id, its | ||
| /// size when it's a blob, and its name as git stores it. | ||
| pub(crate) struct Entry { | ||
| pub(crate) kind: String, | ||
| pub(crate) oid: String, | ||
| pub(crate) size: usize, | ||
| pub(crate) name: Vec<u8>, | ||
| } | ||
| impl Entry { | ||
| /// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs. | ||
| pub(crate) fn parse(record: &[u8]) -> Option<Entry> { | ||
| let tab = record.iter().position(|b| *b == b'\t')?; | ||
| let meta = std::str::from_utf8(&record[..tab]).ok()?; | ||
| let mut fields = meta.split_whitespace().skip(1); | ||
| let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string()); | ||
| let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0); | ||
| Some(Entry { kind, oid, size, name: record[tab + 1..].to_vec() }) | ||
| } | ||
| pub(crate) fn list(out: &[u8]) -> Vec<Entry> { | ||
| out.split(|b| *b == 0).filter_map(Entry::parse).collect() | ||
| } | ||
| } | ||
| /// The entry at `path` in `commit`, with its type, object id and size, in one git call. | ||
| pub(crate) fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> { | ||
| let args = [ | ||
| OsStr::new("ls-tree"), | ||
| OsStr::new("-l"), | ||
| OsStr::new("-z"), | ||
| OsStr::new(commit), | ||
| OsStr::new("--"), | ||
| OsStr::from_bytes(path), | ||
| ]; | ||
| let out = repo.reader.git_bytes(&args)?; | ||
| Entry::list(&out).into_iter().find(|e| e.name == path) | ||
| } | ||
| pub(crate) fn route(owner: &str, name: &str, view: Option<&str>, q: &Q, signed_in: bool) -> View { | ||
| let Some(mut repo) = Repo::open(owner, name) else { | ||
| return if signed_in { View::Missing(true) } else { View::LoginRequired }; | ||
| }; | ||
| if !signed_in && !repo.reader.dir.is_public() { | ||
| return View::LoginRequired; | ||
| } | ||
| repo.signed_in = signed_in; | ||
| let result = match view { | ||
| None => Some(View::Redirect(repo.url("tree", &[]))), | ||
| Some("tree") => view_tree(&repo, q), | ||
| Some("blob") => view_blob(&repo, q, false), | ||
| Some("raw") => view_blob(&repo, q, true), | ||
| Some("archive") => view_archive(&repo, q), | ||
| Some("log") => view_log(&repo, q), | ||
| Some("commit") => view_commit(&repo, q), | ||
| Some("compare") => view_compare(&repo, q), | ||
| Some("tags") => view_tags(&repo), | ||
| Some(_) => None, | ||
| }; | ||
| result.unwrap_or(View::Missing(signed_in)) | ||
| } | ||
+101−0
| @@ -0,0 +1,101 @@ | ||
| //! The tags in a repository. | ||
| use std::collections::HashMap; | ||
| use data_encoding::HEXLOWER; | ||
| use sha2::{Digest, Sha256}; | ||
| use super::Repo; | ||
| use crate::cache::cached; | ||
| use crate::html::ago; | ||
| use crate::urls::lossy; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_tags(repo: &Repo) -> Option<View> { | ||
| let out = repo.reader.git_bytes(&[ | ||
| "for-each-ref", | ||
| "--sort=-creatordate", | ||
| "--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:format:%-d %b %Y)%1f%(objecttype)%1f%(contents:subject)", | ||
| "refs/tags", | ||
| ])?; | ||
| let mut rows: Vec<templates::TagRow> = Vec::new(); | ||
| let mut names: Vec<&[u8]> = Vec::new(); | ||
| let mut targets: Vec<String> = Vec::new(); | ||
| for line in out.split(|b| *b == b'\n') { | ||
| // The tag's message goes last, so one containing the separator stays whole. | ||
| let Ok([name, direct, peeled, stamp, date, kind, note]) = | ||
| <[&[u8]; 7]>::try_from(line.splitn(7, |b| *b == 0x1f).collect::<Vec<_>>()) | ||
| else { | ||
| continue; | ||
| }; | ||
| let target = if peeled.is_empty() { direct } else { peeled }; | ||
| names.push(name); | ||
| targets.push(lossy(target).into_owned()); | ||
| rows.push(templates::TagRow { | ||
| name: lossy(name), | ||
| note: (kind == b"tag" && !note.is_empty()).then(|| lossy(note)), | ||
| sha_link: repo.sha_link(&lossy(target)), | ||
| when: ago(&lossy(stamp), &lossy(date)), | ||
| browse: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""), | ||
| archive: repo.url_at("archive", &repo.reader.tag_ref(name), b"", ""), | ||
| compare: None, | ||
| }); | ||
| } | ||
| // Each tag is compared with the release before it: the nearest tag in its own history. | ||
| for (row, (i, previous)) in rows.iter_mut().zip(previous_tags(repo, &out, &targets).into_iter().enumerate()) { | ||
| if let Some(previous) = previous.and_then(|p| names.get(p)) { | ||
| let (from, to) = (repo.reader.tag_ref(previous), repo.reader.tag_ref(names[i])); | ||
| row.compare = Some((repo.compare_url(&from, &to), format!("Changes since {}", lossy(previous)))); | ||
| } | ||
| } | ||
| Some(View::Html( | ||
| templates::Tags { | ||
| title: format!("Tags in {}/{}", repo.owner, repo.name), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("tags", &repo.reader.default_ref(), None), | ||
| rows, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// For each tag, the index in `names` of the tag before it: the nearest tagged commit back | ||
| /// along its first parents, so a merge's tag follows its main line rather than the branch it | ||
| /// merged. Creation dates can't order releases: tags made in the same second, or added late, | ||
| /// would pair with the wrong neighbour. | ||
| /// | ||
| /// One walk of the tagged history answers for every tag. `--simplify-by-decoration` keeps only | ||
| /// tagged commits and rewrites each one's parents to the nearest tagged ones. The answer is | ||
| /// cached for the whole listing; `listing` (every tag's name, target and date) names it, so any | ||
| /// change to the tags makes a new entry. If git fails, nothing is cached and no links show. | ||
| fn previous_tags(repo: &Repo, listing: &[u8], targets: &[String]) -> Vec<Option<usize>> { | ||
| let key = repo.key("previous-tags", &HEXLOWER.encode(&Sha256::digest(listing)), ""); | ||
| let walk = cached(key, || { | ||
| repo.reader.git(&[ | ||
| "log", | ||
| "--first-parent", | ||
| "--simplify-by-decoration", | ||
| "--decorate-refs=refs/tags/", | ||
| "--parents", | ||
| "--format=%H %P", | ||
| "--tags", | ||
| "--", | ||
| ]) | ||
| }); | ||
| // Each tagged commit and its first rewritten parent, if it has one. | ||
| let parent: HashMap<&str, &str> = walk | ||
| .as_deref() | ||
| .unwrap_or_default() | ||
| .lines() | ||
| .filter_map(|line| { | ||
| let mut ids = line.split(' '); | ||
| Some((ids.next()?, ids.next()?)) | ||
| }) | ||
| .collect(); | ||
| // The first listed tag at a commit (the newest, as the page lists them) stands for it. | ||
| let mut tag_at: HashMap<&str, usize> = HashMap::new(); | ||
| for (i, target) in targets.iter().enumerate() { | ||
| tag_at.entry(target.as_str()).or_insert(i); | ||
| } | ||
| targets.iter().map(|target| parent.get(target.as_str()).and_then(|p| tag_at.get(p).copied())).collect() | ||
| } | ||
+170−0
| @@ -0,0 +1,170 @@ | ||
| //! Folder listings, with the latest change to each entry and the README. | ||
| use std::ffi::OsStr; | ||
| use gitv_core::config; | ||
| use gitv_web::render; | ||
| use super::{Entry, PAGE, Repo, SHOW_LIMIT, entry}; | ||
| use crate::cache::cached; | ||
| use crate::html::{ago, icon, plural, size, subject_or_placeholder}; | ||
| use crate::urls::{Q, clean_path, encode, join, lossy, param, parent_of, spec}; | ||
| use crate::{View, templates}; | ||
| pub(crate) fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = repo.reference(q); | ||
| let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; | ||
| let Some(commit) = repo.reader.resolve(&reference) else { | ||
| if !repo.reader.heads().is_empty() { | ||
| return None; | ||
| } | ||
| let page = templates::Empty { | ||
| title: format!("{}/{}", repo.owner, repo.name), | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("tree", &reference, None), | ||
| host: config::host(), | ||
| owner: &repo.owner, | ||
| name: &repo.name, | ||
| }; | ||
| return Some(View::Html(page.to_string())); | ||
| }; | ||
| let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)]; | ||
| let Some(listing) = repo.reader.git_bytes(&listing) else { | ||
| // A file path: show it in the file view instead. | ||
| return entry(repo, &commit, &path) | ||
| .filter(|e| e.kind == "blob") | ||
| .map(|_| View::Redirect(repo.url_at("blob", &reference, &path, ""))); | ||
| }; | ||
| let mut entries = Entry::list(&listing); | ||
| // Folders first, then files and submodules, each alphabetically. | ||
| entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase())); | ||
| let page: usize = param(q, "page").and_then(|n| n.parse().ok()).unwrap_or(0); | ||
| let offset = page.checked_mul(PAGE)?; | ||
| if page != 0 && offset >= entries.len() { | ||
| return None; | ||
| } | ||
| let mut rows = Vec::new(); | ||
| let visible = &entries[offset..entries.len().min(offset + PAGE)]; | ||
| let names: Vec<_> = visible.iter().map(|item| item.name.as_slice()).collect(); | ||
| let histories = repo.reader.entry_histories(&commit, &path, &names); | ||
| for (item, record) in visible.iter().zip(histories) { | ||
| let path = join(&path, &item.name); | ||
| let (view, class, glyph) = match item.kind.as_str() { | ||
| "tree" => (Some("tree"), "entry dir", "dir"), | ||
| "commit" => (None, "entry sub", "module"), | ||
| _ => (Some("blob"), "entry", "file"), | ||
| }; | ||
| 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: record.as_deref().and_then(|record| repo.entry_commit(record)), | ||
| }; | ||
| rows.push(row); | ||
| } | ||
| let page_url = |number| repo.url_at("tree", &reference, &path, &format!("page={number}")); | ||
| // README.md over README or README.txt, as people expect. | ||
| let readmes = entries.iter().filter(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with(b"readme")); | ||
| let readme = readmes.clone().find(|e| render::is_markdown(&lossy(&e.name))).or_else(|| readmes.clone().next()); | ||
| let readme = readme.filter(|e| e.size <= SHOW_LIMIT).map(|readme| { | ||
| let name = lossy(&readme.name); | ||
| let as_code = !render::is_markdown(&name); | ||
| let rendered = render_file(repo, &readme.oid, readme.size, &name, &path, &reference, as_code, None); | ||
| let content = | ||
| rendered.map_or_else(|| r#"<p class="note">This README couldn't be read.</p>"#.to_string(), |r| r.html); | ||
| (name.into_owned(), content) | ||
| }); | ||
| let title = if path.is_empty() { | ||
| format!("{}/{}", repo.owner, repo.name) | ||
| } else { | ||
| format!("{} at {}", lossy(&path), lossy(&reference)) | ||
| }; | ||
| let head = repo.reader.latest(&commit, &path).map(|head| templates::TreeHead { | ||
| url: repo.url("commit", &[("id", &head.oid)]), | ||
| sha_link: repo.sha_link(&head.oid), | ||
| subject: subject_or_placeholder(&head.subject).to_string(), | ||
| author: head.author, | ||
| when: ago(&head.stamp, &head.date), | ||
| history: repo.url_at("log", &reference, &path, ""), | ||
| }); | ||
| Some(View::Html( | ||
| templates::Tree { | ||
| title, | ||
| signed_in: repo.signed_in, | ||
| masthead: repo.masthead("tree", &reference, Some(&commit)), | ||
| locator: repo.locator("tree", &reference, &path), | ||
| head, | ||
| up: (!path.is_empty()).then(|| repo.url_at("tree", &reference, parent_of(&path), "")), | ||
| rows, | ||
| previous: page.checked_sub(1).map(page_url), | ||
| next: (entries.len() - offset > PAGE).then(|| page_url(page + 1)), | ||
| readme, | ||
| } | ||
| .to_string(), | ||
| )) | ||
| } | ||
| /// A file rendered for display: a summary (`facts`) and its HTML. | ||
| pub(crate) struct Rendered { | ||
| pub(crate) facts: String, | ||
| pub(crate) html: String, | ||
| } | ||
| /// A file rendered for display: highlighted code, or Markdown with links into this repository | ||
| /// at `reference` (the file lives in `dir`). The file view and the README panel both use this, | ||
| /// so they share one cached value per rendering instead of storing different shapes under one | ||
| /// key. The facts and the rendering are cached together, so a repeat view reads no blob at all. | ||
| /// | ||
| /// Code is cached as `facts` 0x1f `line count` 0x1f `highlighted`, and its gutter is built per | ||
| /// request, because only the gutter depends on which lines a link selects. Anything else is | ||
| /// cached as `facts` 0x1f 0x1f `html`. | ||
| #[allow(clippy::too_many_arguments)] | ||
| pub(crate) fn render_file( | ||
| repo: &Repo, | ||
| oid: &str, | ||
| file_size: usize, | ||
| name: &str, | ||
| dir: &[u8], | ||
| reference: &[u8], | ||
| as_code: bool, | ||
| selected: Option<(usize, usize)>, | ||
| ) -> Option<Rendered> { | ||
| let key = if as_code { | ||
| // Highlighting depends only on the content and the file's type, so it's shared. | ||
| format!("code:{oid}:{name}") | ||
| } else { | ||
| // Links depend on the repository, folder and ref too. | ||
| repo.key("md", oid, &format!("{}:{}", encode(dir), encode(reference))) | ||
| }; | ||
| let value = cached(key, || { | ||
| let data = repo.reader.git_bytes(&["cat-file", "blob", oid])?; | ||
| if data.iter().take(8000).any(|b| *b == 0) { | ||
| let note = r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#; | ||
| return Some(format!("{}\x1f\x1f{note}", size(file_size))); | ||
| } | ||
| let text = String::from_utf8_lossy(&data); | ||
| let lines = text.lines().count(); | ||
| let facts = format!("{}, {}", plural(lines, "line", "lines"), size(file_size)); | ||
| Some(if as_code { | ||
| format!("{facts}\x1f{}\x1f{}", lines.max(1), render::highlight(name, &text)) | ||
| } else { | ||
| let html = repo.markdown(&text, dir, reference); | ||
| format!("{facts}\x1f\x1f<article class=\"markdown\">{html}</article>") | ||
| }) | ||
| })?; | ||
| let mut parts = value.splitn(3, '\x1f'); | ||
| let (facts, lines, html) = (parts.next()?, parts.next()?, parts.next()?); | ||
| let html = match lines.parse() { | ||
| Ok(lines) => code_view(lines, html, selected), | ||
| Err(_) => html.to_string(), | ||
| }; | ||
| Some(Rendered { facts: facts.to_string(), html }) | ||
| } | ||
| /// Highlighted source with its line-number gutter. | ||
| pub(crate) fn code_view(lines: usize, code: &str, selected: Option<(usize, usize)>) -> String { | ||
| templates::Code { lines, selected, code }.to_string() | ||
| } | ||
+13−0
| @@ -0,0 +1,13 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %}<div class="pagehead"><h1 class="title">Account</h1><p class="count">Signed in as {{ user }}</p></div>{% if !message.is_empty() %}{% if ok %}<p class="alert ok" role="status">{{ message }}</p>{% else %}<p class="alert" role="alert">{{ message }}</p>{% endif %}{% endif %} | ||
| <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>{% endblock %} | ||
+3−1
| @@ -2,8 +2,10 @@ | ||
| <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="manifest" href="/manifest.webmanifest"><link rel="apple-touch-icon" href="/apple-touch-icon.png"> | ||
| <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)"><meta name="theme-color" content="#171c22" media="(prefers-color-scheme: dark)"> | ||
| <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> | ||
| <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>{% else if title != "Sign in" %}<a class="account" href="/login">Sign in</a>{% endif %}</div></header> | ||
| <main id="main">{% block content %}{% endblock %}</main></body></html> | ||
+5−0
| @@ -0,0 +1,5 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }}{{ locator|safe }} | ||
| <section class="panel"><div class="panel-head"><div class="lead">{{ file_icon|safe }}<b>{{ name }}</b><span class="quiet">{{ facts }}</span></div><div class="side">{% if let Some(views) = views %}<span class="segmented"><a href="{{ views.preview }}"{% if !views.as_code %} aria-current="true"{% endif %}>Preview</a><a href="{{ views.code }}"{% if views.as_code %} aria-current="true"{% endif %}>Code</a></span>{% endif %}<a class="button" href="{{ history }}">History</a><a class="button" href="{{ permalink }}" title="This file at this commit, unchanged when the branch moves">Permalink</a><a class="button" href="{{ raw }}">Raw</a></div></div>{{ content|safe }}</section> | ||
| {% endblock %} | ||
+2−0
| @@ -0,0 +1,2 @@ | ||
| <div class="code-view"><pre class="gutter">{% for n in 1..=lines %}<a id="L{{ n }}" href="#L{{ n }}"{% if self.is_selected(n) %} class="sel"{% endif %}>{{ n }}</a> | ||
| {% endfor %}</pre><pre class="code">{{ code|safe }}</pre></div> | ||
| @@ -0,0 +1,5 @@ | ||
| {% 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 %} | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }} | ||
| <section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{{ title }}</h2><a class="button" href="{{ browse }}">Browse files</a></div> | ||
| {% if !message.is_empty() %}<p class="cbody">{{ message }}</p>{% endif %}</div> | ||
| <dl class="facts"><div><dt>Author</dt><dd>{{ author }} <span class="quiet">{{ email }}</span></dd></div><div><dt>Date</dt><dd>{{ date }}</dd></div> | ||
| <div><dt>Commit</dt><dd><span class="sha">{{ short_id }}</span></dd></div> | ||
| {% if !parent_links.is_empty() %}<div><dt>Parent</dt><dd>{{ parent_links|safe }}</dd></div>{% endif %}</dl></section> | ||
| {{ diff|safe }} | ||
| {% endblock %} | ||
+17−0
| @@ -0,0 +1,17 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }} | ||
| <form class="panel form compare-form" method="get" action="{{ action }}"> | ||
| <label>From<input name="from" value="{{ from }}" list="refs" placeholder="v1.0.0" autocapitalize="none" autocomplete="off" spellcheck="false" required></label> | ||
| <label>To<input name="to" value="{{ to }}" list="refs" placeholder="main" autocapitalize="none" autocomplete="off" spellcheck="false" required></label> | ||
| <button class="button primary" type="submit">Compare</button> | ||
| <datalist id="refs">{% for name in refs %}<option value="{{ name }}">{% endfor %}</datalist> | ||
| </form> | ||
| {% if let Some(message) = message %}<p class="alert" role="alert">{{ message }}</p>{% endif %} | ||
| {% if let Some(summary) = summary %}<div class="compare-summary"><p>{{ summary }}</p>{% if let Some(url) = swap %}<a class="button" href="{{ url }}">Swap</a>{% endif %}</div>{% endif %} | ||
| {% if !rows.is_empty() %}<div class="panel"><ul class="rows"> | ||
| {% include "commit-rows.html" %} | ||
| </ul></div>{% endif %} | ||
| {% if let Some(more) = more %}<p class="note">{{ more }}</p>{% endif %} | ||
| {% if let Some(diff) = diff %}{{ diff|safe }}{% endif %} | ||
| {% endblock %} | ||
+5−0
| @@ -0,0 +1,5 @@ | ||
| <h2 class="changes">{{ file_count }} changed{% if let Some((added, removed)) = totals %} <span class="plus">+{{ added }}</span><span class="minus">−{{ removed }}</span>{% endif %}</h2>{% if too_big %}<p class="note">{{ what }} are too large to show line by line.</p>{% endif %} | ||
| {%- for file in files %}<section class="panel"><div class="panel-head"><div class="lead">{{ file_icon|safe }}<a href="{{ file.href }}"><b>{{ file.path }}</b></a>{% if !file.status.is_empty() %}<span class="status">{{ file.status }}</span>{% endif %}</div><div class="side">{% if let Some(diff) = file.diff %}<span class="plus">+{{ diff.added }}</span><span class="minus">−{{ diff.removed }}</span>{% endif %}</div></div> | ||
| {%- if let Some(diff) = file.diff %}{% if diff.binary %}<p class="note">Binary file changed.</p>{% else if diff.rows.is_empty() %}<p class="note">No content changes.</p>{% else %}<div class="diff-wrap"><table class="diff"> | ||
| {%- for row in diff.rows %}{% if row.class == "hunk" %}<tr class="hunk"><td colspan="3">{{ row.text }}</td></tr>{% else %}<tr class="{{ row.class }}"><td class="num" data-n="{{ row.old }}"></td><td class="num" data-n="{{ row.new }}"></td><td class="line" data-s="{{ row.sign() }}">{{ row.text }}</td></tr>{% endif %}{% endfor -%} | ||
| </table></div>{% endif %}{% endif %}</section>{% endfor %} | ||
+5−0
| @@ -0,0 +1,5 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }}<div class="panel empty"><h2>This repository is empty</h2><p>Push a branch to get started.</p> | ||
| <code>git push git@{{ host }}:{{ owner }}/{{ name }}.git main</code></div> | ||
| {% endblock %} | ||
+12−0
| @@ -0,0 +1,12 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }} | ||
| {% if let Some((url, label)) = compare %}<div class="locator-bar">{{ locator|safe }}<div class="actions"><a class="button" href="{{ url }}">{{ label }}</a></div></div>{% else %}{{ locator|safe }}{% endif %} | ||
| <div class="panel"><ul class="rows"> | ||
| {% include "commit-rows.html" %} | ||
| </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 %} | ||
| @@ -0,0 +1,2 @@ | ||
| <div class="locator"><details class="refmenu"><summary>{{ branch_icon|safe }}{{ current }}{{ chevron_icon|safe }}</summary><div class="menu"><h2>Branches</h2>{% for item in branches %}<a href="{{ item.href }}"{% if item.current %} aria-current="true"{% endif %}>{{ item.name }}</a>{% endfor %}{% if !tags.is_empty() %}<h2>Tags</h2>{% for item in tags %}<a href="{{ item.href }}"{% if item.current %} aria-current="true"{% endif %}>{{ item.name }}</a>{% endfor %}{% endif %}</div></details> | ||
| {% if let Some(root) = root %}<nav class="crumbs" aria-label="Path"><a href="{{ root }}">{{ repo_name }}</a>{% for crumb in crumbs %}<span class="sep">/</span>{% if let Some(href) = crumb.href %}<a href="{{ href }}">{{ crumb.name }}</a>{% else %}<b>{{ crumb.name }}</b>{% endif %}{% endfor %}</nav>{% endif %}</div> | ||
+0−0
No content changes.
| @@ -0,0 +1,4 @@ | ||
| <div class="repohead"><div class="repoid"><div class="repoline"><h1 class="reponame"><a class="own" href="/">{{ owner }}</a><span class="sep">/</span><a href="{{ home }}">{{ name }}</a></h1>{% if let Some(visibility) = visibility %}<span class="vis">{{ visibility }}</span>{% endif %}{% if protected %}<span class="vis" title="Pushes can't force-update or delete branches">Protected</span>{% endif %}</div> | ||
| {% if let Some(description) = description %}<p class="repodesc">{{ description }}</p>{% endif %}</div> | ||
| <div class="clones">{% for (protocol, address) in addresses %}<label class="clone"><span>{{ protocol }}</span><input readonly aria-label="{{ protocol }} clone address" value="{{ address }}"></label>{% endfor %}</div></div> | ||
| <nav class="tabs" aria-label="Repository">{% for tab in tabs %}<a href="{{ tab.href }}"{% if tab.current %} aria-current="page"{% endif %}>{{ tab.icon|safe }}{{ tab.label }}{% if let Some(n) = tab.count %}<span class="n">{{ n }}</span>{% endif %}</a>{% endfor %}</nav> | ||
| @@ -0,0 +1,3 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %}<section class="notfound"><h1 class="title">{{ heading }}</h1> | ||
| {% if !message.is_empty() %}<p class="count">{{ message }}</p>{% endif %}{% if let Some(code) = code %}<code>{{ code }}</code>{% endif %}{% if let Some((href, label)) = link %}<a class="button" href="{{ href }}">{{ label }}</a>{% endif %}</section>{% endblock %} | ||
| @@ -0,0 +1,35 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| <header class="index-head"><h1 class="title">Repositories</h1>{% if total > 0 %}<p class="count">{{ count }}</p>{% endif %}</header> | ||
| {% if total > 1 || !filter.is_empty() %}<form class="index-filter" method="get" action="/" role="search"><input type="search" name="q" value="{{ filter }}" placeholder="Filter by name or description" aria-label="Filter repositories" autocapitalize="none" spellcheck="false"><button class="button" type="submit">Filter</button>{% if !filter.is_empty() %}<a class="button" href="/">Clear</a>{% endif %}</form>{% endif %} | ||
| {% if rows.is_empty() && !filter.is_empty() %} | ||
| <section class="panel index-empty"><h2>No repositories match “{{ filter }}”</h2><a class="button" href="/">Show all repositories</a></section> | ||
| {% else if rows.is_empty() %} | ||
| <section class="panel index-empty"> | ||
| <div class="index-mark">{{ branch|safe }}</div> | ||
| {% if signed_in %} | ||
| <h2>No repositories yet</h2> | ||
| <p>Create your first repository by pushing a branch over SSH.</p> | ||
| <code>git push git@{{ host }}:<owner>/my-project.git main</code> | ||
| {% else %} | ||
| <h2>No public repositories yet</h2> | ||
| <a class="button" href="/login">Sign in to view private repositories</a> | ||
| {% endif %} | ||
| </section> | ||
| {% else %} | ||
| <div class="panel index-list"> | ||
| <div class="index-columns" aria-hidden="true"><span>Repository</span><span>Latest commit</span><span>Updated</span></div> | ||
| <ul class="rows"> | ||
| {% for row in rows %} | ||
| <li><a class="repo-row" href="/{{ row.owner }}/{{ row.name }}/tree"> | ||
| <span class="ridentity"><span class="rname"><span>{{ row.owner }}/</span>{{ row.name }}</span> | ||
| {% if signed_in %}<small>{% if row.public %}Public{% else %}Private{% endif %}</small>{% endif %} | ||
| {% if let Some(description) = row.description %}<span class="rdesc">{{ description }}</span>{% endif %}</span> | ||
| <span class="rlast">{{ row.subject }}</span> | ||
| <span class="rwhen">{{ row.when }}</span> | ||
| </a></li> | ||
| {% endfor %} | ||
| </ul> | ||
| </div> | ||
| {% endif %} | ||
| {% endblock %} | ||
| @@ -0,0 +1 @@ | ||
| <a class="sha" href="{{ href }}">{{ short }}</a> | ||
+7−0
| @@ -0,0 +1,7 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }} | ||
| {% if rows.is_empty() %}<div class="panel empty"><h2>No tags yet</h2><p>Tag a release and push it to see it here.</p><code>git tag -a v1.0.0 -m "v1.0.0" && git push origin v1.0.0</code></div> | ||
| {% else %}<div class="panel"><ul class="rows">{% for row in rows %}<li class="tag-row"><span class="tname">{{ row.name }}</span>{% if let Some(note) = row.note %}<span class="tnote">{{ note }}</span>{% endif %}<span class="tmeta">{{ row.sha_link|safe }}{{ row.when }}</span> | ||
| <span class="tacts">{% if let Some((url, label)) = row.compare %}<a class="button" href="{{ url }}">{{ label }}</a>{% endif %}<a class="button" href="{{ row.archive }}" download>Source (.tar.gz)</a><a class="button" href="{{ row.browse }}">Browse files</a></span></li>{% endfor %}</ul></div>{% endif %} | ||
| {% endblock %} | ||
+1−1
| @@ -6,6 +6,6 @@ | ||
| {% 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> | ||
| <time datetime="{{ change.datetime }}" title="{{ change.full_date }}">{{ change.when }}</time> | ||
| {% endif %} | ||
| </li> | ||
+19−0
| @@ -0,0 +1,19 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %} | ||
| {{ masthead|safe }}{{ locator|safe }} | ||
| <div class="panel"> | ||
| {% if let Some(h) = head %} | ||
| <div class="panel-head"><div class="lead"><b class="who">{{ h.author }}</b><a class="subject" href="{{ h.url }}">{{ h.subject }}</a></div><div class="side">{{ h.sha_link|safe }}<span>{{ h.when }}</span><a href="{{ h.history }}">History</a></div></div> | ||
| {% endif %} | ||
| <ul class="rows tree-list"> | ||
| {% if let Some(url) = up %}<li><a class="entry" href="{{ url }}">{{ crate::html::icon("up")|safe }}<span class="name">..</span></a></li>{% endif %} | ||
| {% for row in rows %}{{ row|safe }}{% endfor %} | ||
| </ul></div> | ||
| {% if previous.is_some() || next.is_some() %} | ||
| <nav class="pager" aria-label="Directory pages"> | ||
| {% if let Some(url) = previous %}<a class="button" href="{{ url }}">Previous</a>{% endif %} | ||
| {% if let Some(url) = next %}<a class="button" href="{{ url }}">Next</a>{% endif %} | ||
| </nav> | ||
| {% endif %} | ||
| {% if let Some((name, content)) = readme %}<section class="panel"><div class="panel-head"><div class="lead">{{ crate::html::icon("book")|safe }}<b>{{ name }}</b></div></div>{{ content|safe }}</section>{% endif %} | ||
| {% endblock %} | ||
+113−26
| @@ -38,7 +38,7 @@ mod signed_out { | ||
| #[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/../"] { | ||
| 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}"); | ||
| @@ -216,11 +216,85 @@ mod signing_in { | ||
| assert!(response.text().contains("Too many failed sign-ins. Try again in 1 minute."), "{}", response.text()); | ||
| } | ||
| #[test] | ||
| fn one_clients_failures_dont_lock_out_another() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let attempt = |address: &str, password: &str, code: &str| { | ||
| let form = [("user", "Um9i"), ("password", password), ("code", code), ("next", "/")]; | ||
| s.post_signed_out_from(address, "/login", &form).status | ||
| }; | ||
| for _ in 0..5 { | ||
| assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 401); | ||
| } | ||
| assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 429, "the attacker is locked out"); | ||
| assert_eq!(attempt("2001:db8:1:2::99", &s.account.password, &s.account.code(0)), 303, "the owner isn't"); | ||
| // An attacker's addresses within one IPv6 /64 share a lock. | ||
| for _ in 0..5 { | ||
| assert_eq!(attempt("2001:db8:9:9::1", "wrong password", "000000"), 401); | ||
| } | ||
| assert_eq!(attempt("2001:db8:9:9::2", "wrong password", "000000"), 429); | ||
| } | ||
| #[test] | ||
| fn many_addresses_together_cant_lock_out_a_browser_that_signed_in_before() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let form = |password: &str, code: &str| { | ||
| [("user", "Um9i".to_string()), ("password", password.into()), ("code", code.into()), ("next", "/".into())] | ||
| }; | ||
| let post = |address: &str, device: Option<&str>, fields: &[(&str, String)]| { | ||
| let fields: Vec<(&str, &str)> = fields.iter().map(|(k, v)| (*k, v.as_str())).collect(); | ||
| match device { | ||
| Some(device) => s.post_from_device(address, device, "/login", &fields), | ||
| None => s.post_signed_out_from(address, "/login", &fields), | ||
| } | ||
| }; | ||
| let first = post("198.51.100.1", None, &form(&s.account.password, &s.account.code(0))); | ||
| assert_eq!(first.status, 303); | ||
| let device = common::set_cookie(&first, "__Host-gitv-device").expect("a trusted-device cookie"); | ||
| assert!(first.header("set-cookie").contains("Max-Age=7776000"), "{}", first.header("set-cookie")); | ||
| // Twelve addresses, each within its own free failures, spend the hourly budget. | ||
| for n in 0..12 { | ||
| for _ in 0..5 { | ||
| // The failure that fills the budget is itself refused as locked. | ||
| let status = post(&format!("203.0.113.{n}"), None, &form("wrong password", "000000")).status; | ||
| assert!(matches!(status, 401 | 429), "{status}"); | ||
| } | ||
| } | ||
| let fresh = post("198.51.100.2", None, &form(&s.account.password, &s.account.code(1))); | ||
| assert_eq!(fresh.status, 429, "a browser never seen before waits out the attack"); | ||
| let known = post("198.51.100.2", Some(&device), &form(&s.account.password, &s.account.code(1))); | ||
| assert_eq!(known.status, 303, "the owner's browser gets in: {}", known.text()); | ||
| let forged = post("198.51.100.3", Some("AAAAAAAAAAA"), &form(&s.account.password, &s.account.code(1))); | ||
| assert_eq!(forged.status, 429, "a made-up device cookie earns nothing"); | ||
| } | ||
| #[test] | ||
| fn attempts_are_logged_with_their_client_and_what_was_wrong() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let attempt = |address: &str, password: &str, code: &str| { | ||
| let form = [("user", "Um9i"), ("password", password), ("code", code), ("next", "/")]; | ||
| s.post_signed_out_from(address, "/login", &form).status | ||
| }; | ||
| assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 401); | ||
| // A code valid in none of the steps the server accepts (one either side of now). | ||
| let valid = [s.account.code(-1), s.account.code(0), s.account.code(1)]; | ||
| let wrong_code = | ||
| ["000000", "111111", "222222", "333333"].into_iter().find(|c| !valid.iter().any(|v| v == c)).unwrap(); | ||
| assert_eq!(attempt("203.0.113.8", &s.account.password, wrong_code), 401); | ||
| assert_eq!(attempt("2001:db8:1:2::5", &s.account.password, &s.account.code(0)), 303); | ||
| let log = s.logged(); | ||
| assert!(log.contains("sign-in failed from 203.0.113.7 (wrong password)"), "{log}"); | ||
| assert!(log.contains("sign-in failed from 203.0.113.8 (right password, wrong code)"), "{log}"); | ||
| assert!(log.contains("sign-in succeeded from 2001:db8:1:2::/64"), "{log}"); | ||
| assert!(!log.contains(&s.account.password), "the password never reaches the log"); | ||
| } | ||
| #[test] | ||
| fn a_forged_cookie_is_not_a_session() { | ||
| let mut s = Server::start_signed_out(repos()); | ||
| s.cookie = Some("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".into()); | ||
| assert_eq!(s.get("/").status, 303); | ||
| assert_eq!(s.get("/account").status, 303); | ||
| } | ||
| } | ||
| @@ -239,14 +313,14 @@ mod signing_out { | ||
| 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"); | ||
| assert_eq!(s.get("/account").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"); | ||
| assert_eq!(s.get("/account").status, 200, "a forged sign-out ended the session"); | ||
| } | ||
| } | ||
| @@ -276,7 +350,7 @@ mod changing_the_password { | ||
| ); | ||
| assert_eq!(response.status, 200, "{}", response.text()); | ||
| assert!(response.text().contains("Password changed.")); | ||
| assert_eq!(s.get("/").status, 200); | ||
| assert_eq!(s.get("/account").status, 200); | ||
| } | ||
| #[test] | ||
| @@ -287,7 +361,7 @@ mod changing_the_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(); | ||
| let loaded = gitv_web::auth::Credentials::load(&s.account.file).unwrap(); | ||
| assert!(loaded.verify_password(new) && !loaded.verify_password(&old)); | ||
| } | ||
| @@ -302,12 +376,12 @@ mod changing_the_password { | ||
| let mut second = Server::start_signed_out(repos()); | ||
| second.port = first.port; | ||
| second.cookie = session_cookie(&response); | ||
| assert_eq!(second.get("/").status, 200); | ||
| assert_eq!(second.get("/account").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"); | ||
| assert_eq!(second.get("/account").status, 303, "the other session survived"); | ||
| assert_eq!(first.get("/account").status, 200, "this session was ended"); | ||
| } | ||
| #[test] | ||
| @@ -316,7 +390,7 @@ mod changing_the_password { | ||
| 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)); | ||
| assert!(gitv_web::auth::Credentials::load(&s.account.file).unwrap().verify_password(&s.account.password)); | ||
| } | ||
| #[test] | ||
| @@ -367,12 +441,12 @@ mod changing_the_password { | ||
| #[test] | ||
| fn on_the_server_signs_everyone_out() { | ||
| let s = Server::start(repos()); | ||
| assert_eq!(s.get("/").status, 200); | ||
| assert_eq!(s.get("/account").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(); | ||
| let mut credentials = gitv_web::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); | ||
| assert_eq!(s.get("/account").status, 303); | ||
| } | ||
| } | ||
| @@ -381,10 +455,11 @@ mod setup { | ||
| #[test] | ||
| fn root_setup_refuses_an_unwritable_custom_directory_before_publication() { | ||
| let Some(_) = gitv::auth::service_owner().unwrap() else { return }; | ||
| let Some(_) = gitv_web::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(); | ||
| 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); | ||
| @@ -394,7 +469,8 @@ mod setup { | ||
| 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(); | ||
| 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)); | ||
| } | ||
| @@ -407,26 +483,26 @@ mod setup { | ||
| let runs: Vec<_> = (0..4) | ||
| .map(|_| { | ||
| scope.spawn(|| { | ||
| Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap() | ||
| 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()); | ||
| assert!(gitv_web::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) | ||
| 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); | ||
| assert_eq!(s.get("/account").status, 303); | ||
| } | ||
| #[test] | ||
| @@ -434,7 +510,7 @@ mod setup { | ||
| 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) | ||
| let out = Command::new(&*common::GITV_WEB) | ||
| .args(["setup", "--force", "--user", user]) | ||
| .env("GITV_WEB_AUTH", &account.file) | ||
| .output() | ||
| @@ -442,22 +518,33 @@ mod setup { | ||
| assert!(!out.status.success(), "{user:?} was accepted"); | ||
| assert!(stderr(&out).contains("user name"), "{}", stderr(&out)); | ||
| } | ||
| let kept = gitv::auth::Credentials::load(&account.file).unwrap(); | ||
| let kept = gitv_web::auth::Credentials::load(&account.file).unwrap(); | ||
| assert!(kept.verify_password(&account.password), "a refused setup replaced the account"); | ||
| } | ||
| #[test] | ||
| fn uses_um9i_by_default() { | ||
| fn names_the_first_account_admin_and_keeps_the_name_when_replacing_it() { | ||
| let dir = scratch("auth-setup-user"); | ||
| let account = common::Account::create(&dir); | ||
| assert_eq!(gitv::auth::Credentials::load(&account.file).unwrap().user(), "Um9i"); | ||
| let file = dir.join("login"); | ||
| let setup = |args: &[&str]| { | ||
| let out = | ||
| Command::new(&*common::GITV_WEB).arg("setup").args(args).env("GITV_WEB_AUTH", &file).output().unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| gitv_web::auth::Credentials::load(&file).unwrap().user().to_string() | ||
| }; | ||
| assert_eq!(setup(&[]), "admin"); | ||
| assert_eq!(setup(&["--force", "--user", "Um9i"]), "Um9i"); | ||
| assert_eq!(setup(&["--force"]), "Um9i", "a replaced account keeps its name"); | ||
| } | ||
| #[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("/"); | ||
| let index = s.get_signed_out("/"); | ||
| assert_eq!(index.status, 200); | ||
| assert!(index.text().contains("No public repositories yet")); | ||
| let response = s.get_signed_out("/account"); | ||
| assert_eq!(response.status, 503); | ||
| assert!(response.text().contains("gitv-web setup")); | ||
| } | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| //! Helpers for the web tests: the shared ones, and a server and HTTP client of their own. | ||
| #![allow(dead_code, unused_imports)] | ||
| #[path = "../../../../testing/host.rs"] | ||
| mod host; | ||
| mod web; | ||
| pub use host::*; | ||
| pub use web::*; | ||
+68−147
| @@ -1,135 +1,14 @@ | ||
| //! Shared helpers for the integration tests: isolated git, a stand-in for ssh that runs | ||
| //! `gitv serve`, and a minimal HTTP client. | ||
| #![allow(dead_code)] | ||
| //! The web tests' own helpers: a running `gitv-web` with its own account, and a minimal HTTP | ||
| //! client. | ||
| use std::collections::HashMap; | ||
| use std::fs; | ||
| use std::io::{BufRead, BufReader, Read, Write}; | ||
| use std::net::TcpStream; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Child, Command, Output, Stdio}; | ||
| pub const GITV: &str = env!("CARGO_BIN_EXE_gitv"); | ||
| pub const GITV_WEB: &str = env!("CARGO_BIN_EXE_gitv-web"); | ||
| /// A fresh, empty directory under Cargo's per-target temporary directory. | ||
| pub fn scratch(name: &str) -> PathBuf { | ||
| let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| /// Git with no user or system config and a fixed identity and clock, so runs are repeatable. | ||
| pub fn git_cmd(dir: &Path) -> Command { | ||
| let mut command = Command::new("git"); | ||
| command | ||
| .current_dir(dir) | ||
| .env("HOME", dir) | ||
| .env("GIT_CONFIG_NOSYSTEM", "1") | ||
| .env("GIT_CONFIG_GLOBAL", "/dev/null") | ||
| .env("GIT_AUTHOR_NAME", "Ada Lovelace") | ||
| .env("GIT_AUTHOR_EMAIL", "ada@example.com") | ||
| .env("GIT_COMMITTER_NAME", "Ada Lovelace") | ||
| .env("GIT_COMMITTER_EMAIL", "ada@example.com") | ||
| .env("GIT_AUTHOR_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_COMMITTER_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_SSH_VARIANT", "simple") | ||
| .stdin(Stdio::null()); | ||
| command | ||
| } | ||
| /// Run git in `dir`, panic with its output on failure, and return trimmed stdout. | ||
| pub fn git(dir: &Path, args: &[&str]) -> String { | ||
| let output = git_cmd(dir).args(args).output().unwrap(); | ||
| assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr)); | ||
| String::from_utf8_lossy(&output.stdout).trim().to_string() | ||
| } | ||
| /// A GITv installation in a scratch directory: repositories, a keys file, and a fake `ssh` | ||
| /// that hands git's command to `gitv serve` as an owner's key would. | ||
| pub struct Host { | ||
| pub dir: PathBuf, | ||
| pub repos: PathBuf, | ||
| pub keys: PathBuf, | ||
| } | ||
| impl Host { | ||
| pub fn new(name: &str) -> Host { | ||
| let dir = scratch(name); | ||
| let repos = dir.join("repos"); | ||
| fs::create_dir_all(&repos).unwrap(); | ||
| let keys = dir.join("authorized_keys"); | ||
| let host = Host { dir, repos, keys }; | ||
| // With GIT_SSH_VARIANT=simple git runs: <ssh> <owner>@host <command>. | ||
| let script = format!( | ||
| "#!/bin/sh\nowner=${{1%%@*}}\nSSH_ORIGINAL_COMMAND=\"$2\" GITV_REPOS='{}' GITV_LOG='{}' exec '{GITV}' serve \"$owner\"\n", | ||
| host.repos.display(), | ||
| host.log().display() | ||
| ); | ||
| let ssh = host.ssh_script(); | ||
| fs::write(&ssh, script).unwrap(); | ||
| fs::set_permissions(&ssh, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| host | ||
| } | ||
| use std::process::{Child, Command, Stdio}; | ||
| /// Where `gitv` writes its operator log in tests. | ||
| pub fn log(&self) -> PathBuf { | ||
| self.dir.join("operator.log") | ||
| } | ||
| /// The operator log so far, empty if nothing was logged. | ||
| pub fn logged(&self) -> String { | ||
| fs::read_to_string(self.log()).unwrap_or_default() | ||
| } | ||
| pub fn ssh_script(&self) -> PathBuf { | ||
| self.dir.join("fake-ssh") | ||
| } | ||
| /// `ssh git@host <command>` as `owner`'s key. | ||
| pub fn ssh(&self, owner: &str, command: &str) -> Output { | ||
| Command::new(GITV) | ||
| .args(["serve", owner]) | ||
| .env("SSH_ORIGINAL_COMMAND", command) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// `gitv <args>` as the administrator, pointed at this host. | ||
| pub fn admin(&self, args: &[&str]) -> Output { | ||
| Command::new(GITV) | ||
| .args(args) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_KEYS", &self.keys) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// Git in `dir`, with remotes reached through this host's fake ssh. | ||
| pub fn git(&self, dir: &Path, args: &[&str]) -> Output { | ||
| git_cmd(dir).env("GIT_SSH_COMMAND", self.ssh_script()).args(args).output().unwrap() | ||
| } | ||
| pub fn repo(&self, owner: &str, name: &str) -> PathBuf { | ||
| self.repos.join(owner).join(format!("{name}.git")) | ||
| } | ||
| } | ||
| pub fn stdout(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stdout).into_owned() | ||
| } | ||
| pub fn stderr(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stderr).into_owned() | ||
| } | ||
| use super::{GITV_WEB, NO_CONFIG, TEST_HOST, scratch, stderr, stdout}; | ||
| /// A web account made by `gitv-web setup`: where it's stored, and what it printed. | ||
| #[derive(Clone)] | ||
| @@ -143,7 +22,8 @@ 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(); | ||
| let out = | ||
| Command::new(&*GITV_WEB).args(["setup", "--user", "Um9i"]).env("GITV_WEB_AUTH", &file).output().unwrap(); | ||
| assert!(out.status.success(), "setup failed: {}", stderr(&out)); | ||
| let printed = stdout(&out); | ||
| let field = |label: &str| { | ||
| @@ -161,8 +41,8 @@ impl Account { | ||
| /// 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)) | ||
| let step = gitv_web::auth::totp_step(now).saturating_add_signed(offset); | ||
| format!("{:06}", gitv_web::auth::totp_code(&self.secret, step)) | ||
| } | ||
| } | ||
| @@ -176,10 +56,12 @@ fn account_dir() -> PathBuf { | ||
| /// 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 child: Child, | ||
| pub port: u16, | ||
| pub account: Account, | ||
| pub cookie: Option<String>, | ||
| /// Where the server's stderr (its log) goes. | ||
| pub log: PathBuf, | ||
| } | ||
| impl Server { | ||
| @@ -222,7 +104,7 @@ impl Server { | ||
| } | ||
| fn launch(repos: &Path, limit: Option<u64>, account: Account) -> Server { | ||
| let mut command = Command::new(GITV_WEB); | ||
| let mut command = Command::new(&*GITV_WEB); | ||
| if let Some(limit) = limit { | ||
| use std::os::unix::process::CommandExt; | ||
| // SAFETY: setrlimit is async-signal-safe and the closure does nothing else. | ||
| @@ -233,12 +115,17 @@ impl Server { | ||
| }); | ||
| } | ||
| } | ||
| static LAUNCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | ||
| let number = LAUNCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| let log = account.file.with_file_name(format!("server-{}-{number}.log", std::process::id())); | ||
| let mut child = command | ||
| .args(["serve", "--port", "0"]) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", repos) | ||
| .env("GITV_WEB_AUTH", &account.file) | ||
| .stdout(Stdio::piped()) | ||
| .stderr(Stdio::null()) | ||
| .stderr(fs::File::create(&log).unwrap()) | ||
| .spawn() | ||
| .unwrap(); | ||
| let mut line = String::new(); | ||
| @@ -249,7 +136,12 @@ impl Server { | ||
| .and_then(|rest| rest.split_whitespace().next()) | ||
| .and_then(|p| p.parse().ok()) | ||
| .unwrap_or_else(|| panic!("unexpected startup line: {line}")); | ||
| Server { child, port, account, cookie: None } | ||
| Server { child, port, account, cookie: None, log } | ||
| } | ||
| /// What the server has logged so far. | ||
| pub fn logged(&self) -> String { | ||
| fs::read_to_string(&self.log).unwrap_or_default() | ||
| } | ||
| /// GET with the session cookie, if signed in. | ||
| @@ -271,13 +163,33 @@ impl Server { | ||
| pub fn post_signed_out(&self, path: &str, form: &[(&str, &str)]) -> Response { | ||
| request(self.port, "POST", path, None, Some(&form_body(form))) | ||
| } | ||
| /// POST a form without any cookie, as Caddy forwards one from the client at `address`. | ||
| pub fn post_signed_out_from(&self, address: &str, path: &str, form: &[(&str, &str)]) -> Response { | ||
| let extra = [("X-Forwarded-For", address)]; | ||
| request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra) | ||
| } | ||
| /// Like [`Server::post_signed_out_from`], from a browser carrying the trusted-device token | ||
| /// `device`. | ||
| pub fn post_from_device(&self, address: &str, device: &str, path: &str, form: &[(&str, &str)]) -> Response { | ||
| let cookie = format!("__Host-gitv-device={device}"); | ||
| let extra = [("X-Forwarded-For", address), ("Cookie", cookie.as_str())]; | ||
| request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra) | ||
| } | ||
| } | ||
| /// The session token a response's `Set-Cookie` gives, if any. | ||
| pub fn session_cookie(response: &Response) -> Option<String> { | ||
| set_cookie(response, "__Host-gitv") | ||
| } | ||
| /// The value a response's `Set-Cookie` headers give the cookie `name`, if any. | ||
| pub fn set_cookie(response: &Response, name: &str) -> Option<String> { | ||
| response | ||
| .header("set-cookie") | ||
| .strip_prefix("__Host-gitv=")? | ||
| .lines() | ||
| .find_map(|line| line.strip_prefix(name)?.strip_prefix('='))? | ||
| .split(';') | ||
| .next() | ||
| .filter(|t| !t.is_empty()) | ||
| @@ -322,8 +234,22 @@ impl 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 { | ||
| request_with(port, method, path, cookie, form, &[]) | ||
| } | ||
| fn request_with( | ||
| port: u16, | ||
| method: &str, | ||
| path: &str, | ||
| cookie: Option<&str>, | ||
| form: Option<&str>, | ||
| extra: &[(&str, &str)], | ||
| ) -> Response { | ||
| let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); | ||
| let mut head = format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n"); | ||
| for (name, value) in extra { | ||
| head += &format!("{name}: {value}\r\n"); | ||
| } | ||
| if let Some(cookie) = cookie { | ||
| head += &format!("Cookie: __Host-gitv={cookie}\r\n"); | ||
| } | ||
| @@ -338,10 +264,15 @@ fn request(port: u16, method: &str, path: &str, cookie: Option<&str>, form: Opti | ||
| let head = String::from_utf8_lossy(&raw[..split]).into_owned(); | ||
| let mut lines = head.lines(); | ||
| let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap(); | ||
| let headers: HashMap<String, String> = lines | ||
| .filter_map(|l| l.split_once(':')) | ||
| .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string())) | ||
| .collect(); | ||
| // A repeated header (Set-Cookie, say) keeps every value, one per line. | ||
| let mut headers: HashMap<String, String> = HashMap::new(); | ||
| for (name, value) in lines.filter_map(|l| l.split_once(':')) { | ||
| let entry = headers.entry(name.trim().to_ascii_lowercase()).or_default(); | ||
| if !entry.is_empty() { | ||
| entry.push('\n'); | ||
| } | ||
| entry.push_str(value.trim()); | ||
| } | ||
| let mut body = raw[split + 4..].to_vec(); | ||
| if headers.get("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) { | ||
| body = dechunk(&body); | ||
| @@ -361,13 +292,3 @@ fn dechunk(mut data: &[u8]) -> Vec<u8> { | ||
| } | ||
| out | ||
| } | ||
| /// A syntactically valid OpenSSH Ed25519 public key built from `seed`. | ||
| pub fn ed25519_key(seed: u8) -> String { | ||
| use base64::Engine; | ||
| let mut blob = 11u32.to_be_bytes().to_vec(); | ||
| blob.extend_from_slice(b"ssh-ed25519"); | ||
| blob.extend_from_slice(&32u32.to_be_bytes()); | ||
| blob.extend_from_slice(&[seed; 32]); | ||
| format!("ssh-ed25519 {} test@example\n", base64::engine::general_purpose::STANDARD.encode(blob)) | ||
| } | ||
crates/gitv-web/tests/web.rsRenamed
+480−14
| @@ -157,6 +157,7 @@ fn fixture() -> &'static Fixture { | ||
| let out = host.git(&work, &[&["push", "-q", "ada@x:ada/site.git"][..], &refs, &extra].concat()); | ||
| assert!(out.status.success(), "{}", common::stderr(&out)); | ||
| assert!(host.admin(&["create", "ada", "empty"]).status.success()); | ||
| assert!(host.admin(&["description", "ada", "site", "Docs & <b>source</b> for the site"]).status.success()); | ||
| // The same README in a second repository: its links must stay in that repository. | ||
| let out = host.git(&work, &["push", "-q", "ada@x:ada/twin.git", &format!("{first}:refs/heads/main")]); | ||
| assert!(out.status.success(), "{}", common::stderr(&out)); | ||
| @@ -250,9 +251,10 @@ fn diff_links_survive_odd_names() { | ||
| for (shown, encoded) in | ||
| [("x b/c.txt", "x%20b/c.txt"), ("q\"uote.txt", "q%22uote.txt"), ("latin1-caf\u{fffd}.txt", "latin1-caf%E9.txt")] | ||
| { | ||
| assert!(html.contains(&format!("<b>{shown}</b>")), "{shown} missing: {html}"); | ||
| // Templates write `"` and `&` as numeric entities. | ||
| assert!(html.contains(&format!("<b>{}</b>", shown.replace('"', """))), "{shown} missing: {html}"); | ||
| let path = format!("/ada/site/blob?ref={}&path={encoded}", fixture().oddities); | ||
| assert!(html.contains(&path.replace('&', "&")), "{shown} isn't linked to {path}"); | ||
| assert!(html.contains(&path.replace('&', "&")), "{shown} isn't linked to {path}"); | ||
| assert_eq!(s.get(&path).status, 200, "{path}"); | ||
| } | ||
| let log = s.get("/ada/site/log?ref=odd").text(); | ||
| @@ -263,7 +265,10 @@ fn diff_links_survive_odd_names() { | ||
| fn a_markdown_readme_wins_over_a_plain_one() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree?ref=odd&path=pref").text(); | ||
| assert!(html.contains("<b>README.md</b>") && html.contains("<h1>Markdown readme</h1>"), "{html}"); | ||
| assert!( | ||
| html.contains("<b>README.md</b>") && html.contains("<h1 id=\"md-markdown-readme\">Markdown readme</h1>"), | ||
| "{html}" | ||
| ); | ||
| } | ||
| #[test] | ||
| @@ -271,6 +276,8 @@ fn huge_commits_still_show_what_changed() { | ||
| let s = server(); | ||
| let page = s.get(&format!("/ada/site/commit?id={}", fixture().huge)); | ||
| assert_eq!(page.status, 200, "the commit exists even when its diff is huge"); | ||
| let upper = s.get(&format!("/ada/site/commit?id={}", fixture().huge[..12].to_uppercase())); | ||
| assert_eq!(upper.status, 200, "an id in capitals names the same commit"); | ||
| let html = page.text(); | ||
| assert!(html.contains("<h2 class=\"ctitle\">Add a huge file</h2>")); | ||
| assert!(html.contains("too large to show line by line"), "{html}"); | ||
| @@ -287,6 +294,8 @@ fn every_page_sends_the_security_headers() { | ||
| assert!(csp.contains("default-src 'none'") && !csp.contains("script-src"), "{path}: {csp}"); | ||
| assert_eq!(page.header("x-content-type-options"), "nosniff", "{path}"); | ||
| assert_eq!(page.header("referrer-policy"), "no-referrer", "{path}"); | ||
| let sandboxed = csp.split(';').any(|d| d.trim() == "sandbox"); | ||
| assert_eq!(sandboxed, path.contains("/raw"), "raw files, and only they, are sandboxed: {path}: {csp}"); | ||
| } | ||
| } | ||
| @@ -307,6 +316,11 @@ fn static_assets_are_served_and_the_stylesheet_is_versioned() { | ||
| ("/fonts/display.woff2", "font/woff2"), | ||
| ("/fonts/text.woff2", "font/woff2"), | ||
| ("/fonts/mono.woff2", "font/woff2"), | ||
| ("/manifest.webmanifest", "application/manifest+json"), | ||
| ("/icons/192.png", "image/png"), | ||
| ("/icons/512.png", "image/png"), | ||
| ("/icons/maskable.png", "image/png"), | ||
| ("/apple-touch-icon.png", "image/png"), | ||
| ] { | ||
| let asset = s.get(path); | ||
| assert_eq!((asset.status, asset.header("content-type")), (200, kind), "{path}"); | ||
| @@ -314,6 +328,34 @@ fn static_assets_are_served_and_the_stylesheet_is_versioned() { | ||
| } | ||
| } | ||
| #[test] | ||
| fn the_browser_can_install_gitv_as_an_app() { | ||
| let s = server(); | ||
| let page = s.get_signed_out("/login"); | ||
| assert!(page.header("content-security-policy").contains("manifest-src 'self'")); | ||
| let html = page.text(); | ||
| assert!(html.contains(r#"<link rel="manifest" href="/manifest.webmanifest">"#), "{html}"); | ||
| assert!(html.contains(r#"<link rel="apple-touch-icon" href="/apple-touch-icon.png">"#), "{html}"); | ||
| let manifest = s.get_signed_out("/manifest.webmanifest"); | ||
| assert_eq!(manifest.status, 200, "signed-out visitors can install from the sign-in page"); | ||
| let json = manifest.text(); | ||
| for field in [ | ||
| r#""name":"GITv""#, | ||
| r#""start_url":"/""#, | ||
| r#""display":"standalone""#, | ||
| r#""sizes":"192x192""#, | ||
| r#""sizes":"512x512""#, | ||
| ] { | ||
| assert!(json.contains(field), "{field} in {json}"); | ||
| } | ||
| for src in json.split(r#""src":""#).skip(1).map(|rest| &rest[..rest.find('"').unwrap()]) { | ||
| let file = s.get_signed_out(src); | ||
| assert_eq!(file.status, 200, "{src}"); | ||
| assert!(file.header("content-type").starts_with("image/"), "{src}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn repository_root_redirects_to_the_tree() { | ||
| let s = server(); | ||
| @@ -334,10 +376,10 @@ fn tree_lists_folders_first_and_renders_the_readme() { | ||
| assert!(html.contains("Commits<span class=\"n\">5</span>"), "commit count on main, side included"); | ||
| assert!(html.contains("Tags<span class=\"n\">3</span>")); | ||
| assert!(html.contains("Add a submodule and a big file"), "latest commit in the header"); | ||
| assert!(html.contains("git@git.um9i.dev:ada/site.git"), "clone address"); | ||
| assert!(html.contains("git@git.example.test:ada/site.git"), "clone address"); | ||
| // README rendering: Markdown, safe links and escaped HTML. | ||
| assert!(html.contains("<article class=\"markdown\"><h1>Fixture {onclick=alert(1) #main .skip}</h1>"), "{html}"); | ||
| assert!(html.contains("<article class=\"markdown\"><h1 id=\"md-fixture-onclickalert1-main-skip\">Fixture {onclick=alert(1) #main .skip}</h1>"), "{html}"); | ||
| assert!(html.contains("href=\"/ada/site/blob?ref=main&path=docs/guide.md\"")); | ||
| assert!(html.contains("href=\"/ada/site/blob?ref=main&path=src\"")); | ||
| assert!(html.contains("href=\"https://example.com\"")); | ||
| @@ -361,7 +403,28 @@ fn tree_rows_link_each_entry_to_its_own_change() { | ||
| .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}"); | ||
| assert!( | ||
| row.contains(message) && row.contains("title=\"2 Jan 2026, 03:04:05 +0000\">2 Jan 2026</time>"), | ||
| "{row}" | ||
| ); | ||
| } | ||
| } | ||
| #[test] | ||
| fn directory_history_matches_git_on_each_side_of_the_batch_boundary() { | ||
| let server = server(); | ||
| let bare = fixture().repos.join("ada/site.git"); | ||
| for (reference, path) in [("main", "big.txt"), ("main", "vendor"), ("main", "side.txt"), ("long", "README.md")] { | ||
| let expected = git(&bare, &["log", "-1", "--format=%H", reference, "--", path]); | ||
| assert!(!expected.is_empty()); | ||
| let page = server.get(&format!("/ada/site/tree?ref={reference}")).text(); | ||
| let row = page | ||
| .split("<li class=\"tree-row\">") | ||
| .skip(1) | ||
| .filter_map(|row| row.split_once("</li>").map(|(row, _)| row)) | ||
| .find(|row| row.contains(&format!(">{path}<"))) | ||
| .unwrap(); | ||
| assert!(row.contains(&format!("/ada/site/commit?id={expected}")), "{reference}:{path}: {row}"); | ||
| } | ||
| } | ||
| @@ -401,12 +464,18 @@ fn file_view_highlights_with_line_numbers() { | ||
| let page = s.get("/ada/site/blob?path=src/main.rs"); | ||
| assert_eq!(page.status, 200); | ||
| let html = page.text(); | ||
| assert!(html.contains("<pre class=\"gutter\" aria-hidden=\"true\">1\n2\n3\n</pre>"), "{html}"); | ||
| assert!( | ||
| html.contains( | ||
| "<pre class=\"gutter\"><a id=\"L1\" href=\"#L1\">1</a>\n<a id=\"L2\" href=\"#L2\">2</a>\n\ | ||
| <a id=\"L3\" href=\"#L3\">3</a>\n</pre>" | ||
| ), | ||
| "every line number links to itself: {html}" | ||
| ); | ||
| assert!(html.contains("hl-"), "highlighted"); | ||
| assert!(html.contains("changed") && !html.contains("<hi>"), "current content, escaped"); | ||
| assert!(html.contains("3 lines, 39 bytes")); | ||
| assert!(html.contains("<b>main.rs</b>")); | ||
| assert!(html.contains("href=\"/ada/site/raw?ref=main&path=src/main.rs\">Raw")); | ||
| assert!(html.contains("href=\"/ada/site/raw?ref=main&path=src/main.rs\">Raw")); | ||
| // A second view comes from the cache and is identical. | ||
| assert_eq!(s.get("/ada/site/blob?path=src/main.rs").text(), html); | ||
| @@ -416,7 +485,7 @@ fn file_view_highlights_with_line_numbers() { | ||
| fn markdown_files_have_preview_and_code_views() { | ||
| let s = server(); | ||
| let preview = s.get("/ada/site/blob?path=docs/guide.md").text(); | ||
| assert!(preview.contains("<article class=\"markdown\"><h1>Guide</h1>"), "{preview}"); | ||
| assert!(preview.contains("<article class=\"markdown\"><h1 id=\"md-guide\">Guide</h1>"), "{preview}"); | ||
| assert!(preview.contains("<table>")); | ||
| assert!(preview.contains("href=\"/ada/site/blob?ref=main&path=src/main.rs\""), "relative link resolved"); | ||
| assert!(preview.contains("aria-current=\"true\">Preview")); | ||
| @@ -498,7 +567,7 @@ fn history_lists_commits_with_tags_and_pages() { | ||
| assert_eq!(order.len(), 5); | ||
| assert!(order.windows(2).all(|w| w[0] < w[1]), "out of order: {order:?}"); | ||
| assert!(html.contains(">v0.1.0</a>") && html.contains(">light</a>"), "tag chips"); | ||
| assert!(html.contains("Ada Lovelace committed 2026-01-02")); | ||
| assert!(html.contains("Ada Lovelace committed 2 Jan 2026")); | ||
| assert!(!html.contains(">Older<"), "one page is enough for main"); | ||
| let first = s.get("/ada/site/log?ref=long").text(); | ||
| @@ -518,12 +587,12 @@ fn commit_shows_message_facts_and_diff() { | ||
| assert!(html.contains("<h2 class=\"ctitle\">Remove old.txt</h2>")); | ||
| assert!(html.contains(&format!("<span class=\"sha\">{}</span>", &f.removal[..12]))); | ||
| assert!(html.contains(&format!("id={}\" ", f.first)) || html.contains(&format!("id={}\"", f.first)), "parent link"); | ||
| assert!(html.contains("3 files changed"), "{html}"); | ||
| assert!(html.contains("3 files changed <span class=\"plus\">+"), "the totals follow the count: {html}"); | ||
| assert!(html.contains("<span class=\"status\">Deleted</span>")); | ||
| // A deleted file links to its last version, in the parent commit. | ||
| assert!(html.contains(&format!("href=\"/ada/site/blob?ref={}&path=old.txt\"", f.first))); | ||
| assert!(html.contains(&format!("href=\"/ada/site/blob?ref={}&path=old.txt\"", f.first))); | ||
| assert!(html.contains("<tr class=\"del\"><td class=\"num\" data-n=\"1\"></td><td class=\"num\" data-n=\"\"></td><td class=\"line\" data-s=\"-\">going away</td></tr>")); | ||
| assert!(html.contains("data-s=\"+\"> println!(\"changed\");</td>")); | ||
| assert!(html.contains("data-s=\"+\"> println!("changed");</td>")); | ||
| assert!(html.contains(&format!("href=\"/ada/site/tree?ref={}\">Browse files", f.removal))); | ||
| let first = s.get(&format!("/ada/site/commit?id={}", &f.first[..10])).text(); | ||
| @@ -570,7 +639,7 @@ fn empty_repository_explains_how_to_start() { | ||
| assert_eq!(page.status, 200); | ||
| let html = page.text(); | ||
| assert!(html.contains("This repository is empty")); | ||
| assert!(html.contains("git push git@git.um9i.dev:ada/empty.git main")); | ||
| assert!(html.contains("git push git@git.example.test:ada/empty.git main")); | ||
| let tags = s.get("/ada/empty/tags").text(); | ||
| assert!(tags.contains("No tags yet")); | ||
| } | ||
| @@ -779,3 +848,400 @@ fn the_index_fingerprint_survives_many_branch_folders() { | ||
| let html = s.get("/").text(); | ||
| assert!(html.contains("After"), "the index is stale: {}", &html[..html.len().min(800)]); | ||
| } | ||
| #[test] | ||
| fn public_web_clone_and_visibility_changes() { | ||
| let host = Host::new("web-visibility"); | ||
| let work = common::scratch("visibility-work"); | ||
| git(&work, &["init", "-qb", "main"]); | ||
| fs::write(work.join("hello"), "public content").unwrap(); | ||
| git(&work, &["add", "hello"]); | ||
| git(&work, &["commit", "-qm", "Public tip"]); | ||
| assert!(host.git(&work, &["push", "ada@test:ada/sharing.git", "main"]).status.success()); | ||
| assert!(host.admin(&["create", "ada", "secret"]).status.success()); | ||
| let server = Server::start(&host.repos); | ||
| let url = format!("http://127.0.0.1:{}/ada/sharing", server.port); | ||
| let refs = "/ada/sharing/info/refs?service=git-upload-pack"; | ||
| assert_eq!(server.get_signed_out(refs).status, 404); | ||
| let empty = server.get_signed_out("/"); | ||
| assert_eq!(empty.status, 200); | ||
| assert!(empty.text().contains("No public repositories yet")); | ||
| assert!(!empty.text().contains("/ada/")); | ||
| assert!(host.ssh("ada", "visibility sharing public").status.success()); | ||
| let index = server.get_signed_out("/").text(); | ||
| assert!(index.contains("/ada/sharing/tree")); | ||
| assert!(!index.contains("/ada/secret/tree")); | ||
| assert!(server.get("/").text().contains("/ada/secret/tree")); | ||
| let page = server.get_signed_out("/ada/sharing/tree").text(); | ||
| assert!(page.contains("https://git.example.test/ada/sharing")); | ||
| // Visitors see only the HTTPS address; the signed-in operator also sees SSH and the visibility. | ||
| assert!(!page.contains("git@git.example.test") && !page.contains("class=\"vis\""), "{page}"); | ||
| let operator = server.get("/ada/sharing/tree").text(); | ||
| assert!(operator.contains("value=\"https://git.example.test/ada/sharing\""), "{operator}"); | ||
| assert!(operator.contains("value=\"git@git.example.test:ada/sharing.git\""), "{operator}"); | ||
| assert!(operator.contains("<span class=\"vis\">Public</span>"), "{operator}"); | ||
| assert!(!operator.contains(">Protected<"), "{operator}"); | ||
| assert!(host.ssh("ada", "protect sharing on").status.success()); | ||
| assert!(server.get("/ada/sharing/tree").text().contains(">Protected</span>")); | ||
| assert!(!server.get_signed_out("/ada/sharing/tree").text().contains("Protected"), "only the operator sees it"); | ||
| assert_eq!(server.get_signed_out("/ada/sharing/raw?path=hello").text(), "public content"); | ||
| // Both protocol versions clone; version 2 is what the server speaks when asked. | ||
| for version in ["0", "2"] { | ||
| let out = common::git_cmd(&work) | ||
| .args(["-c", &format!("protocol.version={version}"), "clone", "-q", &url, &format!("copy-v{version}")]) | ||
| .env("GIT_TRACE_PACKET", "1") | ||
| .output() | ||
| .unwrap(); | ||
| assert!(out.status.success(), "v{version}: {}", String::from_utf8_lossy(&out.stderr)); | ||
| let trace = String::from_utf8_lossy(&out.stderr); | ||
| assert_eq!(trace.contains("< version 2"), version == "2", "v{version}: {trace}"); | ||
| let copy = work.join(format!("copy-v{version}")); | ||
| assert_eq!(git(©, &["rev-parse", "HEAD"]), git(&work, &["rev-parse", "HEAD"])); | ||
| } | ||
| // The address with `.git`, as people often type it, clones too. | ||
| let out = common::git_cmd(&work).args(["clone", "-q", &format!("{url}.git"), "copy-dotgit"]).output().unwrap(); | ||
| assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); | ||
| let copy = work.join("copy-v2"); | ||
| assert!(!host.git(©, &["push", "origin", "HEAD:forbidden"]).status.success()); | ||
| assert!(host.admin(&["visibility", "ada", "sharing", "private"]).status.success()); | ||
| assert_eq!(server.get_signed_out(refs).status, 404); | ||
| assert!(!host.git(©, &["fetch"]).status.success()); | ||
| for view in ["tree", "blob?path=hello", "raw?path=hello", "log", "commit", "tags"] { | ||
| assert_eq!(server.get_signed_out(&format!("/ada/sharing/{view}")).status, 303); | ||
| } | ||
| assert_eq!(server.get("/ada/sharing/raw?path=hello").text(), "public content"); | ||
| } | ||
| #[test] | ||
| fn byte_named_refs_and_paged_trees_keep_the_selected_revision() { | ||
| let host = Host::new("byte-ref-pages"); | ||
| let work = common::scratch("byte-ref-pages-work"); | ||
| git(&work, &["init", "-qb", "main"]); | ||
| for n in 0..52 { | ||
| fs::write(work.join(format!("file-{n:02}")), b"original").unwrap(); | ||
| } | ||
| git(&work, &["add", "."]); | ||
| git(&work, &["commit", "-qm", "First"]); | ||
| fs::write(work.join("file-51"), b"second").unwrap(); | ||
| git(&work, &["commit", "-qam", "Second"]); | ||
| assert!(host.git(&work, &["push", "ada@test:ada/bytes.git", "main"]).status.success()); | ||
| let bare = host.repo("ada", "bytes"); | ||
| for name in [b"refs/heads/odd-\xff".as_slice(), b"refs/tags/odd-\xfe"] { | ||
| assert!( | ||
| common::git_cmd(&bare) | ||
| .arg("update-ref") | ||
| .arg(OsStr::from_bytes(name)) | ||
| .arg("HEAD^") | ||
| .status() | ||
| .unwrap() | ||
| .success() | ||
| ); | ||
| } | ||
| assert!( | ||
| common::git_cmd(&bare) | ||
| .args(["symbolic-ref", "HEAD"]) | ||
| .arg(OsStr::from_bytes(b"refs/heads/odd-\xff")) | ||
| .status() | ||
| .unwrap() | ||
| .success() | ||
| ); | ||
| let server = Server::start(&host.repos); | ||
| let tree = server.get("/ada/bytes/tree").text(); | ||
| assert!( | ||
| html_escape::decode_html_entities(&tree).contains("ref=odd-%FF&page=1"), | ||
| "{}", | ||
| tree.lines().filter(|l| l.contains("Next")).collect::<String>() | ||
| ); | ||
| assert!(!tree.contains("file-51")); | ||
| assert!(server.get("/ada/bytes/tree?ref=odd-%FF&page=1").text().contains("file-51")); | ||
| assert_eq!(server.get("/ada/bytes/raw?ref=odd-%FF&path=file-51").text(), "original"); | ||
| assert_eq!(server.get("/ada/bytes/raw?ref=odd-%FE&path=file-51").text(), "original"); | ||
| assert_eq!(server.get("/ada/bytes/raw?ref=main&path=file-51").text(), "second"); | ||
| assert!(server.get("/ada/bytes/tags").text().contains("ref=odd-%FE")); | ||
| assert!(server.get("/ada/bytes/log").text().contains("ref=odd-%FE")); | ||
| assert_eq!(server.get("/ada/bytes/tree?page=2").status, 404); | ||
| } | ||
| #[test] | ||
| fn sigterm_lets_a_download_in_progress_finish() { | ||
| use std::io::{Read, Write}; | ||
| let host = Host::new("web-shutdown"); | ||
| let work = common::scratch("web-shutdown-work"); | ||
| git(&work, &["init", "-qb", "main"]); | ||
| // Large enough that the response is still streaming when the signal arrives. | ||
| fs::write(work.join("big.bin"), vec![b'x'; 8 << 20]).unwrap(); | ||
| git(&work, &["add", "."]); | ||
| git(&work, &["commit", "-qm", "Big"]); | ||
| assert!(host.git(&work, &["push", "-q", "ada@test:ada/big.git", "main"]).status.success()); | ||
| assert!(host.ssh("ada", "visibility big public").status.success()); | ||
| let mut server = Server::start_signed_out(&host.repos); | ||
| let mut stream = std::net::TcpStream::connect(("127.0.0.1", server.port)).unwrap(); | ||
| write!(stream, "GET /ada/big/raw?path=big.bin HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap(); | ||
| let mut first = [0u8; 1024]; | ||
| let mut got = stream.read(&mut first).unwrap(); | ||
| assert!(got > 0, "the download started"); | ||
| // SAFETY: kill only sends a signal to the server this test started. | ||
| assert_eq!(unsafe { nix::libc::kill(server.child.id() as i32, nix::libc::SIGTERM) }, 0); | ||
| let mut rest = Vec::new(); | ||
| stream.read_to_end(&mut rest).unwrap(); | ||
| got += rest.len(); | ||
| let head_end = first.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4; | ||
| assert_eq!(got - head_end, 8 << 20, "the whole file arrived after the signal"); | ||
| let status = server.child.wait().unwrap(); | ||
| assert!(status.success(), "{status:?}"); | ||
| assert!(server.logged().contains("stopping; finishing requests in progress"), "{}", server.logged()); | ||
| assert!(std::net::TcpStream::connect(("127.0.0.1", server.port)).is_err(), "no new connections"); | ||
| } | ||
| #[test] | ||
| fn file_history_lists_only_the_commits_that_changed_it() { | ||
| let s = server(); | ||
| let f = fixture(); | ||
| let html = s.get("/ada/site/log?path=src/main.rs").text(); | ||
| let expected = git(&f.repos.join("ada/site.git"), &["log", "--format=%s", "main", "--", "src/main.rs"]); | ||
| assert_eq!(expected.lines().collect::<Vec<_>>(), ["Remove old.txt", "First commit"]); | ||
| for subject in expected.lines() { | ||
| assert!(html.contains(subject), "{subject} missing: {html}"); | ||
| } | ||
| assert!(!html.contains("Merge side") && !html.contains("Add a submodule"), "{html}"); | ||
| assert!(html.contains("<title>History of src/main.rs on main"), "{html}"); | ||
| // Literal paths: star*.txt is one file, not a pattern matching globber.txt's commit. | ||
| let star = s.get("/ada/site/log?path=star%2A.txt").text(); | ||
| assert_eq!(star.matches("class=\"commit-row\"").count(), 1, "{star}"); | ||
| // A folder's history, linked from its listing, and pages that keep the path. | ||
| let folder = s.get("/ada/site/tree?path=glob%2A").text(); | ||
| assert!(folder.contains("href=\"/ada/site/log?ref=main&path=glob%2A\">History"), "{folder}"); | ||
| let long = s.get("/ada/site/log?ref=long&path=README.md").text(); | ||
| assert_eq!(long.matches("class=\"commit-row\"").count(), 1, "the empty commits didn't touch README.md"); | ||
| assert_eq!(s.get("/ada/site/log?path=../README.md").status, 404); | ||
| } | ||
| #[test] | ||
| fn file_links_pin_the_commit_and_the_lines() { | ||
| let s = server(); | ||
| let f = fixture(); | ||
| let tip = f.tip.as_str(); | ||
| let html = s.get("/ada/site/blob?path=src/main.rs").text(); | ||
| assert!(html.contains("href=\"/ada/site/log?ref=main&path=src/main.rs\">History"), "{html}"); | ||
| let permalink = format!("href=\"/ada/site/blob?ref={tip}&path=src/main.rs\""); | ||
| assert!(html.contains(&permalink), "the permalink names the commit: {html}"); | ||
| // After the branch moves, the pinned link still shows the old content. | ||
| let pinned = s.get(&format!("/ada/site/blob?ref={}&path=src/main.rs", f.first)).text(); | ||
| assert!(pinned.contains("<hi>") && !pinned.contains("changed&"), "{pinned}"); | ||
| assert!(pinned.contains(&format!(">{}<", &f.first[..12])), "the menu shows a short id: {pinned}"); | ||
| // A selected range is marked by the server, and the permalink keeps it. | ||
| let range = s.get("/ada/site/blob?path=src/main.rs&lines=3-2").text(); | ||
| assert!(range.contains("<a id=\"L1\" href=\"#L1\">1</a>"), "{range}"); | ||
| assert!(range.contains("<a id=\"L2\" href=\"#L2\" class=\"sel\">2</a>"), "{range}"); | ||
| assert!(range.contains("<a id=\"L3\" href=\"#L3\" class=\"sel\">3</a>"), "{range}"); | ||
| let kept = format!("href=\"/ada/site/blob?ref={tip}&path=src/main.rs&lines=2-3#L2\""); | ||
| assert!(range.contains(&kept), "{range}"); | ||
| // A Markdown file's Code view stays the Code view when pinned. | ||
| let code = s.get("/ada/site/blob?path=docs/guide.md&view=code&lines=1").text(); | ||
| assert!(code.contains(&format!("blob?ref={tip}&path=docs/guide.md&view=code&lines=1#L1\"")), "{code}"); | ||
| // A selection that makes no sense selects nothing. | ||
| let bad = s.get("/ada/site/blob?path=src/main.rs&lines=x").text(); | ||
| assert!(!bad.contains("class=\"sel\""), "{bad}"); | ||
| } | ||
| #[test] | ||
| fn comparing_two_releases_lists_the_commits_and_changes_between_them() { | ||
| let s = server(); | ||
| let f = fixture(); | ||
| let html = s.get("/ada/site/compare?from=v0.1.0&to=light").text(); | ||
| assert!(html.contains("<title>Comparing v0.1.0...light"), "{html}"); | ||
| assert!(html.contains("light is 4 commits ahead of v0.1.0."), "{html}"); | ||
| let expected = git(&f.repos.join("ada/site.git"), &["log", "--format=%s", &format!("{}..{}", f.first, f.tip)]); | ||
| assert_eq!(expected.lines().count(), 4); | ||
| for subject in expected.lines() { | ||
| assert!(html.contains(subject), "{subject} missing"); | ||
| } | ||
| assert!(html.matches("class=\"commit-row\"").count() == 4, "{html}"); | ||
| // The changes since the release, with a deleted file linked where it last existed. | ||
| assert!(html.contains("<span class=\"status\">Deleted</span>"), "{html}"); | ||
| assert!(html.contains(&format!("href=\"/ada/site/blob?ref={}&path=old.txt\"", f.first)), "{html}"); | ||
| assert!(html.contains("<span class=\"status\">Added</span>") && html.contains(">side.txt<"), "{html}"); | ||
| assert!(html.contains("href=\"/ada/site/compare?from=light&to=v0.1.0\">Swap"), "{html}"); | ||
| // The same comparison the other way has nothing to show. | ||
| let back = s.get("/ada/site/compare?from=light&to=v0.1.0").text(); | ||
| assert!(back.contains("v0.1.0 has no commits that light lacks."), "{back}"); | ||
| assert!(!back.contains("class=\"commit-row\"") && !back.contains("changed</h2>"), "{back}"); | ||
| let same = s.get(&format!("/ada/site/compare?from=v0.1.0&to={}", f.first)).text(); | ||
| assert!(same.contains("are the same commit."), "{same}"); | ||
| // The tags page links each tag to the changes since the one before it. | ||
| let tags = s.get("/ada/site/tags").text(); | ||
| let link = tags.split("href=\"").find(|part| part.contains("compare?from=")).expect("a comparison link"); | ||
| let url = link.split('"').next().unwrap().replace("&", "&"); | ||
| assert_eq!(s.get(&url).status, 200, "{url}"); | ||
| assert!(tags.contains(">Changes since "), "{tags}"); | ||
| } | ||
| #[test] | ||
| fn a_diverged_branch_shows_only_its_own_changes() { | ||
| let s = server(); | ||
| // `long` left main at the first commit: 55 commits of its own, and 4 of main's it lacks. | ||
| let html = s.get("/ada/site/compare?from=main&to=long").text(); | ||
| assert!(html.contains("long is 55 commits ahead of main and 4 commits behind it."), "{html}"); | ||
| assert_eq!(html.matches("class=\"commit-row\"").count(), 55); | ||
| assert!(!html.contains("Remove old.txt"), "main's own commits aren't listed"); | ||
| // Compared from where the two diverged: main's removal of old.txt isn't a change here. | ||
| assert!(html.contains("0 files changed"), "{html}"); | ||
| assert!(!html.contains("old.txt"), "{html}"); | ||
| // Only `from` is needed; `to` defaults to the default branch. | ||
| let reverse = s.get("/ada/site/compare?from=long").text(); | ||
| assert!(reverse.contains("main is 4 commits ahead of long and 55 commits behind it."), "{reverse}"); | ||
| assert!(reverse.contains(">old.txt<"), "{reverse}"); | ||
| // A branch's history offers the comparison with the default branch; main's doesn't. | ||
| let log = s.get("/ada/site/log?ref=long").text(); | ||
| assert!(log.contains("href=\"/ada/site/compare?from=main&to=long\">Compare with main"), "{log}"); | ||
| assert!(!s.get("/ada/site/log").text().contains("Compare with")); | ||
| } | ||
| #[test] | ||
| fn the_compare_form_and_its_mistakes() { | ||
| let s = server(); | ||
| let form = s.get("/ada/site/compare"); | ||
| assert_eq!(form.status, 200); | ||
| let form = form.text(); | ||
| assert!(form.contains("<form class=\"panel form compare-form\" method=\"get\" action=\"/ada/site/compare\">")); | ||
| assert!(form.contains("<option value=\"v0.1.0\">") && form.contains("<option value=\"long\">"), "{form}"); | ||
| assert!(!form.contains("class=\"commit-row\"")); | ||
| let missing = s.get("/ada/site/compare?from=nope&to=main").text(); | ||
| assert!(missing.contains("There’s no branch, tag or commit named nope."), "{missing}"); | ||
| assert!(missing.contains("value=\"nope\""), "the form keeps what was asked: {missing}"); | ||
| // Escaped like everything else. | ||
| let odd = s.get("/ada/site/compare?from=%3Cb%3E").text(); | ||
| assert!(odd.contains("named <b>.") && !odd.contains("<b>."), "{odd}"); | ||
| // A private repository's comparison needs sign-in, like its other pages. | ||
| assert_eq!(s.get_signed_out("/ada/site/compare?from=v0.1.0&to=light").status, 303); | ||
| } | ||
| #[test] | ||
| fn the_index_shows_descriptions_and_filters_by_name_or_description() { | ||
| let s = server(); | ||
| let all = s.get("/").text(); | ||
| assert!( | ||
| all.contains("<span class=\"rdesc\">Docs & <b>source</b> for the site</span>"), | ||
| "{all}" | ||
| ); | ||
| assert!(all.contains("<input type=\"search\" name=\"q\" value=\"\""), "{all}"); | ||
| let total = all.matches("class=\"repo-row\"").count(); | ||
| assert!(total >= 3, "{all}"); | ||
| let by_name = s.get("/?q=TWIN").text(); | ||
| assert_eq!(by_name.matches("class=\"repo-row\"").count(), 1, "{by_name}"); | ||
| assert!(by_name.contains("href=\"/ada/twin/tree\"")); | ||
| assert!(by_name.contains(&format!("<p class=\"count\">1 of {total}</p>")), "{by_name}"); | ||
| assert!(by_name.contains("value=\"TWIN\"") && by_name.contains(">Clear</a>"), "{by_name}"); | ||
| let by_description = s.get("/?q=source+site").text(); | ||
| assert_eq!(by_description.matches("class=\"repo-row\"").count(), 1, "{by_description}"); | ||
| assert!(by_description.contains("href=\"/ada/site/tree\"")); | ||
| let none = s.get("/?q=%3Cnothing%3E").text(); | ||
| assert!(none.contains("No repositories match “<nothing>”"), "{none}"); | ||
| assert!(!none.contains("class=\"repo-row\"")); | ||
| } | ||
| #[test] | ||
| fn the_header_shows_the_description_visibility_and_clone_addresses() { | ||
| let s = server(); | ||
| let html = s.get("/ada/site/tree").text(); | ||
| assert!(html.contains("<p class=\"repodesc\">Docs & <b>source</b> for the site</p>"), "{html}"); | ||
| assert!(html.contains("<span class=\"vis\">Private</span>"), "{html}"); | ||
| assert_eq!(html.matches("class=\"clone\"").count(), 1, "a private repository clones over SSH only"); | ||
| assert!(html.contains("value=\"git@git.example.test:ada/site.git\""), "{html}"); | ||
| // No description: no empty paragraph. | ||
| assert!(!s.get("/ada/twin/tree").text().contains("repodesc")); | ||
| } | ||
| /// A gzip stream, decompressed by the system's gzip. | ||
| fn gunzip(data: &[u8]) -> Vec<u8> { | ||
| use std::io::Write as _; | ||
| let mut child = std::process::Command::new("gzip") | ||
| .arg("-dc") | ||
| .stdin(std::process::Stdio::piped()) | ||
| .stdout(std::process::Stdio::piped()) | ||
| .spawn() | ||
| .unwrap(); | ||
| child.stdin.take().unwrap().write_all(data).unwrap(); | ||
| let out = child.wait_with_output().unwrap(); | ||
| assert!(out.status.success(), "not a gzip stream"); | ||
| out.stdout | ||
| } | ||
| #[test] | ||
| fn tags_download_as_source_archives() { | ||
| let s = server(); | ||
| let f = fixture(); | ||
| let tags = s.get("/ada/site/tags").text(); | ||
| assert!(tags.contains("href=\"/ada/site/archive?ref=v0.1.0\" download>Source (.tar.gz)"), "{tags}"); | ||
| let download = s.get("/ada/site/archive?ref=refs/tags/v0.1.0"); | ||
| assert_eq!(download.status, 200); | ||
| assert_eq!(download.header("content-type"), "application/gzip"); | ||
| assert_eq!(download.header("content-disposition"), "attachment; filename=\"site-v0.1.0.tar.gz\""); | ||
| assert!(download.header("content-security-policy").starts_with("sandbox")); | ||
| // The same files, times and layout as git archive gives for the tag. | ||
| let repo = f.repos.join("ada/site.git"); | ||
| let local = | ||
| common::git_cmd(&repo).args(["archive", "--format=tar", "--prefix=site-v0.1.0/", "v0.1.0"]).output().unwrap(); | ||
| assert!(local.status.success()); | ||
| let tar = gunzip(&download.body); | ||
| assert!(tar == local.stdout, "the archive differs from git archive's"); | ||
| assert!(tar.windows(25).any(|w| w == b"site-v0.1.0/src/main.rs\0\0"), "files sit under the prefix"); | ||
| // A commit id names the file by a short id; a revision that doesn't exist isn't served. | ||
| let by_id = s.get(&format!("/ada/site/archive?ref={}", f.first)); | ||
| assert_eq!(by_id.header("content-disposition"), format!("attachment; filename=\"site-{}.tar.gz\"", &f.first[..12])); | ||
| assert_eq!(gunzip(&by_id.body).len(), tar.len()); | ||
| assert_eq!(s.get("/ada/site/archive?ref=nope").status, 404); | ||
| assert_eq!(s.get("/ada/site/archive").status, 404); | ||
| // A private repository's archive needs sign-in. | ||
| assert_eq!(s.get_signed_out("/ada/site/archive?ref=refs/tags/v0.1.0").status, 303); | ||
| } | ||
| #[test] | ||
| fn each_tag_compares_with_the_one_before_it_on_its_own_line() { | ||
| let host = Host::new("web-tag-pairs"); | ||
| let work = common::scratch("tag-pairs-work"); | ||
| git(&work, &["init", "-qb", "main"]); | ||
| let commit = |message: &str| git(&work, &["commit", "-q", "--allow-empty", "-m", message]); | ||
| commit("Root"); | ||
| commit("A"); | ||
| git(&work, &["tag", "v1"]); | ||
| commit("B"); | ||
| git(&work, &["checkout", "-qb", "side"]); | ||
| commit("S"); | ||
| git(&work, &["tag", "side-1"]); | ||
| git(&work, &["checkout", "-q", "main"]); | ||
| commit("C"); | ||
| git(&work, &["merge", "-q", "--no-ff", "-m", "Merge side", "side"]); | ||
| git(&work, &["tag", "-a", "v2", "-m", "Two"]); | ||
| commit("D"); | ||
| git(&work, &["tag", "v3"]); | ||
| let out = host.git(&work, &["push", "-q", "ada@x:ada/pairs.git", "main", "--tags"]); | ||
| assert!(out.status.success(), "{}", common::stderr(&out)); | ||
| let server = Server::start(&host.repos); | ||
| let html = server.get("/ada/pairs/tags").text(); | ||
| // Each row, by tag name, and the comparison it offers. | ||
| let offered = |tag: &str| { | ||
| let row = html.split("<li class=\"tag-row\">").find(|row| row.contains(&format!(">{tag}</span>"))).unwrap(); | ||
| row.split(">Changes since ").nth(1).map(|rest| rest.split('<').next().unwrap().to_string()) | ||
| }; | ||
| assert_eq!(offered("v3").as_deref(), Some("v2")); | ||
| assert_eq!(offered("v2").as_deref(), Some("v1"), "a merge's tag follows its main line: {html}"); | ||
| assert_eq!(offered("side-1").as_deref(), Some("v1")); | ||
| assert_eq!(offered("v1"), None, "the first release has nothing before it"); | ||
| assert!(html.contains("href=\"/ada/pairs/compare?from=v1&to=v2\">Changes since v1"), "{html}"); | ||
| } | ||
+15−0
| @@ -0,0 +1,15 @@ | ||
| [package] | ||
| name = "gitv" | ||
| description = "GITv's SSH command handler and administrator CLI" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| license.workspace = true | ||
| publish = false | ||
| [dependencies] | ||
| gitv-core.workspace = true | ||
| base64.workspace = true | ||
| clap.workspace = true | ||
| nix.workspace = true | ||
| sha2.workspace = true | ||
| shlex.workspace = true | ||
+1266−0
| @@ -0,0 +1,1266 @@ | ||
| //! Private Git hosting over OpenSSH and Git's native pack protocol. | ||
| use std::collections::BTreeMap; | ||
| use std::fs; | ||
| use std::io::Write; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, ExitCode, Stdio}; | ||
| use base64::Engine; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv_core::{ | ||
| DESCRIPTION_LIMIT, NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at, | ||
| open_dir_at, open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, unix_now, valid_name, | ||
| }; | ||
| use nix::errno::Errno; | ||
| use nix::fcntl::{Flock, FlockArg, OFlag, RenameFlags, openat, renameat2}; | ||
| use nix::sys::stat::{Mode, fchmod, fstat, mkdirat}; | ||
| use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, geteuid, unlinkat}; | ||
| use std::ffi::OsStr; | ||
| use std::os::fd::{AsFd, OwnedFd}; | ||
| use std::os::unix::ffi::OsStrExt; | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| /// What `help` prints. | ||
| fn help() -> String { | ||
| let host = config::host(); | ||
| format!( | ||
| "Commands for your key, run as: ssh git@{host} <command> | ||
| list list your repositories | ||
| create <name> create an empty repository | ||
| visibility <name> public|private set web access | ||
| protect <name> [on|off] show or set whether pushes may rewrite or delete branches | ||
| description <name> [<text>] show or set the one-line description (\"\" removes it) | ||
| default-branch <name> [<branch>] show or set the branch the web shows and clones check out | ||
| delete <name> --yes move a repository to the trash (the operator can restore it for 30 days) | ||
| Pushing to a repository that does not exist yet creates it." | ||
| ) | ||
| } | ||
| #[derive(Parser)] | ||
| #[command(about = "Private Git hosting over OpenSSH and Git's native pack protocol")] | ||
| struct Cli { | ||
| #[command(subcommand)] | ||
| action: Action, | ||
| } | ||
| #[derive(Subcommand)] | ||
| enum Action { | ||
| /// Create an empty repository (root) | ||
| Create { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| }, | ||
| /// Set repository web visibility to public or private (root) | ||
| Visibility { owner: String, name: String, visibility: String }, | ||
| /// Show or set whether pushes may force-update or delete branches (root) | ||
| Protect { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| /// on: branches only move forwards and are never deleted; off: anything | ||
| value: Option<String>, | ||
| }, | ||
| /// Show or set a repository's one-line description; "" removes it (root) | ||
| Description { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| text: Option<String>, | ||
| }, | ||
| /// Show or set the branch a repository's web pages show and clones check out (root) | ||
| DefaultBranch { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| branch: Option<String>, | ||
| }, | ||
| /// Move a repository to its owner's trash (root) | ||
| Delete { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| /// Confirm deletion | ||
| #[arg(long)] | ||
| yes: bool, | ||
| }, | ||
| /// List deleted repositories waiting in the trash (root) | ||
| Trash, | ||
| /// Put a deleted repository back, under its old name or another (root) | ||
| Restore { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| /// The trash entry, as `gitv trash` lists it: <name>.<deletion time> | ||
| entry: String, | ||
| /// Restore under this name instead | ||
| #[arg(long = "as", value_parser = name)] | ||
| as_name: Option<String>, | ||
| }, | ||
| /// Copy a bare repository, such as one gitv-restore brought back, into place (root) | ||
| Import { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| /// The name to give it; anything already there is never replaced | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| /// The restored repository's directory | ||
| source: PathBuf, | ||
| }, | ||
| /// Permanently remove trash entries deleted at least this many days ago (root) | ||
| Purge { | ||
| #[arg(long, default_value_t = TRASH_DAYS)] | ||
| older_than_days: u64, | ||
| }, | ||
| /// Register an Ed25519 public key for an owner (root) | ||
| AddKey { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| public_key: PathBuf, | ||
| /// A name for the device that holds the key, shown by `gitv keys` | ||
| #[arg(long, value_parser = label)] | ||
| label: Option<String>, | ||
| }, | ||
| /// List registered keys with their owner, fingerprint and label (root) | ||
| Keys { | ||
| /// Only this owner's keys | ||
| #[arg(value_parser = name)] | ||
| owner: Option<String>, | ||
| }, | ||
| /// Revoke a key by its fingerprint, as `gitv keys` lists it (root) | ||
| RemoveKey { | ||
| /// SHA256:<base64>, with or without the SHA256: prefix | ||
| fingerprint: String, | ||
| }, | ||
| /// Handle one SSH request (forced command from authorized_keys) | ||
| Serve { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| }, | ||
| } | ||
| /// [`check_name`], for clap's argument parsing. | ||
| fn name(value: &str) -> Result<String, String> { | ||
| check_name(value).map(str::to_string) | ||
| } | ||
| /// A key's label becomes the comment field of its authorized_keys line, so it must stay on one | ||
| /// line and hold nothing a terminal would act on. | ||
| fn label(value: &str) -> Result<String, String> { | ||
| let value = value.trim(); | ||
| if value.is_empty() || value.chars().count() > 64 || value.chars().any(char::is_control) { | ||
| return Err("a label is 1 to 64 characters, with no control characters".into()); | ||
| } | ||
| Ok(value.to_string()) | ||
| } | ||
| fn check_name(value: &str) -> Result<&str, String> { | ||
| if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) } | ||
| } | ||
| /// Record something for the operator. SSH users only ever see generic errors, so details go to | ||
| /// syslog (facility daemon, tag `gitv`), or, when `GITV_LOG` names a file, are appended there | ||
| /// for local runs and tests. | ||
| fn log_operator(message: &str) { | ||
| let mut message = message.to_string(); | ||
| if let Some(path) = std::env::var_os("GITV_LOG") { | ||
| // Only a record that was actually written counts; otherwise fall back to syslog, so | ||
| // the message is never lost, and say why it ended up there. | ||
| match append_line(Path::new(&path), &format!("gitv: {message}")) { | ||
| Ok(()) => return, | ||
| Err(e) => message = format!("{message} (couldn't write {}: {e})", Path::new(&path).display()), | ||
| } | ||
| } | ||
| let message = std::ffi::CString::new(message.replace('\0', " ")).unwrap_or_default(); | ||
| // SAFETY: both strings are NUL-terminated and outlive the calls; "%s" keeps the message | ||
| // from being read as a format string. | ||
| unsafe { | ||
| nix::libc::openlog(c"gitv".as_ptr(), nix::libc::LOG_PID, nix::libc::LOG_DAEMON); | ||
| nix::libc::syslog(nix::libc::LOG_WARNING, c"%s".as_ptr(), message.as_ptr()); | ||
| } | ||
| } | ||
| /// Append one line to a file, creating it if needed, and make sure it reached the file. | ||
| fn append_line(path: &Path, line: &str) -> std::io::Result<()> { | ||
| let mut file = fs::File::options().create(true).append(true).open(path)?; | ||
| file.write_all(format!("{line}\n").as_bytes())?; | ||
| file.flush() | ||
| } | ||
| fn is_root() -> bool { | ||
| nix::unistd::geteuid().is_root() | ||
| } | ||
| /// The `git` account's ids, when running as root and new files must be handed to it. | ||
| fn git_account() -> Result<Option<(Uid, Gid)>, String> { | ||
| if !is_root() { | ||
| return Ok(None); | ||
| } | ||
| let user = nix::unistd::User::from_name("git").map_err(|e| e.to_string())?.ok_or("no git account")?; | ||
| Ok(Some((user.uid, user.gid))) | ||
| } | ||
| /// The owner's directory, created if needed and returned open. Anything else at that name, | ||
| /// including a symlink to a directory, is refused rather than followed. | ||
| fn owner_directory(owner: &str) -> Result<OwnedFd, String> { | ||
| let root = open_root().ok_or("cannot open the repository root")?; | ||
| let display = repos_root().join(owner); | ||
| // Another push may create it at the same moment; either way, open what's there after. | ||
| match mkdirat(&root, owner, Mode::from_bits_truncate(0o755)) { | ||
| Ok(()) | Err(Errno::EEXIST) => {} | ||
| Err(e) => return Err(format!("cannot create {}: {e}", display.display())), | ||
| } | ||
| let directory = | ||
| open_dir_at(&root, OsStr::new(owner)).map_err(|_| format!("{} is not a directory", display.display()))?; | ||
| if let Some((uid, gid)) = git_account()? { | ||
| fchown(&directory, Some(uid), Some(gid)).map_err(|e| e.to_string())?; | ||
| } | ||
| Ok(directory) | ||
| } | ||
| /// Create `<owner>/<name>.git`. | ||
| /// | ||
| /// The repository is built inside a private staging directory (mode 0700, made fresh under the | ||
| /// open owner directory), so no other user can rename, replace or remove anything inside it. | ||
| /// Initialisation, permissions and ownership all go through handles, and publication renames | ||
| /// out of the staging directory's own handle into the owner directory's, refusing to replace | ||
| /// anything at the name. What gets published is therefore exactly what git initialised. | ||
| fn create(owner: &str, name: &str) -> Result<Created, CreateError> { | ||
| publish_new(owner, name, Contents::Empty) | ||
| } | ||
| /// What a new repository starts as. | ||
| #[derive(Clone, Copy)] | ||
| enum Contents<'a> { | ||
| /// `git init --bare`. | ||
| Empty, | ||
| /// A copy of the bare repository at this path, outside the live tree: one restored from a | ||
| /// backup, say. | ||
| CopyOf(&'a Path), | ||
| } | ||
| /// Make `<owner>/<name>.git` from `contents`, as described for [`create`]. | ||
| fn publish_new(owner: &str, name: &str, contents: Contents) -> Result<Created, CreateError> { | ||
| let directory = owner_directory(owner).map_err(CreateError::Failed)?; | ||
| let target = format!("{name}.git"); | ||
| if kind_at(&directory, OsStr::new(&target)).is_some() { | ||
| return Err(CreateError::EXISTS); | ||
| } | ||
| let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); | ||
| let staging_name = format!(".create-{}-{nanos}-{name}", std::process::id()); | ||
| mkdirat(&directory, staging_name.as_str(), Mode::S_IRWXU) | ||
| .map_err(|e| CreateError::Failed(format!("couldn't make a staging directory: {e}")))?; | ||
| let built = open_dir_at(&directory, OsStr::new(&staging_name)) | ||
| .map_err(|e| CreateError::Failed(format!("couldn't open the staging directory: {e}"))) | ||
| .and_then(|staging| { | ||
| // The directory just made must be ours and private; anything else at the name means | ||
| // someone got there first, so give up rather than build in it. | ||
| let stat = fstat(staging.as_fd()).map_err(|e| CreateError::Failed(e.to_string()))?; | ||
| if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 { | ||
| return Err(CreateError::Failed("the staging directory isn't private".into())); | ||
| } | ||
| build_and_publish(&directory, &staging, &target, contents) | ||
| }); | ||
| // The staging directory is empty now, whether the repository was published or rolled | ||
| // back. Removing it by name only ever removes an empty directory. | ||
| let leftover = unlinkat(&directory, staging_name.as_str(), UnlinkatFlags::RemoveDir).err().map(|e| { | ||
| format!("couldn't remove the staging directory {}: {e}", repos_root().join(owner).join(&staging_name).display()) | ||
| }); | ||
| if let Some(leftover) = &leftover { | ||
| // Whatever the outcome and whoever asked, the operator needs to know. | ||
| log_operator(&format!("creating {owner}/{name}.git: {leftover}")); | ||
| } | ||
| match built { | ||
| Ok(()) => Ok(Created { leftover }), | ||
| // A failure that also left something behind carries both, so whoever reads the detail | ||
| // (an administrator, or the operator log) learns about the directory to clean up. | ||
| Err(error) => Err(match leftover { | ||
| None => error, | ||
| Some(leftover) => error.with_leftover(leftover), | ||
| }), | ||
| } | ||
| } | ||
| /// A repository was created; `leftover` describes anything the operator must clean up. | ||
| struct Created { | ||
| leftover: Option<String>, | ||
| } | ||
| /// Why creation didn't happen. `Exists` is safe to tell anyone; `Failed` carries server details | ||
| /// (paths, git's own messages) that only the operator or an administrator should see. | ||
| enum CreateError { | ||
| /// Something is already at the name. `leftover` notes anything the attempt left behind. | ||
| Exists { | ||
| leftover: Option<String>, | ||
| }, | ||
| Failed(String), | ||
| } | ||
| impl CreateError { | ||
| const EXISTS: CreateError = CreateError::Exists { leftover: None }; | ||
| /// The full story, for the operator or an administrator. | ||
| fn detail(&self) -> String { | ||
| match self { | ||
| CreateError::Exists { leftover: None } => "repository already exists".into(), | ||
| CreateError::Exists { leftover: Some(leftover) } => format!("repository already exists; also {leftover}"), | ||
| CreateError::Failed(detail) => detail.clone(), | ||
| } | ||
| } | ||
| fn with_leftover(self, leftover: String) -> CreateError { | ||
| match self { | ||
| CreateError::Exists { .. } => CreateError::Exists { leftover: Some(leftover) }, | ||
| CreateError::Failed(detail) => CreateError::Failed(format!("{detail}; also {leftover}")), | ||
| } | ||
| } | ||
| } | ||
| /// Run a command whose output only an operator should see: stdout is dropped, and stderr is | ||
| /// captured into the error instead of reaching whoever is connected. | ||
| fn run_privately(mut command: Command, what: &str) -> Result<(), String> { | ||
| let output = command.stdout(Stdio::null()).output().map_err(|e| format!("{what} couldn't start: {e}"))?; | ||
| if output.status.success() { | ||
| Ok(()) | ||
| } else { | ||
| let message = String::from_utf8_lossy(&output.stderr).trim().to_string(); | ||
| Err(format!( | ||
| "{what} failed ({}){}", | ||
| output.status, | ||
| if message.is_empty() { String::new() } else { format!(": {message}") } | ||
| )) | ||
| } | ||
| } | ||
| /// Build a bare repository at `repo` inside the private `staging` directory, then move it to | ||
| /// `target` in `directory`. If anything fails after `repo` was made, it is removed again; it | ||
| /// never removes a `repo` this call didn't make. | ||
| fn build_and_publish( | ||
| directory: &OwnedFd, | ||
| staging: &OwnedFd, | ||
| target: &str, | ||
| contents: Contents, | ||
| ) -> Result<(), CreateError> { | ||
| let failed = |e: &dyn std::fmt::Display| CreateError::Failed(e.to_string()); | ||
| // Only once this succeeds is `repo` ours to roll back. | ||
| mkdirat(staging, "repo", Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; | ||
| let built = (|| { | ||
| let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| failed(&e))?; | ||
| match contents { | ||
| Contents::Empty => { | ||
| // A clean environment, so no caller's init.templateDir can plant hooks in it; | ||
| // and its output stays private, whoever is connected. | ||
| let mut init = git_in(&repo); | ||
| init.args(["init", "--quiet", "--bare", "--initial-branch=main", "."]); | ||
| run_privately(init, "git init").map_err(CreateError::Failed)?; | ||
| } | ||
| Contents::CopyOf(source) => { | ||
| // Everything, the visibility marker, description and HEAD included, with modes and | ||
| // times; links are copied as links, never followed. Not owners (set below) and | ||
| // not SELinux labels: new files take the repository tree's own, not those of | ||
| // the folder a restore was staged in. | ||
| let mut copy = gitv_core::command_in(&repo, "cp"); | ||
| copy.args(["-R", "-P", "--preserve=mode,timestamps,links", "--"]).arg(source.join(".")).arg("."); | ||
| run_privately(copy, "copying the repository").map_err(CreateError::Failed)?; | ||
| // Nothing is published that git can't read whole. | ||
| let mut fsck = git_in(&repo); | ||
| fsck.args(["--git-dir=.", "fsck", "--no-progress", "--full"]); | ||
| run_privately(fsck, "git fsck").map_err(CreateError::Failed)?; | ||
| } | ||
| } | ||
| fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; | ||
| if let Some((uid, gid)) = git_account().map_err(CreateError::Failed)? { | ||
| chown_tree(&repo, uid, gid).map_err(|e| failed(&e))?; | ||
| } | ||
| renameat2(staging, "repo", directory, target, RenameFlags::RENAME_NOREPLACE) | ||
| .map_err(|e| if e == Errno::EEXIST { CreateError::EXISTS } else { failed(&e) }) | ||
| })(); | ||
| if let Err(error) = built { | ||
| return Err(match remove_tree_at(staging, OsStr::new("repo")) { | ||
| Ok(()) => error, | ||
| Err(e) => { | ||
| let problem = format!("couldn't remove a half-built repository after \"{}\": {e}", error.detail()); | ||
| log_operator(&problem); | ||
| CreateError::Failed(problem) | ||
| } | ||
| }); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Copy the bare repository at `source` into the live tree as `<owner>/<name>.git`, never | ||
| /// replacing anything already there: how a repository restored from a backup goes back. | ||
| fn import(owner: &str, name: &str, source: &Path) -> Result<(), String> { | ||
| // Only a real bare repository is copied: a directory, not a link to one, with a HEAD file. | ||
| let from = gitv_core::open_dir(source).map_err(|e| format!("can't open {}: {e}", source.display()))?; | ||
| if kind_at(&from, OsStr::new("HEAD")) != Some(nix::sys::stat::SFlag::S_IFREG) { | ||
| return Err(format!("{} isn't a bare repository", source.display())); | ||
| } | ||
| match publish_new(owner, name, Contents::CopyOf(source)) { | ||
| Ok(created) => { | ||
| println!("imported git@{}:{owner}/{name}.git", config::host()); | ||
| if let Some(leftover) = created.leftover { | ||
| eprintln!("gitv: imported {owner}/{name}.git, but {leftover}"); | ||
| } | ||
| Ok(()) | ||
| } | ||
| Err(CreateError::Exists { .. }) => { | ||
| Err(format!("{owner}/{name}.git already exists; import under another name, or delete it first")) | ||
| } | ||
| Err(error) => Err(error.detail()), | ||
| } | ||
| } | ||
| /// Deleted repositories wait in `<owner>/.trash` for this many days before `gitv purge` removes them. | ||
| const TRASH_DAYS: u64 = 30; | ||
| /// The trash directory inside each owner's directory. Its leading dot keeps it out of every listing. | ||
| const TRASH: &str = ".trash"; | ||
| /// The owner's trash directory, created (private, and the git account's) if needed. | ||
| fn trash_directory(owner_dir: &OwnedFd) -> Result<OwnedFd, String> { | ||
| match mkdirat(owner_dir, TRASH, Mode::S_IRWXU) { | ||
| Ok(()) | Err(Errno::EEXIST) => {} | ||
| Err(e) => return Err(format!("cannot create the trash: {e}")), | ||
| } | ||
| let trash = open_dir_at(owner_dir, OsStr::new(TRASH)).map_err(|_| "the trash is not a directory".to_string())?; | ||
| if let Some((uid, gid)) = git_account()? { | ||
| fchown(&trash, Some(uid), Some(gid)).map_err(|e| e.to_string())?; | ||
| } | ||
| Ok(trash) | ||
| } | ||
| /// A trash entry's repository name and deletion time: `<name>.<unix seconds>`. | ||
| fn parse_trash_entry(entry: &str) -> Option<(&str, u64)> { | ||
| let (name, stamp) = entry.rsplit_once('.')?; | ||
| (valid_name(name) && !stamp.is_empty() && stamp.bytes().all(|b| b.is_ascii_digit())) | ||
| .then_some((name, stamp.parse().ok()?)) | ||
| } | ||
| /// Move `<owner>/<name>.git` into the owner's trash, returning the trash entry's name. One handle | ||
| /// on the owner directory serves the check and the move; if the entry were swapped for a symlink | ||
| /// after the check, only the link would be moved. Nothing is removed until `gitv purge`. | ||
| fn delete(owner: &str, name: &str) -> Result<String, String> { | ||
| let directory = open_owner(owner).ok_or("repository unavailable")?; | ||
| repo_in(&directory, owner, name).ok_or("repository unavailable")?; | ||
| let trash = trash_directory(&directory)?; | ||
| let entry = format!("{name}.{}", unix_now()); | ||
| renameat2(&directory, format!("{name}.git").as_str(), &trash, entry.as_str(), RenameFlags::RENAME_NOREPLACE) | ||
| .map_err(|e| match e { | ||
| Errno::EEXIST => "the repository was deleted moments ago under the same name; try again".to_string(), | ||
| e => e.to_string(), | ||
| })?; | ||
| Ok(entry) | ||
| } | ||
| /// Every trash entry: owner, entry name, and deletion time when the name carries one. | ||
| fn trash_entries() -> Result<Vec<(String, String, Option<u64>)>, String> { | ||
| let root = open_root().ok_or("cannot open the repository root")?; | ||
| let mut found = Vec::new(); | ||
| for owner in entries(&root).into_iter().filter_map(|o| o.into_string().ok()).filter(|o| valid_name(o)) { | ||
| let Some(owner_dir) = open_owner(&owner) else { continue }; | ||
| let trash = match open_dir_at(&owner_dir, OsStr::new(TRASH)) { | ||
| Ok(trash) => trash, | ||
| Err(Errno::ENOENT) => continue, | ||
| Err(e) => return Err(format!("cannot open {owner}/{TRASH}: {e}")), | ||
| }; | ||
| let names = gitv_core::try_entries(&trash).map_err(|e| format!("cannot list {owner}/{TRASH}: {e}"))?; | ||
| for entry in names { | ||
| let entry = entry.to_string_lossy().into_owned(); | ||
| let stamp = parse_trash_entry(&entry).map(|(_, stamp)| stamp); | ||
| found.push((owner.clone(), entry, stamp)); | ||
| } | ||
| } | ||
| found.sort(); | ||
| Ok(found) | ||
| } | ||
| fn list_trash() -> Result<(), String> { | ||
| let now = unix_now(); | ||
| for (owner, entry, stamp) in trash_entries()? { | ||
| match stamp { | ||
| Some(stamp) => { | ||
| let days = now.saturating_sub(stamp) / 86_400; | ||
| let left = TRASH_DAYS.saturating_sub(days); | ||
| println!("{owner} {entry} deleted {days} days ago, purged in {left} days"); | ||
| } | ||
| None => println!("{owner} {entry} (not a trash entry; purge leaves it alone)"), | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Move a trash entry back to `<owner>/<name>.git`, never replacing anything at that name. | ||
| fn restore(owner: &str, entry: &str, as_name: Option<&str>) -> Result<(), String> { | ||
| let (original, _) = parse_trash_entry(entry).ok_or("not a trash entry; see `gitv trash`")?; | ||
| let name = as_name.unwrap_or(original); | ||
| let directory = open_owner(owner).ok_or("no such owner")?; | ||
| let trash = open_dir_at(&directory, OsStr::new(TRASH)).map_err(|_| "this owner has no trash")?; | ||
| renameat2(&trash, entry, &directory, format!("{name}.git").as_str(), RenameFlags::RENAME_NOREPLACE).map_err( | ||
| |e| match e { | ||
| Errno::EEXIST => format!("{owner}/{name}.git already exists; restore with --as <other name>"), | ||
| Errno::ENOENT => "no such trash entry; see `gitv trash`".to_string(), | ||
| e => e.to_string(), | ||
| }, | ||
| )?; | ||
| println!("restored git@{}:{owner}/{name}.git", config::host()); | ||
| Ok(()) | ||
| } | ||
| /// Remove trash entries deleted at least `days` days ago, through handles and without following | ||
| /// symlinks. Entries that don't look like `<name>.<time>` are left for a person to look at. | ||
| fn purge(days: u64) -> Result<(), String> { | ||
| let cutoff = days.saturating_mul(86_400); | ||
| let now = unix_now(); | ||
| let mut failures = 0; | ||
| for (owner, entry, stamp) in trash_entries()? { | ||
| let Some(stamp) = stamp else { continue }; | ||
| if now.saturating_sub(stamp) < cutoff { | ||
| continue; | ||
| } | ||
| let removed = open_owner(&owner) | ||
| .ok_or_else(|| "owner directory unavailable".to_string()) | ||
| .and_then(|dir| open_dir_at(&dir, OsStr::new(TRASH)).map_err(|e| e.to_string())) | ||
| .and_then(|trash| remove_tree_at(&trash, OsStr::new(&entry)).map_err(|e| e.to_string())); | ||
| match removed { | ||
| Ok(()) => println!("purged {owner}/{TRASH}/{entry}"), | ||
| Err(e) => { | ||
| failures += 1; | ||
| log_operator(&format!("purging {owner}/{TRASH}/{entry}: {e}")); | ||
| eprintln!("gitv: couldn't purge {owner}/{TRASH}/{entry}: {e}"); | ||
| } | ||
| } | ||
| } | ||
| if failures == 0 { Ok(()) } else { Err(format!("{failures} trash entries couldn't be purged")) } | ||
| } | ||
| fn add_key(owner: &str, file: &Path, label: Option<&str>) -> Result<(), String> { | ||
| let text = fs::read_to_string(file).map_err(|e| e.to_string())?; | ||
| let parts: Vec<&str> = text.split_whitespace().collect(); | ||
| if parts.len() < 2 || parts[0] != "ssh-ed25519" { | ||
| return Err("expected an OpenSSH Ed25519 public key".into()); | ||
| } | ||
| let engine = base64::engine::general_purpose::STANDARD; | ||
| let blob = engine.decode(parts[1]).map_err(|_| "invalid Ed25519 public key")?; | ||
| let mut header = 11u32.to_be_bytes().to_vec(); | ||
| header.extend_from_slice(b"ssh-ed25519"); | ||
| header.extend_from_slice(&32u32.to_be_bytes()); | ||
| if blob.len() != 51 || blob[..19] != header[..] { | ||
| return Err("invalid Ed25519 public key".into()); | ||
| } | ||
| let token = engine.encode(&blob); | ||
| // Prepare everything the key needs first: publishing the key file is the last step, so a | ||
| // failure leaves no key installed and a retry starts clean. | ||
| owner_directory(owner)?; | ||
| // The key file's own comment is dropped (it is often an email address); only a label the | ||
| // operator chose is kept. | ||
| let comment = label.map(|l| format!(" {l}")).unwrap_or_default(); | ||
| let mut relabelled = false; | ||
| edit_keys(|old| { | ||
| let registered: Vec<KeyLine> = old.lines().filter_map(parse_key_line).filter(|k| k.blob == blob).collect(); | ||
| if registered.is_empty() { | ||
| let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" }; | ||
| let command = config::command(); | ||
| return Ok(format!( | ||
| "{old}{separator}restrict,command=\"{command} serve {owner}\" ssh-ed25519 {token}{comment}\n" | ||
| )); | ||
| } | ||
| // Registering a key again with a label renames it, but only for the owner it already | ||
| // serves: a key never moves to another owner this way. | ||
| let Some(label) = label else { return Err("key already registered".into()) }; | ||
| if registered.iter().any(|k| k.owner() != Some(owner)) { | ||
| return Err("key already registered for another owner".into()); | ||
| } | ||
| relabelled = true; | ||
| Ok(old | ||
| .split_inclusive('\n') | ||
| .map(|row| { | ||
| let line = row.trim_end_matches(['\n', '\r']); | ||
| match parse_key_line(line) { | ||
| // Everything up to the key stays as it was, options included. | ||
| Some(k) if k.blob == blob => format!("{} {label}{}", &line[..k.key_end], &row[line.len()..]), | ||
| _ => row.to_string(), | ||
| } | ||
| }) | ||
| .collect()) | ||
| })?; | ||
| if relabelled { | ||
| println!("relabelled {} as {}", fingerprint(&blob), label.unwrap_or_default()); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Read the keys file, let `change` produce its new contents, and publish them, all under the | ||
| /// keys lock, so two administrators changing keys at once can't undo each other's work. | ||
| fn edit_keys(change: impl FnOnce(&str) -> Result<String, String>) -> Result<(), String> { | ||
| let keys = keys_path(); | ||
| let directory = keys.parent().ok_or("authorized_keys has no directory")?; | ||
| let lock = | ||
| fs::File::options().create(true).append(true).open(directory.join("keys.lock")).map_err(|e| e.to_string())?; | ||
| let _lock = Flock::lock(lock, FlockArg::LockExclusive).map_err(|(_, e)| e.to_string())?; | ||
| let old = read_keys(&keys)?; | ||
| let new = change(&old)?; | ||
| // Readable by sshd. The change counts only once the rename survives a crash. | ||
| gitv_core::publish_file(&keys, new.as_bytes(), 0o644, true, |_| Ok::<(), String>(())) | ||
| .map_err(|e| format!("couldn't write {}: {e}", keys.display()))?; | ||
| relabel(&keys, Path::new("/sys/fs/selinux"), Path::new("/usr/sbin/restorecon")) | ||
| } | ||
| /// The keys file's contents; a missing file holds no keys. | ||
| fn read_keys(keys: &Path) -> Result<String, String> { | ||
| match fs::read_to_string(keys) { | ||
| Ok(text) => Ok(text), | ||
| Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()), | ||
| Err(e) => Err(format!("couldn't read {}: {e}", keys.display())), | ||
| } | ||
| } | ||
| /// A key's fingerprint as `ssh-keygen -l` prints it: unpadded base64 of the blob's SHA-256. | ||
| fn fingerprint(blob: &[u8]) -> String { | ||
| use sha2::{Digest, Sha256}; | ||
| format!("SHA256:{}", base64::engine::general_purpose::STANDARD_NO_PAD.encode(Sha256::digest(blob))) | ||
| } | ||
| /// Print every active key, one per line: owner, fingerprint, label. Lines not written by | ||
| /// `add-key` are listed too, with `-` for an owner that isn't a GITv forced command. | ||
| fn list_keys(only: Option<&str>) -> Result<(), String> { | ||
| let text = read_keys(&keys_path())?; | ||
| let rows: Vec<(&str, String, &str)> = text | ||
| .lines() | ||
| .filter_map(parse_key_line) | ||
| .map(|k| (k.owner().unwrap_or("-"), fingerprint(&k.blob), k.comment)) | ||
| .filter(|(owner, _, _)| only.is_none_or(|o| o == *owner)) | ||
| .collect(); | ||
| if rows.is_empty() { | ||
| eprintln!("gitv: no keys registered"); | ||
| } | ||
| let width = rows.iter().map(|(owner, _, _)| owner.len()).max().unwrap_or(0); | ||
| for (owner, fingerprint, label) in rows { | ||
| println!("{owner:<width$} {fingerprint} {label}"); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Remove the key with this fingerprint. Every other line, including comments and lines | ||
| /// `add-key` didn't write, is kept byte for byte. | ||
| fn remove_key(wanted: &str) -> Result<(), String> { | ||
| let wanted = format!("SHA256:{}", wanted.strip_prefix("SHA256:").unwrap_or(wanted)); | ||
| let mut removed = Vec::new(); | ||
| edit_keys(|old| { | ||
| let mut kept = String::with_capacity(old.len()); | ||
| for row in old.split_inclusive('\n') { | ||
| match parse_key_line(row.trim_end_matches(['\n', '\r'])) { | ||
| Some(k) if fingerprint(&k.blob) == wanted => { | ||
| removed.push(format!("{} {}", k.owner().unwrap_or("-"), k.comment).trim_end().to_string()) | ||
| } | ||
| _ => kept.push_str(row), | ||
| } | ||
| } | ||
| if removed.is_empty() { | ||
| return Err(format!("no key has the fingerprint {wanted}; run: gitv keys")); | ||
| } | ||
| Ok(kept) | ||
| })?; | ||
| for key in removed { | ||
| println!("removed {wanted} ({key}); connections already open stay open until they end"); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Give a file the SELinux label the system's policy names for its path. A file published by | ||
| /// rename carries the label its directory gives new files, not the one the policy names (sshd | ||
| /// reads authorized keys labelled `ssh_home_t`), so without this every added key would leave | ||
| /// the keys file mislabelled. Does nothing where SELinux is off or restorecon isn't installed. | ||
| fn relabel(path: &Path, selinuxfs: &Path, restorecon: &Path) -> Result<(), String> { | ||
| if !selinuxfs.join("enforce").exists() || !restorecon.is_file() { | ||
| return Ok(()); | ||
| } | ||
| let status = Command::new(restorecon).arg(path).stdin(Stdio::null()).status(); | ||
| match status { | ||
| Ok(status) if status.success() => Ok(()), | ||
| outcome => Err(format!( | ||
| "updated the keys, but couldn't give {} its SELinux label ({}); run: restorecon {0}", | ||
| path.display(), | ||
| outcome.map_or_else(|e| e.to_string(), |s| s.to_string()) | ||
| )), | ||
| } | ||
| } | ||
| /// An active authorized_keys line, taken apart. | ||
| struct KeyLine<'a> { | ||
| options: &'a str, | ||
| blob: Vec<u8>, | ||
| comment: &'a str, | ||
| /// Where the key field ends in the line given to [`parse_key_line`]. | ||
| key_end: usize, | ||
| } | ||
| impl<'a> KeyLine<'a> { | ||
| /// The owner a GITv forced command (`command="<gitv> serve <owner>"`) serves. | ||
| fn owner(&self) -> Option<&'a str> { | ||
| let start = self.options.find("command=\"")? + "command=\"".len(); | ||
| let options: &'a str = self.options; | ||
| let value = &options[start..]; | ||
| let value = &value[..value.find('"')?]; | ||
| match value.split_whitespace().collect::<Vec<_>>().as_slice() { | ||
| [_, "serve", owner] if valid_name(owner) => Some(owner), | ||
| _ => None, | ||
| } | ||
| } | ||
| } | ||
| /// Split off the field at the start of `text` (after any spaces or tabs) from what follows it. | ||
| fn next_field(text: &str) -> Option<(&str, &str)> { | ||
| let text = text.trim_start_matches([' ', '\t']); | ||
| let end = text.find([' ', '\t']).unwrap_or(text.len()); | ||
| (end > 0).then(|| (&text[..end], text[end..].trim_matches([' ', '\t']))) | ||
| } | ||
| /// The options, decoded key and comment of an authorized_keys line, wherever the key sits. | ||
| /// | ||
| /// A line is `[options] type key [comment]`. Blank and `#` lines are skipped, options are | ||
| /// skipped as one field (they can hold quoted spaces), and only the key field itself is read, | ||
| /// so a key mentioned in a comment or a commented-out line doesn't count. | ||
| fn parse_key_line(line: &str) -> Option<KeyLine<'_>> { | ||
| const TYPES: [&str; 4] = ["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "sk-ssh-ed25519@openssh.com"]; | ||
| let original = line; | ||
| let line = line.trim_start(); | ||
| if line.is_empty() || line.starts_with('#') { | ||
| return None; | ||
| } | ||
| // Fields are separated by spaces or tabs. The first is the key type, or else the options. | ||
| let (first, _) = next_field(line)?; | ||
| let (options, rest) = if TYPES.contains(&first) { | ||
| ("", line) | ||
| } else { | ||
| let rest = skip_options(line)?; | ||
| (&line[..line.len() - rest.len()], rest) | ||
| }; | ||
| let (kind, rest) = next_field(rest)?; | ||
| if !TYPES.contains(&kind) { | ||
| return None; | ||
| } | ||
| let (key, comment) = next_field(rest)?; | ||
| let blob = base64::engine::general_purpose::STANDARD.decode(key).ok()?; | ||
| // Every field is a slice of the line handed in, so its position is its address's offset. | ||
| let key_end = key.as_ptr() as usize - original.as_ptr() as usize + key.len(); | ||
| Some(KeyLine { options: options.trim_end(), blob, comment, key_end }) | ||
| } | ||
| /// What follows the options field: its end is the first whitespace outside double quotes. | ||
| fn skip_options(line: &str) -> Option<&str> { | ||
| let mut quoted = false; | ||
| let mut escaped = false; | ||
| for (i, c) in line.char_indices() { | ||
| match c { | ||
| _ if escaped => escaped = false, | ||
| '\\' => escaped = true, | ||
| '"' => quoted = !quoted, | ||
| c if c.is_whitespace() && !quoted => return Some(line[i..].trim_start()), | ||
| _ => {} | ||
| } | ||
| } | ||
| None | ||
| } | ||
| fn visibility(owner: &str, name: &str, visibility: &str) -> Result<(), String> { | ||
| let public = match visibility { | ||
| "public" => true, | ||
| "private" => false, | ||
| _ => return Err("choose public or private".into()), | ||
| }; | ||
| repo_dir(check_name(owner)?, check_name(name)?) | ||
| .ok_or("repository unavailable")? | ||
| .set_public(public) | ||
| .map_err(|e| format!("couldn't set visibility: {e}")) | ||
| } | ||
| /// Print whether a repository is protected, or turn protection `on` or `off`. | ||
| fn protect(owner: &str, name: &str, value: Option<&str>) -> Result<(), String> { | ||
| let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?; | ||
| let on = match value { | ||
| None => { | ||
| println!("{}", if repo.is_protected() { "on" } else { "off" }); | ||
| return Ok(()); | ||
| } | ||
| Some("on") => true, | ||
| Some("off") => false, | ||
| Some(_) => return Err("choose on or off".into()), | ||
| }; | ||
| repo.set_protected(on).map_err(|e| format!("couldn't set protection: {e}")) | ||
| } | ||
| /// Print a repository's description, or set it to `text`; an empty text removes it. | ||
| fn description(owner: &str, name: &str, text: Option<&str>) -> Result<(), String> { | ||
| let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?; | ||
| let Some(text) = text else { | ||
| if let Some(text) = repo.description() { | ||
| println!("{text}"); | ||
| } | ||
| return Ok(()); | ||
| }; | ||
| // One line of plain text: the web shows it, and a terminal may print it. | ||
| let text = text.trim(); | ||
| if text.chars().count() > DESCRIPTION_LIMIT || text.chars().any(char::is_control) { | ||
| return Err(format!("a description is one line of at most {DESCRIPTION_LIMIT} characters")); | ||
| } | ||
| repo.set_description((!text.is_empty()).then_some(text)).map_err(|e| format!("couldn't set the description: {e}")) | ||
| } | ||
| /// Print the default branch (where HEAD points), or point it at an existing `branch`. | ||
| fn default_branch(owner: &str, name: &str, branch: Option<&str>) -> Result<(), String> { | ||
| let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?; | ||
| let Some(branch) = branch else { | ||
| let head = git(&repo, &["symbolic-ref", "HEAD"]).map_err(|_| "HEAD doesn't name a branch".to_string())?; | ||
| let head = head.strip_suffix(b"\n").unwrap_or(&head); | ||
| println!("{}", String::from_utf8_lossy(head.strip_prefix(b"refs/heads/").unwrap_or(head))); | ||
| return Ok(()); | ||
| }; | ||
| // Qualified, so a name like `-x` or `HEAD` can only ever mean a branch, and checked as a | ||
| // ref name before git is asked whether that branch exists. | ||
| let full = format!("refs/heads/{branch}"); | ||
| let exists = git(&repo, &["check-ref-format", &full]).is_ok() | ||
| && git(&repo, &["rev-parse", "--verify", "--quiet", &format!("{full}^{{commit}}")]).is_ok(); | ||
| if !exists { | ||
| return Err(format!("there's no branch named {branch}; push it first")); | ||
| } | ||
| git(&repo, &["symbolic-ref", "HEAD", &full]).map_err(|_| "couldn't set the default branch".to_string())?; | ||
| Ok(()) | ||
| } | ||
| /// Handle one SSH request from a key registered to owner. | ||
| fn serve(owner: &str, command: &str) -> Result<u8, String> { | ||
| let args = | ||
| shlex::split(command).ok_or_else(|| format!("unreadable command; run: ssh git@{} help", config::host()))?; | ||
| let args: Vec<&str> = args.iter().map(String::as_str).collect(); | ||
| match args.as_slice() { | ||
| [] | ["help"] => println!("{}", help()), | ||
| [program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path), | ||
| ["visibility", name, value] => visibility(owner, name, value)?, | ||
| // Unquoted words are one description: `description tools A small toolbox`. | ||
| ["protect", name] => protect(owner, name, None)?, | ||
| ["protect", name, value] => protect(owner, name, Some(value))?, | ||
| ["description", name] => description(owner, name, None)?, | ||
| ["description", name, text @ ..] => description(owner, name, Some(&text.join(" ")))?, | ||
| ["default-branch", name] => default_branch(owner, name, None)?, | ||
| ["default-branch", name, branch] => default_branch(owner, name, Some(branch))?, | ||
| ["list"] => { | ||
| // Listed and checked through one handle on the owner's directory. | ||
| let directory = open_owner(owner); | ||
| let mut names: Vec<String> = directory | ||
| .iter() | ||
| .flat_map(entries) | ||
| .filter_map(|e| e.to_str()?.strip_suffix(".git").map(str::to_string)) | ||
| .filter(|n| directory.as_ref().is_some_and(|d| repo_in(d, owner, n).is_some())) | ||
| .collect(); | ||
| names.sort(); | ||
| for name in names { | ||
| println!("git@{}:{owner}/{name}.git", config::host()); | ||
| } | ||
| } | ||
| ["create", name] => { | ||
| // A key holder learns whether it worked, and the clone address; server details go | ||
| // to the operator's log. | ||
| let name = check_name(name)?; | ||
| match create(owner, name) { | ||
| Ok(_) => println!("git@{}:{owner}/{name}.git", config::host()), | ||
| Err(CreateError::Exists { .. }) => return Err("repository already exists".into()), | ||
| Err(error) => { | ||
| log_operator(&format!("ssh create of {owner}/{name}.git failed: {}", error.detail())); | ||
| return Err("couldn't create the repository; the server's operator can see why".into()); | ||
| } | ||
| } | ||
| } | ||
| ["delete", name, rest @ ..] => { | ||
| let name = check_name(name)?; | ||
| if rest != ["--yes"] { | ||
| return Err(format!( | ||
| "this moves {owner}/{name}.git to the trash, where only the server's operator can restore it; run: delete {name} --yes" | ||
| )); | ||
| } | ||
| let entry = delete(owner, name)?; | ||
| log_operator(&format!( | ||
| "{owner}/{name}.git moved to the trash as {owner}/{TRASH}/{entry} by its owner's key" | ||
| )); | ||
| println!( | ||
| "moved {owner}/{name}.git to the trash; the server's operator can restore it for {TRASH_DAYS} days" | ||
| ); | ||
| } | ||
| _ => return Err(format!("unknown command; run: ssh git@{} help", config::host())), | ||
| } | ||
| Ok(0) | ||
| } | ||
| /// Parse `owner/name.git` or `owner/name` (optionally with leading or trailing slash), as | ||
| /// git clients send either and HTTPS clone addresses carry no `.git`. | ||
| fn parse_request(path: &str) -> Option<(&str, &str)> { | ||
| let path = path.strip_prefix('/').unwrap_or(path); | ||
| let path = path.strip_suffix('/').unwrap_or(path); | ||
| let (owner, rest) = path.split_once('/')?; | ||
| let name = rest.strip_suffix(".git").unwrap_or(rest); | ||
| (valid_name(owner) && valid_name(name)).then_some((owner, name)) | ||
| } | ||
| fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> { | ||
| let (requested, name) = parse_request(path).ok_or("repository unavailable")?; | ||
| if requested != owner { | ||
| return Err("repository unavailable".into()); | ||
| } | ||
| let repo = match repo_dir(owner, name) { | ||
| Some(repo) => repo, | ||
| None if program != "git-receive-pack" => return Err("repository unavailable".into()), | ||
| None => { | ||
| // Pushing to a new name creates it, so a fresh project needs no setup step. create() | ||
| // never replaces anything at the name, so a symlink or file there is refused. If a | ||
| // racing push created the repository first, at any moment, this one opens it afresh; | ||
| // either way what it gets must be a real repository. | ||
| // The client only ever hears "repository unavailable"; the cause goes to the | ||
| // operator's log. Losing a race to a push that created it is ordinary, so that stays | ||
| // quiet (create() has already logged any cleanup problem either way). | ||
| match create(owner, name) { | ||
| Ok(_) => eprintln!("gitv: created {owner}/{name}.git"), | ||
| // Another push created it first: ordinary, so quiet. | ||
| Err(CreateError::Exists { .. }) if repo_dir(owner, name).is_some() => {} | ||
| // This attempt genuinely failed, though a racing push's repository lets the | ||
| // push carry on: the operator still hears why. | ||
| Err(error) if repo_dir(owner, name).is_some() => { | ||
| log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail())); | ||
| } | ||
| Err(error) => { | ||
| log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail())); | ||
| return Err("repository unavailable".into()); | ||
| } | ||
| } | ||
| repo_dir(owner, name).ok_or("repository unavailable")? | ||
| } | ||
| }; | ||
| // Run inside the opened directory, so the path can't be swapped for a symlink meanwhile. | ||
| let mut command = repo.command(program); | ||
| // The same clean environment as every other git GITv runs, system config included. | ||
| gitv_core::configure(&mut command); | ||
| command.arg("."); | ||
| // Pass the client's protocol request through (when sshd accepts it), so clients can use the | ||
| // faster protocol v2. | ||
| if let Some(protocol) = std::env::var("GIT_PROTOCOL").ok().as_deref().and_then(gitv_core::git_protocol) { | ||
| command.env("GIT_PROTOCOL", protocol); | ||
| } | ||
| let pushing = program == "git-receive-pack"; | ||
| // A push holds the repository's lock shared from its first look at the refs until HEAD is | ||
| // settled, so a backup (which holds it exclusive) copies before the push or after it. | ||
| let _lock = if pushing { | ||
| Some(repo.lock(false).map_err(|e| { | ||
| log_operator(&format!("{owner}/{name}.git: couldn't lock for a push: {e}")); | ||
| "repository unavailable".to_string() | ||
| })?) | ||
| } else { | ||
| None | ||
| }; | ||
| let before = if pushing { | ||
| // Every ref update gets a reflog entry (bare repositories keep none by default), and | ||
| // objects nothing refers to any more stay as long as those entries do. Given through | ||
| // the environment, so it covers every repository, old or new, and the gc a push | ||
| // triggers inherits it. | ||
| // A protected repository also refuses force-pushes and deletions of every branch (git | ||
| // applies these to refs/heads only; tags stay movable, and the push log records them). | ||
| // Given here, not in the repository's own config, so only `gitv protect` changes it. | ||
| let protection: &[(&str, &str)] = if repo.is_protected() { &PROTECTED_CONFIG } else { &[] }; | ||
| let settings: Vec<_> = PUSH_CONFIG.iter().chain(protection).collect(); | ||
| command.envs(settings.iter().enumerate().flat_map(|(i, (key, value))| { | ||
| [(format!("GIT_CONFIG_KEY_{i}"), *key), (format!("GIT_CONFIG_VALUE_{i}"), *value)] | ||
| })); | ||
| command.env("GIT_CONFIG_COUNT", settings.len().to_string()); | ||
| ref_snapshot(&repo) | ||
| .inspect_err(|e| log_operator(&format!("{owner}/{name}.git: no push log for this push: {e}"))) | ||
| .ok() | ||
| } else { | ||
| None | ||
| }; | ||
| let status = command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).status().map_err(|e| e.to_string())?; | ||
| if let Some(before) = before | ||
| && let Err(e) = ref_snapshot(&repo).and_then(|after| record_push(&repo, &before, &after)) | ||
| { | ||
| log_operator(&format!("{owner}/{name}.git: couldn't write the push log: {e}")); | ||
| } | ||
| if pushing && status.success() { | ||
| fix_head(&repo)?; | ||
| } | ||
| Ok(status.code().unwrap_or(1) as u8) | ||
| } | ||
| /// Configuration every push runs with: no hooks, and what lets overwritten or deleted history be | ||
| /// recovered for [`TRASH_DAYS`] (reflogs on every ref, unreachable objects kept as long as | ||
| /// their entries). | ||
| /// The gc a push may trigger runs within the push rather than detached, so it finishes under | ||
| /// the push's lock too. | ||
| const PUSH_CONFIG: [(&str, &str); 5] = [ | ||
| // GITv runs no hooks. A hook in the repository's own folder (one copied in by `gitv | ||
| // import`, say) would run as the git account on every push, so none ever runs. | ||
| ("core.hooksPath", "/dev/null"), | ||
| ("core.logAllRefUpdates", "always"), | ||
| ("gc.reflogExpireUnreachable", "30.days.ago"), | ||
| ("gc.pruneExpire", "30.days.ago"), | ||
| ("gc.autoDetach", "false"), | ||
| ]; | ||
| /// What a protected repository's pushes also run with: no branch may move except forwards, | ||
| /// and none may be deleted. | ||
| const PROTECTED_CONFIG: [(&str, &str); 2] = [("receive.denyNonFastForwards", "true"), ("receive.denyDeletes", "true")]; | ||
| /// Where each repository records its pushes' ref changes. Git drops a branch's reflog when the | ||
| /// branch is deleted; this keeps the commit it pointed at findable. | ||
| const PUSH_LOG: &str = "gitv-push.log"; | ||
| /// Every ref and the object it names. | ||
| fn ref_snapshot(repo: &RepoDir) -> Result<BTreeMap<Vec<u8>, Vec<u8>>, String> { | ||
| let out = git(repo, &["for-each-ref", "--format=%(objectname) %(refname)"])?; | ||
| // A ref name can't contain a space or a newline. | ||
| Ok(out | ||
| .split(|b| *b == b'\n') | ||
| .filter_map(|line| { | ||
| let space = line.iter().position(|b| *b == b' ')?; | ||
| Some((line[space + 1..].to_vec(), line[..space].to_vec())) | ||
| }) | ||
| .collect()) | ||
| } | ||
| /// Append one line per changed ref to [`PUSH_LOG`]: `<unix time> <old> <new> <ref>`, with `-` | ||
| /// for a ref that didn't exist before or doesn't after. Two pushes landing at once may share | ||
| /// their lines between them, but every change before and after is recorded. | ||
| fn record_push( | ||
| repo: &RepoDir, | ||
| before: &BTreeMap<Vec<u8>, Vec<u8>>, | ||
| after: &BTreeMap<Vec<u8>, Vec<u8>>, | ||
| ) -> Result<(), String> { | ||
| let now = unix_now().to_string(); | ||
| let mut lines = Vec::new(); | ||
| let mut line = |old: &[u8], new: &[u8], name: &[u8]| { | ||
| lines.extend_from_slice(now.as_bytes()); | ||
| for field in [old, new, name] { | ||
| lines.push(b' '); | ||
| lines.extend_from_slice(field); | ||
| } | ||
| lines.push(b'\n'); | ||
| }; | ||
| for (name, old) in before { | ||
| match after.get(name) { | ||
| Some(new) if new == old => {} | ||
| Some(new) => line(old, new, name), | ||
| None => line(old, b"-", name), | ||
| } | ||
| } | ||
| for (name, new) in after.iter().filter(|(name, _)| !before.contains_key(*name)) { | ||
| line(b"-", new, name); | ||
| } | ||
| if lines.is_empty() { | ||
| return Ok(()); | ||
| } | ||
| let flags = OFlag::O_WRONLY | OFlag::O_APPEND | OFlag::O_CREAT | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC; | ||
| let fd = openat(repo.handle(), PUSH_LOG, flags, Mode::from_bits_truncate(0o640)).map_err(|e| e.to_string())?; | ||
| // One write, so lines from simultaneous pushes don't interleave mid-line. | ||
| fs::File::from(fd).write_all(&lines).map_err(|e| e.to_string()) | ||
| } | ||
| /// Point HEAD at a pushed branch when its current target does not exist. Branch names are | ||
| /// bytes (one per line; a ref can't contain a newline), so names with spaces, non-breaking | ||
| /// spaces or non-UTF-8 bytes are passed to git exactly as they are. | ||
| fn fix_head(repo: &RepoDir) -> Result<(), String> { | ||
| if git(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]).is_ok() { | ||
| return Ok(()); | ||
| } | ||
| let out = git(repo, &["for-each-ref", "--format=%(refname)", "refs/heads"])?; | ||
| let heads: Vec<&[u8]> = out.split(|b| *b == b'\n').filter(|h| !h.is_empty()).collect(); | ||
| let Some(first) = heads.first() else { return Ok(()) }; | ||
| let preferred: [&[u8]; 2] = [b"refs/heads/main", b"refs/heads/master"]; | ||
| let choice = preferred.into_iter().find(|r| heads.contains(r)).unwrap_or(first); | ||
| let status = git_command(repo) | ||
| .args([OsStr::new("symbolic-ref"), OsStr::new("HEAD"), OsStr::from_bytes(choice)]) | ||
| .status() | ||
| .map_err(|e| e.to_string())?; | ||
| if !status.success() { | ||
| return Err("could not set the default branch".into()); | ||
| } | ||
| let name = String::from_utf8_lossy(&choice[b"refs/heads/".len()..]).into_owned(); | ||
| eprintln!("gitv: default branch is now {name}"); | ||
| Ok(()) | ||
| } | ||
| fn run() -> Result<u8, String> { | ||
| let cli = Cli::parse(); | ||
| if let Err(error) = config::load() { | ||
| if matches!(cli.action, Action::Serve { .. }) { | ||
| // A key holder needn't see the server's paths; the operator does. | ||
| log_operator(&format!("bad configuration: {error}")); | ||
| return Err("the server is misconfigured; its operator can see why".into()); | ||
| } | ||
| return Err(error); | ||
| } | ||
| if let Action::Serve { owner } = &cli.action { | ||
| return serve(owner, &std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default()); | ||
| } | ||
| // Locally (GITV_REPOS set) administration runs as yourself. | ||
| if !is_root() && !gitv_core::is_local() { | ||
| return Err("run repository and key administration as root".into()); | ||
| } | ||
| match cli.action { | ||
| Action::Create { owner, name } => { | ||
| // An administrator sees everything. | ||
| let created = create(&owner, &name).map_err(|e| e.detail())?; | ||
| println!("git@{}:{owner}/{name}.git", config::host()); | ||
| if let Some(leftover) = created.leftover { | ||
| eprintln!("gitv: created {owner}/{name}.git, but {leftover}"); | ||
| } | ||
| } | ||
| Action::Delete { owner, name, yes } => { | ||
| if !yes { | ||
| return Err(format!( | ||
| "this moves {owner}/{name}.git to the trash for {TRASH_DAYS} days; pass --yes to confirm" | ||
| )); | ||
| } | ||
| let entry = delete(&owner, &name)?; | ||
| println!("moved {owner}/{name}.git to {owner}/{TRASH}/{entry}; restore with: gitv restore {owner} {entry}"); | ||
| } | ||
| Action::Trash => list_trash()?, | ||
| Action::Restore { owner, entry, as_name } => restore(&owner, &entry, as_name.as_deref())?, | ||
| Action::Purge { older_than_days } => purge(older_than_days)?, | ||
| Action::Import { owner, name, source } => import(&owner, &name, &source)?, | ||
| Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?, | ||
| Action::Protect { owner, name, value } => protect(&owner, &name, value.as_deref())?, | ||
| Action::Description { owner, name, text } => description(&owner, &name, text.as_deref())?, | ||
| Action::DefaultBranch { owner, name, branch } => default_branch(&owner, &name, branch.as_deref())?, | ||
| Action::AddKey { owner, public_key, label } => add_key(&owner, &public_key, label.as_deref())?, | ||
| Action::Keys { owner } => list_keys(owner.as_deref())?, | ||
| Action::RemoveKey { fingerprint } => remove_key(&fingerprint)?, | ||
| Action::Serve { .. } => unreachable!(), | ||
| } | ||
| Ok(0) | ||
| } | ||
| fn main() -> ExitCode { | ||
| match run() { | ||
| Ok(code) => ExitCode::from(code), | ||
| Err(error) => { | ||
| eprintln!("gitv: {error}"); | ||
| ExitCode::FAILURE | ||
| } | ||
| } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use nix::fcntl::{OFlag, open}; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| /// A fresh, empty directory for one test. | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| fn open_path(path: &Path) -> OwnedFd { | ||
| open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap() | ||
| } | ||
| #[test] | ||
| fn published_files_are_relabelled_only_where_selinux_is_on() { | ||
| let dir = scratch("relabel"); | ||
| fs::create_dir_all(dir.join("selinuxfs")).unwrap(); | ||
| let keys = dir.join("authorized_keys"); | ||
| fs::write(&keys, "").unwrap(); | ||
| // A stand-in restorecon that records what it was asked to relabel. | ||
| let record = dir.join("relabelled"); | ||
| let fake = dir.join("restorecon"); | ||
| fs::write(&fake, format!("#!/bin/sh\necho \"$1\" >> '{}'\n", record.display())).unwrap(); | ||
| fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| relabel(&keys, &dir.join("selinuxfs"), &fake).unwrap(); | ||
| assert!(!record.exists(), "SELinux is off (no enforce file): nothing to do"); | ||
| relabel(&keys, &dir.join("selinuxfs"), &dir.join("missing")).unwrap(); | ||
| fs::write(dir.join("selinuxfs/enforce"), "1").unwrap(); | ||
| relabel(&keys, &dir.join("selinuxfs"), &fake).unwrap(); | ||
| assert_eq!(fs::read_to_string(&record).unwrap().trim(), keys.to_str().unwrap()); | ||
| fs::write(&fake, "#!/bin/sh\nexit 1\n").unwrap(); | ||
| let error = relabel(&keys, &dir.join("selinuxfs"), &fake).unwrap_err(); | ||
| assert!(error.contains("run: restorecon"), "{error}"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn creation_errors_keep_their_leftovers() { | ||
| let leftover = || "couldn't remove the staging directory /x".to_string(); | ||
| assert_eq!(CreateError::EXISTS.detail(), "repository already exists"); | ||
| assert_eq!( | ||
| CreateError::EXISTS.with_leftover(leftover()).detail(), | ||
| "repository already exists; also couldn't remove the staging directory /x" | ||
| ); | ||
| assert_eq!( | ||
| CreateError::Failed("git init failed".into()).with_leftover(leftover()).detail(), | ||
| "git init failed; also couldn't remove the staging directory /x" | ||
| ); | ||
| // Still "exists" for the callers that treat it specially. | ||
| assert!(matches!(CreateError::EXISTS.with_leftover(leftover()), CreateError::Exists { .. })); | ||
| } | ||
| #[test] | ||
| fn private_commands_keep_their_errors_for_the_operator() { | ||
| let mut command = gitv_core::git_base(); | ||
| command.args(["init", "--no-such-option"]); | ||
| let error = run_privately(command, "git init").unwrap_err(); | ||
| assert!(error.starts_with("git init failed (exit status: 129): "), "{error}"); | ||
| assert!(error.contains("no-such-option"), "git's own message is captured: {error}"); | ||
| } | ||
| #[test] | ||
| fn a_log_file_that_cannot_be_written_is_reported() { | ||
| let missing = std::env::temp_dir().join(format!("gitv-no-such-dir-{}/log", std::process::id())); | ||
| assert!(append_line(&missing, "x").is_err(), "a failed write must not count as logged"); | ||
| let file = std::env::temp_dir().join(format!("gitv-log-{}", std::process::id())); | ||
| let _ = fs::remove_file(&file); | ||
| append_line(&file, "one").unwrap(); | ||
| append_line(&file, "two").unwrap(); | ||
| assert_eq!(fs::read_to_string(&file).unwrap(), "one\ntwo\n"); | ||
| let _ = fs::remove_file(&file); | ||
| } | ||
| #[test] | ||
| fn a_failed_build_never_removes_what_it_did_not_make() { | ||
| let dir = scratch("build"); | ||
| // A staging directory that already holds someone's `repo`, as it would if the staging | ||
| // name had been swapped for another private directory before it was opened. | ||
| fs::create_dir_all(dir.join("owner/.staging/repo")).unwrap(); | ||
| fs::write(dir.join("owner/.staging/repo/sentinel"), "precious").unwrap(); | ||
| let owner = open_path(&dir.join("owner")); | ||
| let staging = open_path(&dir.join("owner/.staging")); | ||
| let result = build_and_publish(&owner, &staging, "new.git", Contents::Empty); | ||
| assert!(result.is_err(), "building over an existing repo succeeded"); | ||
| assert_eq!(fs::read_to_string(dir.join("owner/.staging/repo/sentinel")).unwrap(), "precious"); | ||
| assert!(!dir.join("owner/new.git").exists(), "nothing was published"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_failed_build_cleans_up_what_it_made() { | ||
| let dir = scratch("build-clean"); | ||
| fs::create_dir_all(dir.join("owner/.staging")).unwrap(); | ||
| // The target is taken, so publication fails after the repository was built. | ||
| fs::create_dir_all(dir.join("owner/new.git")).unwrap(); | ||
| let owner = open_path(&dir.join("owner")); | ||
| let staging = open_path(&dir.join("owner/.staging")); | ||
| let error = build_and_publish(&owner, &staging, "new.git", Contents::Empty) | ||
| .err() | ||
| .map(|e| e.detail()) | ||
| .unwrap_or_default(); | ||
| assert!(error.contains("already exists"), "{error}"); | ||
| assert!(fs::read_dir(dir.join("owner/.staging")).unwrap().next().is_none(), "the half-built repo is gone"); | ||
| assert!(fs::read_dir(dir.join("owner/new.git")).unwrap().next().is_none(), "the target is untouched"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
+334−0
| @@ -0,0 +1,334 @@ | ||
| //! `deploy/gitv-backup` and `deploy/gitv-restore`, run against a scratch installation. | ||
| mod common; | ||
| use std::fs; | ||
| use std::os::unix::fs::MetadataExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, Output}; | ||
| use std::time::Duration; | ||
| use common::{Host, git, scratch, stderr}; | ||
| const BACKUP: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../deploy/gitv-backup"); | ||
| const RESTORE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../deploy/gitv-restore"); | ||
| /// A host with a web sign-in folder, and somewhere for its backups. | ||
| struct Setup { | ||
| host: Host, | ||
| backups: PathBuf, | ||
| web: PathBuf, | ||
| ssh: PathBuf, | ||
| } | ||
| impl Setup { | ||
| fn new(name: &str) -> Setup { | ||
| let host = Host::new(name); | ||
| let web = host.dir.join("web"); | ||
| fs::create_dir_all(&web).unwrap(); | ||
| fs::write(web.join("login"), "user=Um9i\n").unwrap(); | ||
| fs::write(&host.keys, "restrict,command=\"gitv serve ada\" ssh-ed25519 AAAA\n").unwrap(); | ||
| // Beside the host, not in it: the keys file's folder is backed up whole, and a backup | ||
| // folder inside it would copy every earlier snapshot into each new one. | ||
| let backups = scratch(&format!("{name}-backups")); | ||
| fs::remove_dir(&backups).unwrap(); | ||
| // Stand-ins for /etc/ssh: host keys, and configuration that isn't backed up. | ||
| let ssh = scratch(&format!("{name}-ssh")); | ||
| fs::write(ssh.join("ssh_host_ed25519_key"), "private\n").unwrap(); | ||
| fs::write(ssh.join("ssh_host_ed25519_key.pub"), "public\n").unwrap(); | ||
| fs::write(ssh.join("sshd_config"), "Port 22\n").unwrap(); | ||
| Setup { host, backups, web, ssh } | ||
| } | ||
| fn run(&self, script: &str, args: &[&str]) -> Output { | ||
| Command::new(script) | ||
| .args(args) | ||
| .env("GITV_REPOS", &self.host.repos) | ||
| .env("GITV_KEYS", &self.host.keys) | ||
| .env("GITV_WEB_AUTH", self.web.join("login")) | ||
| .env("GITV_BACKUP_DIR", &self.backups) | ||
| .env("GITV_BACKUP_SSH_DIR", &self.ssh) | ||
| .env("GITV_BACKUP_REQUIRE_MOUNT", "0") | ||
| .env("GITV_BACKUP_LOCK_WAIT", "1") | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| fn backup(&self) -> Output { | ||
| // Snapshots are named by the second. | ||
| std::thread::sleep(Duration::from_millis(1100)); | ||
| self.run(BACKUP, &[]) | ||
| } | ||
| fn latest(&self) -> PathBuf { | ||
| fs::canonicalize(self.backups.join("gitv/latest")).unwrap() | ||
| } | ||
| fn push(&self, work: &Path, name: &str) { | ||
| let out = self.host.git(work, &["push", "-q", &format!("ada@x:ada/{name}.git"), "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| } | ||
| } | ||
| fn work(name: &str) -> PathBuf { | ||
| let dir = scratch(name); | ||
| git(&dir, &["init", "-q", "-b", "main"]); | ||
| fs::write(dir.join("a.txt"), "one\n").unwrap(); | ||
| git(&dir, &["add", "."]); | ||
| git(&dir, &["commit", "-qm", "First"]); | ||
| dir | ||
| } | ||
| fn commit(dir: &Path, message: &str) { | ||
| fs::write(dir.join("a.txt"), format!("{message}\n")).unwrap(); | ||
| git(dir, &["commit", "-qam", message]); | ||
| } | ||
| #[test] | ||
| fn snapshots_hold_everything_and_restore_whole() { | ||
| let setup = Setup::new("backup-whole"); | ||
| let work = work("backup-whole-work"); | ||
| setup.push(&work, "project"); | ||
| setup.push(&work, "old"); | ||
| assert!(setup.host.admin(&["visibility", "ada", "project", "public"]).status.success()); | ||
| assert!(setup.host.admin(&["delete", "ada", "old", "--yes"]).status.success()); | ||
| assert!(setup.host.admin(&["create", "ada", "empty"]).status.success()); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let first = setup.latest(); | ||
| let repo = first.join("repos/ada/project.git"); | ||
| assert!(repo.join("gitv-public").is_file(), "visibility is kept"); | ||
| assert!(repo.join("gitv-push.log").is_file(), "the push log is kept"); | ||
| assert!(first.join("repos/ada/empty.git/HEAD").is_file(), "empty repositories are kept"); | ||
| assert_eq!(fs::read_dir(first.join("repos/ada/.trash")).unwrap().count(), 1, "the trash is kept"); | ||
| assert!(fs::read_to_string(first.join("etc-gitv/authorized_keys")).unwrap().contains("ssh-ed25519")); | ||
| assert_eq!(fs::read_to_string(first.join("gitv-web/login")).unwrap(), "user=Um9i\n"); | ||
| assert_eq!(fs::read_to_string(first.join("ssh-host-keys/ssh_host_ed25519_key")).unwrap(), "private\n"); | ||
| assert!(first.join("ssh-host-keys/ssh_host_ed25519_key.pub").is_file()); | ||
| assert!(!first.join("ssh-host-keys/sshd_config").exists(), "only the host keys are kept"); | ||
| let manifest = fs::read_to_string(first.join("MANIFEST")).unwrap(); | ||
| assert!(manifest.contains("repositories: 2")); | ||
| assert!(!manifest.contains("stale") && !manifest.contains("missing"), "a clean snapshot reports no problems"); | ||
| // The next snapshot shares unchanged files with this one. | ||
| commit(&work, "Second"); | ||
| setup.push(&work, "project"); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let second = setup.latest(); | ||
| assert_ne!(first, second); | ||
| let objects = |root: &Path| root.join("repos/ada/project.git/objects"); | ||
| let first_commit = git(&work, &["rev-parse", "HEAD~1"]); | ||
| let loose = format!("{}/{}", &first_commit[..2], &first_commit[2..]); | ||
| assert_eq!( | ||
| fs::metadata(objects(&first).join(&loose)).unwrap().ino(), | ||
| fs::metadata(objects(&second).join(&loose)).unwrap().ino(), | ||
| "an unchanged object is a hard link, not a second copy" | ||
| ); | ||
| // Restoring gives a working repository at the newest state, and refuses to overwrite. | ||
| let target = scratch("backup-whole-restored"); | ||
| let out = setup.run(RESTORE, &["latest", target.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("2 repositories verified"), "{}", stderr(&out)); | ||
| assert_eq!(git(&target.join("repos/ada/project.git"), &["log", "--format=%s", "main"]), "Second\nFirst"); | ||
| assert!(!setup.run(RESTORE, &["latest", target.to_str().unwrap()]).status.success(), "a full target is refused"); | ||
| // A bad name is refused before anything is copied: the target is never even created. | ||
| let elsewhere = setup.host.dir.join("not-restored"); | ||
| for name in ["../../etc", "2026-01-01T000000Z", ""] { | ||
| let out = setup.run(RESTORE, &[name, elsewhere.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "{name:?} was restored"); | ||
| assert!(!elsewhere.exists(), "{name:?} copied something"); | ||
| } | ||
| let out = setup.run(RESTORE, &["check"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(!setup.backups.join("gitv/restore-check").exists(), "the drill cleans up"); | ||
| } | ||
| #[test] | ||
| fn a_corrupt_repository_fails_the_backup_and_keeps_latest() { | ||
| let setup = Setup::new("backup-corrupt"); | ||
| let work = work("backup-corrupt-work"); | ||
| setup.push(&work, "project"); | ||
| assert!(setup.backup().status.success()); | ||
| let good = setup.latest(); | ||
| // Lose an object the branch needs. | ||
| let tree = git(&work, &["rev-parse", "HEAD^{tree}"]); | ||
| fs::remove_file(setup.host.repo("ada", "project").join(format!("objects/{}/{}", &tree[..2], &tree[2..]))).unwrap(); | ||
| let out = setup.backup(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("fsck failed for ada/project.git"), "{}", stderr(&out)); | ||
| assert_eq!(setup.latest(), good, "latest still names the last good snapshot"); | ||
| let failed = fs::read_dir(setup.backups.join("gitv/snapshots")) | ||
| .unwrap() | ||
| .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".failed")) | ||
| .count(); | ||
| assert_eq!(failed, 1); | ||
| } | ||
| #[test] | ||
| fn a_push_in_progress_keeps_its_last_copy_without_holding_up_the_rest() { | ||
| let setup = Setup::new("backup-lock"); | ||
| let work = work("backup-lock-work"); | ||
| setup.push(&work, "busy"); | ||
| setup.push(&work, "other"); | ||
| // Hold the lock as a push does; the backup gives up on it after its (one second) wait. | ||
| let repo = gitv_core::RepoDir::at(&setup.host.repo("ada", "busy")).unwrap(); | ||
| let held = repo.lock(false).unwrap(); | ||
| // Never backed up before: there is no copy to keep, but the other repository is backed up. | ||
| let out = setup.backup(); | ||
| assert!(!out.status.success(), "an incomplete backup must fail"); | ||
| assert!(stderr(&out).contains("ada/busy.git for over 1s, and no earlier snapshot"), "{}", stderr(&out)); | ||
| let first = setup.latest(); | ||
| assert!(first.join("repos/ada/other.git/HEAD").is_file(), "the other repository was backed up"); | ||
| assert!(!first.join("repos/ada/busy.git").exists()); | ||
| assert!(fs::read_to_string(first.join("MANIFEST")).unwrap().contains("never backed up): ada/busy.git")); | ||
| drop(held); | ||
| // Backed up once, then held again while it moves on: the snapshot keeps the earlier copy. | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let good = setup.latest(); | ||
| commit(&work, "Second"); | ||
| setup.push(&work, "busy"); | ||
| setup.push(&work, "other"); | ||
| let held = repo.lock(false).unwrap(); | ||
| let out = setup.backup(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("kept its copy from"), "{}", stderr(&out)); | ||
| let latest = setup.latest(); | ||
| assert_ne!(latest, good, "everything else still moves on"); | ||
| let tip = |root: &Path, name: &str| git(&root.join(format!("repos/ada/{name}.git")), &["log", "-1", "--format=%s"]); | ||
| assert_eq!(tip(&latest, "busy"), "First", "the held repository is its last good copy"); | ||
| assert_eq!(tip(&latest, "other"), "Second"); | ||
| let head = |root: &Path| fs::metadata(root.join("repos/ada/busy.git/HEAD")).unwrap().ino(); | ||
| assert_eq!(head(&latest), head(&good), "the kept copy is hard links, not a second copy"); | ||
| drop(held); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(tip(&setup.latest(), "busy"), "Second"); | ||
| } | ||
| #[test] | ||
| fn latest_is_replaced_in_one_step() { | ||
| let setup = Setup::new("backup-latest"); | ||
| let work = work("backup-latest-work"); | ||
| setup.push(&work, "project"); | ||
| // A leftover from a run that crashed between making the new link and renaming it. | ||
| fs::create_dir_all(setup.backups.join("gitv")).unwrap(); | ||
| std::os::unix::fs::symlink("snapshots/gone", setup.backups.join("gitv/.latest.new")).unwrap(); | ||
| assert!(setup.backup().status.success()); | ||
| assert!(setup.latest().join("MANIFEST").is_file()); | ||
| assert!(fs::symlink_metadata(setup.backups.join("gitv/.latest.new")).is_err(), "nothing is left beside it"); | ||
| } | ||
| #[test] | ||
| fn a_restore_check_without_snapshots_copies_nothing() { | ||
| let setup = Setup::new("backup-none"); | ||
| fs::create_dir_all(setup.backups.join("gitv/snapshots")).unwrap(); | ||
| let out = setup.run(RESTORE, &["check"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("no such snapshot"), "{}", stderr(&out)); | ||
| assert!(!setup.backups.join("gitv/restore-check").exists(), "nothing was copied"); | ||
| } | ||
| #[test] | ||
| fn an_unmounted_backup_directory_is_refused() { | ||
| let setup = Setup::new("backup-unmounted"); | ||
| let out = Command::new(BACKUP) | ||
| .env("GITV_REPOS", &setup.host.repos) | ||
| .env("GITV_BACKUP_DIR", &setup.backups) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("not a mounted volume"), "{}", stderr(&out)); | ||
| assert!(!setup.backups.join("gitv").exists(), "nothing was written"); | ||
| } | ||
| #[test] | ||
| fn one_repository_comes_back_from_a_snapshot_after_its_trash_is_purged() { | ||
| let setup = Setup::new("backup-one"); | ||
| let host = &setup.host; | ||
| let work = work("backup-one-work"); | ||
| git(&work, &["branch", "release"]); | ||
| git(&work, &["tag", "-a", "v1", "-m", "One"]); | ||
| git(&work, &["tag", "light"]); | ||
| let out = host.git(&work, &["push", "-q", "ada@x:ada/tools.git", "main", "release", "v1", "light"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| for args in [ | ||
| &["visibility", "ada", "tools", "public"][..], | ||
| &["default-branch", "ada", "tools", "release"], | ||
| &["description", "ada", "tools", "Tools for ada"], | ||
| ] { | ||
| let out = host.admin(args); | ||
| assert!(out.status.success(), "{args:?}: {}", stderr(&out)); | ||
| } | ||
| let refs = |repo: &Path| git(repo, &["for-each-ref", "--format=%(objectname) %(refname)"]); | ||
| let before = refs(&host.repo("ada", "tools")); | ||
| assert_eq!(before.lines().count(), 4, "{before}"); | ||
| let out = setup.backup(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let snapshot = setup.latest().file_name().unwrap().to_str().unwrap().to_string(); | ||
| // Deleted, purged from the trash, and the name since taken by a new repository. | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| let out = host.admin(&["purge", "--older-than-days", "0"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_dir(host.repos.join("ada/.trash")).unwrap().count(), 0, "the trash was purged"); | ||
| assert!(host.admin(&["create", "ada", "tools"]).status.success()); | ||
| let out = setup.run(RESTORE, &["find", "ada/tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), snapshot); | ||
| assert!(!setup.run(RESTORE, &["find", "ada/missing"]).status.success()); | ||
| let target = scratch("backup-one-restored"); | ||
| let out = setup.run(RESTORE, &["latest", target.to_str().unwrap(), "ada/tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("gitv import ada tools"), "{}", stderr(&out)); | ||
| let restored = target.join("tools.git"); | ||
| assert_eq!(fs::read_dir(&target).unwrap().count(), 1, "only that repository was copied"); | ||
| // The new repository at the name is never replaced. | ||
| let out = host.admin(&["import", "ada", "tools", restored.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already exists"), "{}", stderr(&out)); | ||
| assert_eq!(refs(&host.repo("ada", "tools")), "", "the new repository is untouched"); | ||
| let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")) | ||
| .unwrap() | ||
| .map(|e| e.unwrap().file_name().into_string().unwrap()) | ||
| .filter(|n| n.starts_with(".create")) | ||
| .collect(); | ||
| assert!(leftovers.is_empty(), "{leftovers:?}"); | ||
| // Under another name it comes back whole: refs, default branch, visibility, description. | ||
| let out = host.admin(&["import", "ada", "tools-restored", restored.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let back = host.repo("ada", "tools-restored"); | ||
| assert_eq!(refs(&back), before); | ||
| assert_eq!(git(&back, &["symbolic-ref", "HEAD"]), "refs/heads/release"); | ||
| assert!(back.join("gitv-public").is_file(), "still public"); | ||
| assert_eq!(fs::read_to_string(back.join("description")).unwrap(), "Tools for ada\n"); | ||
| let out = host.ssh("ada", "list"); | ||
| assert!(String::from_utf8_lossy(&out.stdout).contains("ada/tools-restored.git")); | ||
| let clone = scratch("backup-one-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/tools-restored.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "release"); | ||
| // Names that aren't OWNER/NAME, and repositories a snapshot doesn't hold, copy nothing. | ||
| let elsewhere = host.dir.join("not-restored"); | ||
| for repo in ["ada/../etc", "ada", "ada/tools/x", "Ada/tools", "ada/missing"] { | ||
| let out = setup.run(RESTORE, &["latest", elsewhere.to_str().unwrap(), repo]); | ||
| assert!(!out.status.success(), "{repo} was restored"); | ||
| assert!(!elsewhere.exists(), "{repo} copied something"); | ||
| } | ||
| // Only a bare repository is imported. | ||
| let out = host.admin(&["import", "ada", "other", work.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "a working copy was imported"); | ||
| assert!(!host.repo("ada", "other").exists()); | ||
| } | ||
+8−0
| @@ -0,0 +1,8 @@ | ||
| //! Helpers for the SSH and backup tests, shared with the web tests. | ||
| #![allow(dead_code, unused_imports)] | ||
| #[path = "../../../../testing/host.rs"] | ||
| mod host; | ||
| pub use host::*; | ||
+939−0
| @@ -0,0 +1,939 @@ | ||
| //! `gitv serve` (what a key runs over SSH) and the administrator commands, exercised with real | ||
| //! git pushes and clones through a stand-in for ssh. | ||
| mod common; | ||
| use std::fs; | ||
| use common::{Host, ed25519_key, git, scratch, stderr, stdout}; | ||
| /// A working copy with one commit on `branch`. | ||
| fn work(name: &str, branch: &str) -> std::path::PathBuf { | ||
| let dir = scratch(name); | ||
| git(&dir, &["init", "-q", "-b", branch]); | ||
| fs::write(dir.join("hello.txt"), "hello\n").unwrap(); | ||
| git(&dir, &["add", "."]); | ||
| git(&dir, &["commit", "-qm", "First"]); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn help_lists_the_commands() { | ||
| let host = Host::new("ssh-help"); | ||
| for command in ["", "help"] { | ||
| let out = host.ssh("ada", command); | ||
| assert!(out.status.success()); | ||
| assert!(stdout(&out).contains("create <name>"), "{}", stdout(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn unknown_and_unreadable_commands_are_refused() { | ||
| let host = Host::new("ssh-unknown"); | ||
| for command in ["rm -rf /", "list extra", "create", "git-upload-pack", "create 'unterminated"] { | ||
| let out = host.ssh("ada", command); | ||
| assert!(!out.status.success(), "{command} should fail"); | ||
| assert!(stderr(&out).starts_with("gitv: "), "{command}: {}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn create_list_and_delete() { | ||
| let host = Host::new("ssh-crud"); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@git.example.test:ada/notes.git"); | ||
| assert!(host.repo("ada", "notes").join("HEAD").is_file()); | ||
| assert!(!host.ssh("ada", "create notes").status.success(), "duplicates are refused"); | ||
| host.ssh("ada", "create alpha"); | ||
| assert_eq!( | ||
| stdout(&host.ssh("ada", "list")), | ||
| "git@git.example.test:ada/alpha.git\ngit@git.example.test:ada/notes.git\n" | ||
| ); | ||
| assert_eq!(stdout(&host.ssh("bob", "list")), "", "owners only see their own repositories"); | ||
| let out = host.ssh("ada", "delete notes"); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("delete notes --yes"), "{}", stderr(&out)); | ||
| assert!(host.repo("ada", "notes").exists(), "nothing is deleted without --yes"); | ||
| let out = host.ssh("ada", "delete notes --yes"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stdout(&out).contains("trash"), "{}", stdout(&out)); | ||
| assert!(!host.repo("ada", "notes").exists()); | ||
| assert_eq!(trash(&host, "ada").len(), 1, "the repository waits in the trash"); | ||
| assert!(host.logged().contains("ada/notes.git moved to the trash"), "{}", host.logged()); | ||
| assert!(!host.ssh("ada", "delete notes --yes").status.success(), "a missing repository can't be deleted"); | ||
| assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.example.test:ada/alpha.git\n", "the trash isn't listed"); | ||
| } | ||
| /// The names in an owner's trash. | ||
| fn trash(host: &Host, owner: &str) -> Vec<String> { | ||
| let mut names: Vec<String> = fs::read_dir(host.repos.join(owner).join(".trash")) | ||
| .map(|dir| dir.map(|e| e.unwrap().file_name().into_string().unwrap()).collect()) | ||
| .unwrap_or_default(); | ||
| names.sort(); | ||
| names | ||
| } | ||
| #[test] | ||
| fn names_are_validated() { | ||
| let host = Host::new("ssh-names"); | ||
| for name in ["Upper", "-dash", "has.dot", "a/b", "..", &"x".repeat(64)] { | ||
| let out = host.ssh("ada", &format!("create '{name}'")); | ||
| assert!(!out.status.success(), "{name} should be refused"); | ||
| } | ||
| assert!(fs::read_dir(&host.repos).unwrap().next().is_none(), "nothing was created"); | ||
| assert!(host.ssh("ada", "create ok_name-2").status.success()); | ||
| } | ||
| #[test] | ||
| fn push_creates_the_repository_and_clone_reads_it() { | ||
| let host = Host::new("ssh-push"); | ||
| let dir = work("ssh-push-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("gitv: created ada/project.git"), "{}", stderr(&out)); | ||
| let clone = scratch("ssh-push-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_to_string(clone.join("copy/hello.txt")).unwrap(), "hello\n"); | ||
| // The address without `.git` names the same repository. | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project", "bare-name"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(clone.join("bare-name/hello.txt").is_file()); | ||
| // A second push updates the same repository. | ||
| fs::write(dir.join("hello.txt"), "hello again\n").unwrap(); | ||
| git(&dir, &["commit", "-qam", "Second"]); | ||
| assert!(host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]).status.success()); | ||
| let log = git(&host.repo("ada", "project"), &["log", "--format=%s", "main"]); | ||
| assert_eq!(log, "Second\nFirst"); | ||
| } | ||
| #[test] | ||
| fn fetching_a_missing_repository_fails_without_creating_it() { | ||
| let host = Host::new("ssh-missing"); | ||
| let clone = scratch("ssh-missing-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/nothing.git"]); | ||
| assert!(!out.status.success()); | ||
| assert!(!host.repo("ada", "nothing").exists()); | ||
| } | ||
| #[test] | ||
| fn keys_only_reach_their_owners_repositories() { | ||
| let host = Host::new("ssh-owner"); | ||
| let dir = work("ssh-owner-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "bob@x:bob/private.git", "main"]).status.success()); | ||
| let clone = scratch("ssh-owner-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:bob/private.git"]); | ||
| assert!(!out.status.success(), "ada read bob's repository"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:bob/other.git", "main"]); | ||
| assert!(!out.status.success(), "ada created a repository for bob"); | ||
| assert!(!host.repo("bob", "other").exists()); | ||
| for path in ["'../bob/private.git'", "'ada/../bob/private.git'", "'/etc/passwd'", "'ada/x'"] { | ||
| let out = host.ssh("ada", &format!("git-upload-pack {path}")); | ||
| assert!(!out.status.success(), "{path} was served"); | ||
| assert!(stderr(&out).contains("repository unavailable"), "{path}: {}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn pushing_master_alone_makes_it_the_default_branch() { | ||
| let host = Host::new("ssh-head"); | ||
| let dir = work("ssh-head-work", "master"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/legacy.git", "master"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("default branch is now master"), "{}", stderr(&out)); | ||
| assert_eq!(git(&host.repo("ada", "legacy"), &["symbolic-ref", "HEAD"]), "refs/heads/master"); | ||
| // A clone now checks out master without being told to. | ||
| let clone = scratch("ssh-head-clone"); | ||
| assert!(host.git(&clone, &["clone", "-q", "ada@x:ada/legacy.git", "copy"]).status.success()); | ||
| assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "master"); | ||
| } | ||
| #[test] | ||
| fn admin_create_and_delete() { | ||
| let host = Host::new("admin-crud"); | ||
| let out = host.admin(&["create", "ada", "tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@git.example.test:ada/tools.git"); | ||
| assert_eq!(git(&host.repo("ada", "tools"), &["symbolic-ref", "HEAD"]), "refs/heads/main"); | ||
| let out = host.admin(&["delete", "ada", "tools"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("--yes"), "{}", stderr(&out)); | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| assert!(!host.repo("ada", "tools").exists()); | ||
| assert!(!host.admin(&["create", "Ada", "tools"]).status.success(), "owner names are validated"); | ||
| } | ||
| #[test] | ||
| fn deleted_repositories_can_be_restored_until_purged() { | ||
| let host = Host::new("admin-trash"); | ||
| let dir = work("admin-trash-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]).status.success()); | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| let [entry] = <[String; 1]>::try_from(trash(&host, "ada")).unwrap(); | ||
| assert!(entry.starts_with("tools."), "{entry}"); | ||
| let listed = stdout(&host.admin(&["trash"])); | ||
| assert!(listed.contains(&format!("ada {entry}")) && listed.contains("deleted 0 days ago"), "{listed}"); | ||
| // Restoring never replaces what is at the name now. | ||
| assert!(host.admin(&["create", "ada", "tools"]).status.success()); | ||
| let out = host.admin(&["restore", "ada", &entry]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("--as"), "{}", stderr(&out)); | ||
| let out = host.admin(&["restore", "ada", &entry, "--as", "tools-old"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(git(&host.repo("ada", "tools-old"), &["log", "--format=%s", "main"]), "First"); | ||
| assert!(trash(&host, "ada").is_empty()); | ||
| assert!(!host.admin(&["restore", "ada", &entry]).status.success(), "an entry restores once"); | ||
| assert!(!host.admin(&["restore", "ada", "../../etc"]).status.success(), "entries are validated"); | ||
| // A purge keeps recent entries and removes old enough ones. | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| assert!(host.admin(&["purge"]).status.success()); | ||
| assert_eq!(trash(&host, "ada").len(), 1, "a fresh entry survives the default purge"); | ||
| let out = host.admin(&["purge", "--older-than-days", "0"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stdout(&out).contains("purged ada/.trash/tools."), "{}", stdout(&out)); | ||
| assert!(trash(&host, "ada").is_empty()); | ||
| } | ||
| #[test] | ||
| fn overwritten_and_deleted_branches_stay_recoverable() { | ||
| let host = Host::new("ssh-recovery"); | ||
| let dir = work("ssh-recovery-work", "main"); | ||
| let remote = "ada@x:ada/history.git"; | ||
| assert!(host.git(&dir, &["push", "-q", remote, "main", "main:topic"]).status.success()); | ||
| let first = git(&dir, &["rev-parse", "HEAD"]); | ||
| // Rewrite main and force it over the old commit, then delete topic. | ||
| git(&dir, &["commit", "-q", "--amend", "-m", "Rewritten"]); | ||
| let rewritten = git(&dir, &["rev-parse", "HEAD"]); | ||
| assert!(host.git(&dir, &["push", "-qf", remote, "main"]).status.success()); | ||
| assert!(host.git(&dir, &["push", "-q", remote, ":topic"]).status.success()); | ||
| let repo = host.repo("ada", "history"); | ||
| assert_eq!(git(&repo, &["rev-parse", "main@{1}"]), first, "the reflog keeps the overwritten commit"); | ||
| let log = fs::read_to_string(repo.join("gitv-push.log")).unwrap(); | ||
| let lines: Vec<Vec<&str>> = log.lines().map(|l| l.split(' ').skip(1).collect()).collect(); | ||
| assert_eq!( | ||
| lines, | ||
| [ | ||
| vec!["-", first.as_str(), "refs/heads/main"], | ||
| vec!["-", first.as_str(), "refs/heads/topic"], | ||
| vec![first.as_str(), rewritten.as_str(), "refs/heads/main"], | ||
| vec![first.as_str(), "-", "refs/heads/topic"], | ||
| ], | ||
| "{log}" | ||
| ); | ||
| assert_eq!(git(&repo, &["cat-file", "-t", &first]), "commit", "the deleted branch's commit is still there"); | ||
| } | ||
| #[test] | ||
| fn the_configuration_file_sets_the_host_and_the_forced_command() { | ||
| let host = Host::new("ssh-config"); | ||
| let config = host.dir.join("gitv.conf"); | ||
| fs::write(&config, "# this server\nhost = Code.Example.org\ncommand = /opt/gitv/bin/gitv\n").unwrap(); | ||
| let admin = |args: &[&str]| { | ||
| std::process::Command::new(&*common::GITV) | ||
| .args(args) | ||
| .env("GITV_CONFIG", &config) | ||
| .env("GITV_REPOS", &host.repos) | ||
| .env("GITV_KEYS", &host.keys) | ||
| .output() | ||
| .unwrap() | ||
| }; | ||
| let out = admin(&["create", "ada", "tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@code.example.org:ada/tools.git"); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(3)).unwrap(); | ||
| assert!(admin(&["add-key", "ada", key.to_str().unwrap()]).status.success()); | ||
| assert!(fs::read_to_string(&host.keys).unwrap().starts_with("restrict,command=\"/opt/gitv/bin/gitv serve ada\"")); | ||
| // A mistake stops every command, and a key holder isn't shown the server's paths. | ||
| fs::write(&config, "hostname = code.example.org\n").unwrap(); | ||
| let out = admin(&["create", "ada", "other"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("unknown setting `hostname`"), "{}", stderr(&out)); | ||
| let out = std::process::Command::new(&*common::GITV) | ||
| .args(["serve", "ada"]) | ||
| .env("SSH_ORIGINAL_COMMAND", "list") | ||
| .env("GITV_CONFIG", &config) | ||
| .env("GITV_REPOS", &host.repos) | ||
| .env("GITV_LOG", host.log()) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("misconfigured") && !stderr(&out).contains("gitv.conf"), "{}", stderr(&out)); | ||
| assert!(host.logged().contains("unknown setting `hostname`"), "{}", host.logged()); | ||
| } | ||
| #[test] | ||
| fn admin_add_key() { | ||
| let host = Host::new("admin-keys"); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(7)).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let keys = fs::read_to_string(&host.keys).unwrap(); | ||
| assert!(keys.starts_with("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 AAAA"), "{keys}"); | ||
| assert!(!keys.contains("test@example"), "the key's comment is dropped"); | ||
| assert!(host.repos.join("ada").is_dir(), "the owner's directory exists"); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| let second = host.dir.join("bob.pub"); | ||
| fs::write(&second, ed25519_key(9)).unwrap(); | ||
| assert!(host.admin(&["add-key", "bob", second.to_str().unwrap()]).status.success()); | ||
| assert_eq!(fs::read_to_string(&host.keys).unwrap().lines().count(), 2, "both keys are kept"); | ||
| } | ||
| #[test] | ||
| fn admin_add_key_rejects_bad_keys() { | ||
| let host = Host::new("admin-badkeys"); | ||
| let cases = [ | ||
| ("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ test\n".to_string()), | ||
| ("garbage", "not a key\n".to_string()), | ||
| ("bad-base64", "ssh-ed25519 !!!!\n".to_string()), | ||
| ("short", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n".to_string()), | ||
| ("options", format!("command=\"sh\" {}", ed25519_key(1))), | ||
| ]; | ||
| for (name, text) in cases { | ||
| let file = host.dir.join(format!("{name}.pub")); | ||
| fs::write(&file, text).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "{name} was accepted"); | ||
| } | ||
| assert!(!host.keys.exists(), "no key was written"); | ||
| } | ||
| #[test] | ||
| fn admin_needs_root_outside_a_local_tree() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; | ||
| } | ||
| let out = std::process::Command::new(&*common::GITV) | ||
| .args(["create", "ada", "tools"]) | ||
| .env_remove("GITV_REPOS") | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("as root"), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn symlinked_repositories_are_refused() { | ||
| let host = Host::new("ssh-symlink-repo"); | ||
| let dir = work("ssh-symlink-repo-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "bob@x:bob/real.git", "main"]).status.success()); | ||
| // ada/link.git points at bob's repository: following it would cross the owner boundary. | ||
| fs::create_dir_all(host.repos.join("ada")).unwrap(); | ||
| std::os::unix::fs::symlink(host.repo("bob", "real"), host.repo("ada", "link")).unwrap(); | ||
| let clone = scratch("ssh-symlink-repo-clone"); | ||
| assert!(!host.git(&clone, &["clone", "-q", "ada@x:ada/link.git"]).status.success(), "read through a symlink"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/link.git", "main:other"]); | ||
| assert!(!out.status.success(), "wrote through a symlink"); | ||
| assert!(git(&host.repo("bob", "real"), &["branch", "--list", "other"]).is_empty()); | ||
| assert_eq!(stdout(&host.ssh("ada", "list")), "", "symlinks aren't listed"); | ||
| assert!(!host.ssh("ada", "delete link --yes").status.success()); | ||
| assert!(host.repo("bob", "real").join("HEAD").is_file(), "the target survives"); | ||
| } | ||
| #[test] | ||
| fn symlinked_owner_directories_are_refused() { | ||
| let host = Host::new("ssh-symlink-owner"); | ||
| let outside = scratch("ssh-symlink-owner-outside"); | ||
| std::os::unix::fs::symlink(&outside, host.repos.join("ada")).unwrap(); | ||
| let dir = work("ssh-symlink-owner-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/new.git", "main"]); | ||
| assert!(!out.status.success(), "created a repository through a symlinked owner directory"); | ||
| assert!(!host.ssh("ada", "create other").status.success()); | ||
| assert!(fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the tree"); | ||
| } | ||
| #[test] | ||
| fn simultaneous_first_pushes_all_succeed() { | ||
| let host = std::sync::Arc::new(Host::new("ssh-race")); | ||
| let dir = work("ssh-race-work", "main"); | ||
| // Each push sends its own branch: racing to create one *branch* is git's business, but | ||
| // racing to create the *repository* must not fail anyone. | ||
| let pushes: Vec<_> = (0..6) | ||
| .map(|n| { | ||
| let (host, dir) = (host.clone(), dir.clone()); | ||
| std::thread::spawn(move || host.git(&dir, &["push", "-q", "ada@x:ada/raced.git", &format!("main:b{n}")])) | ||
| }) | ||
| .collect(); | ||
| for push in pushes { | ||
| let out = push.join().unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| } | ||
| let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect(); | ||
| assert_eq!(leftovers, [std::ffi::OsString::from("raced.git")], "no staging directories left behind"); | ||
| assert_eq!(git(&host.repo("ada", "raced"), &["for-each-ref", "--format=%(refname:lstrip=2)"]).lines().count(), 6); | ||
| assert_eq!(host.logged(), "", "losing a creation race is ordinary and isn't logged"); | ||
| } | ||
| #[test] | ||
| fn add_key_failure_installs_nothing() { | ||
| let host = Host::new("admin-keys-atomic"); | ||
| // A file where the owner's directory should go makes preparing the owner fail. | ||
| fs::write(host.repos.join("ada"), "not a directory").unwrap(); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(3)).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(!host.keys.exists(), "the key was installed although the command failed"); | ||
| // Once the problem is fixed, a retry succeeds rather than finding the key already there. | ||
| fs::remove_file(host.repos.join("ada")).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn a_failed_key_write_leaves_no_temporary_file() { | ||
| use std::os::unix::process::CommandExt; | ||
| let host = Host::new("admin-keys-cleanup"); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(4)).unwrap(); | ||
| let mut command = std::process::Command::new(&*common::GITV); | ||
| command | ||
| .args(["add-key", "ada", key.to_str().unwrap()]) | ||
| .env("GITV_HOST", common::TEST_HOST) | ||
| .env("GITV_CONFIG", common::NO_CONFIG) | ||
| .env("GITV_REPOS", &host.repos) | ||
| .env("GITV_KEYS", &host.keys); | ||
| // Files may grow to 16 bytes, so writing the new keys file fails part way. With SIGXFSZ | ||
| // ignored the write returns an error instead of killing the process. | ||
| // SAFETY: signal and setrlimit are async-signal-safe and the closure does nothing else. | ||
| unsafe { | ||
| command.pre_exec(|| { | ||
| nix::libc::signal(nix::libc::SIGXFSZ, nix::libc::SIG_IGN); | ||
| nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_FSIZE, 16, 16) | ||
| .map_err(std::io::Error::from) | ||
| }); | ||
| } | ||
| let out = command.output().unwrap(); | ||
| assert!(!out.status.success(), "the write should have failed"); | ||
| assert!(stderr(&out).contains("File too large"), "it failed while writing: {}", stderr(&out)); | ||
| assert!(!host.keys.exists(), "no keys file was published"); | ||
| let left: Vec<_> = fs::read_dir(&host.dir) | ||
| .unwrap() | ||
| .map(|e| e.unwrap().file_name().into_string().unwrap()) | ||
| .filter(|n| n.starts_with(".authorized_keys")) | ||
| .collect(); | ||
| assert!(left.is_empty(), "temporary files left behind: {left:?}"); | ||
| } | ||
| #[test] | ||
| fn add_key_respects_existing_lines() { | ||
| let host = Host::new("admin-keys-existing"); | ||
| let blob = ed25519_key(5); | ||
| let blob = blob.split_whitespace().nth(1).unwrap(); | ||
| // Written by hand: options in front, a comment after, and no final newline. | ||
| fs::write(&host.keys, format!("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob} laptop")) | ||
| .unwrap(); | ||
| let same = host.dir.join("same.pub"); | ||
| fs::write(&same, ed25519_key(5)).unwrap(); | ||
| let out = host.admin(&["add-key", "bob", same.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "the same key was registered twice"); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| let other = host.dir.join("other.pub"); | ||
| fs::write(&other, ed25519_key(6)).unwrap(); | ||
| assert!(host.admin(&["add-key", "bob", other.to_str().unwrap()]).status.success()); | ||
| let keys = fs::read_to_string(&host.keys).unwrap(); | ||
| let lines: Vec<&str> = keys.lines().collect(); | ||
| assert_eq!(lines.len(), 2, "{keys}"); | ||
| assert!( | ||
| lines[0].ends_with(" laptop") && lines[1].starts_with("restrict,command=\"/usr/local/bin/gitv serve bob\"") | ||
| ); | ||
| } | ||
| #[test] | ||
| fn the_readme_fake_ssh_script_works() { | ||
| let host = Host::new("ssh-script"); | ||
| let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/fake-ssh"); | ||
| let dir = work("ssh-script-work", "main"); | ||
| let out = common::git_cmd(&dir) | ||
| .env("GIT_SSH_COMMAND", &script) | ||
| .env("GITV_REPOS", &host.repos) | ||
| .args(["push", "-q", "um9i@local:um9i/demo.git", "main"]) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(host.repo("um9i", "demo").join("HEAD").is_file()); | ||
| } | ||
| #[test] | ||
| fn default_branch_repair_keeps_branch_names_exact() { | ||
| use std::os::unix::ffi::OsStrExt; | ||
| // Names that whitespace splitting or UTF-8 conversion would mangle. | ||
| let names: [&[u8]; 2] = ["trunk\u{a0}line".as_bytes(), b"caf\xe9"]; | ||
| for (n, name) in names.iter().enumerate() { | ||
| let host = Host::new(&format!("ssh-head-bytes-{n}")); | ||
| let dir = work(&format!("ssh-head-bytes-{n}-work"), "main"); | ||
| let target = [b"main:refs/heads/".as_slice(), name].concat(); | ||
| let out = common::git_cmd(&dir) | ||
| .env("GIT_SSH_COMMAND", host.ssh_script()) | ||
| .args([std::ffi::OsStr::new("push"), "-q".as_ref(), "ada@x:ada/odd.git".as_ref()]) | ||
| .arg(std::ffi::OsStr::from_bytes(&target)) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let head = common::git_cmd(&host.repo("ada", "odd")).args(["symbolic-ref", "HEAD"]).output().unwrap(); | ||
| assert_eq!( | ||
| head.stdout, | ||
| [b"refs/heads/".as_slice(), name, b"\n"].concat(), | ||
| "HEAD names the pushed branch exactly" | ||
| ); | ||
| let clone = scratch(&format!("ssh-head-bytes-{n}-clone")); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/odd.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(clone.join("copy/hello.txt").is_file(), "the clone checked out the default branch"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn commented_keys_do_not_block_registration() { | ||
| let host = Host::new("admin-keys-comments"); | ||
| let key = ed25519_key(8); | ||
| let blob = key.split_whitespace().nth(1).unwrap(); | ||
| // The key is retired (commented out) and also mentioned in another key's comment. | ||
| let other = ed25519_key(9); | ||
| let other_blob = other.split_whitespace().nth(1).unwrap(); | ||
| fs::write( | ||
| &host.keys, | ||
| format!( | ||
| "# restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob}\n\ | ||
| # ssh-ed25519 {blob} old laptop\n\ | ||
| command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {other_blob} replaces ssh-ed25519 {blob}\n" | ||
| ), | ||
| ) | ||
| .unwrap(); | ||
| let file = host.dir.join("ada.pub"); | ||
| fs::write(&file, &key).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| // A real duplicate behind quoted options with spaces is still caught. | ||
| let again = host.dir.join("bob.pub"); | ||
| fs::write(&again, &other).unwrap(); | ||
| let out = host.admin(&["add-key", "carol", again.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn tab_separated_keys_are_recognised() { | ||
| let host = Host::new("admin-keys-tabs"); | ||
| let key = ed25519_key(11); | ||
| let blob = key.split_whitespace().nth(1).unwrap(); | ||
| // An active key written with tabs between its fields, with and without options. | ||
| fs::write( | ||
| &host.keys, | ||
| format!("ssh-ed25519\t{blob}\tlaptop\nrestrict\tssh-ed25519\t{}\n", { | ||
| let other = ed25519_key(12); | ||
| other.split_whitespace().nth(1).unwrap().to_string() | ||
| }), | ||
| ) | ||
| .unwrap(); | ||
| for (seed, owner) in [(11, "bob"), (12, "carol")] { | ||
| let file = host.dir.join(format!("{owner}.pub")); | ||
| fs::write(&file, ed25519_key(seed)).unwrap(); | ||
| let out = host.admin(&["add-key", owner, file.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "key {seed} was registered a second time"); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn creation_never_replaces_what_is_at_the_name() { | ||
| let host = Host::new("admin-create-noreplace"); | ||
| // An empty directory (which a plain rename would silently replace) and a symlink. | ||
| fs::create_dir_all(host.repo("ada", "empty")).unwrap(); | ||
| let elsewhere = scratch("admin-create-noreplace-elsewhere"); | ||
| std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "link")).unwrap(); | ||
| for name in ["empty", "link"] { | ||
| let out = host.admin(&["create", "ada", name]); | ||
| assert!(!out.status.success(), "{name} was created over"); | ||
| assert!(stderr(&out).contains("already exists"), "{name}: {}", stderr(&out)); | ||
| } | ||
| assert!(fs::read_dir(host.repo("ada", "empty")).unwrap().next().is_none(), "the directory is untouched"); | ||
| assert!(fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing was written through the symlink"); | ||
| let names: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect(); | ||
| assert_eq!(names.len(), 2, "no staging directory left behind: {names:?}"); | ||
| } | ||
| #[test] | ||
| fn purging_removes_links_inside_a_repository_without_following_them() { | ||
| let host = Host::new("admin-delete-links"); | ||
| assert!(host.admin(&["create", "ada", "tools"]).status.success()); | ||
| let outside = scratch("admin-delete-links-outside"); | ||
| fs::write(outside.join("precious.txt"), "keep").unwrap(); | ||
| std::os::unix::fs::symlink(&outside, host.repo("ada", "tools").join("escape")).unwrap(); | ||
| let out = host.admin(&["delete", "ada", "tools", "--yes"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(!host.repo("ada", "tools").exists()); | ||
| let out = host.admin(&["purge", "--older-than-days", "0"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_to_string(outside.join("precious.txt")).unwrap(), "keep"); | ||
| assert!(trash(&host, "ada").is_empty(), "the trash is emptied"); | ||
| assert_eq!(fs::read_dir(host.repos.join("ada")).unwrap().count(), 1, "only the trash itself is left"); | ||
| } | ||
| #[test] | ||
| fn a_failed_first_push_tells_the_operator_why() { | ||
| let host = Host::new("ssh-first-push-log"); | ||
| let elsewhere = scratch("ssh-first-push-log-elsewhere"); | ||
| fs::create_dir_all(host.repos.join("ada")).unwrap(); | ||
| std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "taken")).unwrap(); | ||
| let dir = work("ssh-first-push-log-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/taken.git", "main"]); | ||
| assert!(!out.status.success()); | ||
| // The client gets the generic answer, without server details. | ||
| assert!(stderr(&out).contains("gitv: repository unavailable"), "{}", stderr(&out)); | ||
| assert!(!stderr(&out).contains("already exists"), "{}", stderr(&out)); | ||
| // The operator gets the cause. | ||
| let log = host.logged(); | ||
| assert!(log.contains("first push to ada/taken.git couldn't create it: repository already exists"), "{log}"); | ||
| } | ||
| #[test] | ||
| fn ssh_create_keeps_server_details_for_the_operator() { | ||
| let host = Host::new("ssh-create-private"); | ||
| // A file where the owner's directory should be: creation fails on the server's side. | ||
| fs::write(host.repos.join("ada"), "not a directory").unwrap(); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(!out.status.success()); | ||
| let said = stderr(&out); | ||
| assert!(said.contains("couldn't create the repository; the server's operator can see why"), "{said}"); | ||
| assert!(!said.contains(host.repos.to_str().unwrap()), "a server path reached the client: {said}"); | ||
| let log = host.logged(); | ||
| assert!(log.contains("ssh create of ada/notes.git failed:") && log.contains("is not a directory"), "{log}"); | ||
| // An administrator running the same thing sees the details directly. | ||
| let out = host.admin(&["create", "ada", "notes"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("is not a directory"), "{}", stderr(&out)); | ||
| // "Already exists" is safe to tell anyone. | ||
| fs::remove_file(host.repos.join("ada")).unwrap(); | ||
| assert!(host.ssh("ada", "create notes").status.success()); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(stderr(&out).contains("gitv: repository already exists"), "{}", stderr(&out)); | ||
| } | ||
| /// The owner sshd would run `gitv serve` for when `key` connects: the forced command of the | ||
| /// first active line holding that key, as sshd reads authorized_keys. `None` means sshd | ||
| /// refuses the key. | ||
| fn sshd_owner(keys: &std::path::Path, key: &str) -> Option<String> { | ||
| let blob = key.split_whitespace().nth(1).unwrap(); | ||
| let text = fs::read_to_string(keys).unwrap_or_default(); | ||
| let line = text | ||
| .lines() | ||
| .filter(|l| !l.trim_start().starts_with('#')) | ||
| .find(|l| l.split([' ', '\t']).any(|field| field == blob))?; | ||
| let command = line.split("serve ").nth(1)?; | ||
| Some(command.split('"').next()?.to_string()) | ||
| } | ||
| /// The fingerprint `ssh-keygen -l` prints for a key file. | ||
| fn ssh_keygen_fingerprint(file: &std::path::Path) -> String { | ||
| let out = std::process::Command::new("ssh-keygen").arg("-lf").arg(file).output().unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| stdout(&out).split_whitespace().nth(1).unwrap().to_string() | ||
| } | ||
| #[test] | ||
| fn keys_are_listed_and_revoked_one_at_a_time() { | ||
| let host = Host::new("admin-keys-revoke"); | ||
| let add = |owner: &str, seed: u8, label: &str| { | ||
| let file = host.dir.join(format!("{owner}-{seed}.pub")); | ||
| fs::write(&file, ed25519_key(seed)).unwrap(); | ||
| let out = host.admin(&["add-key", owner, file.to_str().unwrap(), "--label", label]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| file | ||
| }; | ||
| let laptop = add("ada", 21, "ada's laptop"); | ||
| add("ada", 22, "desktop"); | ||
| add("bob", 23, "bob's phone"); | ||
| let out = host.admin(&["create", "ada", "tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let listed = stdout(&host.admin(&["keys"])); | ||
| let rows: Vec<&str> = listed.lines().collect(); | ||
| assert_eq!(rows.len(), 3, "{listed}"); | ||
| let laptop_print = ssh_keygen_fingerprint(&laptop); | ||
| assert!(rows[0].starts_with("ada ") && rows[0].contains(&laptop_print), "{listed}"); | ||
| assert!(rows[0].ends_with(" ada's laptop"), "the label is kept whole: {listed}"); | ||
| assert!(rows[2].starts_with("bob ") && rows[2].ends_with("bob's phone"), "{listed}"); | ||
| let only_ada = stdout(&host.admin(&["keys", "ada"])); | ||
| assert_eq!(only_ada.lines().count(), 2, "{only_ada}"); | ||
| assert!(!only_ada.contains("bob"), "{only_ada}"); | ||
| // A fingerprint that matches nothing changes nothing. | ||
| let before = fs::read(&host.keys).unwrap(); | ||
| let out = host.admin(&["remove-key", "SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("no key has the fingerprint"), "{}", stderr(&out)); | ||
| assert_eq!(fs::read(&host.keys).unwrap(), before); | ||
| // Revoking the laptop (prefix optional) leaves the desktop working. | ||
| let bare = laptop_print.strip_prefix("SHA256:").unwrap(); | ||
| let out = host.admin(&["remove-key", bare]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stdout(&out).contains("ada ada's laptop"), "{}", stdout(&out)); | ||
| assert_eq!(sshd_owner(&host.keys, &ed25519_key(21)), None, "the revoked key no longer gets in"); | ||
| let owner = sshd_owner(&host.keys, &ed25519_key(22)).expect("the other key still gets in"); | ||
| let out = host.ssh(&owner, "list"); | ||
| assert!(out.status.success() && stdout(&out).contains("ada/tools.git"), "{}", stderr(&out)); | ||
| assert_eq!(sshd_owner(&host.keys, &ed25519_key(23)).as_deref(), Some("bob")); | ||
| assert!(!stdout(&host.admin(&["keys"])).contains(&laptop_print)); | ||
| } | ||
| #[test] | ||
| fn removing_a_key_keeps_every_other_line_exactly() { | ||
| let host = Host::new("admin-keys-remove-exact"); | ||
| let blob = |seed| ed25519_key(seed).split_whitespace().nth(1).unwrap().to_string(); | ||
| // Hand-written: a comment, options with quoted spaces, tabs, a non-GITv key, and the key | ||
| // to remove last with no final newline. | ||
| let kept = format!( | ||
| "# retired: ssh-ed25519 {}\n\ | ||
| command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {} work\n\ | ||
| ssh-ed25519\t{}\tbackup box\n", | ||
| blob(31), | ||
| blob(32), | ||
| blob(33) | ||
| ); | ||
| fs::write(&host.keys, format!("{kept}restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {}", blob(31))) | ||
| .unwrap(); | ||
| let listed = stdout(&host.admin(&["keys"])); | ||
| assert_eq!(listed.lines().count(), 3, "the commented-out key isn't listed: {listed}"); | ||
| assert!(listed.contains("bob ") && listed.contains("- ") && listed.contains("backup box"), "{listed}"); | ||
| let file = host.dir.join("ada.pub"); | ||
| fs::write(&file, ed25519_key(31)).unwrap(); | ||
| let out = host.admin(&["remove-key", &ssh_keygen_fingerprint(&file)]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_to_string(&host.keys).unwrap(), kept, "only the active line went"); | ||
| } | ||
| #[test] | ||
| fn key_labels_stay_on_one_line() { | ||
| let host = Host::new("admin-keys-labels"); | ||
| let file = host.dir.join("ada.pub"); | ||
| fs::write(&file, ed25519_key(41)).unwrap(); | ||
| for label in ["", " ", "two\nlines", "\u{1b}[31mred", &"x".repeat(65)] { | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", label]); | ||
| assert!(!out.status.success(), "{label:?} was accepted"); | ||
| } | ||
| assert!(!host.keys.exists(), "no key was written"); | ||
| } | ||
| #[test] | ||
| fn descriptions_are_set_shown_and_removed() { | ||
| let host = Host::new("ssh-description"); | ||
| assert!(host.ssh("ada", "create tools").status.success()); | ||
| // `git init` writes a placeholder, which doesn't count as a description. | ||
| let out = host.ssh("ada", "description tools"); | ||
| assert!(out.status.success() && stdout(&out).is_empty(), "{}", stdout(&out)); | ||
| assert!(host.ssh("ada", "description tools A small toolbox").status.success()); | ||
| assert_eq!(stdout(&host.ssh("ada", "description tools")), "A small toolbox\n"); | ||
| assert_eq!(fs::read_to_string(host.repo("ada", "tools").join("description")).unwrap(), "A small toolbox\n"); | ||
| // Quoted, as one argument, from the admin command too. | ||
| let out = host.admin(&["description", "ada", "tools", " Tools for ada "]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n"); | ||
| for bad in ["description tools 'two\nlines'", &format!("description tools {}", "x".repeat(161))] { | ||
| let out = host.ssh("ada", bad); | ||
| assert!(!out.status.success(), "{bad} was accepted"); | ||
| assert!(stderr(&out).contains("one line of at most 160"), "{}", stderr(&out)); | ||
| } | ||
| assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n", "a refusal changes nothing"); | ||
| assert!(host.ssh("ada", "description tools ''").status.success()); | ||
| assert!(!host.repo("ada", "tools").join("description").exists()); | ||
| // Only the owner's own repositories. | ||
| assert!(!host.ssh("bob", "description tools Mine now").status.success()); | ||
| let leftovers: Vec<_> = fs::read_dir(host.repo("ada", "tools")) | ||
| .unwrap() | ||
| .map(|e| e.unwrap().file_name().into_string().unwrap()) | ||
| .filter(|n| n.starts_with(".description")) | ||
| .collect(); | ||
| assert!(leftovers.is_empty(), "{leftovers:?}"); | ||
| } | ||
| #[test] | ||
| fn the_default_branch_can_be_chosen_among_existing_branches() { | ||
| let host = Host::new("ssh-default-branch"); | ||
| let dir = work("ssh-default-branch-work", "main"); | ||
| git(&dir, &["branch", "release"]); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main", "release"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n"); | ||
| let out = host.ssh("ada", "default-branch tools release"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n"); | ||
| let head = common::git_cmd(&host.repo("ada", "tools")).args(["symbolic-ref", "HEAD"]).output().unwrap(); | ||
| assert_eq!(head.stdout, b"refs/heads/release\n"); | ||
| // Names that aren't existing branches, or aren't branch names at all, change nothing. | ||
| for bad in ["missing", "-x", "../main", "HEAD", "refs/heads/main", "main^"] { | ||
| let out = host.ssh("ada", &format!("default-branch tools '{bad}'")); | ||
| assert!(!out.status.success(), "{bad} was accepted"); | ||
| assert!(stderr(&out).contains("no branch named"), "{bad}: {}", stderr(&out)); | ||
| } | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n"); | ||
| let out = host.admin(&["default-branch", "ada", "tools", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n"); | ||
| assert!(!host.ssh("bob", "default-branch tools release").status.success()); | ||
| } | ||
| #[test] | ||
| fn adding_a_key_again_with_a_label_renames_it() { | ||
| let host = Host::new("admin-keys-relabel"); | ||
| let file = host.dir.join("ada.pub"); | ||
| fs::write(&file, ed25519_key(51)).unwrap(); | ||
| let blob = ed25519_key(52).split_whitespace().nth(1).unwrap().to_string(); | ||
| // Another key, written by hand: options with quoted spaces, an old comment, no final newline. | ||
| let handwritten = | ||
| format!("command=\"/usr/local/bin/gitv serve ada\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {blob}"); | ||
| fs::write(&host.keys, format!("# keep me\n{handwritten} old laptop")).unwrap(); | ||
| assert!(host.admin(&["add-key", "ada", file.to_str().unwrap()]).status.success()); | ||
| // Again without a label is still a mistake. | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); | ||
| assert!(!out.status.success() && stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| // With one, the key is renamed in place. | ||
| let before = fs::read_to_string(&host.keys).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", "omarchy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stdout(&out).starts_with("relabelled SHA256:") && stdout(&out).trim_end().ends_with(" omarchy")); | ||
| let after = fs::read_to_string(&host.keys).unwrap(); | ||
| assert_eq!(after.lines().count(), before.lines().count(), "no line was added"); | ||
| assert_eq!(after.lines().nth(2).unwrap(), format!("{} omarchy", before.lines().nth(2).unwrap())); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", "work laptop"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!( | ||
| fs::read_to_string(&host.keys) | ||
| .unwrap() | ||
| .lines() | ||
| .nth(2) | ||
| .unwrap() | ||
| .ends_with(&format!("{} work laptop", ed25519_key(51).split_whitespace().nth(1).unwrap())) | ||
| ); | ||
| // A hand-written line keeps its options; only the comment changes, and the ending stays. | ||
| let other = host.dir.join("other.pub"); | ||
| fs::write(&other, ed25519_key(52)).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", other.to_str().unwrap(), "--label", "desk"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let text = fs::read_to_string(&host.keys).unwrap(); | ||
| assert!(text.starts_with(&format!("# keep me\n{handwritten} desk\n")), "{text}"); | ||
| assert!(stdout(&host.admin(&["keys", "ada"])).contains(" desk\n")); | ||
| // A key never moves to another owner, and a refusal changes nothing. | ||
| let before = fs::read(&host.keys).unwrap(); | ||
| let out = host.admin(&["add-key", "bob", file.to_str().unwrap(), "--label", "mine"]); | ||
| assert!(!out.status.success() && stderr(&out).contains("another owner"), "{}", stderr(&out)); | ||
| assert_eq!(fs::read(&host.keys).unwrap(), before); | ||
| } | ||
| #[test] | ||
| fn a_protected_repository_refuses_rewrites_and_deletions() { | ||
| let host = Host::new("ssh-protect"); | ||
| let dir = work("ssh-protect-work", "main"); | ||
| git(&dir, &["branch", "feature"]); | ||
| let push = |args: &[&str]| host.git(&dir, &[&["push", "ada@x:ada/tools.git"][..], args].concat()); | ||
| assert!(push(&["main", "feature"]).status.success()); | ||
| assert_eq!(stdout(&host.ssh("ada", "protect tools")), "off\n"); | ||
| let out = host.ssh("ada", "protect tools on"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&host.ssh("ada", "protect tools")), "on\n"); | ||
| let repo = host.repo("ada", "tools"); | ||
| let tip = |branch: &str| git(&repo, &["rev-parse", branch]); | ||
| // Moving forwards, and new branches and tags, still work. | ||
| fs::write(dir.join("hello.txt"), "more\n").unwrap(); | ||
| git(&dir, &["commit", "-qam", "Second"]); | ||
| git(&dir, &["tag", "v1"]); | ||
| let out = push(&["main", "v1", "main:refs/heads/new"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let second = tip("main"); | ||
| // A rewrite of any branch, and any deletion, is refused and changes nothing. | ||
| git(&dir, &["commit", "-q", "--amend", "-m", "Rewritten"]); | ||
| let out = push(&["--force", "main"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("non-fast-forward"), "{}", stderr(&out)); | ||
| assert_eq!(tip("main"), second); | ||
| // Every branch, not just the default: `new` is at Second, and First would rewind it. | ||
| let out = push(&["--force", "HEAD~1:new"]); | ||
| assert!(!out.status.success(), "other branches are protected too"); | ||
| assert_eq!(tip("new"), second); | ||
| let out = push(&[":feature"]); | ||
| assert!(!out.status.success(), "a branch was deleted"); | ||
| assert!(stderr(&out).contains("deletion prohibited"), "{}", stderr(&out)); | ||
| assert!(git(&repo, &["show-ref"]).contains("refs/heads/feature")); | ||
| // Git applies both settings to branches only. A deleted tag is still in the push log, so | ||
| // it can be put back. | ||
| assert!(push(&[":refs/tags/v1"]).status.success(), "git now protects tags too: update the docs"); | ||
| let log = fs::read_to_string(repo.join("gitv-push.log")).unwrap(); | ||
| assert!(log.lines().last().unwrap().ends_with(&format!(" {second} - refs/tags/v1")), "{log}"); | ||
| // Kept by gitv, not in the repository's own config, where a later tool might drop it. | ||
| assert!(!fs::read_to_string(repo.join("config")).unwrap().contains("receive.")); | ||
| // Recovery still records every change that did happen, and only those. | ||
| assert_eq!(log.lines().count(), 6, "{log}"); | ||
| // Only the owner's key, and only on or off. | ||
| assert!(!host.ssh("bob", "protect tools off").status.success()); | ||
| assert!(!host.ssh("ada", "protect tools maybe").status.success()); | ||
| assert_eq!(stdout(&host.ssh("ada", "protect tools")), "on\n"); | ||
| // Turned off, as root here, a rewrite goes through. | ||
| assert!(host.admin(&["protect", "ada", "tools", "off"]).status.success()); | ||
| let out = push(&["--force", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_ne!(tip("main"), second); | ||
| } | ||
| #[test] | ||
| fn hooks_in_a_repository_never_run() { | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let host = Host::new("ssh-no-hooks"); | ||
| let dir = work("ssh-no-hooks-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]).status.success()); | ||
| // A hook planted in the repository, as one copied in with a restored folder could be. | ||
| let ran = host.dir.join("hook-ran"); | ||
| let hooks = host.repo("ada", "tools").join("hooks"); | ||
| fs::create_dir_all(&hooks).unwrap(); | ||
| for hook in ["pre-receive", "post-receive", "update"] { | ||
| let path = hooks.join(hook); | ||
| fs::write(&path, format!("#!/bin/sh\ntouch '{}'\n", ran.display())).unwrap(); | ||
| fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| } | ||
| fs::write(dir.join("hello.txt"), "again\n").unwrap(); | ||
| git(&dir, &["commit", "-qam", "Second"]); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(!ran.exists(), "a hook ran"); | ||
| } | ||
deploy/CaddyfileAdded
+24−0
| @@ -0,0 +1,24 @@ | ||
| git.um9i.dev { | ||
| # Browsers that have visited once refuse plain HTTP for a year, so the Secure session | ||
| # cookie can't be stripped by a downgrade. | ||
| header Strict-Transport-Security "max-age=31536000; includeSubDomains" | ||
| # One JSON line per request. Caddy leaves Cookie, Set-Cookie and Authorization values | ||
| # out of these logs, so session tokens never reach the disk. | ||
| log { | ||
| output file /var/log/caddy/gitv-access.log { | ||
| roll_size 50MiB | ||
| roll_keep 10 | ||
| roll_keep_for 720h | ||
| } | ||
| format json | ||
| } | ||
| # Pages, diffs and source compress well. Caddy's default list of types leaves git packs, | ||
| # fonts and images alone, since they are compressed already. The one secret in any page | ||
| # (the Account page's form token) shares the page with nothing a visitor can echo into it, | ||
| # so compression can't be used to guess it (BREACH). | ||
| encode zstd gzip | ||
| reverse_proxy 127.0.0.1:8080 | ||
| } | ||
deploy/gitv-backupAdded
+180−0
| @@ -0,0 +1,180 @@ | ||
| #!/bin/bash | ||
| # Snapshot everything GITv needs to come back after losing the server: the repositories (with | ||
| # their trash, reflogs, push logs and visibility markers), the SSH keys file, the web sign-in, | ||
| # and the server's SSH host keys (so a rebuilt server is the one clients already trust). | ||
| # | ||
| # Each run writes <backup dir>/gitv/snapshots/<UTC time>/, a plain copy that restores with | ||
| # rsync or cp. Files unchanged since the previous snapshot are hard links to it, so a snapshot | ||
| # costs only what changed. Each repository is copied under its exclusive lock (pushes hold it | ||
| # shared), then checked with git fsck; only a snapshot that passes becomes `latest`. | ||
| # | ||
| # Settings (environment; the systemd unit sets the backup directory): | ||
| # GITV_BACKUP_DIR where the volume is mounted (/mnt/gitv-backup) | ||
| # GITV_BACKUP_KEEP_DAYS delete snapshots older than this (30) | ||
| # GITV_BACKUP_REQUIRE_MOUNT refuse unless the dir is a mount (1) | ||
| # GITV_BACKUP_LOCK_WAIT seconds to wait for a push (900) | ||
| # GITV_BACKUP_SSH_DIR where the SSH host keys are (/etc/ssh) | ||
| # GITV_REPOS, GITV_KEYS, GITV_WEB_AUTH as for gitv and gitv-web. | ||
| set -euo pipefail | ||
| umask 077 | ||
| dest=${GITV_BACKUP_DIR:-/mnt/gitv-backup} | ||
| keep_days=${GITV_BACKUP_KEEP_DAYS:-30} | ||
| lock_wait=${GITV_BACKUP_LOCK_WAIT:-900} | ||
| repos=${GITV_REPOS:-/srv/gitv/repos} | ||
| keys_dir=$(dirname "${GITV_KEYS:-/etc/gitv/authorized_keys}") | ||
| web_dir=$(dirname "${GITV_WEB_AUTH:-/var/lib/gitv-web/login}") | ||
| ssh_dir=${GITV_BACKUP_SSH_DIR:-/etc/ssh} | ||
| say() { echo "gitv-backup: $*" >&2; } | ||
| die() { say "$*"; exit 1; } | ||
| # An unmounted volume would silently fill the server's own disk instead. | ||
| if [[ ${GITV_BACKUP_REQUIRE_MOUNT:-1} == 1 ]] && ! mountpoint -q "$dest"; then | ||
| die "$dest is not a mounted volume; mount the backup volume there first" | ||
| fi | ||
| [[ -d $repos && ! -L $repos ]] || die "$repos is not a directory" | ||
| base=$dest/gitv | ||
| snapshots=$base/snapshots | ||
| mkdir -p "$snapshots" | ||
| chmod 700 "$base" | ||
| # One backup at a time. | ||
| exec 9>"$base/.lock" | ||
| flock -n 9 || die "another backup is running" | ||
| # Leftovers from a run that crashed part way. | ||
| find "$snapshots" -mindepth 1 -maxdepth 1 -name '*.partial' -exec rm -rf {} + | ||
| stamp=$(date -u +%Y-%m-%dT%H%M%SZ) | ||
| [[ -e $snapshots/$stamp ]] && die "snapshot $stamp already exists" | ||
| snap=$snapshots/$stamp.partial | ||
| previous=$(readlink -f "$base/latest" 2>/dev/null || true) | ||
| [[ -d $previous ]] || previous= | ||
| # copy FROM TO PART [rsync options...]: copy FROM to TO, hard-linking files unchanged since | ||
| # the previous snapshot's PART. | ||
| copy() { | ||
| local from=$1 to=$2 part=$3 | ||
| shift 3 | ||
| local link=() | ||
| if [[ -n $previous && -d $previous/$part ]]; then link=(--link-dest="$previous/$part"); fi | ||
| rsync -a --delete "${link[@]}" "$@" "$from" "$to" | ||
| } | ||
| # Everything but the repositories themselves: owner folders, the trash, anything unexpected. | ||
| mkdir -p "$snap/repos" | ||
| copy "$repos/" "$snap/repos/" repos --exclude='/*/*.git/' || die "copying $repos failed" | ||
| # Each repository under its lock, so no push is caught half way. The lock is taken on a | ||
| # descriptor for the directory itself: `flock PATH` would create an empty file at PATH if the | ||
| # repository were deleted after the listing, leaving a file that blocks the name for good. | ||
| # | ||
| # A repository a push holds for longer than lock_wait keeps the previous snapshot's copy (or | ||
| # none, if it has never been backed up), so one long push can't cost every other repository | ||
| # its backup. The snapshot still becomes `latest`, but the run fails so the operator hears. | ||
| count=0 | ||
| stale=() | ||
| missing=() | ||
| while IFS= read -r -d '' repo; do | ||
| rel=${repo#"$repos"/} | ||
| if ! { exec {fd}<"$repo"; } 2>/dev/null; then | ||
| say "$rel was deleted during the backup; skipped" | ||
| continue | ||
| fi | ||
| mkdir -p "$snap/repos/$rel" | ||
| link=() | ||
| if [[ -n $previous && -d $previous/repos/$rel ]]; then link=(--link-dest="$previous/repos/$rel"); fi | ||
| locked=0 | ||
| flock -E 75 -x -w "$lock_wait" "$fd" || locked=$? | ||
| if ((locked == 75)); then | ||
| exec {fd}<&- | ||
| if [[ -n ${link[*]} ]]; then | ||
| rsync -a "$previous/repos/$rel/" "$snap/repos/$rel/" "${link[@]}" || die "reusing the previous copy of $rel failed" | ||
| say "a push held $rel for over ${lock_wait}s; kept its copy from $(basename "$previous")" | ||
| stale+=("$rel") | ||
| count=$((count + 1)) | ||
| else | ||
| rm -rf "${snap:?}/repos/$rel" | ||
| say "a push held $rel for over ${lock_wait}s, and no earlier snapshot has it; not backed up" | ||
| missing+=("$rel") | ||
| fi | ||
| continue | ||
| fi | ||
| ((locked == 0)) || die "couldn't lock $rel" | ||
| copied=0 | ||
| rsync -a --delete "${link[@]}" "$repo/" "$snap/repos/$rel/" || copied=$? | ||
| exec {fd}<&- | ||
| if ((copied)); then | ||
| if [[ ! -e $repo ]]; then | ||
| say "$rel was deleted during the backup; skipped" | ||
| rm -rf "${snap:?}/repos/$rel" | ||
| continue | ||
| fi | ||
| die "copying $rel failed" | ||
| fi | ||
| count=$((count + 1)) | ||
| done < <(find "$repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0 | sort -z) | ||
| # The SSH keys and the web sign-in (whose authenticator secret makes this backup sensitive). | ||
| for pair in "$keys_dir:etc-gitv" "$web_dir:gitv-web"; do | ||
| from=${pair%:*} to=${pair##*:} | ||
| if [[ -d $from ]]; then | ||
| copy "$from/" "$snap/$to/" "$to" || die "copying $from failed" | ||
| else | ||
| say "warning: $from doesn't exist; not backed up" | ||
| fi | ||
| done | ||
| # The host keys only (ssh_host_*), not the rest of sshd's configuration. A rebuilt server | ||
| # without them greets every client with "REMOTE HOST IDENTIFICATION HAS CHANGED". | ||
| if compgen -G "$ssh_dir/ssh_host_*" >/dev/null; then | ||
| copy "$ssh_dir/" "$snap/ssh-host-keys/" ssh-host-keys --include='ssh_host_*' --exclude='*' || | ||
| die "copying the SSH host keys from $ssh_dir failed" | ||
| else | ||
| say "warning: no SSH host keys in $ssh_dir; not backed up" | ||
| fi | ||
| # Prove the copies are whole: every ref and reflog entry must reach complete history. | ||
| failed=0 | ||
| while IFS= read -r -d '' copy_dir; do | ||
| if ! env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \ | ||
| git -c safe.directory='*' --git-dir="$copy_dir" fsck --no-progress --connectivity-only >/dev/null 2>"$base/fsck.err"; then | ||
| say "fsck failed for ${copy_dir#"$snap"/repos/}: $(head -c 2000 "$base/fsck.err")" | ||
| failed=$((failed + 1)) | ||
| fi | ||
| done < <(find "$snap/repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0) | ||
| rm -f "$base/fsck.err" | ||
| { | ||
| echo "snapshot: $stamp" | ||
| echo "host: $(hostname)" | ||
| echo "repositories: $count" | ||
| # Only when there is something to say, so anything scanning for these lines finds problems. | ||
| ((${#stale[@]} == 0)) || echo "stale (a push held them; copied from the previous snapshot): ${stale[*]}" | ||
| ((${#missing[@]} == 0)) || echo "missing (a push held them; never backed up): ${missing[*]}" | ||
| echo "previous: ${previous:+$(basename "$previous")}" | ||
| echo "$(git --version)" | ||
| } >"$snap/MANIFEST" | ||
| if ((failed)); then | ||
| mv "$snap" "$snapshots/$stamp.failed" | ||
| die "$failed repositories failed verification; kept as $stamp.failed, latest is unchanged" | ||
| fi | ||
| mv "$snap" "$snapshots/$stamp" | ||
| # Made beside `latest` and renamed over it, so a crash never leaves no `latest` at all. | ||
| ln -sfn "snapshots/$stamp" "$base/.latest.new" | ||
| mv -T "$base/.latest.new" "$base/latest" | ||
| say "snapshot $stamp: $count repositories" | ||
| # Retention: snapshots older than keep_days, never the newest. | ||
| find "$snapshots" -mindepth 1 -maxdepth 1 -type d -mtime +"$keep_days" ! -name "$stamp" -print0 | | ||
| while IFS= read -r -d '' old; do | ||
| rm -rf "$old" && say "removed old snapshot $(basename "$old")" | ||
| done | ||
| # Everything else is backed up; now fail, so a held repository shows in `systemctl --failed`. | ||
| if ((${#stale[@]} + ${#missing[@]})); then | ||
| die "incomplete: stale ${stale[*]:-none}; missing ${missing[*]:-none} (pushes held them for over ${lock_wait}s)" | ||
| fi | ||
+34−0
| @@ -0,0 +1,34 @@ | ||
| [Unit] | ||
| Description=Snapshot GITv repositories, keys and web sign-in to the backup volume | ||
| RequiresMountsFor=/mnt/gitv-backup | ||
| [Service] | ||
| Type=oneshot | ||
| Environment=GITV_BACKUP_DIR=/mnt/gitv-backup | ||
| ExecStart=/usr/local/sbin/gitv-backup | ||
| Nice=10 | ||
| IOSchedulingClass=idle | ||
| NoNewPrivileges=yes | ||
| ProtectSystem=strict | ||
| ReadWritePaths=/mnt/gitv-backup | ||
| ProtectHome=yes | ||
| PrivateTmp=yes | ||
| PrivateDevices=yes | ||
| PrivateNetwork=yes | ||
| ProtectKernelTunables=yes | ||
| ProtectKernelModules=yes | ||
| ProtectControlGroups=yes | ||
| RestrictSUIDSGID=yes | ||
| ProtectProc=invisible | ||
| ProtectClock=yes | ||
| ProtectKernelLogs=yes | ||
| ProtectHostname=yes | ||
| LockPersonality=yes | ||
| MemoryDenyWriteExecute=yes | ||
| RestrictNamespaces=yes | ||
| RestrictRealtime=yes | ||
| SystemCallArchitectures=native | ||
| SystemCallFilter=@system-service | ||
| SystemCallErrorNumber=EPERM | ||
| # Read every repository and private folder, and keep owners and modes in the copies. | ||
| CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH CAP_CHOWN CAP_FOWNER | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| [Unit] | ||
| Description=Daily GITv backup | ||
| [Timer] | ||
| OnCalendar=*-*-* 02:30 | ||
| RandomizedDelaySec=30m | ||
| Persistent=true | ||
| [Install] | ||
| WantedBy=timers.target | ||
+29−0
| @@ -0,0 +1,29 @@ | ||
| [Unit] | ||
| Description=Remove GITv repositories deleted more than 30 days ago | ||
| [Service] | ||
| Type=oneshot | ||
| ExecStart=/usr/local/bin/gitv purge | ||
| NoNewPrivileges=yes | ||
| ProtectSystem=strict | ||
| ReadWritePaths=/srv/gitv/repos | ||
| ProtectHome=yes | ||
| PrivateTmp=yes | ||
| PrivateDevices=yes | ||
| PrivateNetwork=yes | ||
| ProtectKernelTunables=yes | ||
| ProtectKernelModules=yes | ||
| ProtectControlGroups=yes | ||
| RestrictSUIDSGID=yes | ||
| ProtectProc=invisible | ||
| ProtectClock=yes | ||
| ProtectKernelLogs=yes | ||
| ProtectHostname=yes | ||
| LockPersonality=yes | ||
| MemoryDenyWriteExecute=yes | ||
| RestrictNamespaces=yes | ||
| RestrictRealtime=yes | ||
| SystemCallArchitectures=native | ||
| SystemCallFilter=@system-service | ||
| SystemCallErrorNumber=EPERM | ||
| CapabilityBoundingSet=CAP_DAC_OVERRIDE | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| [Unit] | ||
| Description=Daily purge of GITv's repository trash | ||
| [Timer] | ||
| OnCalendar=daily | ||
| RandomizedDelaySec=1h | ||
| Persistent=true | ||
| [Install] | ||
| WantedBy=timers.target | ||
deploy/gitv-restoreAdded
+134−0
| @@ -0,0 +1,134 @@ | ||
| #!/bin/bash | ||
| # Restore a gitv-backup snapshot into an empty directory and verify it there. It never writes | ||
| # into the live tree: move what you need into place afterwards (see the README's recovery steps). | ||
| # | ||
| # gitv-restore list the snapshots, newest last | ||
| # gitv-restore find OWNER/NAME the snapshots holding that repository, newest last | ||
| # gitv-restore <snapshot|latest> DIR copy it to DIR (which must be empty or absent) and check it | ||
| # gitv-restore <snapshot|latest> DIR OWNER/NAME | ||
| # copy just that repository to DIR/NAME.git and check it; | ||
| # put it back with: gitv import OWNER NAME DIR/NAME.git | ||
| # gitv-restore check restore latest to a scratch folder on the volume, check | ||
| # it, and remove it: a drill proving backups restore | ||
| # | ||
| # GITV_BACKUP_DIR as for gitv-backup. | ||
| set -euo pipefail | ||
| umask 077 | ||
| base=${GITV_BACKUP_DIR:-/mnt/gitv-backup}/gitv | ||
| say() { echo "gitv-restore: $*" >&2; } | ||
| die() { say "$*"; exit 1; } | ||
| snapshot_dir() { | ||
| local name=$1 | ||
| [[ $name == latest ]] && name=$(basename "$(readlink -f "$base/latest" 2>/dev/null || true)") | ||
| [[ $name =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{6}Z$ ]] || die "no such snapshot: $1 (see: gitv-restore list)" | ||
| [[ -d $base/snapshots/$name ]] || die "no such snapshot: $name" | ||
| echo "$base/snapshots/$name" | ||
| } | ||
| # Never copy anything but a snapshot: an empty or wrong source must not become `rsync /`. | ||
| check_snapshot() { | ||
| [[ -n $1 && -d $1/repos && -f $1/MANIFEST ]] || die "not a snapshot: '$1'" | ||
| } | ||
| # A restore goes only into a folder that is empty or absent, so it never mixes with anything. | ||
| check_target() { | ||
| if [[ -e $1 ]] && [[ -n $(ls -A "$1") ]]; then die "$1 isn't empty"; fi | ||
| } | ||
| # Whether git can read the whole repository, with no user or system configuration. | ||
| verify() { | ||
| env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \ | ||
| git -c safe.directory='*' --git-dir="$1" fsck --no-progress --full >/dev/null | ||
| } | ||
| # OWNER/NAME, checked against gitv's name rule, into $owner and $name. | ||
| parse_repo() { | ||
| local part='[a-z0-9][a-z0-9_-]{0,62}' | ||
| [[ $1 =~ ^($part)/($part)$ ]] || die "name the repository as OWNER/NAME: $1" | ||
| owner=${BASH_REMATCH[1]} name=${BASH_REMATCH[2]} | ||
| } | ||
| # The repository in a snapshot, if it holds one: real directories only, never links. | ||
| snapshot_repo() { | ||
| local dir=$1/repos/$owner | ||
| [[ -d $dir && ! -L $dir && -d $dir/$name.git && ! -L $dir/$name.git ]] && echo "$dir/$name.git" | ||
| } | ||
| # Copy a snapshot to an empty target with owners and modes kept, then fsck every repository. | ||
| restore() { | ||
| local from=$1 to=$2 | ||
| check_snapshot "$from" | ||
| check_target "$to" | ||
| mkdir -p "$to" | ||
| rsync -a "$from/" "$to/" | ||
| local count=0 failed=0 repo | ||
| while IFS= read -r -d '' repo; do | ||
| count=$((count + 1)) | ||
| if ! verify "$repo"; then | ||
| say "fsck failed for ${repo#"$to"/repos/}" | ||
| failed=$((failed + 1)) | ||
| fi | ||
| done < <(find "$to/repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0) | ||
| ((failed == 0)) || die "$failed of $count repositories failed fsck" | ||
| say "restored $(basename "$from") to $to: $count repositories verified" | ||
| } | ||
| # Copy one repository out of a snapshot to TARGET/NAME.git, owners and modes kept, and fsck it. | ||
| restore_one() { | ||
| local from=$1 to=$2 source | ||
| check_snapshot "$from" | ||
| source=$(snapshot_repo "$from") || die "$(basename "$from") doesn't hold $owner/$name (see: gitv-restore find $owner/$name)" | ||
| check_target "$to" | ||
| mkdir -p "$to" | ||
| rsync -a "$source" "$to/" | ||
| verify "$to/$name.git" || die "fsck failed for the restored $owner/$name" | ||
| say "restored $owner/$name from $(basename "$from") to $to/$name.git and verified it" | ||
| say "put it back with: gitv import $owner $name $to/$name.git (or another name)" | ||
| } | ||
| if (($# == 0)); then | ||
| sed -n '2,13p' "$0" | ||
| exit 0 | ||
| fi | ||
| case $1 in | ||
| list) | ||
| ls -1 "$base/snapshots" | ||
| ;; | ||
| check) | ||
| # A failed lookup must stop here: `die` inside $(...) only ends the subshell. | ||
| from=$(snapshot_dir latest) || exit 1 | ||
| scratch=$base/restore-check | ||
| rm -rf "$scratch" | ||
| trap 'rm -rf "$scratch"' EXIT | ||
| restore "$from" "$scratch" | ||
| ;; | ||
| find) | ||
| [[ $# == 2 ]] || die "usage: gitv-restore find OWNER/NAME" | ||
| parse_repo "$2" | ||
| found=0 | ||
| for snapshot in "$base"/snapshots/*/; do | ||
| snapshot=${snapshot%/} | ||
| if snapshot_repo "$snapshot" >/dev/null; then | ||
| basename "$snapshot" | ||
| found=1 | ||
| fi | ||
| done | ||
| ((found)) || die "no snapshot holds $owner/$name" | ||
| ;; | ||
| -h | --help) | ||
| sed -n '2,13p' "$0" | ||
| ;; | ||
| *) | ||
| [[ $# == 2 || $# == 3 ]] || die "usage: gitv-restore <snapshot|latest> DIR [OWNER/NAME]" | ||
| from=$(snapshot_dir "$1") || exit 1 | ||
| if [[ $# == 3 ]]; then | ||
| parse_repo "$3" | ||
| restore_one "$from" "$2" | ||
| else | ||
| restore "$from" "$2" | ||
| fi | ||
| ;; | ||
| esac | ||
+33−0
| @@ -0,0 +1,33 @@ | ||
| [Unit] | ||
| Description=Prove the latest GITv backup restores: copy it out and fsck every repository | ||
| RequiresMountsFor=/mnt/gitv-backup | ||
| [Service] | ||
| Type=oneshot | ||
| Environment=GITV_BACKUP_DIR=/mnt/gitv-backup | ||
| ExecStart=/usr/local/sbin/gitv-restore check | ||
| Nice=10 | ||
| IOSchedulingClass=idle | ||
| NoNewPrivileges=yes | ||
| ProtectSystem=strict | ||
| ReadWritePaths=/mnt/gitv-backup | ||
| ProtectHome=yes | ||
| PrivateTmp=yes | ||
| PrivateDevices=yes | ||
| PrivateNetwork=yes | ||
| ProtectKernelTunables=yes | ||
| ProtectKernelModules=yes | ||
| ProtectControlGroups=yes | ||
| RestrictSUIDSGID=yes | ||
| ProtectProc=invisible | ||
| ProtectClock=yes | ||
| ProtectKernelLogs=yes | ||
| ProtectHostname=yes | ||
| LockPersonality=yes | ||
| MemoryDenyWriteExecute=yes | ||
| RestrictNamespaces=yes | ||
| RestrictRealtime=yes | ||
| SystemCallArchitectures=native | ||
| SystemCallFilter=@system-service | ||
| SystemCallErrorNumber=EPERM | ||
| CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH CAP_CHOWN CAP_FOWNER | ||
+9−0
| @@ -0,0 +1,9 @@ | ||
| [Unit] | ||
| Description=Weekly GITv restore drill | ||
| [Timer] | ||
| OnCalendar=Sun *-*-* 04:00 | ||
| Persistent=true | ||
| [Install] | ||
| WantedBy=timers.target | ||
+47−0
| @@ -0,0 +1,47 @@ | ||
| [Unit] | ||
| Description=GITv repository browser | ||
| After=network.target | ||
| [Service] | ||
| User=gitv-web | ||
| Group=gitv-web | ||
| SupplementaryGroups=git | ||
| ExecStart=/usr/local/bin/gitv-web serve --port 8080 | ||
| Restart=on-failure | ||
| StateDirectory=gitv-web | ||
| StateDirectoryMode=0700 | ||
| UMask=0077 | ||
| NoNewPrivileges=yes | ||
| ProtectSystem=strict | ||
| ProtectHome=yes | ||
| PrivateTmp=yes | ||
| PrivateDevices=yes | ||
| ProtectKernelTunables=yes | ||
| ProtectKernelModules=yes | ||
| ProtectControlGroups=yes | ||
| RestrictSUIDSGID=yes | ||
| CapabilityBoundingSet= | ||
| RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 | ||
| ProtectProc=invisible | ||
| ProtectClock=yes | ||
| ProtectKernelLogs=yes | ||
| ProtectHostname=yes | ||
| LockPersonality=yes | ||
| MemoryDenyWriteExecute=yes | ||
| RestrictNamespaces=yes | ||
| RestrictRealtime=yes | ||
| SystemCallArchitectures=native | ||
| SystemCallFilter=@system-service | ||
| SystemCallErrorNumber=EPERM | ||
| # No chown, setuid or the like: the browser and the git it runs only read. | ||
| SystemCallFilter=~@privileged | ||
| # Renders, transfers and the git commands they run share these. Sized for the 1 GB droplet, | ||
| # leaving room for sshd, Caddy and pushes: past MemoryMax the kernel ends a runaway clone | ||
| # (git pack-objects works inside this limit) rather than the whole machine thrashing. Raise | ||
| # both on a bigger droplet. | ||
| MemoryHigh=512M | ||
| MemoryMax=640M | ||
| TasksMax=512 | ||
| [Install] | ||
| WantedBy=multi-user.target | ||
deploy/gitv.confAdded
+8−0
| @@ -0,0 +1,8 @@ | ||
| # GITv settings, installed at /etc/gitv/gitv.conf (readable by the git and gitv-web accounts). | ||
| # Both gitv (over SSH) and gitv-web read it at startup; see crates/gitv-core/src/config.rs. | ||
| # The name people reach this server by, in clone addresses and help. | ||
| host = git.um9i.dev | ||
| # Where gitv is installed: what `gitv add-key` writes into each key's forced command. | ||
| command = /usr/local/bin/gitv | ||
+10−0
| @@ -0,0 +1,10 @@ | ||
| # Per-key forced commands are installed here by gitv add-key. | ||
| Match User git | ||
| AuthenticationMethods publickey | ||
| AuthorizedKeysFile /etc/gitv/authorized_keys | ||
| PasswordAuthentication no | ||
| KbdInteractiveAuthentication no | ||
| PermitTTY no | ||
| DisableForwarding yes | ||
| PermitUserRC no | ||
| Match all | ||
licenses/about.hbsAdded
+12−0
| @@ -0,0 +1,12 @@ | ||
| {{#each licenses}} | ||
| ================================================================================ | ||
| {{{name}}} ({{{id}}}) | ||
| Used by: | ||
| {{#each used_by}} | ||
| - {{{crate.name}}} {{{crate.version}}}{{#if crate.repository}} <{{{crate.repository}}}>{{/if}} | ||
| {{/each}} | ||
| {{{text}}} | ||
| {{/each}} | ||
licenses/about.tomlAdded
+40−0
| @@ -0,0 +1,40 @@ | ||
| # cargo-about configuration for THIRD-PARTY-LICENSES (see scripts/third-party-licenses). | ||
| # Licences GITv's dependencies may use. Where a crate offers a choice, the first listed here | ||
| # that it offers is the one recorded. | ||
| accepted = [ | ||
| "MIT", | ||
| "Apache-2.0", | ||
| "Apache-2.0 WITH LLVM-exception", | ||
| "BSD-2-Clause", | ||
| "BSD-3-Clause", | ||
| "ISC", | ||
| "Zlib", | ||
| "Unicode-3.0", | ||
| "BSL-1.0", | ||
| "0BSD", | ||
| "Unlicense", | ||
| ] | ||
| # Only what is compiled into the released Linux binaries. | ||
| targets = ["x86_64-unknown-linux-gnu"] | ||
| ignore-build-dependencies = true | ||
| ignore-dev-dependencies = true | ||
| # GITv's own crates are covered by LICENSE. | ||
| private = { ignore = true } | ||
| # onig_sys says only "MIT", but it builds the Oniguruma C library (BSD-2-Clause) into | ||
| # gitv-web, whose notice must travel with the binary too. | ||
| [onig_sys.clarify] | ||
| license = "MIT AND BSD-2-Clause" | ||
| [[onig_sys.clarify.files]] | ||
| path = "LICENSE.md" | ||
| license = "MIT" | ||
| checksum = "71f321038b088358004bee991635ac09e4c703bec467d3c30c06992c0595f189" | ||
| [[onig_sys.clarify.files]] | ||
| path = "oniguruma/COPYING" | ||
| license = "BSD-2-Clause" | ||
| checksum = "70ba5469ea0bab6e18a32d7009068f996503168d27be57747e08da34337ff26f" | ||
+1−1
| @@ -9,4 +9,4 @@ | ||
| set -eu | ||
| root=$(cd "$(dirname "$0")/.." && pwd) | ||
| owner=${1%%@*} | ||
| SSH_ORIGINAL_COMMAND=$2 GITV_REPOS=${GITV_REPOS:-$root/dev/repos} exec "$root/target/debug/gitv" serve "$owner" | ||
| SSH_ORIGINAL_COMMAND=$2 GITV_REPOS=${GITV_REPOS:-$root/dev/repos} exec "${CARGO_TARGET_DIR:-$root/target}/debug/gitv" serve "$owner" | ||
+49−0
| @@ -0,0 +1,49 @@ | ||
| #!/bin/sh | ||
| # Regenerate THIRD-PARTY-LICENSES: the licences and notices of everything built into GITv's | ||
| # binaries that isn't GITv's own code. Run it whenever dependencies change; CI checks that the | ||
| # committed file is current. Needs cargo-about (cargo install cargo-about --locked --features cli). | ||
| # | ||
| # scripts/third-party-licenses # rewrite THIRD-PARTY-LICENSES | ||
| # scripts/third-party-licenses FILE # write FILE instead | ||
| set -eu | ||
| root=$(cd "$(dirname "$0")/.." && pwd) | ||
| cd "$root" | ||
| out=${1:-THIRD-PARTY-LICENSES} | ||
| tmp="$out.tmp.$$" | ||
| trap 'rm -f "$tmp"' EXIT | ||
| { | ||
| cat <<'HEADER' | ||
| Third-party software in GITv | ||
| ============================ | ||
| GITv itself is licensed under the GNU Affero General Public License, version 3 or later (see | ||
| LICENSE). The gitv and gitv-web binaries also contain the software below, each under its own | ||
| licence, reproduced here as those licences require. Generated by scripts/third-party-licenses. | ||
| HEADER | ||
| cargo about generate --locked --fail -c licenses/about.toml licenses/about.hbs | ||
| cat <<'FONTS' | ||
| ================================================================================ | ||
| Red Hat Display, Red Hat Text and Red Hat Mono fonts (OFL-1.1) | ||
| Built into gitv-web, from crates/gitv-web/assets/fonts. | ||
| FONTS | ||
| cat crates/gitv-web/assets/fonts/OFL.txt | ||
| cat <<'SYNTAXES' | ||
| ================================================================================ | ||
| Syntax definitions from Sublime Text's Packages | ||
| Built into gitv-web through syntect's default syntax set, from | ||
| https://github.com/sublimehq/Packages. Unless a file there says otherwise: | ||
| Permission to copy, use, modify, sell and distribute this | ||
| software is granted. This software is provided "as is" without | ||
| express or implied warranty, and with no claim as to its | ||
| suitability for any purpose. | ||
| SYNTAXES | ||
| } > "$tmp" | ||
| mv "$tmp" "$out" | ||
| trap - EXIT | ||
src/bin/gitv-web/main.rsDeleted
+0−1543
| @@ -1,1543 +0,0 @@ | ||
| //! 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; | ||
| use std::collections::HashMap; | ||
| use std::ffi::{OsStr, OsString}; | ||
| use std::fmt::Write as _; | ||
| 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::routing::{get, post}; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv::render; | ||
| use gitv::{ | ||
| HOST, RepoDir, entries, git, git_capped, open_dir_at, open_owner, open_root, percent_decode, repo_dir, repo_in, | ||
| repos_root, try_entries, try_kind_at, | ||
| }; | ||
| 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 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 | ||
| /// still pick up every change. | ||
| static STYLE_URL: LazyLock<String> = LazyLock::new(|| { | ||
| use std::hash::{Hash, Hasher}; | ||
| let mut hasher = std::hash::DefaultHasher::new(); | ||
| STYLESHEET.hash(&mut hasher); | ||
| format!("/style.css?v={:012x}", hasher.finish() & 0xffff_ffff_ffff) | ||
| }); | ||
| const PAGE: usize = 50; | ||
| /// Largest file the Raw view serves; bigger files are for `git clone`. | ||
| const RAW_LIMIT: usize = 50 << 20; | ||
| /// Largest file shown on a page; bigger files offer Raw instead. | ||
| const SHOW_LIMIT: usize = 1 << 20; | ||
| /// Largest patch shown on a commit page; only this much is ever read. | ||
| const DIFF_LIMIT: usize = 2 << 20; | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Cache | ||
| /// Rendered HTML and git answers keyed by immutable object ids, so repeat views skip the | ||
| /// expensive work. Keys for anything that contains links include the repository, since the | ||
| /// same content in two repositories links differently. Emptied whenever it outgrows its budget. | ||
| #[derive(Default)] | ||
| struct Cache { | ||
| entries: HashMap<String, Arc<str>>, | ||
| bytes: usize, | ||
| } | ||
| static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default); | ||
| const CACHE_BUDGET: usize = 32 << 20; | ||
| /// The cached value for `key`, or `make`'s. A failure (`None`) is never cached, so a git | ||
| /// command that timed out is retried next time instead of leaving a blank forever. | ||
| fn cached(key: String, make: impl FnOnce() -> Option<String>) -> Option<Arc<str>> { | ||
| if let Some(hit) = CACHE.lock().ok().and_then(|c| c.entries.get(&key).cloned()) { | ||
| return Some(hit); | ||
| } | ||
| let value: Arc<str> = make()?.into(); | ||
| // Something this big would evict much of everything else to fit; serve it uncached. | ||
| if key.len() + value.len() > CACHE_BUDGET / 4 { | ||
| return Some(value); | ||
| } | ||
| if let Ok(mut cache) = CACHE.lock() { | ||
| let key_len = key.len(); | ||
| if cache.bytes + key_len + value.len() > CACHE_BUDGET { | ||
| cache.entries.clear(); | ||
| cache.bytes = 0; | ||
| } | ||
| // Two requests can render the same key at once; count only the entry that stays. | ||
| if let Some(old) = cache.entries.insert(key, Arc::clone(&value)) { | ||
| cache.bytes -= key_len + old.len(); | ||
| } | ||
| cache.bytes += key_len + value.len(); | ||
| } | ||
| Some(value) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Responses | ||
| #[derive(Parser)] | ||
| #[command(about = "Read-only web browser for GITv repositories")] | ||
| struct Cli { | ||
| #[command(subcommand)] | ||
| action: Action, | ||
| } | ||
| #[derive(Subcommand)] | ||
| enum Action { | ||
| /// Serve the browser on localhost | ||
| Serve { | ||
| #[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 { | ||
| Html(String), | ||
| /// Bytes, content type, and a download name for files the browser shouldn't display. | ||
| Raw(Vec<u8>, &'static str, Option<Vec<u8>>), | ||
| Redirect(String), | ||
| Missing, | ||
| } | ||
| const SECURITY: [(header::HeaderName, &str); 4] = [ | ||
| ( | ||
| header::CONTENT_SECURITY_POLICY, | ||
| "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"), | ||
| (header::CACHE_CONTROL, "no-store"), | ||
| ]; | ||
| impl IntoResponse for View { | ||
| fn into_response(self) -> Response { | ||
| let html = [(header::CONTENT_TYPE, "text/html; charset=utf-8")]; | ||
| match self { | ||
| View::Html(body) => (SECURITY, html, body).into_response(), | ||
| View::Raw(data, kind, download) => { | ||
| let mut response = (SECURITY, [(header::CONTENT_TYPE, kind)], data).into_response(); | ||
| if let Some(value) = | ||
| download.and_then(|name| format!("attachment; filename*=UTF-8''{}", encode(&name)).parse().ok()) | ||
| { | ||
| response.headers_mut().insert(header::CONTENT_DISPOSITION, value); | ||
| } | ||
| response | ||
| } | ||
| View::Redirect(to) => Redirect::to(&to).into_response(), | ||
| View::Missing => (StatusCode::NOT_FOUND, SECURITY, html, view_missing()).into_response(), | ||
| } | ||
| } | ||
| } | ||
| fn static_file(kind: &'static str, data: &'static [u8]) -> Response { | ||
| ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "max-age=86400")], data).into_response() | ||
| } | ||
| fn stylesheet() -> Response { | ||
| let headers = | ||
| [(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=31536000, immutable")]; | ||
| (headers, STYLESHEET).into_response() | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Query strings and paths | ||
| // | ||
| // File paths are bytes, not text: git allows any bytes but `/` and NUL in a name, so a path | ||
| // is decoded from the URL, checked and handed to git without ever passing through UTF-8. | ||
| /// Query parameters with their values percent-decoded to raw bytes. The first of a repeated | ||
| /// key wins. | ||
| type Q = HashMap<String, Vec<u8>>; | ||
| fn parse_query(raw: Option<&str>) -> Q { | ||
| let mut query = Q::new(); | ||
| for pair in raw.unwrap_or("").split('&').filter(|p| !p.is_empty()) { | ||
| let (key, value) = pair.split_once('=').unwrap_or((pair, "")); | ||
| // In a query string `+` is a space; an encoded plus (`%2B`) stays a plus. | ||
| let (key, value) = (key.replace('+', " "), value.replace('+', " ")); | ||
| if let Ok(key) = String::from_utf8(percent_decode(&key)) { | ||
| query.entry(key).or_insert_with(|| percent_decode(&value)); | ||
| } | ||
| } | ||
| query | ||
| } | ||
| /// A text parameter; one that isn't valid UTF-8 counts as absent. | ||
| fn param(q: &Q, key: &str) -> Option<String> { | ||
| q.get(key).and_then(|v| String::from_utf8(v.clone()).ok()) | ||
| } | ||
| fn encode(value: &[u8]) -> String { | ||
| let mut out = String::with_capacity(value.len()); | ||
| for &b in value { | ||
| match b { | ||
| b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char), | ||
| _ => { | ||
| let _ = write!(out, "%{b:02X}"); | ||
| } | ||
| } | ||
| } | ||
| out | ||
| } | ||
| /// A repository-relative path with no `.`, `..`, empty or absolute parts and no NUL. | ||
| fn clean_path(value: &[u8]) -> Option<Vec<u8>> { | ||
| let parts: Vec<&[u8]> = value.split(|b| *b == b'/').filter(|p| !p.is_empty()).collect(); | ||
| if parts.iter().any(|p| *p == b"." || *p == b".." || p.contains(&0)) { | ||
| return None; | ||
| } | ||
| Some(parts.join(&b'/')) | ||
| } | ||
| fn parent_of(path: &[u8]) -> &[u8] { | ||
| path.iter().rposition(|b| *b == b'/').map_or(&[], |i| &path[..i]) | ||
| } | ||
| fn file_name(path: &[u8]) -> &[u8] { | ||
| path.iter().rposition(|b| *b == b'/').map_or(path, |i| &path[i + 1..]) | ||
| } | ||
| fn join(dir: &[u8], name: &[u8]) -> Vec<u8> { | ||
| if dir.is_empty() { name.to_vec() } else { [dir, b"/", name].concat() } | ||
| } | ||
| /// Bytes for display. Names that aren't UTF-8 show replacement characters, but links keep | ||
| /// the real bytes. | ||
| fn lossy(bytes: &[u8]) -> Cow<'_, str> { | ||
| String::from_utf8_lossy(bytes) | ||
| } | ||
| /// `<commit>:<path>` for git, path bytes intact. | ||
| fn spec(commit: &str, path: &[u8]) -> OsString { | ||
| let mut spec = format!("{commit}:").into_bytes(); | ||
| spec.extend_from_slice(path); | ||
| OsString::from_vec(spec) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Formatting | ||
| fn icon(name: &str) -> String { | ||
| let path = match name { | ||
| "dir" => r#"<path d="M2 4.5c0-.6.4-1 1-1h3.2l1.4 1.5H13c.6 0 1 .4 1 1v6.5c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1z"/>"#, | ||
| "file" => r#"<path d="M4 1.8h5.3L12.5 5v9.2H4z"/><path d="M9 1.8v3.5h3.5"/>"#, | ||
| "branch" => { | ||
| r#"<circle cx="4.5" cy="3.5" r="1.6"/><circle cx="4.5" cy="12.5" r="1.6"/><circle cx="11.5" cy="5" r="1.6"/><path d="M4.5 5.1v5.8M11.5 6.6c0 2.6-2.2 3.3-7 4.3"/>"# | ||
| } | ||
| "tag" => r#"<path d="M2 2.5h5.3l6.2 6.2-4.8 4.8-6.7-6.7z"/><circle cx="5" cy="5.5" r="1"/>"#, | ||
| "book" => { | ||
| r#"<path d="M2.5 3h4c.8 0 1.5.7 1.5 1.5V13c0-.6-.5-1-1-1h-4.5zM13.5 3h-4c-.8 0-1.5.7-1.5 1.5V13c0-.6.5-1 1-1h4.5z"/>"# | ||
| } | ||
| "code" => r#"<path d="M5.5 4.5 2 8l3.5 3.5M10.5 4.5 14 8l-3.5 3.5"/>"#, | ||
| "commits" => r#"<circle cx="8" cy="8" r="2.4"/><path d="M1.5 8h4.1M10.4 8h4.1"/>"#, | ||
| "chevron" => r#"<path d="M4.5 6.5 8 10l3.5-3.5"/>"#, | ||
| "up" => r#"<path d="M8 13V3.5M4 7.5l4-4 4 4"/>"#, | ||
| "module" => r#"<rect x="2.5" y="2.5" width="11" height="11" rx="2"/><path d="M5.5 8h5M8 5.5v5"/>"#, | ||
| _ => "", | ||
| }; | ||
| format!(r#"<svg class="ic" viewBox="0 0 16 16" aria-hidden="true">{path}</svg>"#) | ||
| } | ||
| /// "3 hours ago" for recent times, the calendar date (as git printed it) after a month. | ||
| fn ago(stamp: &str, date: &str) -> String { | ||
| let Ok(then) = stamp.parse::<u64>() else { return date.to_string() }; | ||
| let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); | ||
| let span = now.saturating_sub(then); | ||
| let unit = |n: u64, word: &str| format!("{n} {word}{} ago", if n == 1 { "" } else { "s" }); | ||
| match span { | ||
| 0..60 => "just now".into(), | ||
| 60..3600 => unit(span / 60, "minute"), | ||
| 3600..86400 => unit(span / 3600, "hour"), | ||
| 86400..2_592_000 => unit(span / 86400, "day"), | ||
| _ => date.to_string(), | ||
| } | ||
| } | ||
| /// A commit subject for display; an empty one would leave an invisible link. | ||
| fn subject_or_placeholder(subject: &str) -> &str { | ||
| if subject.trim().is_empty() { "(no message)" } else { subject } | ||
| } | ||
| fn plural(count: usize, one: &str, many: &str) -> String { | ||
| format!("{count} {}", if count == 1 { one } else { many }) | ||
| } | ||
| fn size(bytes: usize) -> String { | ||
| match bytes { | ||
| 0..1024 => plural(bytes, "byte", "bytes"), | ||
| 1024..1_048_576 => format!("{:.1} KB", bytes as f64 / 1024.0), | ||
| _ => format!("{:.1} MB", bytes as f64 / 1_048_576.0), | ||
| } | ||
| } | ||
| /// A page for someone signed in: the top bar links to their account. | ||
| fn page(title: &str, body: &str) -> String { | ||
| layout(title, body, true) | ||
| } | ||
| /// A page, with the account link in the top bar only when `signed_in`. | ||
| fn layout(title: &str, body: &str, signed_in: bool) -> String { | ||
| templates::Layout { title, body, signed_in }.to_string() | ||
| } | ||
| fn view_missing() -> String { | ||
| page( | ||
| "Not found", | ||
| r#"<section class="notfound"><h1 class="title">Nothing here</h1> | ||
| <p class="count">That repository, branch, file or commit doesn’t exist, or the link is malformed.</p> | ||
| <a class="button" href="/">Back to repositories</a></section>"#, | ||
| ) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Repository access | ||
| struct Repo { | ||
| owner: String, | ||
| name: String, | ||
| dir: RepoDir, | ||
| heads: OnceCell<Vec<String>>, | ||
| tags: OnceCell<Vec<String>>, | ||
| } | ||
| /// The newest commit on a ref: full hash, subject, author, unix time, short date. | ||
| struct Head { | ||
| oid: String, | ||
| subject: String, | ||
| author: String, | ||
| stamp: String, | ||
| date: String, | ||
| } | ||
| impl Head { | ||
| /// Parse `%H %an %ct %cs %s`, separated by 0x1f. The subject goes last and the split stops | ||
| /// at five fields, so a subject that itself contains the separator byte stays whole. | ||
| fn parse(out: &str) -> Option<Head> { | ||
| let f: Vec<&str> = out.trim_end_matches('\n').splitn(5, '\x1f').collect(); | ||
| let [oid, author, stamp, date, subject] = <[&str; 5]>::try_from(f).ok()?; | ||
| Some(Head { | ||
| oid: oid.into(), | ||
| subject: subject.into(), | ||
| author: author.into(), | ||
| stamp: stamp.into(), | ||
| date: date.into(), | ||
| }) | ||
| } | ||
| } | ||
| impl Repo { | ||
| /// A repository opened through its owner and repository directories with symlinks refused; | ||
| /// every git command then runs inside that open directory. | ||
| fn open(owner: &str, name: &str) -> Option<Repo> { | ||
| Some(Repo::from_dir(owner, name, repo_dir(owner, name)?)) | ||
| } | ||
| fn from_dir(owner: &str, name: &str, dir: RepoDir) -> Repo { | ||
| Repo { dir, owner: owner.into(), name: name.into(), heads: OnceCell::new(), tags: OnceCell::new() } | ||
| } | ||
| fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> { | ||
| git(&self.dir, args).ok() | ||
| } | ||
| fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> { | ||
| self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned()) | ||
| } | ||
| fn url(&self, view: &str, query: &[(&str, &str)]) -> String { | ||
| let query: Vec<String> = | ||
| query.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k}={}", encode(v.as_bytes()))).collect(); | ||
| let base = format!("/{}/{}/{view}", self.owner, self.name); | ||
| if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) } | ||
| } | ||
| /// A tree, blob or raw link for a path, which may not be UTF-8. | ||
| fn url_at(&self, view: &str, reference: &str, path: &[u8], extra: &str) -> String { | ||
| let mut url = self.url(view, &[("ref", reference)]); | ||
| if !path.is_empty() { | ||
| url.push(if url.contains('?') { '&' } else { '?' }); | ||
| let _ = write!(url, "path={}", encode(path)); | ||
| } | ||
| if !extra.is_empty() { | ||
| url.push(if url.contains('?') { '&' } else { '?' }); | ||
| url.push_str(extra); | ||
| } | ||
| url | ||
| } | ||
| /// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch. | ||
| fn default_ref(&self) -> String { | ||
| let head = self.git(&["symbolic-ref", "HEAD"]); | ||
| // Strip only git's newline: a branch name can end in other (Unicode) whitespace. | ||
| let head = | ||
| head.as_deref().map(|h| h.strip_suffix('\n').unwrap_or(h)).and_then(|h| h.strip_prefix("refs/heads/")); | ||
| let heads = self.heads(); | ||
| let name = match head.filter(|h| heads.iter().any(|b| b == h)) { | ||
| Some(head) => head.to_string(), | ||
| None => match ["main", "master"].into_iter().map(String::from).find(|b| heads.contains(b)) { | ||
| Some(branch) => branch, | ||
| None => match heads.first() { | ||
| Some(first) => first.clone(), | ||
| None => return "HEAD".into(), | ||
| }, | ||
| }, | ||
| }; | ||
| // In the form links use, so a branch named like a commit id still opens itself. | ||
| self.branch_ref(&name) | ||
| } | ||
| /// Names under a namespace exactly as git stores them (not `refname:short`, which can | ||
| /// add `heads/` or `tags/` to tell apart a branch and tag of the same name). | ||
| fn list_refs(&self, namespace: &str) -> Vec<String> { | ||
| self.git(&["for-each-ref", "--format=%(refname:lstrip=2)", namespace]) | ||
| .map(|s| s.lines().map(str::to_string).collect()) | ||
| .unwrap_or_default() | ||
| } | ||
| fn heads(&self) -> &[String] { | ||
| self.heads.get_or_init(|| self.list_refs("refs/heads")) | ||
| } | ||
| fn tags(&self) -> &[String] { | ||
| self.tags.get_or_init(|| self.list_refs("refs/tags")) | ||
| } | ||
| /// The commit a reference names, in this order: | ||
| /// | ||
| /// - `refs/heads/NAME` or `refs/tags/NAME` for an existing branch or tag: the form links | ||
| /// use whenever a plain name could be misread (see [`Repo::branch_ref`]); | ||
| /// - a full commit id, always as an object, whatever refs are named; | ||
| /// - a branch, then a tag, by exact name, so any name git allows works and none is read as | ||
| /// revision syntax; | ||
| /// - `HEAD`, then an abbreviated commit id, again only as an object. | ||
| fn resolve(&self, reference: &str) -> Option<String> { | ||
| let is_head = |n: &str| self.heads().iter().any(|h| h == n); | ||
| let is_tag = |n: &str| self.tags().iter().any(|t| t == n); | ||
| let hex = reference.bytes().all(|b| b.is_ascii_hexdigit()); | ||
| let full = if let Some(name) = reference.strip_prefix("refs/heads/").filter(|n| is_head(n)) { | ||
| format!("refs/heads/{name}") | ||
| } else if let Some(name) = reference.strip_prefix("refs/tags/").filter(|n| is_tag(n)) { | ||
| format!("refs/tags/{name}") | ||
| } else if hex && matches!(reference.len(), 40 | 64) { | ||
| return self.commit_object(reference); | ||
| } else if is_head(reference) { | ||
| format!("refs/heads/{reference}") | ||
| } else if is_tag(reference) { | ||
| format!("refs/tags/{reference}") | ||
| } else if reference == "HEAD" { | ||
| "HEAD".to_string() | ||
| } else if hex && reference.len() >= 4 { | ||
| return self.commit_object(reference); | ||
| } else { | ||
| return None; | ||
| }; | ||
| let spec = format!("{full}^{{commit}}"); | ||
| self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into()) | ||
| } | ||
| /// The commit whose id is or starts with `id`, looked up among objects only: a branch or | ||
| /// tag that happens to be named like an id can't redirect it. Annotated tag objects peel to | ||
| /// their commit. An ambiguous abbreviation finds nothing. | ||
| fn commit_object(&self, id: &str) -> Option<String> { | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) { | ||
| return None; | ||
| } | ||
| let id = id.to_ascii_lowercase(); | ||
| let candidates = self.git(&["rev-parse", &format!("--disambiguate={id}")])?; | ||
| let found: Vec<String> = candidates | ||
| .lines() | ||
| .filter_map(|oid| { | ||
| // A full id: git reads 40 or 64 hex digits as an object before any ref. | ||
| let peeled = self.git(&["rev-parse", "--verify", "--quiet", &format!("{oid}^{{commit}}")])?; | ||
| Some(peeled.trim().to_string()) | ||
| }) | ||
| .collect(); | ||
| match found.as_slice() { | ||
| [one] => Some(one.clone()), | ||
| _ => None, | ||
| } | ||
| } | ||
| /// Whether a plain name in a link would resolve to itself: it mustn't look like a full | ||
| /// commit id or a qualified ref, which [`Repo::resolve`] reads first. | ||
| fn plain_is_safe(name: &str) -> bool { | ||
| let full_id = matches!(name.len(), 40 | 64) && name.bytes().all(|b| b.is_ascii_hexdigit()); | ||
| !full_id && !name.starts_with("refs/") && name != "HEAD" | ||
| } | ||
| /// How a link names a branch: plainly when that can't be misread, else `refs/heads/NAME`. | ||
| fn branch_ref(&self, name: &str) -> String { | ||
| if Self::plain_is_safe(name) { name.to_string() } else { format!("refs/heads/{name}") } | ||
| } | ||
| /// How a link names a tag: plainly when that can't be misread or taken by a same-named | ||
| /// branch, else `refs/tags/NAME`. | ||
| fn tag_ref(&self, name: &str) -> String { | ||
| if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) { | ||
| name.to_string() | ||
| } else { | ||
| format!("refs/tags/{name}") | ||
| } | ||
| } | ||
| /// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking | ||
| /// history for a path can be slow, so answers for a fixed commit are cached. | ||
| fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> { | ||
| Head::parse(&self.latest_raw(rev, path)?) | ||
| } | ||
| /// [`Repo::latest`] as git printed it, for callers that cache it themselves. | ||
| fn latest_raw(&self, rev: &str, path: &[u8]) -> Option<String> { | ||
| let lookup = || { | ||
| let mut args: Vec<&OsStr> = | ||
| ["log", "-1", "--format=%H%x1f%an%x1f%ct%x1f%cs%x1f%s", rev, "--"].map(OsStr::new).to_vec(); | ||
| if !path.is_empty() { | ||
| args.push(OsStr::from_bytes(path)); | ||
| } | ||
| self.git(&args).filter(|out| !out.trim().is_empty()) | ||
| }; | ||
| let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()); | ||
| if is_oid { | ||
| Some(cached(format!("latest:{}:{rev}:{}", self.dir.path.display(), encode(path)), lookup)?.to_string()) | ||
| } else { | ||
| lookup() | ||
| } | ||
| } | ||
| /// 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()); | ||
| cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string())) | ||
| .and_then(|count| count.parse().ok()) | ||
| .unwrap_or(0) | ||
| } | ||
| /// Tag names grouped by the commit they point at, for labelling history. | ||
| fn tags_by_commit(&self) -> HashMap<String, Vec<String>> { | ||
| let mut found: HashMap<String, Vec<String>> = HashMap::new(); | ||
| let out = self.git(&["for-each-ref", "--format=%(objectname) %(*objectname) %(refname:lstrip=2)", "refs/tags"]); | ||
| for line in out.unwrap_or_default().lines() { | ||
| // Tag names can't contain spaces, but an unpeeled tag leaves the middle field empty. | ||
| let mut fields = line.splitn(3, ' '); | ||
| if let (Some(direct), Some(peeled), Some(name)) = (fields.next(), fields.next(), fields.next()) { | ||
| let commit = if peeled.is_empty() { direct } else { peeled }; | ||
| found.entry(commit.to_string()).or_default().push(name.to_string()); | ||
| } | ||
| } | ||
| found | ||
| } | ||
| /// A cache key for rendered content of `oid` that links within this repository. | ||
| fn key(&self, kind: &str, oid: &str, extra: &str) -> String { | ||
| format!("{kind}:{}/{}:{oid}:{extra}", self.owner, self.name) | ||
| } | ||
| /// Render a Markdown file from directory `dir`, linking repository paths at `reference`. | ||
| fn markdown(&self, source: &str, dir: &[u8], reference: &str) -> String { | ||
| render::markdown(source, dir, &|path, image| { | ||
| if image { | ||
| self.url_at("raw", reference, path, "") | ||
| } else if path.is_empty() { | ||
| self.url("tree", &[("ref", reference)]) | ||
| } else { | ||
| self.url_at("blob", reference, path, "") | ||
| } | ||
| }) | ||
| } | ||
| /// Name, clone address and tabs, shared by every repository page. `commit` is `reference` | ||
| /// already resolved, when the caller has it. | ||
| fn masthead(&self, active: &str, reference: &str, commit: Option<&str>) -> String { | ||
| let commit = commit.map(str::to_string).or_else(|| self.resolve(reference)); | ||
| let commits = commit.map_or(0, |c| self.commit_count(&c)); | ||
| let tags = self.tags().len(); | ||
| let tab = |view: &str, glyph: &str, label: &str, count: Option<usize>| { | ||
| let current = if view == active { r#" aria-current="page""# } else { "" }; | ||
| let query: &[(&str, &str)] = if view == "tags" { &[] } else { &[("ref", reference)] }; | ||
| let badge = count.map_or(String::new(), |n| format!(r#"<span class="n">{n}</span>"#)); | ||
| format!(r#"<a href="{}"{current}>{}{label}{badge}</a>"#, attr(&self.url(view, query)), icon(glyph)) | ||
| }; | ||
| format!( | ||
| r#"<div class="repohead"><h1 class="reponame"><a class="own" href="/">{owner}</a><span class="sep">/</span><a href="{home}">{name}</a></h1> | ||
| <label class="clone"><span>SSH</span><input readonly aria-label="Clone address" value="git@{HOST}:{owner}/{name}.git"></label></div> | ||
| <nav class="tabs" aria-label="Repository">{}{}{}</nav>"#, | ||
| tab("tree", "code", "Code", None), | ||
| tab("log", "commits", "Commits", Some(commits)), | ||
| tab("tags", "tag", "Tags", Some(tags)), | ||
| owner = esc(&self.owner), | ||
| name = esc(&self.name), | ||
| home = attr(&self.url("tree", &[])), | ||
| ) | ||
| } | ||
| /// Branch and tag menu, then the path as breadcrumbs. | ||
| fn locator(&self, view: &str, reference: &str, path: &[u8]) -> String { | ||
| // `link` is what the URL carries; `name` is what people see. | ||
| let item = |link: String, name: &str| { | ||
| let current = if link == reference { r#" aria-current="true""# } else { "" }; | ||
| let href = self.url_at(view, &link, path, ""); | ||
| format!(r#"<a href="{}"{current}>{}</a>"#, attr(&href), esc(name)) | ||
| }; | ||
| let branches: String = self.heads().iter().map(|b| item(self.branch_ref(b), b)).collect(); | ||
| let tags: String = self.tags().iter().map(|t| item(self.tag_ref(t), t)).collect(); | ||
| let mut menu = format!("<h2>Branches</h2>{branches}"); | ||
| if !tags.is_empty() { | ||
| menu += &format!("<h2>Tags</h2>{tags}"); | ||
| } | ||
| let mut crumbs = String::new(); | ||
| if !path.is_empty() { | ||
| let _ = write!( | ||
| crumbs, | ||
| r#"<a href="{}">{}</a>"#, | ||
| attr(&self.url("tree", &[("ref", reference)])), | ||
| esc(&self.name) | ||
| ); | ||
| let parts: Vec<&[u8]> = path.split(|b| *b == b'/').collect(); | ||
| for (i, part) in parts.iter().enumerate() { | ||
| crumbs += r#"<span class="sep">/</span>"#; | ||
| if i + 1 == parts.len() { | ||
| let _ = write!(crumbs, "<b>{}</b>", esc(&lossy(part))); | ||
| } else { | ||
| let href = self.url_at("tree", reference, &parts[..=i].join(&b'/'), ""); | ||
| let _ = write!(crumbs, r#"<a href="{}">{}</a>"#, attr(&href), esc(&lossy(part))); | ||
| } | ||
| } | ||
| crumbs = format!(r#"<nav class="crumbs" aria-label="Path">{crumbs}</nav>"#); | ||
| } | ||
| format!( | ||
| r#"<div class="locator"><details class="refmenu"><summary>{}{}{}</summary><div class="menu">{menu}</div></details> | ||
| {crumbs}</div>"#, | ||
| icon("branch"), | ||
| esc(reference | ||
| .strip_prefix("refs/heads/") | ||
| .or_else(|| reference.strip_prefix("refs/tags/")) | ||
| .unwrap_or(reference)), | ||
| icon("chevron"), | ||
| ) | ||
| } | ||
| fn sha_link(&self, oid: &str) -> String { | ||
| format!( | ||
| r#"<a class="sha" href="{}">{}</a>"#, | ||
| attr(&self.url("commit", &[("id", oid)])), | ||
| &oid[..oid.len().min(7)] | ||
| ) | ||
| } | ||
| } | ||
| /// One entry of a tree listing: `blob`, `tree` or `commit` (a submodule), its object id, its | ||
| /// size when it's a blob, and its name as git stores it. | ||
| struct Entry { | ||
| kind: String, | ||
| oid: String, | ||
| size: usize, | ||
| name: Vec<u8>, | ||
| } | ||
| impl Entry { | ||
| /// Parse a `git ls-tree -l -z` record: `mode type oid size<TAB>name`, size `-` for non-blobs. | ||
| fn parse(record: &[u8]) -> Option<Entry> { | ||
| let tab = record.iter().position(|b| *b == b'\t')?; | ||
| let meta = std::str::from_utf8(&record[..tab]).ok()?; | ||
| let mut fields = meta.split_whitespace().skip(1); | ||
| let (kind, oid) = (fields.next()?.to_string(), fields.next()?.to_string()); | ||
| let size = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0); | ||
| Some(Entry { kind, oid, size, name: record[tab + 1..].to_vec() }) | ||
| } | ||
| fn list(out: &[u8]) -> Vec<Entry> { | ||
| out.split(|b| *b == 0).filter_map(Entry::parse).collect() | ||
| } | ||
| } | ||
| /// The entry at `path` in `commit`, with its type, object id and size, in one git call. | ||
| fn entry(repo: &Repo, commit: &str, path: &[u8]) -> Option<Entry> { | ||
| let args = [ | ||
| OsStr::new("ls-tree"), | ||
| OsStr::new("-l"), | ||
| OsStr::new("-z"), | ||
| OsStr::new(commit), | ||
| OsStr::new("--"), | ||
| OsStr::from_bytes(path), | ||
| ]; | ||
| let out = repo.git_bytes(&args)?; | ||
| Entry::list(&out).into_iter().find(|e| e.name == path) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Views | ||
| /// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8 | ||
| /// (no valid owner or repository name is). | ||
| fn sorted_names(dir: &impl AsFd) -> Vec<String> { | ||
| let mut names: Vec<String> = | ||
| entries(dir).into_iter().filter_map(|n| n.into_string().ok()).filter(|n| !n.starts_with('.')).collect(); | ||
| names.sort(); | ||
| names | ||
| } | ||
| /// A fingerprint of a repository's branches, for caching its row on the index. Git updates a | ||
| /// ref by renaming a file into place (a loose ref under `refs/heads`, or `packed-refs` and | ||
| /// `HEAD` in the repository directory, or a table under `reftable`), and a rename changes the | ||
| /// directory's modification time. So the times of those directories change whenever a branch | ||
| /// or HEAD does. It reads them through the repository's open handle, the same directory git | ||
| /// reads, never through a path. The current minute is included too, which bounds staleness | ||
| /// should two pushes land within the filesystem's timestamp granularity. | ||
| fn refs_fingerprint(repo: &RepoDir) -> Option<String> { | ||
| /// Append a directory's modification time. | ||
| fn note(stamp: &mut String, dir: &impl AsFd) -> Option<()> { | ||
| let meta = nix::sys::stat::fstat(dir.as_fd()).ok()?; | ||
| let _ = write!(stamp, ":{}.{}", meta.st_mtime, meta.st_mtime_nsec); | ||
| Some(()) | ||
| } | ||
| /// Note `dir` and every directory under it, depth first, holding open only the directories | ||
| /// on the current path, never all the siblings at once. Any directory that can't be read | ||
| /// makes the whole fingerprint `None`, so a partial one is never trusted. | ||
| fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> { | ||
| note(stamp, dir)?; | ||
| let mut names = try_entries(dir).ok()?; | ||
| names.sort(); | ||
| // Ref files (and entries deleted since the listing) are covered by their directory's | ||
| // time; only subdirectories need visiting. | ||
| for name in names { | ||
| // An entry that can't be inspected might be a folder; a fingerprint that skipped it | ||
| // could miss a change, so the whole fingerprint is abandoned instead. | ||
| if try_kind_at(dir, &name).ok()? == Some(SFlag::S_IFDIR) { | ||
| stamp.push('/'); | ||
| walk(stamp, &open_dir_at(dir, &name).ok()?)?; | ||
| } | ||
| } | ||
| Some(()) | ||
| } | ||
| /// A directory that may legitimately be absent: absent is a fact, unreadable is not. | ||
| fn optional(parent: &impl AsFd, name: &str) -> Option<Option<OwnedFd>> { | ||
| match open_dir_at(parent, OsStr::new(name)) { | ||
| Ok(dir) => Some(Some(dir)), | ||
| Err(nix::errno::Errno::ENOENT) => Some(None), | ||
| Err(_) => None, | ||
| } | ||
| } | ||
| let minute = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() / 60; | ||
| let mut stamp = format!("{minute}"); | ||
| note(&mut stamp, &repo.handle())?; | ||
| let refs = optional(&repo.handle(), "refs")?; | ||
| for dir in [refs.as_ref(), optional(&repo.handle(), "reftable")?.as_ref()] { | ||
| match dir { | ||
| Some(dir) => note(&mut stamp, dir)?, | ||
| None => stamp.push_str(":-"), | ||
| } | ||
| } | ||
| if let Some(refs) = refs.as_ref() | ||
| && let Some(heads) = optional(refs, "heads")? | ||
| { | ||
| walk(&mut stamp, &heads)?; | ||
| } | ||
| Some(stamp) | ||
| } | ||
| /// One row of the index: everything it shows, and no open repository handle, so a large | ||
| /// installation holds one handle at a time however many repositories it lists. | ||
| struct Row { | ||
| owner: String, | ||
| name: String, | ||
| head: Option<Head>, | ||
| } | ||
| fn view_index() -> View { | ||
| let mut rows = Vec::new(); | ||
| let root = open_root(); | ||
| for owner in root.as_ref().map(sorted_names).unwrap_or_default() { | ||
| // Read through the owner's open directory: a symlinked owner isn't followed or listed. | ||
| let Some(owner_dir) = open_owner(&owner) else { continue }; | ||
| for entry in sorted_names(&owner_dir) { | ||
| let Some(name) = entry.strip_suffix(".git") else { continue }; | ||
| let Some(dir) = repo_in(&owner_dir, &owner, name) else { continue }; | ||
| let repo = Repo::from_dir(&owner, name, dir); | ||
| // HEAD usually names a real branch; only look further when it doesn't. An empty | ||
| // repository caches as an empty answer. | ||
| let lookup = || { | ||
| Some( | ||
| repo.latest_raw("HEAD", b"") | ||
| .or_else(|| repo.latest_raw(&repo.default_ref(), b"")) | ||
| .unwrap_or_default(), | ||
| ) | ||
| }; | ||
| let raw = match refs_fingerprint(&repo.dir) { | ||
| Some(stamp) => cached(format!("index:{}:{stamp}", repo.dir.path.display()), lookup), | ||
| None => lookup().map(Arc::from), | ||
| }; | ||
| let head = raw.as_deref().and_then(Head::parse); | ||
| // `repo`, and with it the directory handle, is dropped here. | ||
| rows.push(Row { owner: owner.clone(), name: name.to_string(), head }); | ||
| } | ||
| } | ||
| rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0))); | ||
| let items: String = rows | ||
| .iter() | ||
| .map(|Row { owner, name, head }| { | ||
| let (last, when) = head.as_ref().map_or(("No commits yet".into(), String::new()), |h| { | ||
| (esc(subject_or_placeholder(&h.subject)).into_owned(), ago(&h.stamp, &h.date)) | ||
| }); | ||
| format!( | ||
| r#"<li><a class="repo-row" href="{}"><span class="rname"><span>{}/</span>{}</span><span class="rlast">{last}</span><span class="rwhen">{when}</span></a></li>"#, | ||
| attr(&format!("/{owner}/{name}/tree")), | ||
| esc(owner), | ||
| esc(name) | ||
| ) | ||
| }) | ||
| .collect(); | ||
| let listing = if items.is_empty() { | ||
| format!( | ||
| r#"<div class="panel empty"><h2>No repositories yet</h2><p>Push to a new name and GITv creates the repository.</p> | ||
| <code>git push git@{HOST}:um9i/my-project.git main</code></div>"# | ||
| ) | ||
| } else { | ||
| format!(r#"<div class="panel"><ul class="rows">{items}</ul></div>"#) | ||
| }; | ||
| let count = plural(rows.len(), "repository", "repositories"); | ||
| View::Html(page( | ||
| "Repositories", | ||
| &format!( | ||
| r#"<div class="pagehead"><h1 class="title">Repositories</h1><p class="count">{count}</p></div>{listing}"# | ||
| ), | ||
| )) | ||
| } | ||
| fn view_tree(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref()); | ||
| let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?; | ||
| let Some(commit) = repo.resolve(&reference) else { | ||
| if !repo.heads().is_empty() { | ||
| return None; | ||
| } | ||
| let body = repo.masthead("tree", &reference, None) | ||
| + &format!( | ||
| r#"<div class="panel empty"><h2>This repository is empty</h2><p>Push a branch to get started.</p> | ||
| <code>git push git@{HOST}:{}/{}.git main</code></div>"#, | ||
| esc(&repo.owner), | ||
| esc(&repo.name) | ||
| ); | ||
| return Some(View::Html(page(&format!("{}/{}", repo.owner, repo.name), &body))); | ||
| }; | ||
| let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)]; | ||
| let Some(listing) = repo.git_bytes(&listing) else { | ||
| // A file path: show it in the file view instead. | ||
| return entry(repo, &commit, &path) | ||
| .filter(|e| e.kind == "blob") | ||
| .map(|_| View::Redirect(repo.url_at("blob", &reference, &path, ""))); | ||
| }; | ||
| let mut entries = Entry::list(&listing); | ||
| // Folders first, then files and submodules, each alphabetically. | ||
| entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase())); | ||
| let mut body = repo.masthead("tree", &reference, Some(&commit)) + &repo.locator("tree", &reference, &path); | ||
| body += r#"<div class="panel">"#; | ||
| if let Some(head) = repo.latest(&commit, &path) { | ||
| let _ = write!( | ||
| body, | ||
| r#"<div class="panel-head"><div class="lead"><b class="who">{}</b><a class="subject" href="{}">{}</a></div><div class="side">{}<span>{}</span></div></div>"#, | ||
| esc(&head.author), | ||
| attr(&repo.url("commit", &[("id", &head.oid)])), | ||
| esc(subject_or_placeholder(&head.subject)), | ||
| repo.sha_link(&head.oid), | ||
| ago(&head.stamp, &head.date) | ||
| ); | ||
| } | ||
| body += r#"<ul class="rows">"#; | ||
| if !path.is_empty() { | ||
| let up = repo.url_at("tree", &reference, parent_of(&path), ""); | ||
| let _ = write!( | ||
| body, | ||
| r#"<li><a class="entry" href="{}">{}<span class="name">..</span></a></li>"#, | ||
| attr(&up), | ||
| icon("up") | ||
| ); | ||
| } | ||
| for item in &entries { | ||
| let path = join(&path, &item.name); | ||
| let (view, class, glyph) = match item.kind.as_str() { | ||
| "tree" => (Some("tree"), "entry dir", "dir"), | ||
| "commit" => (None, "entry sub", "module"), | ||
| _ => (Some("blob"), "entry", "file"), | ||
| }; | ||
| 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>"; | ||
| // README.md over README or README.txt, as people expect. | ||
| let readmes = entries.iter().filter(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with(b"readme")); | ||
| let readme = readmes.clone().find(|e| render::is_markdown(&lossy(&e.name))).or_else(|| readmes.clone().next()); | ||
| if let Some(readme) = readme.filter(|e| e.size <= SHOW_LIMIT) { | ||
| let name = lossy(&readme.name); | ||
| let rendered = | ||
| render_file(repo, &readme.oid, readme.size, &name, &path, &reference, !render::is_markdown(&name)); | ||
| let content = rendered | ||
| .as_deref() | ||
| .and_then(|r| r.split_once('\x1f')) | ||
| .map_or(r#"<p class="note">This README couldn't be read.</p>"#, |(_, html)| html); | ||
| let _ = write!( | ||
| body, | ||
| r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b></div></div>{content}</section>"#, | ||
| icon("book"), | ||
| esc(&name) | ||
| ); | ||
| } | ||
| let title = if path.is_empty() { | ||
| format!("{}/{}", repo.owner, repo.name) | ||
| } else { | ||
| format!("{} at {reference}", lossy(&path)) | ||
| }; | ||
| Some(View::Html(page(&title, &body))) | ||
| } | ||
| /// A file rendered for display, as `facts` 0x1f `html`: highlighted code, or Markdown with | ||
| /// links into this repository at `reference` (the file lives in `dir`). The file view and the | ||
| /// README panel both use this, so they share one cached value per rendering instead of | ||
| /// storing different shapes under one key. The facts and the rendering are cached together, | ||
| /// so a repeat view reads no blob at all. | ||
| fn render_file( | ||
| repo: &Repo, | ||
| oid: &str, | ||
| file_size: usize, | ||
| name: &str, | ||
| dir: &[u8], | ||
| reference: &str, | ||
| as_code: bool, | ||
| ) -> Option<Arc<str>> { | ||
| let key = if as_code { | ||
| // Highlighting depends only on the content and the file's type, so it's shared. | ||
| format!("code:{oid}:{name}") | ||
| } else { | ||
| // Links depend on the repository, folder and ref too. | ||
| repo.key("md", oid, &format!("{}:{reference}", encode(dir))) | ||
| }; | ||
| cached(key, || { | ||
| let data = repo.git_bytes(&["cat-file", "blob", oid])?; | ||
| if data.iter().take(8000).any(|b| *b == 0) { | ||
| let note = r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#; | ||
| return Some(format!("{}\x1f{note}", size(file_size))); | ||
| } | ||
| let text = String::from_utf8_lossy(&data); | ||
| let facts = format!("{}, {}", plural(text.lines().count(), "line", "lines"), size(file_size)); | ||
| let html = if as_code { | ||
| code_view(name, &text) | ||
| } else { | ||
| format!(r#"<article class="markdown">{}</article>"#, repo.markdown(&text, dir, reference)) | ||
| }; | ||
| Some(format!("{facts}\x1f{html}")) | ||
| }) | ||
| } | ||
| /// Highlighted source with a line-number gutter. | ||
| fn code_view(path: &str, text: &str) -> String { | ||
| let lines = text.lines().count().max(1); | ||
| let gutter: String = (1..=lines).map(|n| format!("{n}\n")).collect(); | ||
| format!( | ||
| r#"<div class="code-view"><pre class="gutter" aria-hidden="true">{gutter}</pre><pre class="code">{}</pre></div>"#, | ||
| render::highlight(path, text) | ||
| ) | ||
| } | ||
| fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> { | ||
| let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref()); | ||
| let path = clean_path(q.get("path")?)?; | ||
| let commit = repo.resolve(&reference)?; | ||
| let item = entry(repo, &commit, &path)?; | ||
| match item.kind.as_str() { | ||
| "blob" => {} | ||
| // Markdown links can't tell files from folders, so a file link to a folder lands here. | ||
| "tree" => return Some(View::Redirect(repo.url_at("tree", &reference, &path, ""))), | ||
| _ => return None, | ||
| } | ||
| let name = lossy(file_name(&path)).into_owned(); | ||
| if raw { | ||
| if item.size > RAW_LIMIT { | ||
| return Some(View::Html(page( | ||
| "File too large", | ||
| &format!( | ||
| r#"<section class="notfound"><h1 class="title">This file is too large to download here</h1> | ||
| <p class="count">{} is {}. Clone the repository to get it.</p><code>git clone git@{HOST}:{}/{}.git</code></section>"#, | ||
| esc(&name), | ||
| size(item.size), | ||
| esc(&repo.owner), | ||
| esc(&repo.name) | ||
| ), | ||
| ))); | ||
| } | ||
| let data = repo.git_bytes(&["cat-file", "blob", &item.oid])?; | ||
| let binary = data.iter().take(8000).any(|b| *b == 0); | ||
| let kind = match name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() { | ||
| Some("png") => "image/png", | ||
| Some("jpg" | "jpeg") => "image/jpeg", | ||
| Some("gif") => "image/gif", | ||
| Some("webp") => "image/webp", | ||
| // Safe to serve as an image: the page's policy blocks any script inside it. | ||
| Some("svg") => "image/svg+xml", | ||
| _ if binary => "application/octet-stream", | ||
| _ => "text/plain; charset=utf-8", | ||
| }; | ||
| let download = (kind == "application/octet-stream").then(|| file_name(&path).to_vec()); | ||
| return Some(View::Raw(data, kind, download)); | ||
| } | ||
| let too_big = item.size > SHOW_LIMIT; | ||
| let markdown = !too_big && render::is_markdown(&name); | ||
| let as_code = !markdown || param(q, "view").as_deref() == Some("code"); | ||
| let rendered: Arc<str> = if too_big { | ||
| format!( | ||
| "{}\x1f{}", | ||
| size(item.size), | ||
| r#"<p class="note">This file is too large to show here. Use Raw to open it.</p>"# | ||
| ) | ||
| .into() | ||
| } else { | ||
| render_file(repo, &item.oid, item.size, &name, parent_of(&path), &reference, as_code)? | ||
| }; | ||
| let (facts, content) = rendered.split_once('\x1f').unwrap_or(("", &rendered)); | ||
| let mut side = String::new(); | ||
| if markdown { | ||
| let link = |label: &str, view: &str, on: bool| { | ||
| let current = if on { r#" aria-current="true""# } else { "" }; | ||
| let extra = if view.is_empty() { String::new() } else { format!("view={view}") }; | ||
| format!(r#"<a href="{}"{current}>{label}</a>"#, attr(&repo.url_at("blob", &reference, &path, &extra))) | ||
| }; | ||
| let _ = write!( | ||
| side, | ||
| r#"<span class="segmented">{}{}</span>"#, | ||
| link("Preview", "", !as_code), | ||
| link("Code", "code", as_code) | ||
| ); | ||
| } | ||
| let _ = write!(side, r#"<a class="button" href="{}">Raw</a>"#, attr(&repo.url_at("raw", &reference, &path, ""))); | ||
| let body = repo.masthead("tree", &reference, Some(&commit)) | ||
| + &repo.locator("blob", &reference, &path) | ||
| + &format!( | ||
| r#"<section class="panel"><div class="panel-head"><div class="lead">{}<b>{}</b><span class="quiet">{facts}</span></div><div class="side">{side}</div></div>{content}</section>"#, | ||
| icon("file"), | ||
| esc(&name) | ||
| ); | ||
| Some(View::Html(page(&format!("{} at {reference}", lossy(&path)), &body))) | ||
| } | ||
| fn view_log(repo: &Repo, q: &Q) -> Option<View> { | ||
| let reference = param(q, "ref").unwrap_or_else(|| repo.default_ref()); | ||
| let number: usize = param(q, "page").and_then(|p| p.parse().ok()).unwrap_or(0); | ||
| let skip = number.checked_mul(PAGE)?; | ||
| let commit = repo.resolve(&reference)?; | ||
| let out = repo.git(&[ | ||
| "log", | ||
| &format!("-n{}", PAGE + 1), | ||
| &format!("--skip={skip}"), | ||
| "--format=%H%x1f%an%x1f%ct%x1f%cs%x1f%s", | ||
| &commit, | ||
| "--", | ||
| ])?; | ||
| let lines: Vec<&str> = out.lines().collect(); | ||
| let tags = repo.tags_by_commit(); | ||
| 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(|name| templates::TagLink { name, url: repo.url("tree", &[("ref", &repo.tag_ref(name))]) }) | ||
| .collect(); | ||
| 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 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. | ||
| struct Change { | ||
| status: &'static str, | ||
| path: Vec<u8>, | ||
| } | ||
| /// Parse `git show -z --name-status`: a status (`M`, `A`, `D`, `R100`, ...) then one path, or | ||
| /// two (old and new) for renames and copies. | ||
| fn parse_changes(out: &[u8]) -> Vec<Change> { | ||
| let mut fields = out.split(|b| *b == 0).filter(|f| !f.is_empty()); | ||
| let mut changes = Vec::new(); | ||
| while let Some(code) = fields.next() { | ||
| let (status, paths) = match code.first() { | ||
| Some(b'A') => ("Added", 1), | ||
| Some(b'D') => ("Deleted", 1), | ||
| Some(b'R') => ("Renamed", 2), | ||
| Some(b'C') => ("Copied", 2), | ||
| _ => ("", 1), | ||
| }; | ||
| let mut path = None; | ||
| for _ in 0..paths { | ||
| path = fields.next(); | ||
| } | ||
| let Some(path) = path else { break }; | ||
| changes.push(Change { status, path: path.to_vec() }); | ||
| } | ||
| changes | ||
| } | ||
| /// The lines of one file's diff: (class, old number, new number, text). | ||
| struct FileDiff { | ||
| rows: Vec<(&'static str, String, String, String)>, | ||
| added: usize, | ||
| removed: usize, | ||
| binary: bool, | ||
| } | ||
| /// Split `git show` patch output into one entry per `diff --git` section, in order. Names come | ||
| /// from [`parse_changes`], not from these human-readable headers, which quote or misplace odd names. | ||
| fn parse_diff(text: &str) -> Vec<FileDiff> { | ||
| let mut files: Vec<FileDiff> = Vec::new(); | ||
| let (mut old, mut new) = (0usize, 0usize); | ||
| for line in text.lines() { | ||
| if line.starts_with("diff --git ") { | ||
| files.push(FileDiff { rows: Vec::new(), added: 0, removed: 0, binary: false }); | ||
| continue; | ||
| } | ||
| let Some(file) = files.last_mut() else { continue }; | ||
| let in_hunk = !file.rows.is_empty(); | ||
| if !in_hunk && line.starts_with("Binary files ") { | ||
| file.binary = true; | ||
| } else if line.starts_with("@@") { | ||
| let nums: Vec<usize> = line | ||
| .split_whitespace() | ||
| .skip(1) | ||
| .take(2) | ||
| .map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0)) | ||
| .collect(); | ||
| (old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0)); | ||
| file.rows.push(("hunk", String::new(), String::new(), line.to_string())); | ||
| } else if !in_hunk { | ||
| continue; | ||
| } else if let Some(t) = line.strip_prefix('+') { | ||
| file.rows.push(("add", String::new(), new.to_string(), t.to_string())); | ||
| new += 1; | ||
| file.added += 1; | ||
| } else if let Some(t) = line.strip_prefix('-') { | ||
| file.rows.push(("del", old.to_string(), String::new(), t.to_string())); | ||
| old += 1; | ||
| file.removed += 1; | ||
| } else if let Some(t) = line.strip_prefix(' ') { | ||
| file.rows.push(("ctx", old.to_string(), new.to_string(), t.to_string())); | ||
| old += 1; | ||
| new += 1; | ||
| } | ||
| } | ||
| files | ||
| } | ||
| fn view_commit(repo: &Repo, q: &Q) -> Option<View> { | ||
| let id = param(q, "id")?; | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { | ||
| return None; | ||
| } | ||
| // Looked up as an object only: a branch named like this id can't redirect the page. | ||
| let commit = repo.commit_object(&id)?; | ||
| // NUL between fields: a commit message can't contain one, so the subject and body can hold | ||
| // any other byte, the separator git output elsewhere uses included. | ||
| let meta = repo.git(&[ | ||
| "show", | ||
| "-s", | ||
| "--date=format:%-d %b %Y, %H:%M", | ||
| "--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b", | ||
| &commit, | ||
| ])?; | ||
| let f: Vec<&str> = meta.splitn(7, '\0').collect(); | ||
| let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; | ||
| let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::<Vec<_>>().join(" "); | ||
| let mut body = repo.masthead("log", &repo.default_ref(), None); | ||
| let message = message.trim(); | ||
| let _ = write!( | ||
| body, | ||
| r#"<section class="panel"><div class="cmsg"><div class="chead"><h2 class="ctitle">{}</h2><a class="button" href="{}">Browse files</a></div>{}</div><dl class="facts"> | ||
| <div><dt>Author</dt><dd>{} <span class="quiet">{}</span></dd></div><div><dt>Date</dt><dd>{}</dd></div> | ||
| <div><dt>Commit</dt><dd><span class="sha">{}</span></dd></div>{}</dl></section>"#, | ||
| esc(subject_or_placeholder(subject)), | ||
| attr(&repo.url("tree", &[("ref", oid)])), | ||
| if message.is_empty() { String::new() } else { format!(r#"<p class="cbody">{}</p>"#, esc(message)) }, | ||
| esc(author), | ||
| esc(email), | ||
| esc(date), | ||
| &oid[..12], | ||
| if parent_links.is_empty() { | ||
| String::new() | ||
| } else { | ||
| format!("<div><dt>Parent</dt><dd>{parent_links}</dd></div>") | ||
| } | ||
| ); | ||
| // A commit's diff never changes, so its rendering is cached. If git can't produce it, the | ||
| // page still shows the commit, with a note. | ||
| let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents)) | ||
| .unwrap_or_else(|| r#"<p class="note">This commit’s changes couldn’t be read.</p>"#.into()); | ||
| body += &diff; | ||
| Some(View::Html(page(subject_or_placeholder(subject), &body))) | ||
| } | ||
| /// A commit's changes as one panel per file. Only [`DIFF_LIMIT`] bytes of patch are read; past | ||
| /// that the files are listed without their lines. | ||
| fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option<String> { | ||
| // A merge shows what it brought in relative to its first parent. | ||
| let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"]; | ||
| let names = repo.git_bytes(&[&["show", "-z", "--name-status"][..], &options, &[oid]].concat())?; | ||
| let changes = parse_changes(&names); | ||
| let (patch, too_big) = | ||
| git_capped(&repo.dir, &[&["show", "--patch"][..], &options, &[oid]].concat(), DIFF_LIMIT).ok()?; | ||
| let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) }; | ||
| // The two listings come from the same diff, in the same order; if they ever disagree, show | ||
| // names only rather than pair lines with the wrong file. | ||
| let paired = files.len() == changes.len(); | ||
| let mut body = String::new(); | ||
| let (added, removed) = files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed)); | ||
| let totals = if paired { | ||
| format!(r#" <span class="plus">+{added}</span><span class="minus">−{removed}</span>"#) | ||
| } else { | ||
| String::new() | ||
| }; | ||
| let _ = write!(body, r#"<h2 class="changes">{} changed{totals}</h2>"#, plural(changes.len(), "file", "files")); | ||
| if too_big { | ||
| body += r#"<p class="note">This commit’s changes are too large to show line by line.</p>"#; | ||
| } | ||
| for (i, change) in changes.iter().enumerate() { | ||
| let file = files.get(i).filter(|_| paired); | ||
| let status = if change.status.is_empty() { | ||
| String::new() | ||
| } else { | ||
| format!(r#"<span class="status">{}</span>"#, change.status) | ||
| }; | ||
| // A deleted file still exists in the parent commit. | ||
| let at = if change.status == "Deleted" { parents.split_whitespace().next().unwrap_or(oid) } else { oid }; | ||
| let link = repo.url_at("blob", at, &change.path, ""); | ||
| let counts = file.map_or(String::new(), |f| { | ||
| format!(r#"<span class="plus">+{}</span><span class="minus">−{}</span>"#, f.added, f.removed) | ||
| }); | ||
| let _ = write!( | ||
| body, | ||
| r#"<section class="panel"><div class="panel-head"><div class="lead">{}<a href="{}"><b>{}</b></a>{status}</div><div class="side">{counts}</div></div>"#, | ||
| icon("file"), | ||
| attr(&link), | ||
| esc(&lossy(&change.path)) | ||
| ); | ||
| match file { | ||
| None => {} | ||
| Some(f) if f.binary => body += r#"<p class="note">Binary file changed.</p>"#, | ||
| Some(f) if f.rows.is_empty() => body += r#"<p class="note">No content changes.</p>"#, | ||
| Some(f) => { | ||
| body += r#"<div class="diff-wrap"><table class="diff">"#; | ||
| for (class, o, n, text) in &f.rows { | ||
| if *class == "hunk" { | ||
| let _ = write!(body, r#"<tr class="hunk"><td colspan="3">{}</td></tr>"#, esc(text)); | ||
| } else { | ||
| let sign = match *class { | ||
| "add" => "+", | ||
| "del" => "-", | ||
| _ => " ", | ||
| }; | ||
| let _ = write!( | ||
| body, | ||
| r#"<tr class="{class}"><td class="num" data-n="{o}"></td><td class="num" data-n="{n}"></td><td class="line" data-s="{sign}">{}</td></tr>"#, | ||
| esc(text) | ||
| ); | ||
| } | ||
| } | ||
| body += "</table></div>"; | ||
| } | ||
| } | ||
| body += "</section>"; | ||
| } | ||
| Some(body) | ||
| } | ||
| fn view_tags(repo: &Repo) -> Option<View> { | ||
| let out = repo.git(&[ | ||
| "for-each-ref", | ||
| "--sort=-creatordate", | ||
| "--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:short)%1f%(objecttype)%1f%(contents:subject)", | ||
| "refs/tags", | ||
| ])?; | ||
| let mut rows = String::new(); | ||
| for line in out.lines() { | ||
| // The tag's message goes last, so one containing the separator stays whole. | ||
| let Ok([name, direct, peeled, stamp, date, kind, note]) = | ||
| <[&str; 7]>::try_from(line.splitn(7, '\x1f').collect::<Vec<_>>()) | ||
| else { | ||
| continue; | ||
| }; | ||
| let target = if peeled.is_empty() { direct } else { peeled }; | ||
| let note = if kind == "tag" && !note.is_empty() { | ||
| format!(r#"<span class="tnote">{}</span>"#, esc(note)) | ||
| } else { | ||
| String::new() | ||
| }; | ||
| let _ = write!( | ||
| rows, | ||
| r#"<li class="tag-row"><span class="tname">{}</span>{note}<span class="tmeta">{}{}</span> | ||
| <span class="tacts"><a class="button" href="{}">Browse files</a></span></li>"#, | ||
| esc(name), | ||
| repo.sha_link(target), | ||
| ago(stamp, date), | ||
| attr(&repo.url("tree", &[("ref", &repo.tag_ref(name))])) | ||
| ); | ||
| } | ||
| let listing = if rows.is_empty() { | ||
| r#"<div class="panel empty"><h2>No tags yet</h2><p>Tag a release and push it to see it here.</p><code>git tag -a v1.0.0 -m "v1.0.0" && git push origin v1.0.0</code></div>"#.to_string() | ||
| } else { | ||
| format!(r#"<div class="panel"><ul class="rows">{rows}</ul></div>"#) | ||
| }; | ||
| let body = repo.masthead("tags", &repo.default_ref(), None) + &listing; | ||
| Some(View::Html(page(&format!("Tags in {}/{}", repo.owner, repo.name), &body))) | ||
| } | ||
| fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View { | ||
| let Some(repo) = Repo::open(owner, name) else { return View::Missing }; | ||
| let result = match view { | ||
| None => Some(View::Redirect(repo.url("tree", &[]))), | ||
| Some("tree") => view_tree(&repo, q), | ||
| Some("blob") => view_blob(&repo, q, false), | ||
| Some("raw") => view_blob(&repo, q, true), | ||
| Some("log") => view_log(&repo, q), | ||
| Some("commit") => view_commit(&repo, q), | ||
| Some("tags") => view_tags(&repo), | ||
| Some(_) => None, | ||
| }; | ||
| result.unwrap_or(View::Missing) | ||
| } | ||
| /// Pages rendered at once. Each runs several git processes, so a burst of requests queues | ||
| /// here instead of starting hundreds of them. | ||
| static RENDERS: LazyLock<Arc<tokio::sync::Semaphore>> = LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(16))); | ||
| /// Git calls block, so every page renders on the blocking pool. The permit moves into the | ||
| /// blocking work itself: if the request is cancelled while rendering, the slot stays taken | ||
| /// until the work actually ends. | ||
| async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View { | ||
| let Ok(permit) = Arc::clone(&RENDERS).acquire_owned().await else { return View::Missing }; | ||
| let work = move || { | ||
| let _permit = permit; | ||
| f() | ||
| }; | ||
| tokio::task::spawn_blocking(work).await.unwrap_or_else(|error| { | ||
| eprintln!("gitv-web: a page failed to render: {error}"); | ||
| View::Missing | ||
| }) | ||
| } | ||
| 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)] | ||
| mod tests { | ||
| use super::*; | ||
| #[test] | ||
| fn percent_decoding_keeps_raw_bytes() { | ||
| assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings"); | ||
| assert_eq!(parse_query(Some("p=a+b%2Bc"))["p"], b"a b+c"); | ||
| assert_eq!(percent_decode("caf%C3%A9"), "café".as_bytes()); | ||
| assert_eq!(percent_decode("%FF%00"), [0xff, 0]); | ||
| assert_eq!(percent_decode("100%"), b"100%"); | ||
| assert_eq!(percent_decode("%zz%4"), b"%zz%4"); | ||
| } | ||
| #[test] | ||
| fn query_first_value_wins() { | ||
| let q = parse_query(Some("path=a&path=b&ref=main&flag")); | ||
| assert_eq!(q["path"], b"a"); | ||
| assert_eq!(param(&q, "ref").as_deref(), Some("main")); | ||
| assert_eq!(q["flag"], b""); | ||
| } | ||
| #[test] | ||
| fn paths_are_cleaned_as_bytes() { | ||
| assert_eq!(clean_path(b"/a//b/"), Some(b"a/b".to_vec())); | ||
| assert_eq!(clean_path(b"a/../b"), None); | ||
| assert_eq!(clean_path(b"./a"), None); | ||
| assert_eq!(clean_path(b"a\0b"), None); | ||
| assert_eq!(clean_path(&[0xff, b'/', b'x']), Some(vec![0xff, b'/', b'x'])); | ||
| assert_eq!(encode(&[b'a', b' ', 0xff, b'/']), "a%20%FF/"); | ||
| } | ||
| #[test] | ||
| fn an_incomplete_fingerprint_is_never_trusted() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; // Root reads anything, so the unreadable folder below can't be made. | ||
| } | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-fingerprint-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| for folder in ["refs/heads/open", "refs/heads/locked/inner"] { | ||
| std::fs::create_dir_all(dir.join(folder)).unwrap(); | ||
| } | ||
| let repo = RepoDir::at(&dir).unwrap(); | ||
| assert!(refs_fingerprint(&repo).is_some()); | ||
| // A branch folder that can't be read: its refs could change unseen. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o000)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint missing a folder was trusted"); | ||
| // Names readable but not searchable: the folder's children can't be inspected. | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o444)).unwrap(); | ||
| assert_eq!(refs_fingerprint(&repo), None, "a fingerprint with an uninspectable folder was trusted"); | ||
| std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o755)).unwrap(); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn name_status_parsing() { | ||
| let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0"; | ||
| let changes = parse_changes(out); | ||
| let got: Vec<(&str, &[u8])> = changes.iter().map(|c| (c.status, c.path.as_slice())).collect(); | ||
| assert_eq!( | ||
| got, | ||
| [("", &b"src/a b.rs"[..]), ("Renamed", b"new\tname"), ("Deleted", b"gone"), ("Added", b"\xffbin")] | ||
| ); | ||
| } | ||
| } | ||
+0−66
| @@ -1,66 +0,0 @@ | ||
| 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>, | ||
| } | ||
src/bin/gitv.rsDeleted
+0−613
| @@ -1,613 +0,0 @@ | ||
| //! Private Git hosting over OpenSSH and Git's native pack protocol. | ||
| use std::fs; | ||
| use std::io::Write; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, ExitCode, Stdio}; | ||
| use base64::Engine; | ||
| use clap::{Parser, Subcommand}; | ||
| use gitv::{ | ||
| HOST, NAME_RULE, RepoDir, chown_tree, entries, git, git_command, git_in, keys_path, kind_at, open_dir_at, | ||
| open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, valid_name, | ||
| }; | ||
| use nix::errno::Errno; | ||
| use nix::fcntl::{Flock, FlockArg, RenameFlags, renameat, renameat2}; | ||
| use nix::sys::stat::{Mode, fchmod, fstat, mkdirat}; | ||
| use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, geteuid, unlinkat}; | ||
| use std::ffi::OsStr; | ||
| use std::os::fd::{AsFd, OwnedFd}; | ||
| use std::os::unix::ffi::OsStrExt; | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| const HELP: &str = "Commands for your key, run as: ssh git@git.um9i.dev <command> | ||
| list list your repositories | ||
| create <name> create an empty repository | ||
| delete <name> --yes delete a repository permanently | ||
| Pushing to a repository that does not exist yet creates it."; | ||
| #[derive(Parser)] | ||
| #[command(about = "Private Git hosting over OpenSSH and Git's native pack protocol")] | ||
| struct Cli { | ||
| #[command(subcommand)] | ||
| action: Action, | ||
| } | ||
| #[derive(Subcommand)] | ||
| enum Action { | ||
| /// Create an empty repository (root) | ||
| Create { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| }, | ||
| /// Delete a repository permanently (root) | ||
| Delete { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| #[arg(value_parser = name)] | ||
| name: String, | ||
| /// Confirm permanent deletion | ||
| #[arg(long)] | ||
| yes: bool, | ||
| }, | ||
| /// Register an Ed25519 public key for an owner (root) | ||
| AddKey { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| public_key: PathBuf, | ||
| }, | ||
| /// Handle one SSH request (forced command from authorized_keys) | ||
| Serve { | ||
| #[arg(value_parser = name)] | ||
| owner: String, | ||
| }, | ||
| } | ||
| fn name(value: &str) -> Result<String, String> { | ||
| if valid_name(value) { Ok(value.to_string()) } else { Err(NAME_RULE.into()) } | ||
| } | ||
| fn check_name(value: &str) -> Result<&str, String> { | ||
| if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) } | ||
| } | ||
| /// Record something for the operator. SSH users only ever see generic errors, so details go to | ||
| /// syslog (facility daemon, tag `gitv`), or, when `GITV_LOG` names a file, are appended there | ||
| /// for local runs and tests. | ||
| fn log_operator(message: &str) { | ||
| let mut message = message.to_string(); | ||
| if let Some(path) = std::env::var_os("GITV_LOG") { | ||
| // Only a record that was actually written counts; otherwise fall back to syslog, so | ||
| // the message is never lost, and say why it ended up there. | ||
| match append_line(Path::new(&path), &format!("gitv: {message}")) { | ||
| Ok(()) => return, | ||
| Err(e) => message = format!("{message} (couldn't write {}: {e})", Path::new(&path).display()), | ||
| } | ||
| } | ||
| let message = std::ffi::CString::new(message.replace('\0', " ")).unwrap_or_default(); | ||
| // SAFETY: both strings are NUL-terminated and outlive the calls; "%s" keeps the message | ||
| // from being read as a format string. | ||
| unsafe { | ||
| nix::libc::openlog(c"gitv".as_ptr(), nix::libc::LOG_PID, nix::libc::LOG_DAEMON); | ||
| nix::libc::syslog(nix::libc::LOG_WARNING, c"%s".as_ptr(), message.as_ptr()); | ||
| } | ||
| } | ||
| /// Append one line to a file, creating it if needed, and make sure it reached the file. | ||
| fn append_line(path: &Path, line: &str) -> std::io::Result<()> { | ||
| let mut file = fs::File::options().create(true).append(true).open(path)?; | ||
| file.write_all(format!("{line}\n").as_bytes())?; | ||
| file.flush() | ||
| } | ||
| fn is_root() -> bool { | ||
| nix::unistd::geteuid().is_root() | ||
| } | ||
| /// The `git` account's ids, when running as root and new files must be handed to it. | ||
| fn git_account() -> Result<Option<(Uid, Gid)>, String> { | ||
| if !is_root() { | ||
| return Ok(None); | ||
| } | ||
| let user = nix::unistd::User::from_name("git").map_err(|e| e.to_string())?.ok_or("no git account")?; | ||
| Ok(Some((user.uid, user.gid))) | ||
| } | ||
| /// The owner's directory, created if needed and returned open. Anything else at that name, | ||
| /// including a symlink to a directory, is refused rather than followed. | ||
| fn owner_directory(owner: &str) -> Result<OwnedFd, String> { | ||
| let root = open_root().ok_or("cannot open the repository root")?; | ||
| let display = repos_root().join(owner); | ||
| // Another push may create it at the same moment; either way, open what's there after. | ||
| match mkdirat(&root, owner, Mode::from_bits_truncate(0o755)) { | ||
| Ok(()) | Err(Errno::EEXIST) => {} | ||
| Err(e) => return Err(format!("cannot create {}: {e}", display.display())), | ||
| } | ||
| let directory = | ||
| open_dir_at(&root, OsStr::new(owner)).map_err(|_| format!("{} is not a directory", display.display()))?; | ||
| if let Some((uid, gid)) = git_account()? { | ||
| fchown(&directory, Some(uid), Some(gid)).map_err(|e| e.to_string())?; | ||
| } | ||
| Ok(directory) | ||
| } | ||
| /// Create `<owner>/<name>.git`. | ||
| /// | ||
| /// The repository is built inside a private staging directory (mode 0700, made fresh under the | ||
| /// open owner directory), so no other user can rename, replace or remove anything inside it. | ||
| /// Initialisation, permissions and ownership all go through handles, and publication renames | ||
| /// out of the staging directory's own handle into the owner directory's, refusing to replace | ||
| /// anything at the name. What gets published is therefore exactly what git initialised. | ||
| fn create(owner: &str, name: &str) -> Result<Created, CreateError> { | ||
| let directory = owner_directory(owner).map_err(CreateError::Failed)?; | ||
| let target = format!("{name}.git"); | ||
| if kind_at(&directory, OsStr::new(&target)).is_some() { | ||
| return Err(CreateError::EXISTS); | ||
| } | ||
| let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); | ||
| let staging_name = format!(".create-{}-{nanos}-{name}", std::process::id()); | ||
| mkdirat(&directory, staging_name.as_str(), Mode::S_IRWXU) | ||
| .map_err(|e| CreateError::Failed(format!("couldn't make a staging directory: {e}")))?; | ||
| let built = open_dir_at(&directory, OsStr::new(&staging_name)) | ||
| .map_err(|e| CreateError::Failed(format!("couldn't open the staging directory: {e}"))) | ||
| .and_then(|staging| { | ||
| // The directory just made must be ours and private; anything else at the name means | ||
| // someone got there first, so give up rather than build in it. | ||
| let stat = fstat(staging.as_fd()).map_err(|e| CreateError::Failed(e.to_string()))?; | ||
| if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 { | ||
| return Err(CreateError::Failed("the staging directory isn't private".into())); | ||
| } | ||
| build_and_publish(&directory, &staging, &target) | ||
| }); | ||
| // The staging directory is empty now, whether the repository was published or rolled | ||
| // back. Removing it by name only ever removes an empty directory. | ||
| let leftover = unlinkat(&directory, staging_name.as_str(), UnlinkatFlags::RemoveDir).err().map(|e| { | ||
| format!("couldn't remove the staging directory {}: {e}", repos_root().join(owner).join(&staging_name).display()) | ||
| }); | ||
| if let Some(leftover) = &leftover { | ||
| // Whatever the outcome and whoever asked, the operator needs to know. | ||
| log_operator(&format!("creating {owner}/{name}.git: {leftover}")); | ||
| } | ||
| match built { | ||
| Ok(()) => Ok(Created { leftover }), | ||
| // A failure that also left something behind carries both, so whoever reads the detail | ||
| // (an administrator, or the operator log) learns about the directory to clean up. | ||
| Err(error) => Err(match leftover { | ||
| None => error, | ||
| Some(leftover) => error.with_leftover(leftover), | ||
| }), | ||
| } | ||
| } | ||
| /// A repository was created; `leftover` describes anything the operator must clean up. | ||
| struct Created { | ||
| leftover: Option<String>, | ||
| } | ||
| /// Why creation didn't happen. `Exists` is safe to tell anyone; `Failed` carries server details | ||
| /// (paths, git's own messages) that only the operator or an administrator should see. | ||
| enum CreateError { | ||
| /// Something is already at the name. `leftover` notes anything the attempt left behind. | ||
| Exists { | ||
| leftover: Option<String>, | ||
| }, | ||
| Failed(String), | ||
| } | ||
| impl CreateError { | ||
| const EXISTS: CreateError = CreateError::Exists { leftover: None }; | ||
| /// The full story, for the operator or an administrator. | ||
| fn detail(&self) -> String { | ||
| match self { | ||
| CreateError::Exists { leftover: None } => "repository already exists".into(), | ||
| CreateError::Exists { leftover: Some(leftover) } => format!("repository already exists; also {leftover}"), | ||
| CreateError::Failed(detail) => detail.clone(), | ||
| } | ||
| } | ||
| fn with_leftover(self, leftover: String) -> CreateError { | ||
| match self { | ||
| CreateError::Exists { .. } => CreateError::Exists { leftover: Some(leftover) }, | ||
| CreateError::Failed(detail) => CreateError::Failed(format!("{detail}; also {leftover}")), | ||
| } | ||
| } | ||
| } | ||
| /// Run a command whose output only an operator should see: stdout is dropped, and stderr is | ||
| /// captured into the error instead of reaching whoever is connected. | ||
| fn run_privately(mut command: Command, what: &str) -> Result<(), String> { | ||
| let output = command.stdout(Stdio::null()).output().map_err(|e| format!("{what} couldn't start: {e}"))?; | ||
| if output.status.success() { | ||
| Ok(()) | ||
| } else { | ||
| let message = String::from_utf8_lossy(&output.stderr).trim().to_string(); | ||
| Err(format!( | ||
| "{what} failed ({}){}", | ||
| output.status, | ||
| if message.is_empty() { String::new() } else { format!(": {message}") } | ||
| )) | ||
| } | ||
| } | ||
| /// Build a bare repository at `repo` inside the private `staging` directory, then move it to | ||
| /// `target` in `directory`. If anything fails after `repo` was made, it is removed again; it | ||
| /// never removes a `repo` this call didn't make. | ||
| fn build_and_publish(directory: &OwnedFd, staging: &OwnedFd, target: &str) -> Result<(), CreateError> { | ||
| let failed = |e: &dyn std::fmt::Display| CreateError::Failed(e.to_string()); | ||
| // Only once this succeeds is `repo` ours to roll back. | ||
| mkdirat(staging, "repo", Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; | ||
| let built = (|| { | ||
| let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| failed(&e))?; | ||
| // A clean environment, so no caller's init.templateDir can plant hooks in it; and its | ||
| // output stays private, whoever is connected. | ||
| let mut init = git_in(&repo); | ||
| init.args(["init", "--quiet", "--bare", "--initial-branch=main", "."]); | ||
| run_privately(init, "git init").map_err(CreateError::Failed)?; | ||
| fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?; | ||
| if let Some((uid, gid)) = git_account().map_err(CreateError::Failed)? { | ||
| chown_tree(&repo, uid, gid).map_err(|e| failed(&e))?; | ||
| } | ||
| renameat2(staging, "repo", directory, target, RenameFlags::RENAME_NOREPLACE) | ||
| .map_err(|e| if e == Errno::EEXIST { CreateError::EXISTS } else { failed(&e) }) | ||
| })(); | ||
| if let Err(error) = built { | ||
| return Err(match remove_tree_at(staging, OsStr::new("repo")) { | ||
| Ok(()) => error, | ||
| Err(e) => { | ||
| let problem = format!("couldn't remove a half-built repository after \"{}\": {e}", error.detail()); | ||
| log_operator(&problem); | ||
| CreateError::Failed(problem) | ||
| } | ||
| }); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Delete `<owner>/<name>.git`. One handle on the owner directory serves the check, the rename | ||
| /// and the removal, which works through handles all the way down and never follows a symlink. | ||
| fn delete(owner: &str, name: &str) -> Result<(), String> { | ||
| let directory = open_owner(owner).ok_or("repository unavailable")?; | ||
| repo_in(&directory, owner, name).ok_or("repository unavailable")?; | ||
| // A hidden name stops the repository serving at once, before the slow removal. If the | ||
| // entry were swapped for a symlink after the check, only the link would be moved and removed. | ||
| let staging = format!(".delete-{}-{name}", std::process::id()); | ||
| renameat(&directory, format!("{name}.git").as_str(), &directory, staging.as_str()).map_err(|e| e.to_string())?; | ||
| remove_tree_at(&directory, OsStr::new(&staging)).map_err(|e| e.to_string())?; | ||
| println!("deleted {owner}/{name}.git"); | ||
| Ok(()) | ||
| } | ||
| fn add_key(owner: &str, file: &Path) -> Result<(), String> { | ||
| let text = fs::read_to_string(file).map_err(|e| e.to_string())?; | ||
| let parts: Vec<&str> = text.split_whitespace().collect(); | ||
| if parts.len() < 2 || parts[0] != "ssh-ed25519" { | ||
| return Err("expected an OpenSSH Ed25519 public key".into()); | ||
| } | ||
| let engine = base64::engine::general_purpose::STANDARD; | ||
| let blob = engine.decode(parts[1]).map_err(|_| "invalid Ed25519 public key")?; | ||
| let mut header = 11u32.to_be_bytes().to_vec(); | ||
| header.extend_from_slice(b"ssh-ed25519"); | ||
| header.extend_from_slice(&32u32.to_be_bytes()); | ||
| if blob.len() != 51 || blob[..19] != header[..] { | ||
| return Err("invalid Ed25519 public key".into()); | ||
| } | ||
| let token = engine.encode(&blob); | ||
| // Prepare everything the key needs first: publishing the key file is the last step, so a | ||
| // failure leaves no key installed and a retry starts clean. | ||
| owner_directory(owner)?; | ||
| let keys = keys_path(); | ||
| let directory = keys.parent().ok_or("authorized_keys has no directory")?; | ||
| // Serialise writers, so two keys added at once can't overwrite each other. | ||
| let lock = | ||
| fs::File::options().create(true).append(true).open(directory.join("keys.lock")).map_err(|e| e.to_string())?; | ||
| let _lock = Flock::lock(lock, FlockArg::LockExclusive).map_err(|(_, e)| e.to_string())?; | ||
| let old = match fs::read_to_string(&keys) { | ||
| Ok(text) => text, | ||
| Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), | ||
| Err(e) => return Err(e.to_string()), | ||
| }; | ||
| if old.lines().any(|row| key_blob(row).as_deref() == Some(blob.as_slice())) { | ||
| return Err("key already registered".into()); | ||
| } | ||
| let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" }; | ||
| let line = format!("{separator}restrict,command=\"/usr/local/bin/gitv serve {owner}\" ssh-ed25519 {token}\n"); | ||
| let temporary = directory.join(format!(".authorized_keys.{}", std::process::id())); | ||
| let mut out = fs::File::create(&temporary).map_err(|e| e.to_string())?; | ||
| out.write_all(format!("{old}{line}").as_bytes()).map_err(|e| e.to_string())?; | ||
| out.set_permissions(fs::Permissions::from_mode(0o644)).map_err(|e| e.to_string())?; | ||
| out.sync_all().map_err(|e| e.to_string())?; | ||
| fs::rename(&temporary, &keys).map_err(|e| e.to_string())?; | ||
| Ok(()) | ||
| } | ||
| /// The decoded Ed25519 key in an authorized_keys line, wherever it sits: after options, and | ||
| /// before any comment. | ||
| /// | ||
| /// A line is `[options] type key [comment]`. Blank and `#` lines are skipped, options are | ||
| /// skipped as one field (they can hold quoted spaces), and only the key field itself is read, | ||
| /// so a key mentioned in a comment or a commented-out line doesn't count. | ||
| fn key_blob(line: &str) -> Option<Vec<u8>> { | ||
| const TYPES: [&str; 4] = ["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "sk-ssh-ed25519@openssh.com"]; | ||
| let line = line.trim_start(); | ||
| if line.is_empty() || line.starts_with('#') { | ||
| return None; | ||
| } | ||
| // Fields are separated by spaces or tabs. The first is the key type, or else the options. | ||
| let first = line.split([' ', '\t']).next()?; | ||
| let rest = if TYPES.contains(&first) { line } else { skip_options(line)? }; | ||
| let mut fields = rest.split([' ', '\t']).filter(|f| !f.is_empty()); | ||
| if !TYPES.contains(&fields.next()?) { | ||
| return None; | ||
| } | ||
| base64::engine::general_purpose::STANDARD.decode(fields.next()?).ok() | ||
| } | ||
| /// What follows the options field: its end is the first whitespace outside double quotes. | ||
| fn skip_options(line: &str) -> Option<&str> { | ||
| let mut quoted = false; | ||
| let mut escaped = false; | ||
| for (i, c) in line.char_indices() { | ||
| match c { | ||
| _ if escaped => escaped = false, | ||
| '\\' => escaped = true, | ||
| '"' => quoted = !quoted, | ||
| c if c.is_whitespace() && !quoted => return Some(line[i..].trim_start()), | ||
| _ => {} | ||
| } | ||
| } | ||
| None | ||
| } | ||
| /// Handle one SSH request from a key registered to owner. | ||
| fn serve(owner: &str, command: &str) -> Result<u8, String> { | ||
| let args = shlex::split(command).ok_or("unreadable command; run: ssh git@git.um9i.dev help")?; | ||
| let args: Vec<&str> = args.iter().map(String::as_str).collect(); | ||
| match args.as_slice() { | ||
| [] | ["help"] => println!("{HELP}"), | ||
| [program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path), | ||
| ["list"] => { | ||
| // Listed and checked through one handle on the owner's directory. | ||
| let directory = open_owner(owner); | ||
| let mut names: Vec<String> = directory | ||
| .iter() | ||
| .flat_map(entries) | ||
| .filter_map(|e| e.to_str()?.strip_suffix(".git").map(str::to_string)) | ||
| .filter(|n| directory.as_ref().is_some_and(|d| repo_in(d, owner, n).is_some())) | ||
| .collect(); | ||
| names.sort(); | ||
| for name in names { | ||
| println!("git@{HOST}:{owner}/{name}.git"); | ||
| } | ||
| } | ||
| ["create", name] => { | ||
| // A key holder learns whether it worked, and the clone address; server details go | ||
| // to the operator's log. | ||
| let name = check_name(name)?; | ||
| match create(owner, name) { | ||
| Ok(_) => println!("git@{HOST}:{owner}/{name}.git"), | ||
| Err(CreateError::Exists { .. }) => return Err("repository already exists".into()), | ||
| Err(error) => { | ||
| log_operator(&format!("ssh create of {owner}/{name}.git failed: {}", error.detail())); | ||
| return Err("couldn't create the repository; the server's operator can see why".into()); | ||
| } | ||
| } | ||
| } | ||
| ["delete", name, rest @ ..] => { | ||
| let name = check_name(name)?; | ||
| if rest != ["--yes"] { | ||
| return Err(format!("deleting {owner}/{name}.git is permanent; run: delete {name} --yes")); | ||
| } | ||
| delete(owner, name)?; | ||
| } | ||
| _ => return Err("unknown command; run: ssh git@git.um9i.dev help".into()), | ||
| } | ||
| Ok(0) | ||
| } | ||
| /// Parse `owner/name.git` (optionally with leading or trailing slash). | ||
| fn parse_request(path: &str) -> Option<(&str, &str)> { | ||
| let path = path.strip_prefix('/').unwrap_or(path); | ||
| let path = path.strip_suffix('/').unwrap_or(path); | ||
| let (owner, rest) = path.split_once('/')?; | ||
| let name = rest.strip_suffix(".git")?; | ||
| (valid_name(owner) && valid_name(name)).then_some((owner, name)) | ||
| } | ||
| fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> { | ||
| let (requested, name) = parse_request(path).ok_or("repository unavailable")?; | ||
| if requested != owner { | ||
| return Err("repository unavailable".into()); | ||
| } | ||
| let repo = match repo_dir(owner, name) { | ||
| Some(repo) => repo, | ||
| None if program != "git-receive-pack" => return Err("repository unavailable".into()), | ||
| None => { | ||
| // Pushing to a new name creates it, so a fresh project needs no setup step. create() | ||
| // never replaces anything at the name, so a symlink or file there is refused. If a | ||
| // racing push created the repository first, at any moment, this one opens it afresh; | ||
| // either way what it gets must be a real repository. | ||
| // The client only ever hears "repository unavailable"; the cause goes to the | ||
| // operator's log. Losing a race to a push that created it is ordinary, so that stays | ||
| // quiet (create() has already logged any cleanup problem either way). | ||
| match create(owner, name) { | ||
| Ok(_) => eprintln!("gitv: created {owner}/{name}.git"), | ||
| // Another push created it first: ordinary, so quiet. | ||
| Err(CreateError::Exists { .. }) if repo_dir(owner, name).is_some() => {} | ||
| // This attempt genuinely failed, though a racing push's repository lets the | ||
| // push carry on: the operator still hears why. | ||
| Err(error) if repo_dir(owner, name).is_some() => { | ||
| log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail())); | ||
| } | ||
| Err(error) => { | ||
| log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail())); | ||
| return Err("repository unavailable".into()); | ||
| } | ||
| } | ||
| repo_dir(owner, name).ok_or("repository unavailable")? | ||
| } | ||
| }; | ||
| // Run inside the opened directory, so the path can't be swapped for a symlink meanwhile. | ||
| let mut command = repo.command(program); | ||
| command.arg(".").env_clear().env("PATH", "/usr/bin:/bin").env("HOME", "/var/empty"); | ||
| // Pass the client's protocol request through (when sshd accepts it), so clients can use the | ||
| // faster protocol v2. | ||
| if let Ok(protocol) = std::env::var("GIT_PROTOCOL") | ||
| && protocol.len() <= 64 | ||
| && protocol.bytes().all(|b| b.is_ascii_alphanumeric() || b"=:.".contains(&b)) | ||
| { | ||
| command.env("GIT_PROTOCOL", protocol); | ||
| } | ||
| let status = command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).status().map_err(|e| e.to_string())?; | ||
| if program == "git-receive-pack" && status.success() { | ||
| fix_head(&repo)?; | ||
| } | ||
| Ok(status.code().unwrap_or(1) as u8) | ||
| } | ||
| /// Point HEAD at a pushed branch when its current target does not exist. Branch names are | ||
| /// bytes (one per line; a ref can't contain a newline), so names with spaces, non-breaking | ||
| /// spaces or non-UTF-8 bytes are passed to git exactly as they are. | ||
| fn fix_head(repo: &RepoDir) -> Result<(), String> { | ||
| if git(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]).is_ok() { | ||
| return Ok(()); | ||
| } | ||
| let out = git(repo, &["for-each-ref", "--format=%(refname)", "refs/heads"])?; | ||
| let heads: Vec<&[u8]> = out.split(|b| *b == b'\n').filter(|h| !h.is_empty()).collect(); | ||
| let Some(first) = heads.first() else { return Ok(()) }; | ||
| let preferred: [&[u8]; 2] = [b"refs/heads/main", b"refs/heads/master"]; | ||
| let choice = preferred.into_iter().find(|r| heads.contains(r)).unwrap_or(first); | ||
| let status = git_command(repo) | ||
| .args([OsStr::new("symbolic-ref"), OsStr::new("HEAD"), OsStr::from_bytes(choice)]) | ||
| .status() | ||
| .map_err(|e| e.to_string())?; | ||
| if !status.success() { | ||
| return Err("could not set the default branch".into()); | ||
| } | ||
| let name = String::from_utf8_lossy(&choice[b"refs/heads/".len()..]).into_owned(); | ||
| eprintln!("gitv: default branch is now {name}"); | ||
| Ok(()) | ||
| } | ||
| fn run() -> Result<u8, String> { | ||
| let cli = Cli::parse(); | ||
| if let Action::Serve { owner } = &cli.action { | ||
| return serve(owner, &std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default()); | ||
| } | ||
| // Locally (GITV_REPOS set) administration runs as yourself. | ||
| if !is_root() && !gitv::is_local() { | ||
| return Err("run repository and key administration as root".into()); | ||
| } | ||
| match cli.action { | ||
| Action::Create { owner, name } => { | ||
| // An administrator sees everything. | ||
| let created = create(&owner, &name).map_err(|e| e.detail())?; | ||
| println!("git@{HOST}:{owner}/{name}.git"); | ||
| if let Some(leftover) = created.leftover { | ||
| eprintln!("gitv: created {owner}/{name}.git, but {leftover}"); | ||
| } | ||
| } | ||
| Action::Delete { owner, name, yes } => { | ||
| if !yes { | ||
| return Err(format!("deleting {owner}/{name}.git is permanent; pass --yes to confirm")); | ||
| } | ||
| delete(&owner, &name)?; | ||
| } | ||
| Action::AddKey { owner, public_key } => add_key(&owner, &public_key)?, | ||
| Action::Serve { .. } => unreachable!(), | ||
| } | ||
| Ok(0) | ||
| } | ||
| fn main() -> ExitCode { | ||
| match run() { | ||
| Ok(code) => ExitCode::from(code), | ||
| Err(error) => { | ||
| eprintln!("gitv: {error}"); | ||
| ExitCode::FAILURE | ||
| } | ||
| } | ||
| } | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use nix::fcntl::{OFlag, open}; | ||
| fn open_path(path: &Path) -> OwnedFd { | ||
| open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap() | ||
| } | ||
| #[test] | ||
| fn creation_errors_keep_their_leftovers() { | ||
| let leftover = || "couldn't remove the staging directory /x".to_string(); | ||
| assert_eq!(CreateError::EXISTS.detail(), "repository already exists"); | ||
| assert_eq!( | ||
| CreateError::EXISTS.with_leftover(leftover()).detail(), | ||
| "repository already exists; also couldn't remove the staging directory /x" | ||
| ); | ||
| assert_eq!( | ||
| CreateError::Failed("git init failed".into()).with_leftover(leftover()).detail(), | ||
| "git init failed; also couldn't remove the staging directory /x" | ||
| ); | ||
| // Still "exists" for the callers that treat it specially. | ||
| assert!(matches!(CreateError::EXISTS.with_leftover(leftover()), CreateError::Exists { .. })); | ||
| } | ||
| #[test] | ||
| fn private_commands_keep_their_errors_for_the_operator() { | ||
| let mut command = gitv::git_base(); | ||
| command.args(["init", "--no-such-option"]); | ||
| let error = run_privately(command, "git init").unwrap_err(); | ||
| assert!(error.starts_with("git init failed (exit status: 129): "), "{error}"); | ||
| assert!(error.contains("no-such-option"), "git's own message is captured: {error}"); | ||
| } | ||
| #[test] | ||
| fn a_log_file_that_cannot_be_written_is_reported() { | ||
| let missing = std::env::temp_dir().join(format!("gitv-no-such-dir-{}/log", std::process::id())); | ||
| assert!(append_line(&missing, "x").is_err(), "a failed write must not count as logged"); | ||
| let file = std::env::temp_dir().join(format!("gitv-log-{}", std::process::id())); | ||
| let _ = fs::remove_file(&file); | ||
| append_line(&file, "one").unwrap(); | ||
| append_line(&file, "two").unwrap(); | ||
| assert_eq!(fs::read_to_string(&file).unwrap(), "one\ntwo\n"); | ||
| let _ = fs::remove_file(&file); | ||
| } | ||
| #[test] | ||
| fn a_failed_build_never_removes_what_it_did_not_make() { | ||
| let dir = std::env::temp_dir().join(format!("gitv-build-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| // A staging directory that already holds someone's `repo`, as it would if the staging | ||
| // name had been swapped for another private directory before it was opened. | ||
| fs::create_dir_all(dir.join("owner/.staging/repo")).unwrap(); | ||
| fs::write(dir.join("owner/.staging/repo/sentinel"), "precious").unwrap(); | ||
| let owner = open_path(&dir.join("owner")); | ||
| let staging = open_path(&dir.join("owner/.staging")); | ||
| let result = build_and_publish(&owner, &staging, "new.git"); | ||
| assert!(result.is_err(), "building over an existing repo succeeded"); | ||
| assert_eq!(fs::read_to_string(dir.join("owner/.staging/repo/sentinel")).unwrap(), "precious"); | ||
| assert!(!dir.join("owner/new.git").exists(), "nothing was published"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_failed_build_cleans_up_what_it_made() { | ||
| let dir = std::env::temp_dir().join(format!("gitv-build-clean-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(dir.join("owner/.staging")).unwrap(); | ||
| // The target is taken, so publication fails after the repository was built. | ||
| fs::create_dir_all(dir.join("owner/new.git")).unwrap(); | ||
| let owner = open_path(&dir.join("owner")); | ||
| let staging = open_path(&dir.join("owner/.staging")); | ||
| let error = build_and_publish(&owner, &staging, "new.git").err().map(|e| e.detail()).unwrap_or_default(); | ||
| assert!(error.contains("already exists"), "{error}"); | ||
| assert!(fs::read_dir(dir.join("owner/.staging")).unwrap().next().is_none(), "the half-built repo is gone"); | ||
| assert!(fs::read_dir(dir.join("owner/new.git")).unwrap().next().is_none(), "the target is untouched"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
templates/history.htmlDeleted
+0−15
| @@ -1,15 +0,0 @@ | ||
| {% 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 %} | ||
templates/layout.htmlDeleted
+0−2
| @@ -1,2 +0,0 @@ | ||
| {% extends "base.html" %} | ||
| {% block content %}{{ body|safe }}{% endblock %} | ||
testing/host.rsAdded
+171−0
| @@ -0,0 +1,171 @@ | ||
| //! Helpers shared by both packages' integration tests: isolated git, scratch folders, and a | ||
| //! stand-in for ssh that runs `gitv serve`. Each package's `tests/common/mod.rs` includes this | ||
| //! file; the web tests add their own server and HTTP client. | ||
| #![allow(dead_code)] | ||
| use std::fs; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, Output, Stdio}; | ||
| use std::sync::LazyLock; | ||
| /// The `gitv` binary. A test can only be told where its own package's binaries are, so the | ||
| /// web tests find it beside their own executable, where a workspace build puts it. | ||
| pub static GITV: LazyLock<String> = LazyLock::new(|| binary(option_env!("CARGO_BIN_EXE_gitv"), "gitv")); | ||
| /// The `gitv-web` binary, found the same way. | ||
| pub static GITV_WEB: LazyLock<String> = LazyLock::new(|| binary(option_env!("CARGO_BIN_EXE_gitv-web"), "gitv-web")); | ||
| fn binary(own: Option<&str>, name: &str) -> String { | ||
| if let Some(path) = own { | ||
| return path.to_string(); | ||
| } | ||
| // The binaries sit in target/<profile>. Test executables are somewhere below it: in | ||
| // target/<profile>/deps, or deeper in newer Cargo's build directory layout. So look in each | ||
| // folder above this test for a file with the binary's name. | ||
| let exe = std::env::current_exe().unwrap(); | ||
| exe.ancestors() | ||
| .skip(1) | ||
| .map(|dir| dir.join(name)) | ||
| .find(|path| path.is_file()) | ||
| .map(|path| path.to_string_lossy().into_owned()) | ||
| .unwrap_or_else(|| { | ||
| panic!("{name} isn't built near {}; run the tests from the workspace root with `cargo test`", exe.display()) | ||
| }) | ||
| } | ||
| /// The hostname every test installation is configured with. | ||
| pub const TEST_HOST: &str = "git.example.test"; | ||
| /// A configuration file that doesn't exist, so the machine's own /etc/gitv/gitv.conf never applies. | ||
| pub const NO_CONFIG: &str = "/nonexistent/gitv.conf"; | ||
| /// A fresh, empty directory under Cargo's per-target temporary directory. | ||
| pub fn scratch(name: &str) -> PathBuf { | ||
| let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| /// Git with no user or system config and a fixed identity and clock, so runs are repeatable. | ||
| pub fn git_cmd(dir: &Path) -> Command { | ||
| let mut command = Command::new("git"); | ||
| command | ||
| .current_dir(dir) | ||
| .env("HOME", dir) | ||
| .env("GIT_CONFIG_NOSYSTEM", "1") | ||
| .env("GIT_CONFIG_GLOBAL", "/dev/null") | ||
| .env("GIT_AUTHOR_NAME", "Ada Lovelace") | ||
| .env("GIT_AUTHOR_EMAIL", "ada@example.com") | ||
| .env("GIT_COMMITTER_NAME", "Ada Lovelace") | ||
| .env("GIT_COMMITTER_EMAIL", "ada@example.com") | ||
| .env("GIT_AUTHOR_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_COMMITTER_DATE", "2026-01-02T03:04:05Z") | ||
| .env("GIT_SSH_VARIANT", "simple") | ||
| .stdin(Stdio::null()); | ||
| command | ||
| } | ||
| /// Run git in `dir`, panic with its output on failure, and return trimmed stdout. | ||
| pub fn git(dir: &Path, args: &[&str]) -> String { | ||
| let output = git_cmd(dir).args(args).output().unwrap(); | ||
| assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr)); | ||
| String::from_utf8_lossy(&output.stdout).trim().to_string() | ||
| } | ||
| /// A GITv installation in a scratch directory: repositories, a keys file, and a fake `ssh` | ||
| /// that hands git's command to `gitv serve` as an owner's key would. | ||
| pub struct Host { | ||
| pub dir: PathBuf, | ||
| pub repos: PathBuf, | ||
| pub keys: PathBuf, | ||
| } | ||
| impl Host { | ||
| pub fn new(name: &str) -> Host { | ||
| let dir = scratch(name); | ||
| let repos = dir.join("repos"); | ||
| fs::create_dir_all(&repos).unwrap(); | ||
| let keys = dir.join("authorized_keys"); | ||
| let host = Host { dir, repos, keys }; | ||
| // With GIT_SSH_VARIANT=simple git runs: <ssh> <owner>@host <command>. | ||
| let script = format!( | ||
| "#!/bin/sh\nowner=${{1%%@*}}\nSSH_ORIGINAL_COMMAND=\"$2\" GITV_REPOS='{}' GITV_LOG='{}' GITV_HOST={TEST_HOST} GITV_CONFIG={NO_CONFIG} exec '{}' serve \"$owner\"\n", | ||
| host.repos.display(), | ||
| host.log().display(), | ||
| *GITV | ||
| ); | ||
| let ssh = host.ssh_script(); | ||
| fs::write(&ssh, script).unwrap(); | ||
| fs::set_permissions(&ssh, fs::Permissions::from_mode(0o755)).unwrap(); | ||
| host | ||
| } | ||
| /// Where `gitv` writes its operator log in tests. | ||
| pub fn log(&self) -> PathBuf { | ||
| self.dir.join("operator.log") | ||
| } | ||
| /// The operator log so far, empty if nothing was logged. | ||
| pub fn logged(&self) -> String { | ||
| fs::read_to_string(self.log()).unwrap_or_default() | ||
| } | ||
| pub fn ssh_script(&self) -> PathBuf { | ||
| self.dir.join("fake-ssh") | ||
| } | ||
| /// `ssh git@host <command>` as `owner`'s key. | ||
| pub fn ssh(&self, owner: &str, command: &str) -> Output { | ||
| Command::new(&*GITV) | ||
| .args(["serve", owner]) | ||
| .env("SSH_ORIGINAL_COMMAND", command) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// `gitv <args>` as the administrator, pointed at this host. | ||
| pub fn admin(&self, args: &[&str]) -> Output { | ||
| Command::new(&*GITV) | ||
| .args(args) | ||
| .env("GITV_HOST", TEST_HOST) | ||
| .env("GITV_CONFIG", NO_CONFIG) | ||
| .env("GITV_REPOS", &self.repos) | ||
| .env("GITV_KEYS", &self.keys) | ||
| .env("GITV_LOG", self.log()) | ||
| .stdin(Stdio::null()) | ||
| .output() | ||
| .unwrap() | ||
| } | ||
| /// Git in `dir`, with remotes reached through this host's fake ssh. | ||
| pub fn git(&self, dir: &Path, args: &[&str]) -> Output { | ||
| git_cmd(dir).env("GIT_SSH_COMMAND", self.ssh_script()).args(args).output().unwrap() | ||
| } | ||
| pub fn repo(&self, owner: &str, name: &str) -> PathBuf { | ||
| self.repos.join(owner).join(format!("{name}.git")) | ||
| } | ||
| } | ||
| pub fn stdout(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stdout).into_owned() | ||
| } | ||
| pub fn stderr(output: &Output) -> String { | ||
| String::from_utf8_lossy(&output.stderr).into_owned() | ||
| } | ||
| /// A syntactically valid OpenSSH Ed25519 public key built from `seed`. | ||
| pub fn ed25519_key(seed: u8) -> String { | ||
| use base64::Engine; | ||
| let mut blob = 11u32.to_be_bytes().to_vec(); | ||
| blob.extend_from_slice(b"ssh-ed25519"); | ||
| blob.extend_from_slice(&32u32.to_be_bytes()); | ||
| blob.extend_from_slice(&[seed; 32]); | ||
| format!("ssh-ed25519 {} test@example\n", base64::engine::general_purpose::STANDARD.encode(blob)) | ||
| } | ||
tests/ssh.rsDeleted
+0−477
| @@ -1,477 +0,0 @@ | ||
| //! `gitv serve` (what a key runs over SSH) and the administrator commands, exercised with real | ||
| //! git pushes and clones through a stand-in for ssh. | ||
| mod common; | ||
| use std::fs; | ||
| use common::{Host, ed25519_key, git, scratch, stderr, stdout}; | ||
| /// A working copy with one commit on `branch`. | ||
| fn work(name: &str, branch: &str) -> std::path::PathBuf { | ||
| let dir = scratch(name); | ||
| git(&dir, &["init", "-q", "-b", branch]); | ||
| fs::write(dir.join("hello.txt"), "hello\n").unwrap(); | ||
| git(&dir, &["add", "."]); | ||
| git(&dir, &["commit", "-qm", "First"]); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn help_lists_the_commands() { | ||
| let host = Host::new("ssh-help"); | ||
| for command in ["", "help"] { | ||
| let out = host.ssh("ada", command); | ||
| assert!(out.status.success()); | ||
| assert!(stdout(&out).contains("create <name>"), "{}", stdout(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn unknown_and_unreadable_commands_are_refused() { | ||
| let host = Host::new("ssh-unknown"); | ||
| for command in ["rm -rf /", "list extra", "create", "git-upload-pack", "create 'unterminated"] { | ||
| let out = host.ssh("ada", command); | ||
| assert!(!out.status.success(), "{command} should fail"); | ||
| assert!(stderr(&out).starts_with("gitv: "), "{command}: {}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn create_list_and_delete() { | ||
| let host = Host::new("ssh-crud"); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@git.um9i.dev:ada/notes.git"); | ||
| assert!(host.repo("ada", "notes").join("HEAD").is_file()); | ||
| assert!(!host.ssh("ada", "create notes").status.success(), "duplicates are refused"); | ||
| host.ssh("ada", "create alpha"); | ||
| assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.um9i.dev:ada/alpha.git\ngit@git.um9i.dev:ada/notes.git\n"); | ||
| assert_eq!(stdout(&host.ssh("bob", "list")), "", "owners only see their own repositories"); | ||
| let out = host.ssh("ada", "delete notes"); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("delete notes --yes"), "{}", stderr(&out)); | ||
| assert!(host.repo("ada", "notes").exists(), "nothing is deleted without --yes"); | ||
| assert!(host.ssh("ada", "delete notes --yes").status.success()); | ||
| assert!(!host.repo("ada", "notes").exists()); | ||
| assert!(!host.ssh("ada", "delete notes --yes").status.success(), "a missing repository can't be deleted"); | ||
| } | ||
| #[test] | ||
| fn names_are_validated() { | ||
| let host = Host::new("ssh-names"); | ||
| for name in ["Upper", "-dash", "has.dot", "a/b", "..", &"x".repeat(64)] { | ||
| let out = host.ssh("ada", &format!("create '{name}'")); | ||
| assert!(!out.status.success(), "{name} should be refused"); | ||
| } | ||
| assert!(fs::read_dir(&host.repos).unwrap().next().is_none(), "nothing was created"); | ||
| assert!(host.ssh("ada", "create ok_name-2").status.success()); | ||
| } | ||
| #[test] | ||
| fn push_creates_the_repository_and_clone_reads_it() { | ||
| let host = Host::new("ssh-push"); | ||
| let dir = work("ssh-push-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("gitv: created ada/project.git"), "{}", stderr(&out)); | ||
| let clone = scratch("ssh-push-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(fs::read_to_string(clone.join("copy/hello.txt")).unwrap(), "hello\n"); | ||
| // A second push updates the same repository. | ||
| fs::write(dir.join("hello.txt"), "hello again\n").unwrap(); | ||
| git(&dir, &["commit", "-qam", "Second"]); | ||
| assert!(host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]).status.success()); | ||
| let log = git(&host.repo("ada", "project"), &["log", "--format=%s", "main"]); | ||
| assert_eq!(log, "Second\nFirst"); | ||
| } | ||
| #[test] | ||
| fn fetching_a_missing_repository_fails_without_creating_it() { | ||
| let host = Host::new("ssh-missing"); | ||
| let clone = scratch("ssh-missing-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/nothing.git"]); | ||
| assert!(!out.status.success()); | ||
| assert!(!host.repo("ada", "nothing").exists()); | ||
| } | ||
| #[test] | ||
| fn keys_only_reach_their_owners_repositories() { | ||
| let host = Host::new("ssh-owner"); | ||
| let dir = work("ssh-owner-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "bob@x:bob/private.git", "main"]).status.success()); | ||
| let clone = scratch("ssh-owner-clone"); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:bob/private.git"]); | ||
| assert!(!out.status.success(), "ada read bob's repository"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:bob/other.git", "main"]); | ||
| assert!(!out.status.success(), "ada created a repository for bob"); | ||
| assert!(!host.repo("bob", "other").exists()); | ||
| for path in ["'../bob/private.git'", "'ada/../bob/private.git'", "'/etc/passwd'", "'ada/x'"] { | ||
| let out = host.ssh("ada", &format!("git-upload-pack {path}")); | ||
| assert!(!out.status.success(), "{path} was served"); | ||
| assert!(stderr(&out).contains("repository unavailable"), "{path}: {}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn pushing_master_alone_makes_it_the_default_branch() { | ||
| let host = Host::new("ssh-head"); | ||
| let dir = work("ssh-head-work", "master"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/legacy.git", "master"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(stderr(&out).contains("default branch is now master"), "{}", stderr(&out)); | ||
| assert_eq!(git(&host.repo("ada", "legacy"), &["symbolic-ref", "HEAD"]), "refs/heads/master"); | ||
| // A clone now checks out master without being told to. | ||
| let clone = scratch("ssh-head-clone"); | ||
| assert!(host.git(&clone, &["clone", "-q", "ada@x:ada/legacy.git", "copy"]).status.success()); | ||
| assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "master"); | ||
| } | ||
| #[test] | ||
| fn admin_create_and_delete() { | ||
| let host = Host::new("admin-crud"); | ||
| let out = host.admin(&["create", "ada", "tools"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert_eq!(stdout(&out).trim(), "git@git.um9i.dev:ada/tools.git"); | ||
| assert_eq!(git(&host.repo("ada", "tools"), &["symbolic-ref", "HEAD"]), "refs/heads/main"); | ||
| let out = host.admin(&["delete", "ada", "tools"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("--yes"), "{}", stderr(&out)); | ||
| assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success()); | ||
| assert!(!host.repo("ada", "tools").exists()); | ||
| assert!(!host.admin(&["create", "Ada", "tools"]).status.success(), "owner names are validated"); | ||
| } | ||
| #[test] | ||
| fn admin_add_key() { | ||
| let host = Host::new("admin-keys"); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(7)).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let keys = fs::read_to_string(&host.keys).unwrap(); | ||
| assert!(keys.starts_with("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 AAAA"), "{keys}"); | ||
| assert!(!keys.contains("test@example"), "the key's comment is dropped"); | ||
| assert!(host.repos.join("ada").is_dir(), "the owner's directory exists"); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| let second = host.dir.join("bob.pub"); | ||
| fs::write(&second, ed25519_key(9)).unwrap(); | ||
| assert!(host.admin(&["add-key", "bob", second.to_str().unwrap()]).status.success()); | ||
| assert_eq!(fs::read_to_string(&host.keys).unwrap().lines().count(), 2, "both keys are kept"); | ||
| } | ||
| #[test] | ||
| fn admin_add_key_rejects_bad_keys() { | ||
| let host = Host::new("admin-badkeys"); | ||
| let cases = [ | ||
| ("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ test\n".to_string()), | ||
| ("garbage", "not a key\n".to_string()), | ||
| ("bad-base64", "ssh-ed25519 !!!!\n".to_string()), | ||
| ("short", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n".to_string()), | ||
| ("options", format!("command=\"sh\" {}", ed25519_key(1))), | ||
| ]; | ||
| for (name, text) in cases { | ||
| let file = host.dir.join(format!("{name}.pub")); | ||
| fs::write(&file, text).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "{name} was accepted"); | ||
| } | ||
| assert!(!host.keys.exists(), "no key was written"); | ||
| } | ||
| #[test] | ||
| fn admin_needs_root_outside_a_local_tree() { | ||
| if nix::unistd::geteuid().is_root() { | ||
| return; | ||
| } | ||
| let out = std::process::Command::new(common::GITV) | ||
| .args(["create", "ada", "tools"]) | ||
| .env_remove("GITV_REPOS") | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("as root"), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn symlinked_repositories_are_refused() { | ||
| let host = Host::new("ssh-symlink-repo"); | ||
| let dir = work("ssh-symlink-repo-work", "main"); | ||
| assert!(host.git(&dir, &["push", "-q", "bob@x:bob/real.git", "main"]).status.success()); | ||
| // ada/link.git points at bob's repository: following it would cross the owner boundary. | ||
| fs::create_dir_all(host.repos.join("ada")).unwrap(); | ||
| std::os::unix::fs::symlink(host.repo("bob", "real"), host.repo("ada", "link")).unwrap(); | ||
| let clone = scratch("ssh-symlink-repo-clone"); | ||
| assert!(!host.git(&clone, &["clone", "-q", "ada@x:ada/link.git"]).status.success(), "read through a symlink"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/link.git", "main:other"]); | ||
| assert!(!out.status.success(), "wrote through a symlink"); | ||
| assert!(git(&host.repo("bob", "real"), &["branch", "--list", "other"]).is_empty()); | ||
| assert_eq!(stdout(&host.ssh("ada", "list")), "", "symlinks aren't listed"); | ||
| assert!(!host.ssh("ada", "delete link --yes").status.success()); | ||
| assert!(host.repo("bob", "real").join("HEAD").is_file(), "the target survives"); | ||
| } | ||
| #[test] | ||
| fn symlinked_owner_directories_are_refused() { | ||
| let host = Host::new("ssh-symlink-owner"); | ||
| let outside = scratch("ssh-symlink-owner-outside"); | ||
| std::os::unix::fs::symlink(&outside, host.repos.join("ada")).unwrap(); | ||
| let dir = work("ssh-symlink-owner-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/new.git", "main"]); | ||
| assert!(!out.status.success(), "created a repository through a symlinked owner directory"); | ||
| assert!(!host.ssh("ada", "create other").status.success()); | ||
| assert!(fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the tree"); | ||
| } | ||
| #[test] | ||
| fn simultaneous_first_pushes_all_succeed() { | ||
| let host = std::sync::Arc::new(Host::new("ssh-race")); | ||
| let dir = work("ssh-race-work", "main"); | ||
| // Each push sends its own branch: racing to create one *branch* is git's business, but | ||
| // racing to create the *repository* must not fail anyone. | ||
| let pushes: Vec<_> = (0..6) | ||
| .map(|n| { | ||
| let (host, dir) = (host.clone(), dir.clone()); | ||
| std::thread::spawn(move || host.git(&dir, &["push", "-q", "ada@x:ada/raced.git", &format!("main:b{n}")])) | ||
| }) | ||
| .collect(); | ||
| for push in pushes { | ||
| let out = push.join().unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| } | ||
| let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect(); | ||
| assert_eq!(leftovers, [std::ffi::OsString::from("raced.git")], "no staging directories left behind"); | ||
| assert_eq!(git(&host.repo("ada", "raced"), &["for-each-ref", "--format=%(refname:lstrip=2)"]).lines().count(), 6); | ||
| assert_eq!(host.logged(), "", "losing a creation race is ordinary and isn't logged"); | ||
| } | ||
| #[test] | ||
| fn add_key_failure_installs_nothing() { | ||
| let host = Host::new("admin-keys-atomic"); | ||
| // A file where the owner's directory should go makes preparing the owner fail. | ||
| fs::write(host.repos.join("ada"), "not a directory").unwrap(); | ||
| let key = host.dir.join("ada.pub"); | ||
| fs::write(&key, ed25519_key(3)).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(!host.keys.exists(), "the key was installed although the command failed"); | ||
| // Once the problem is fixed, a retry succeeds rather than finding the key already there. | ||
| fs::remove_file(host.repos.join("ada")).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn add_key_respects_existing_lines() { | ||
| let host = Host::new("admin-keys-existing"); | ||
| let blob = ed25519_key(5); | ||
| let blob = blob.split_whitespace().nth(1).unwrap(); | ||
| // Written by hand: options in front, a comment after, and no final newline. | ||
| fs::write(&host.keys, format!("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob} laptop")) | ||
| .unwrap(); | ||
| let same = host.dir.join("same.pub"); | ||
| fs::write(&same, ed25519_key(5)).unwrap(); | ||
| let out = host.admin(&["add-key", "bob", same.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "the same key was registered twice"); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| let other = host.dir.join("other.pub"); | ||
| fs::write(&other, ed25519_key(6)).unwrap(); | ||
| assert!(host.admin(&["add-key", "bob", other.to_str().unwrap()]).status.success()); | ||
| let keys = fs::read_to_string(&host.keys).unwrap(); | ||
| let lines: Vec<&str> = keys.lines().collect(); | ||
| assert_eq!(lines.len(), 2, "{keys}"); | ||
| assert!( | ||
| lines[0].ends_with(" laptop") && lines[1].starts_with("restrict,command=\"/usr/local/bin/gitv serve bob\"") | ||
| ); | ||
| } | ||
| #[test] | ||
| fn the_readme_fake_ssh_script_works() { | ||
| let host = Host::new("ssh-script"); | ||
| let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("scripts/fake-ssh"); | ||
| let dir = work("ssh-script-work", "main"); | ||
| let out = common::git_cmd(&dir) | ||
| .env("GIT_SSH_COMMAND", &script) | ||
| .env("GITV_REPOS", &host.repos) | ||
| .args(["push", "-q", "um9i@local:um9i/demo.git", "main"]) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(host.repo("um9i", "demo").join("HEAD").is_file()); | ||
| } | ||
| #[test] | ||
| fn default_branch_repair_keeps_branch_names_exact() { | ||
| use std::os::unix::ffi::OsStrExt; | ||
| // Names that whitespace splitting or UTF-8 conversion would mangle. | ||
| let names: [&[u8]; 2] = ["trunk\u{a0}line".as_bytes(), b"caf\xe9"]; | ||
| for (n, name) in names.iter().enumerate() { | ||
| let host = Host::new(&format!("ssh-head-bytes-{n}")); | ||
| let dir = work(&format!("ssh-head-bytes-{n}-work"), "main"); | ||
| let target = [b"main:refs/heads/".as_slice(), name].concat(); | ||
| let out = common::git_cmd(&dir) | ||
| .env("GIT_SSH_COMMAND", host.ssh_script()) | ||
| .args([std::ffi::OsStr::new("push"), "-q".as_ref(), "ada@x:ada/odd.git".as_ref()]) | ||
| .arg(std::ffi::OsStr::from_bytes(&target)) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| let head = common::git_cmd(&host.repo("ada", "odd")).args(["symbolic-ref", "HEAD"]).output().unwrap(); | ||
| assert_eq!( | ||
| head.stdout, | ||
| [b"refs/heads/".as_slice(), name, b"\n"].concat(), | ||
| "HEAD names the pushed branch exactly" | ||
| ); | ||
| let clone = scratch(&format!("ssh-head-bytes-{n}-clone")); | ||
| let out = host.git(&clone, &["clone", "-q", "ada@x:ada/odd.git", "copy"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(clone.join("copy/hello.txt").is_file(), "the clone checked out the default branch"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn commented_keys_do_not_block_registration() { | ||
| let host = Host::new("admin-keys-comments"); | ||
| let key = ed25519_key(8); | ||
| let blob = key.split_whitespace().nth(1).unwrap(); | ||
| // The key is retired (commented out) and also mentioned in another key's comment. | ||
| let other = ed25519_key(9); | ||
| let other_blob = other.split_whitespace().nth(1).unwrap(); | ||
| fs::write( | ||
| &host.keys, | ||
| format!( | ||
| "# restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob}\n\ | ||
| # ssh-ed25519 {blob} old laptop\n\ | ||
| command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {other_blob} replaces ssh-ed25519 {blob}\n" | ||
| ), | ||
| ) | ||
| .unwrap(); | ||
| let file = host.dir.join("ada.pub"); | ||
| fs::write(&file, &key).unwrap(); | ||
| let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| // A real duplicate behind quoted options with spaces is still caught. | ||
| let again = host.dir.join("bob.pub"); | ||
| fs::write(&again, &other).unwrap(); | ||
| let out = host.admin(&["add-key", "carol", again.to_str().unwrap()]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn tab_separated_keys_are_recognised() { | ||
| let host = Host::new("admin-keys-tabs"); | ||
| let key = ed25519_key(11); | ||
| let blob = key.split_whitespace().nth(1).unwrap(); | ||
| // An active key written with tabs between its fields, with and without options. | ||
| fs::write( | ||
| &host.keys, | ||
| format!("ssh-ed25519\t{blob}\tlaptop\nrestrict\tssh-ed25519\t{}\n", { | ||
| let other = ed25519_key(12); | ||
| other.split_whitespace().nth(1).unwrap().to_string() | ||
| }), | ||
| ) | ||
| .unwrap(); | ||
| for (seed, owner) in [(11, "bob"), (12, "carol")] { | ||
| let file = host.dir.join(format!("{owner}.pub")); | ||
| fs::write(&file, ed25519_key(seed)).unwrap(); | ||
| let out = host.admin(&["add-key", owner, file.to_str().unwrap()]); | ||
| assert!(!out.status.success(), "key {seed} was registered a second time"); | ||
| assert!(stderr(&out).contains("already registered"), "{}", stderr(&out)); | ||
| } | ||
| } | ||
| #[test] | ||
| fn creation_never_replaces_what_is_at_the_name() { | ||
| let host = Host::new("admin-create-noreplace"); | ||
| // An empty directory (which a plain rename would silently replace) and a symlink. | ||
| fs::create_dir_all(host.repo("ada", "empty")).unwrap(); | ||
| let elsewhere = scratch("admin-create-noreplace-elsewhere"); | ||
| std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "link")).unwrap(); | ||
| for name in ["empty", "link"] { | ||
| let out = host.admin(&["create", "ada", name]); | ||
| assert!(!out.status.success(), "{name} was created over"); | ||
| assert!(stderr(&out).contains("already exists"), "{name}: {}", stderr(&out)); | ||
| } | ||
| assert!(fs::read_dir(host.repo("ada", "empty")).unwrap().next().is_none(), "the directory is untouched"); | ||
| assert!(fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing was written through the symlink"); | ||
| let names: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect(); | ||
| assert_eq!(names.len(), 2, "no staging directory left behind: {names:?}"); | ||
| } | ||
| #[test] | ||
| fn deletion_removes_links_inside_a_repository_without_following_them() { | ||
| let host = Host::new("admin-delete-links"); | ||
| assert!(host.admin(&["create", "ada", "tools"]).status.success()); | ||
| let outside = scratch("admin-delete-links-outside"); | ||
| fs::write(outside.join("precious.txt"), "keep").unwrap(); | ||
| std::os::unix::fs::symlink(&outside, host.repo("ada", "tools").join("escape")).unwrap(); | ||
| let out = host.admin(&["delete", "ada", "tools", "--yes"]); | ||
| assert!(out.status.success(), "{}", stderr(&out)); | ||
| assert!(!host.repo("ada", "tools").exists()); | ||
| assert_eq!(fs::read_to_string(outside.join("precious.txt")).unwrap(), "keep"); | ||
| assert!(fs::read_dir(host.repos.join("ada")).unwrap().next().is_none(), "no staging directory left behind"); | ||
| } | ||
| #[test] | ||
| fn a_failed_first_push_tells_the_operator_why() { | ||
| let host = Host::new("ssh-first-push-log"); | ||
| let elsewhere = scratch("ssh-first-push-log-elsewhere"); | ||
| fs::create_dir_all(host.repos.join("ada")).unwrap(); | ||
| std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "taken")).unwrap(); | ||
| let dir = work("ssh-first-push-log-work", "main"); | ||
| let out = host.git(&dir, &["push", "-q", "ada@x:ada/taken.git", "main"]); | ||
| assert!(!out.status.success()); | ||
| // The client gets the generic answer, without server details. | ||
| assert!(stderr(&out).contains("gitv: repository unavailable"), "{}", stderr(&out)); | ||
| assert!(!stderr(&out).contains("already exists"), "{}", stderr(&out)); | ||
| // The operator gets the cause. | ||
| let log = host.logged(); | ||
| assert!(log.contains("first push to ada/taken.git couldn't create it: repository already exists"), "{log}"); | ||
| } | ||
| #[test] | ||
| fn ssh_create_keeps_server_details_for_the_operator() { | ||
| let host = Host::new("ssh-create-private"); | ||
| // A file where the owner's directory should be: creation fails on the server's side. | ||
| fs::write(host.repos.join("ada"), "not a directory").unwrap(); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(!out.status.success()); | ||
| let said = stderr(&out); | ||
| assert!(said.contains("couldn't create the repository; the server's operator can see why"), "{said}"); | ||
| assert!(!said.contains(host.repos.to_str().unwrap()), "a server path reached the client: {said}"); | ||
| let log = host.logged(); | ||
| assert!(log.contains("ssh create of ada/notes.git failed:") && log.contains("is not a directory"), "{log}"); | ||
| // An administrator running the same thing sees the details directly. | ||
| let out = host.admin(&["create", "ada", "notes"]); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("is not a directory"), "{}", stderr(&out)); | ||
| // "Already exists" is safe to tell anyone. | ||
| fs::remove_file(host.repos.join("ada")).unwrap(); | ||
| assert!(host.ssh("ada", "create notes").status.success()); | ||
| let out = host.ssh("ada", "create notes"); | ||
| assert!(stderr(&out).contains("gitv: repository already exists"), "{}", stderr(&out)); | ||
| } | ||