# Progress

## This attempt (#3, Topcoat)

91 tests. Active milestone in [current.md](current.md).

### Milestone 0 — Skeleton · done

Topcoat 0.5 app serving pages, `AppConfig` from `STEID_*` env, SQLite pool in app
context. Split into a library plus a thin binary — the domain layer had no consumers
yet and read as ~30 dead-code warnings in a bare binary, and it unlocks `tests/`.
Topcoat's link-time page discovery works from a library; that was checked, not assumed.

**Requires rustc ≥ 1.95.** On older toolchains `cargo add topcoat` silently resolves to
an empty `topcoat v0.0.0` placeholder instead of failing.

### Milestone 1 — Identity, thin · done

**Domain.** Typed IDs, `Email`, `PasswordHash`, `OrgName`, `Organization`, `User`,
`Membership`, `Role`, `Actor`, `Session`, `SetupToken`, `DomainError`. Value objects
pair `new()` (validates) with `from_trusted()` (skips, for rows already validated).

**Application.** `claim_instance`, `login`, `resolve_actor`, `record_session`,
`end_session`, `sweep_expired`. `PasswordHasher` port with Argon2 and a stub.

**Infrastructure.** Migrations for orgs, users, memberships, sessions. In-memory and
SQLite implementations of every port. Root layout, `/setup`, `/login`, `/logout`, home,
and `/api/me`.

`describe_identity` is the first use case with two consumers — the home page and
`/api/me` both read through it. Until that existed, "the application layer is
transport-neutral" was an assertion with one caller behind it.

**Verified in a browser and by curl:** wrong token refused with nothing written;
correct token creates org + user + owner membership and signs the owner in; session
authenticates; logout clears cookie and row; wrong password bounces; right one signs
in; re-claiming a claimed instance is refused.

#### Decisions worth remembering

- **`Actor` is an enum with an explicit `Anonymous`**, not `Option<UserId>`. Attempt #2
  used a placeholder `UserId("ssh-anonymous")` and it became a security hole. A variant
  can't be forgotten the way a sentinel can.
- **`login` verifies a dummy hash when no user matched.** Returning early on the
  unknown-email path makes it measurably faster and leaks which addresses have
  accounts. A test pins that the dummy stays parseable — if it stops being, `verify`
  bails early and the defence dies silently.
- **`SetupToken` compares in constant time.** An early-return comparison leaks how much
  of the token is right, which recovers it a character at a time.
- **The setup token is only in app context while unclaimed**, so a claimed instance has
  nothing for a claim attempt to match.
- **SQLite ignores foreign keys unless asked**, per connection. `foreign_keys(true)`
  plus a test that a user pointing at a missing org is refused.
- **`sqlx migrate add` stamps versions to the second** — three calls in one second
  collide, leaving apply order ambiguous between tables that reference each other.
- **An unparseable role surfaces as an error**, never as "no membership". The latter
  silently downgrades an owner to no access.
- **`Secure` session cookies over plain-HTTP localhost fail silently.** See
  [runbook.md](runbook.md#steid_insecure_cookies--development-only). This one actually
  bit, and it looked exactly like broken auth logic.

---

## Reference: what attempt #2 proved

Not this repo's progress. This is a catalogue of what was built and **verified working**
in `steid-backup-2026-07-31`, so the rebuild can crib rather than rediscover.

Final state: single crate, ~4,200 LOC, 60 passing tests, five milestones.

### Identity

Domain model (User, Organization, Membership, Actor, Role), `Email` and
`PasswordHash` value objects, typed IDs, `DomainError`, four repository ports with
in-memory and SQLite implementations each. `RegistrationPolicy` (Personal / Invite /
Open) driving which routes exist. Argon2 hashing behind a `PasswordHasher` port with a
stub for tests. Use cases: `bootstrap_owner`, `register_user`, `login`, `create_invite`.
Signed-cookie sessions via an `AuthUser` extractor.

**Gotcha:** organizations must be saved before users — the FK runs that direction.
Both `bootstrap_owner` and `register_user` had to be fixed for this.

### Repo model

`Repository` entity, `RepoId`, `Visibility` (Public/Private), `RepoRepository` port,
migration `006_create_repositories.sql`. `create_repo` use case validates the name,
rejects duplicates, and initialises the bare repo on disk in the same call. Bare repos
live at `{data_dir}/{org}/{repo}.git`, `data_dir` defaulting to `./data`. Repos are
created empty, no initial commit, like GitHub.

### Git over SSH

`GitStorage` port (`init_bare`, `repo_path`) with `DiskGitStorage` shelling out to
`git init --bare`. `GitProtocolServer` port (`upload_pack`, `receive_pack`) with
`GitBinary` spawning `git upload-pack` / `git receive-pack` via
`tokio::process::Command` and pumping stdio with `tokio::io::copy`.

`serve_clone` and `serve_push` use cases enforce visibility and actor checks **before
any protocol byte flows** — that ordering is the whole point of putting them in the
application layer.

#### SSH channel bridging

The fiddly part, and worth re-reading before Milestone 3:

- Store `Channel<Msg>` per `ChannelId` in the handler's map on `channel_open_session`
- On `exec_request`, take the channel, split it with `into_stream()` +
  `tokio::io::split`
- Take stderr via `make_writer_ext(Some(1))` **before** `into_stream()` — that call
  consumes the channel, so the order is not optional
- No `data()` or `channel_eof()` handlers needed once the streams are split

An earlier iteration used mpsc channels, custom `ChannelReader`/`ChannelWriter`, and a
`spawn_blocking` thread. All of it was deleted and the result was simpler.

### SSH key auth and authorization

`SshKey { id, user_id, name, fingerprint, openssh }` + port, migration
`007_create_ssh_keys.sql` (`fingerprint` UNIQUE). Fingerprints are SHA256 via
`russh::keys::ssh_key::PublicKey::fingerprint(HashAlg::Sha256)`, stored as `SHA256:…`.
`add_ssh_key` parses the openssh blob, dedupes on fingerprint, and re-encodes to a
canonical form before storing.

`auth_none` rejects. `auth_publickey` fingerprints the offered key, looks it up, and
on a match stores `user_id` on the handler; `exec_request` builds the real `Actor`
from it.

Authorization rules as shipped:

| Operation | Requirement |
|---|---|
| Clone, public repo | open |
| Clone, private repo | any membership in the repo's org |
| Push | `Role::Owner` membership in the repo's org |

Web UI at `/{owner}/keys` — owner-only, lists fingerprints, accepts openssh via
textarea, revokes per-row.

**Verified end-to-end:** clone with an unregistered key → `Permission denied` (exit
128); register via web UI → clone and push both succeed; second unregistered key →
rejected at auth; revoke via web UI → subsequent clone rejected at auth.

### Security notes

Attempt #2 ran with a **named, deliberate backdoor** between milestones: SSH accepted
any connection and passed a placeholder `Actor` (`UserId("ssh-anonymous")`), leaving
push open to anyone who could reach the port. It was recorded with an explicit
tightening point (`ssh.rs::exec_request`) and a closing milestone, and it did close.

That practice is worth keeping. When this attempt opens a hole to make progress, name
it, name the line that closes it, and name the milestone.

### Never built

Repo browsing (tree/blob/log), HTTP smart protocol, personal access tokens, flash
messages, issues, PRs, blogs, pages, project showcases. Milestones 5–8 in
[ROADMAP.md](ROADMAP.md) are all greenfield.
