GITv
master
CLAUDE.md141 lines, 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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.