diff --git a/.ai/designs/architecture-overview.md b/.ai/designs/architecture-overview.md index 2613b61..3298cfe 100644 --- a/.ai/designs/architecture-overview.md +++ b/.ai/designs/architecture-overview.md @@ -1,7 +1,8 @@ # Architecture overview -Status: phase 1 walking skeleton built and verified against a real `loreserver`. Last updated -2026-11-25. +Status: phase 1 walking skeleton built and verified against a real `loreserver`; a first +production deployment (Linux, systemd, Caddy, TLS, backups) is written but not yet run on +Linux. Last updated 2026-11-26. ## What lore-forge is @@ -112,6 +113,7 @@ never needs Zig. See [desktop-client.md](desktop-client.md). | Desktop client | A per-user client service (Rust, liblore) with a C++ Dear ImGui tray GUI (pixel-art look) on vendored UHDK and a later Rust TUI as frontends, in `desktop/` | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) | | Desktop SYNC and SUBMIT | SYNC pulls and keeps local edits; SUBMIT commits and pushes the files checked in CHANGES, all by default | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) | | Desktop autosync and locks | Autosync only pulls, and warns and refuses rather than overwrite overlapping local edits; the GUI locks and unlocks files, SUBMIT releases your locks, and the service refuses submits of files others hold (Lore itself does not enforce locks) | Owner, 2026-11-26; details in [desktop-client.md](desktop-client.md) | +| Production deployment | One Linux host with systemd; one public hostname and Let's Encrypt certificate shared by Caddy (forge) and `loreserver` (QUIC and gRPC over TLS); nightly backups that stop `loreserver` for seconds | Owner, 2026-11-26; details in [deployment.md](deployment.md) | | Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference | | Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed | | Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Owner, 2026-11-25 | @@ -156,6 +158,9 @@ never needs Zig. See [desktop-client.md](desktop-client.md). 5. **Game-development specifics.** Asset previews (textures, `.uasset` thumbnails), lock management. +Deployment is not a phase of its own: [deployment.md](deployment.md) records the production +shape and what about it is verified. + The desktop client has its own milestones, in [desktop-client.md](desktop-client.md). Milestones 1 (the GUI and tray shell), 2 (liblore in the service: real workspaces, sign-in through the forge, clone, submit and sync) and 3 (file locking, autosync and notifications) are diff --git a/.ai/designs/deployment.md b/.ai/designs/deployment.md new file mode 100644 index 0000000..3e4f558 --- /dev/null +++ b/.ai/designs/deployment.md @@ -0,0 +1,84 @@ +# Deployment + +Status: first production shape built 2026-11-26; the e2e test covers its TLS and backup +paths, the systemd units and installer have not yet run on Linux. Operator instructions are in +[deploy/README.md](../../deploy/README.md). + +## Decisions + +| Topic | Decision | Source | +| --- | --- | --- | +| Host | One Linux machine with systemd; lore-forge and `loreserver` as two units | Owner, 2026-11-26 | +| Reach and certificate | One public hostname for both: the forge on 443 and `loreserver` on 41337 (UDP and TCP), sharing one Let's Encrypt certificate | Owner, 2026-11-26 | +| Proxy | Caddy obtains the certificate and proxies to lore-forge over h2c; `loreserver` reads a copy of the same certificate | Owner, 2026-11-26 | +| Backups | Copy the store live, stop `loreserver`, copy again with the database, start it; nightly, 14 kept, hard links between them | Owner, 2026-11-26 | +| Lore config | Generated in full by `lore-forge loreserver-config` (trust, TLS, stores, ports, loopback HTTP), used by the units, `scripts/start.sh` and the e2e test alike | Implementation choice | +| Secret key | A root-only file handed to lore-forge as the systemd credential `secret-key`; never in backups | Implementation choice | +| Remote shown to users | `LORE_FORGE_LORE_REMOTE`, by default `lores://`, or `lore://` for a loopback host | Implementation choice | + +## Layout + +``` +Caddy :80 :443 ──h2c──▶ lore-forge 127.0.0.1:8080 ── /var/lib/lore-forge + ▲ discovery, JWKS, registry and names (through https://host) +loreserver :41337 udp+tcp (TLS) ── /var/lib/loreserver/store + 127.0.0.1:41339 (HTTP, file content for lore-forge's browser) +``` + +- Binaries under `/opt/lore-forge/bin`, settings in `/etc/lore-forge/lore-forge.env`, read by + both units. +- `loreserver.service` copies Caddy's certificate to `/etc/loreserver/tls` and writes its + configuration to `/run/loreserver/forge.toml` before each start. +- `lore-forge-certs.path` restarts `loreserver` when Caddy renews the certificate, because + `loreserver` reads it only at startup. +- `loreserver` only *wants* lore-forge, so restarting lore-forge does not restart it and + drop its locks. + +## Verified + +In Lore v0.14.0's `docs/reference/lore-server-config.md` and `lore-cli-config.md`: + +- `[server.grpc]` serves TLS when it has a `certificate` block. Without one it is plaintext. +- `[server.http]` has no TLS setting. Lore's clients do not use it; only lore-forge's + browser reads file content there, so it is bound to `127.0.0.1`. +- `lores://` validates the server certificate and is the default scheme. `lore://` accepts + any certificate on QUIC and sends gRPC, tokens included, without TLS. +- The `local` lock store is an in-memory map. Every `loreserver` restart releases every lock. +- `loreserver` re-fetches the JWKS on an unknown key ID, so key rotation needs no restart. + +By `scripts/e2e-lore.sh` against the v0.14.0 release, on macOS: + +- `loreserver` loads a P-256 key in SEC1 form (`EC PRIVATE KEY`), which is how Caddy stores + its keys, for both QUIC and gRPC. +- The CLI, liblore (the desktop service) and lore-forge's browser all work over `lores://` + and TLS gRPC. They trust a private CA through `SSL_CERT_FILE`, so the clients use native + roots plus that variable. +- A client without the CA is refused, and so is a `lore://` client against the TLS endpoint. +- `loreserver` does not log a "listening" line at its default level. Readiness is checked + with `GET /health_check` on the HTTP port. +- A revision pushed just before `scripts/backup.sh` survives the SIGTERM stop and is in the + backup. A restore brings back that state, drops a revision pushed after it, and serves both + the CLI and the browser. + +## Assumed, not yet checked + +- The units, `install.sh`, `lore-forge-certs` and the Caddy site work as written on Debian 12 + or Ubuntu 22.04+. None has run on Linux. +- Caddy's package keeps certificates at + `/var/lib/caddy/.local/share/caddy/certificates/acme-v02.api.letsencrypt.org-directory//`. +- Caddy passes Lore's gRPC (including streams) to lore-forge over h2c with + `flush_interval -1`. +- The server reaches itself at its public name (or through `/etc/hosts`). +- Pushes and clones of real asset sizes (gigabytes) behave; the e2e pushes bytes. + +## Open + +- **Locks across restarts.** Backups, certificate renewals and upgrades restart `loreserver`, + which releases every lock. Options: lore-forge keeps the lock list and re-takes locks after a + restart, or a plugin lock store. To decide with the owner. +- **Durability between flushes.** The local stores flush every 10 s. Whether an acknowledged + push survives a crash, rather than a clean stop, is unchecked. +- **Off-machine backups.** `backup.sh` writes to a local directory. Copying off the machine + is left to the operator. +- **Upgrade testing.** Moving to a new Lore release should be tried on a copy of the store + first; there is no tooling for that yet. diff --git a/.ai/designs/lore-integration.md b/.ai/designs/lore-integration.md index ea0b5ed..069d386 100644 --- a/.ai/designs/lore-integration.md +++ b/.ai/designs/lore-integration.md @@ -46,10 +46,14 @@ Lore calls this the capability profile. lore-forge implements all of it; details | Token exchange with a resource indicator | RFC 8693, RFC 8707 | Per-repository tokens | | Revocation | RFC 7009 | `lore auth logout` | -## Server configuration lore-forge will generate +## Server configuration lore-forge generates -A sketch of the `loreserver` settings for this design. Field names are from the config -reference; the values are examples. +`lore-forge loreserver-config` writes the whole `loreserver` configuration. The trust settings +are below. With `--store`, `--tls-cert`/`--tls-key`, `--port` and `--http-port`, it also places +the stores, gives both public endpoints (QUIC and gRPC) the certificate, moves the ports, and +always binds the plaintext HTTP endpoint to `127.0.0.1`. The deployment that uses this is in +[deployment.md](deployment.md). Field names are from the config reference; the values are +examples. ```toml [server.auth] @@ -75,6 +79,20 @@ Defaults worth knowing: `resource_id_template` is `urc-{id}` and `resource_wildc **Start order:** `loreserver` fetches the issuer's keys at startup and refuses to start if it cannot. lore-forge must be up first. +**Transport security** (verified in v0.14.0's `lore-server-config.md` and `lore-cli-config.md`, +and by `scripts/e2e-lore.sh`, which runs over TLS by default): + +- `[server.grpc]` serves TLS only with its own `certificate` block. Without one it is + plaintext, and the CLI's gRPC calls carry tokens in the clear. +- `[server.http]` cannot serve TLS. Lore's clients do not use it. +- `lores://` validates the certificate and is the default scheme. `lore://` accepts any QUIC + certificate and sends gRPC without TLS. +- Clients trust the system's roots, or the file `SSL_CERT_FILE` names. `loreserver` reads P-256 + keys in SEC1 form. +- Readiness: `loreserver` logs no "listening" line by default; `GET /health_check` on the HTTP + port answers once it is up. +- The `local` lock store is in memory, so a `loreserver` restart releases every lock. + ## Surfaces lore-forge uses | Need | Lore surface | Verified | @@ -260,6 +278,8 @@ and confirmed by `scripts/e2e-lore.sh` against the v0.14.0 release: - Whether a TreeNode in a linked repository can be read with a token for the parent repository, or needs one for the linked repository. - Paging `RevisionList` with `signature_backward`; the browser does not page yet. +- Whether a push `loreserver` has acknowledged survives a crash within the local stores' + 10-second flush interval. A clean SIGTERM stop keeps it (shown by the e2e backup check). ## Upstream files worth reading diff --git a/.ai/designs/storage.md b/.ai/designs/storage.md index d42c284..6498045 100644 --- a/.ai/designs/storage.md +++ b/.ai/designs/storage.md @@ -49,12 +49,14 @@ deployments already started from `run/` keep their data. ## Secrets -One 32-byte key, supplied through the environment, encrypts: +One 32-byte key, supplied through the environment (`LORE_FORGE_SECRET_KEY`), a file +(`LORE_FORGE_SECRET_KEY_FILE`) or the systemd credential `secret-key`, encrypts: - provider client secrets (GitHub, Discord, Google); - lore-forge's private token signing keys. -The key is not stored in the data directory. `scripts/start.sh` keeps it in `run/secret.key` +The key is not stored in the data directory. A deployment from `deploy/` keeps it in +`/etc/lore-forge/secret.key` (root only). `scripts/start.sh` keeps it in `run/secret.key` (mode 600), next to the data directory `run/forge-data/` rather than inside it, and tells the operator to back it up separately. As in piki, losing it means provider secrets must be re-entered; here it also means new signing keys, which invalidates outstanding tokens and @@ -113,9 +115,20 @@ statuses. Full-text search can use SQLite's FTS5. ## Backups -- Back up the main database and the encryption key (stored separately). +Built (2026-11-26); see [deployment.md](deployment.md) and `deploy/README.md`. + +- `lore-forge backup-database ` writes a consistent copy of the main database with + `VACUUM INTO` while lore-forge runs. It opens the database read-only and without + migrations, so running it as root leaves no files the service cannot open. The copy is + integrity-checked before the command returns. +- `scripts/backup.sh` takes the database and `loreserver`'s store at the same moment. It + copies the store live, stops `loreserver`, copies again with the database, then restarts + `loreserver`. Backups are timestamped directories, hard-linked to the previous one. +- `scripts/restore.sh` puts one back, moving what it replaces aside. +- The encryption key is never in a backup; it is kept separately. - The render cache does not need backing up. -- Repository data is backed up through `loreserver`'s own storage. +- Verified by `scripts/e2e-lore.sh`: a revision pushed just before the backup is restored, and + one pushed after it is not. ## Open questions diff --git a/AGENTS.md b/AGENTS.md index c14079c..139c88f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,12 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on default the release pinned in `lore.lock`, fetched into `.lore/` by `scripts/fetch-lore.sh`. Set `LORE_BIN_DIR` to test another build, and `LORE_PORT`/`FORGE_PORT` to run it beside a deployment started by `scripts/start.sh`. Run it after any change to the issuer, registry or - directory, and whenever the Lore version moves. `SMOKE=1` stops after one login and push. + directory, the generated `loreserver` config, the backup scripts, and whenever the Lore + version moves. `SMOKE=1` stops after one login and push. + It runs loreserver over TLS (`lores://`) with a CA made for the run, trusted through + `SSL_CERT_FILE` by the lore commands, lore-forge and the desktop service only; `NO_TLS=1` + uses `lore://`. It ends with a backup, a push, and a restore through `scripts/backup.sh` and + `scripts/restore.sh`. It also drives the desktop `forge-service` through `scripts/desktop-e2e.py`, so run it after service changes too; `NO_DESKTOP=1` skips that. That part signs in a second user, bob, with a CLI working copy, to check locks and autosync between two users. The service logs at @@ -58,10 +63,12 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on | `crates/forge-id` | Secret key, passwords, signing keys and JWTs, users, sessions, the issuer (`src/issuer/`) | | `crates/forge-lore` | Vendored Lore protos (`proto/`), the gRPC directory and registry, generated `loreserver` config | | `crates/forge-web` | axum routes: issuer endpoints, pages (maud), CSRF and security headers | -| `crates/lore-forge` | The binary: `serve`, `loreserver-config`, `generate-secret-key`, `create-user` | +| `crates/lore-forge` | The binary: `serve`, `loreserver-config`, `generate-secret-key`, `create-user`, `rotate-signing-key`, `backup-database` | | `scripts/start.sh` | Starts a deployment from `run/` (git-ignored): settings, secret key, both servers | | `scripts/fetch-lore.sh`, `lore.lock` | Downloads the pinned Lore release into `.lore/` (git-ignored), checking SHA-256; `--liblore` fetches liblore and `lore.h` | | `scripts/e2e-lore.sh`, `scripts/desktop-e2e.py` | End-to-end test against real Lore, including the desktop service | +| `scripts/backup.sh`, `scripts/restore.sh` | Back up and restore the database and loreserver's store together | +| `deploy/` | Production on Linux: `install.sh`, systemd units, the Caddy site, the settings template, `README.md` for operators | | `desktop/` | The desktop client: `gui/` (C++ tray app), `service/` and `protocol/` (Rust), `lore-sys/` (liblore bindings; `gen/` regenerates them), `vendor/` (UHDK, Dear ImGui) | - [.ai/designs/](.ai/designs/) holds the design documents. Start with @@ -77,6 +84,7 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on | [web-ui.md](.ai/designs/web-ui.md) | Server-rendered UI stack and its security constraints | | [forge-features.md](.ai/designs/forge-features.md) | Repo browser, change requests, landing, activity | | [storage.md](.ai/designs/storage.md) | SQLite, the data directory, tables | +| [deployment.md](.ai/designs/deployment.md) | Production on Linux: TLS, Caddy, systemd, backups | | [desktop-client.md](.ai/designs/desktop-client.md) | The desktop client: service, GUI, TUI, their protocol, liblore, UHDK | ## Working on the design diff --git a/Cargo.lock b/Cargo.lock index 2bbcac9..b719f64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -387,6 +387,22 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpubits" version = "0.1.1" @@ -1468,6 +1484,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "p256" version = "0.14.0" @@ -1982,6 +2004,7 @@ version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ + "log", "once_cell", "ring", "rustls-pki-types", @@ -1990,6 +2013,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" @@ -2023,6 +2058,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -2043,6 +2087,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "serde" version = "1.0.229" @@ -2605,9 +2672,11 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", + "rustls-native-certs", "socket2", "sync_wrapper", "tokio", + "tokio-rustls", "tokio-stream", "tokio-util", "tower", diff --git a/crates/forge-lore/Cargo.toml b/crates/forge-lore/Cargo.toml index b810b77..44a57d9 100644 --- a/crates/forge-lore/Cargo.toml +++ b/crates/forge-lore/Cargo.toml @@ -15,7 +15,7 @@ reqwest.workspace = true thiserror.workspace = true tokio.workspace = true tokio-stream.workspace = true -tonic = { workspace = true, features = ["channel"] } +tonic = { workspace = true, features = ["channel", "tls-ring", "tls-native-roots"] } tonic-prost.workspace = true tonic-types.workspace = true tracing.workspace = true diff --git a/crates/forge-lore/src/lib.rs b/crates/forge-lore/src/lib.rs index 665f658..da1742e 100644 --- a/crates/forge-lore/src/lib.rs +++ b/crates/forge-lore/src/lib.rs @@ -11,6 +11,8 @@ //! It also renders the `loreserver` configuration that points Lore at lore-forge, and reads //! repositories from `loreserver` for the web UI ([`reader`]). +use std::path::Path; +use std::path::PathBuf; use std::pin::Pin; use std::sync::Arc; @@ -221,12 +223,29 @@ fn hex_to_bytes(hex: &str) -> Option> { .collect() } -/// The `loreserver` settings that make it trust lore-forge: verify lore-forge's tokens with -/// per-repository authorization, advertise lore-forge as the OIDC issuer, and use -/// lore-forge as the user directory and repository registry. -pub fn loreserver_config(config: &forge_id::IssuerConfig) -> String { +/// Where and how `loreserver` runs, beyond trusting lore-forge. +#[derive(Clone, Debug, Default)] +pub struct LoreserverSettings { + /// The directory for the immutable and mutable stores. Without one, `loreserver` keeps them + /// in the system temporary directory, which a reboot can clear. + pub store: Option, + /// PEM certificate and key for the public QUIC and gRPC endpoints. Without them QUIC uses a + /// self-signed certificate made at each start, and gRPC is plaintext, which is fine only on + /// one machine. + pub tls: Option<(PathBuf, PathBuf)>, + /// The QUIC (UDP) and gRPC (TCP) port, 41337 by default. + pub port: Option, + /// The HTTP port, 41339 by default. It is plaintext and bound to loopback. + pub http_port: Option, +} + +/// The `loreserver` configuration: trust lore-forge's tokens with per-repository +/// authorization, advertise lore-forge as the OIDC issuer, user directory and repository +/// registry, and place the stores and certificates `settings` names. +pub fn loreserver_config(config: &forge_id::IssuerConfig, settings: &LoreserverSettings) -> String { let quote = |value: &str| format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")); - format!( + let path = |path: &Path| quote(&path.to_string_lossy()); + let mut toml = format!( "# Generated by lore-forge. Merge into loreserver's configuration.\n\ # loreserver fetches lore-forge's signing keys at startup, so start lore-forge first.\n\ \n\ @@ -247,7 +266,36 @@ pub fn loreserver_config(config: &forge_id::IssuerConfig) -> String { audience = quote(&config.lore_url), client_id = quote(&config.client_id), template = quote(&config.resource_template()), - ) + ); + let mut table = |name: &str, lines: &[String]| { + toml.push_str(&format!("\n[{name}]\n")); + for line in lines { + toml.push_str(line); + toml.push('\n'); + } + }; + if let Some(port) = settings.port { + table("server.quic", &[format!("port = {port}")]); + table("server.grpc", &[format!("port = {port}")]); + } + if let Some((cert, key)) = &settings.tls { + let files = [format!("cert_file = {}", path(cert)), format!("pkey_file = {}", path(key))]; + table("server.quic.certificate", &files); + table("server.grpc.certificate", &files); + } + // The HTTP endpoint has no TLS setting, and Lore clients do not use it: only lore-forge's + // repository browser reads file content there, from the same machine. + let mut http = vec!["host = \"127.0.0.1\"".to_owned()]; + if let Some(port) = settings.http_port { + http.push(format!("port = {port}")); + } + table("server.http", &http); + if let Some(store) = &settings.store { + table("immutable_store.local", &[format!("path = {}", path(store))]); + table("mutable_store.local", &[format!("path = {}", path(store))]); + } + table("telemetry.logger", &["format = \"text\"".to_owned()]); + toml } #[cfg(test)] @@ -267,10 +315,39 @@ mod tests { &"https://lore.example.com".parse().unwrap(), "lore-cli", ); - let toml = loreserver_config(&config); + let toml = loreserver_config(&config, &LoreserverSettings::default()); assert!(toml.contains("jwt_issuer = \"https://forge.example.com\"")); assert!(toml.contains("jwt_audience = [\"https://lore.example.com\"]")); assert!(toml.contains("resource_template = \"https://lore.example.com/partitions/{id}\"")); assert!(toml.contains("user_url = \"https://forge.example.com\"")); + assert!(toml.contains("[server.http]\nhost = \"127.0.0.1\"\n")); + assert!(!toml.contains("certificate")); + assert!(!toml.contains("_store")); + } + + #[test] + fn generated_config_places_stores_certificates_and_ports() { + let config = forge_id::IssuerConfig::new( + &"https://lore.example.com".parse().unwrap(), + &"https://lore.example.com".parse().unwrap(), + "lore-cli", + ); + let settings = LoreserverSettings { + store: Some("/var/lib/loreserver/store".into()), + tls: Some(("/etc/loreserver/tls/cert.pem".into(), "/etc/loreserver/tls/key \"x\".pem".into())), + port: Some(42337), + http_port: Some(42339), + }; + let toml = loreserver_config(&config, &settings); + for table in ["server.quic.certificate", "server.grpc.certificate"] { + assert!(toml.contains(&format!( + "[{table}]\ncert_file = \"/etc/loreserver/tls/cert.pem\"\npkey_file = \"/etc/loreserver/tls/key \\\"x\\\".pem\"\n" + ))); + } + assert!(toml.contains("[server.quic]\nport = 42337\n")); + assert!(toml.contains("[server.grpc]\nport = 42337\n")); + assert!(toml.contains("[server.http]\nhost = \"127.0.0.1\"\nport = 42339\n")); + assert!(toml.contains("[immutable_store.local]\npath = \"/var/lib/loreserver/store\"\n")); + assert!(toml.contains("[mutable_store.local]\npath = \"/var/lib/loreserver/store\"\n")); } } diff --git a/crates/forge-lore/src/reader.rs b/crates/forge-lore/src/reader.rs index 0b01417..47e3eec 100644 --- a/crates/forge-lore/src/reader.rs +++ b/crates/forge-lore/src/reader.rs @@ -18,6 +18,7 @@ use tokio_stream::StreamExt; use tonic::Request; use tonic::metadata::MetadataValue; use tonic::transport::Channel; +use tonic::transport::ClientTlsConfig; use tonic::transport::Endpoint; use crate::proto::lore::model::v1 as model; @@ -66,11 +67,18 @@ pub struct Lore { } impl Lore { - /// `grpc_url` is the public gRPC endpoint (`http://host:41337`), `content_url` the HTTP - /// endpoint (`http://host:41339`). Nothing connects until the first read. + /// `grpc_url` is the public gRPC endpoint (`http://host:41337`, or `https://` when it has a + /// certificate), `content_url` the HTTP endpoint (`http://127.0.0.1:41339`). Nothing + /// connects until the first read. pub fn new(grpc_url: &str, content_url: &str) -> Result { - let channel = Endpoint::from_shared(grpc_url.to_owned()) - .map_err(|error| format!("{grpc_url}: {error}"))? + let mut endpoint = Endpoint::from_shared(grpc_url.to_owned()).map_err(|error| format!("{grpc_url}: {error}"))?; + if endpoint.uri().scheme_str() == Some("https") { + // The system's roots, or the file `SSL_CERT_FILE` names, as for Lore's own clients. + endpoint = endpoint + .tls_config(ClientTlsConfig::new().with_native_roots()) + .map_err(|error| format!("{grpc_url}: {error}"))?; + } + let channel = endpoint .connect_timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(30)) .connect_lazy(); diff --git a/crates/forge-store/src/lib.rs b/crates/forge-store/src/lib.rs index 0184f58..dc4ac11 100644 --- a/crates/forge-store/src/lib.rs +++ b/crates/forge-store/src/lib.rs @@ -26,6 +26,8 @@ pub enum StoreError { Open(#[source] sqlx::Error), #[error("applying migrations: {0}")] Migrate(#[from] sqlx::migrate::MigrateError), + #[error("backing up the database: {0}")] + Backup(#[source] sqlx::Error), } /// The lore-forge database. @@ -67,6 +69,37 @@ impl Store { } } +/// Writes a consistent copy of the database in `data_dir` to `to`, which must not exist, +/// while lore-forge keeps running. The copy is a plain database file that can replace +/// [`DATABASE_FILE`] in a data directory, and is checked before this returns. +/// +/// The database is opened read-only and without migrations, so a backup run as another user +/// (root, from a timer) neither changes it nor leaves files the service cannot open. +pub async fn backup_database(data_dir: &Path, to: &Path) -> Result<(), StoreError> { + let read_only = |path: &Path| { + SqliteConnectOptions::from_str("sqlite:").map(|options| options.filename(path).read_only(true)) + }; + let source = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(read_only(&data_dir.join(DATABASE_FILE)).map_err(StoreError::Backup)?) + .await + .map_err(StoreError::Backup)?; + let vacuum = sqlx::query("VACUUM INTO ?").bind(to.to_string_lossy().into_owned()).execute(&source).await; + source.close().await; + vacuum.map_err(StoreError::Backup)?; + let copy = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(read_only(to).map_err(StoreError::Backup)?) + .await + .map_err(StoreError::Backup)?; + let check: Result<(String,), _> = sqlx::query_as("PRAGMA integrity_check").fetch_one(©).await; + copy.close().await; + match check.map_err(StoreError::Backup)? { + (ok,) if ok == "ok" => Ok(()), + (problem,) => Err(StoreError::Backup(sqlx::Error::Protocol(format!("the copy fails its integrity check: {problem}")))), + } +} + /// The current time in Unix seconds, the unit every table uses. pub fn now() -> i64 { SystemTime::now() @@ -148,6 +181,13 @@ pub mod testing { let store = Store::open(dir.path()).await.expect("open test store"); TestStore { store, _dir: dir } } + + impl TestStore { + /// The temporary directory the database lives in. + pub fn dir(&self) -> &std::path::Path { + self._dir.path() + } + } } #[cfg(test)] @@ -165,4 +205,22 @@ mod tests { assert!(names.iter().any(|name| name == expected), "{expected} missing"); } } + + #[tokio::test] + async fn backup_is_a_database_that_opens_with_the_same_rows() { + let store = super::testing::store().await; + super::set_setting(store.pool(), "signup", "invite").await.unwrap(); + let restored = store.dir().join("restored"); + std::fs::create_dir(&restored).unwrap(); + let copy = restored.join(super::DATABASE_FILE); + super::backup_database(store.dir(), ©).await.unwrap(); + assert!(super::backup_database(store.dir(), ©).await.is_err(), "overwrote a backup"); + let missing = store.dir().join("missing"); + assert!(super::backup_database(&missing, &missing.join("copy")).await.is_err(), "backed up nothing"); + assert!(!missing.exists(), "made a data directory"); + + super::set_setting(store.pool(), "signup", "open").await.unwrap(); + let copy = super::Store::open(&restored).await.unwrap(); + assert_eq!(super::setting(copy.pool(), "signup").await.unwrap().as_deref(), Some("invite")); + } } diff --git a/crates/forge-web/src/lib.rs b/crates/forge-web/src/lib.rs index 9354988..f5e678c 100644 --- a/crates/forge-web/src/lib.rs +++ b/crates/forge-web/src/lib.rs @@ -35,18 +35,35 @@ struct Inner { oauth: OAuth, lore: forge_lore::reader::Lore, limiter: limiter::Limiter, + /// The remote Lore clients use, for instructions. + lore_remote: String, /// `scheme://host[:port]` of the canonical URL, for checking `Origin`. public_origin: String, secure_cookies: bool, } impl AppState { - pub fn new(pool: SqlitePool, issuer: Arc, oauth: OAuth, lore: forge_lore::reader::Lore) -> Self { + pub fn new( + pool: SqlitePool, + issuer: Arc, + oauth: OAuth, + lore: forge_lore::reader::Lore, + lore_remote: String, + ) -> Self { let public = url::Url::parse(&issuer.config().issuer).expect("issuer URL is a URL"); let public_origin = public.origin().ascii_serialization(); let secure_cookies = public.scheme() == "https"; AppState { - inner: Arc::new(Inner { pool, issuer, oauth, lore, limiter: limiter::Limiter::default(), public_origin, secure_cookies }), + inner: Arc::new(Inner { + pool, + issuer, + oauth, + lore, + lore_remote, + limiter: limiter::Limiter::default(), + public_origin, + secure_cookies, + }), } } @@ -74,6 +91,24 @@ impl AppState { fn limiter(&self) -> &limiter::Limiter { &self.inner.limiter } + + /// The remote Lore clients use, such as `lores://lore.example.com:41337`. + fn lore_remote(&self) -> &str { + &self.inner.lore_remote + } +} + +/// The Lore remote for a deployment whose Lore URL is `lore_url`: its host and any port under +/// `lores://`, which checks the server's certificate, or `lore://` for a loopback host, where +/// `loreserver` makes its own certificate. +pub fn default_lore_remote(lore_url: &str) -> String { + let Ok(url) = url::Url::parse(lore_url) else { return lore_url.to_owned() }; + let Some(host) = url.host_str() else { return lore_url.to_owned() }; + let scheme = if matches!(host, "localhost" | "127.0.0.1" | "[::1]") { "lore" } else { "lores" }; + match url.port() { + Some(port) => format!("{scheme}://{host}:{port}"), + None => format!("{scheme}://{host}"), + } } /// The routes this crate serves: the issuer's endpoints, the UI and the API. diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index a95c7e9..65cc4e3 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -344,17 +344,9 @@ pub fn browser(user_agent: &str) -> String { } } -/// The `lore://` remote of the configured Lore server. +/// The remote Lore clients use for the configured Lore server. pub fn lore_remote(state: &AppState) -> String { - let lore = &state.issuer().config().lore_url; - match url::Url::parse(lore) { - Ok(url) => match (url.host_str(), url.port()) { - (Some(host), Some(port)) => format!("lore://{host}:{port}"), - (Some(host), None) => format!("lore://{host}"), - _ => lore.clone(), - }, - Err(_) => lore.clone(), - } + state.lore_remote().to_owned() } // Static files ------------------------------------------------------------------------------ diff --git a/crates/forge-web/src/tests.rs b/crates/forge-web/src/tests.rs index d612f40..707af6c 100644 --- a/crates/forge-web/src/tests.rs +++ b/crates/forge-web/src/tests.rs @@ -43,7 +43,8 @@ async fn build(provider_base: Option<&str>, lore: forge_lore::reader::Lore) -> A if let Some(base) = provider_base { oauth = oauth.with_test_base(base); } - App { router: super::router(super::AppState::new(pool, issuer, oauth, lore)), store } + let remote = super::default_lore_remote(&issuer.config().lore_url); + App { router: super::router(super::AppState::new(pool, issuer, oauth, lore, remote)), store } } struct Reply { @@ -639,3 +640,12 @@ async fn the_browser_reports_an_unreachable_lore_server() { assert_eq!(reply.status, StatusCode::BAD_GATEWAY); assert!(reply.body.contains("Could not read the repository from the Lore server"), "{}", reply.body); } + +#[test] +fn lore_remote_checks_certificates_except_on_loopback() { + use super::default_lore_remote as remote; + assert_eq!(remote("https://lore.example.com"), "lores://lore.example.com"); + assert_eq!(remote("https://lore.example.com:41337"), "lores://lore.example.com:41337"); + assert_eq!(remote("https://localhost"), "lore://localhost"); + assert_eq!(remote("https://127.0.0.1:42337"), "lore://127.0.0.1:42337"); +} diff --git a/crates/lore-forge/src/main.rs b/crates/lore-forge/src/main.rs index ee15f48..593fb02 100644 --- a/crates/lore-forge/src/main.rs +++ b/crates/lore-forge/src/main.rs @@ -34,7 +34,7 @@ enum Command { /// Run the server. Serve(ServeArgs), /// Print the loreserver configuration that makes Lore trust this lore-forge. - LoreserverConfig(Urls), + LoreserverConfig(LoreserverConfigArgs), /// Print a new secret key for LORE_FORGE_SECRET_KEY. GenerateSecretKey, /// Create an account directly in the database, reading its password from standard input. @@ -42,6 +42,75 @@ enum Command { /// Make a new token signing key current. The previous key keeps verifying; the one before /// it is retired. A running server picks the change up within a minute. RotateSigningKey(DataDir), + /// Write a consistent copy of the database to a new file while the server runs. + BackupDatabase(BackupArgs), +} + +#[derive(Args)] +struct LoreserverConfigArgs { + #[command(flatten)] + urls: Urls, + /// The directory for loreserver's repository stores. Without it they go to the system + /// temporary directory, which a reboot can clear. + #[arg(long, env = "LORE_FORGE_LORESERVER_STORE")] + store: Option, + /// PEM certificate for loreserver's QUIC and gRPC endpoints, for the host in the Lore URL. + #[arg(long, env = "LORE_FORGE_LORESERVER_TLS_CERT", requires = "tls_key")] + tls_cert: Option, + /// The certificate's PEM private key. + #[arg(long, env = "LORE_FORGE_LORESERVER_TLS_KEY", requires = "tls_cert")] + tls_key: Option, + /// loreserver's QUIC and gRPC port (default 41337). + #[arg(long)] + port: Option, + /// loreserver's HTTP port (default 41339), bound to loopback. + #[arg(long)] + http_port: Option, + /// Write the configuration to this file instead of standard output. + #[arg(long)] + output: Option, +} + +fn loreserver_config(args: LoreserverConfigArgs) -> anyhow::Result<()> { + let settings = forge_lore::LoreserverSettings { + store: args.store, + tls: args.tls_cert.zip(args.tls_key), + port: args.port, + http_port: args.http_port, + }; + let toml = forge_lore::loreserver_config(&args.urls.issuer_config()?, &settings); + match args.output { + None => print!("{toml}"), + Some(path) => { + // Replaced whole, so loreserver never reads half a file. + let partial = path.with_extension("toml.partial"); + std::fs::write(&partial, toml).with_context(|| format!("writing {}", partial.display()))?; + std::fs::rename(&partial, &path).with_context(|| format!("writing {}", path.display()))?; + } + } + Ok(()) +} + +#[derive(Args)] +struct BackupArgs { + /// Where the database lives. + #[arg(long, env = "LORE_FORGE_DATA_DIR", default_value = "./data")] + data_dir: PathBuf, + /// The file to write. It must not exist yet. + to: PathBuf, +} + +async fn backup_database(args: BackupArgs) -> anyhow::Result<()> { + if args.to.exists() { + bail!("{} already exists", args.to.display()); + } + let database = args.data_dir.join(forge_store::DATABASE_FILE); + if !database.is_file() { + bail!("there is no database at {}", database.display()); + } + forge_store::backup_database(&args.data_dir, &args.to).await?; + println!("wrote {}", args.to.display()); + Ok(()) } #[derive(Args)] @@ -144,6 +213,11 @@ struct ServeArgs { /// loreserver's HTTP endpoint, from which the repository browser reads file content. #[arg(long, env = "LORE_FORGE_LORE_HTTP_URL", default_value = "http://127.0.0.1:41339")] lore_http_url: String, + /// The remote Lore clients use, shown in clone and login instructions, such as + /// `lores://lore.example.com:41337`. By default derived from the Lore URL: `lores://`, or + /// `lore://` for a loopback host. + #[arg(long, env = "LORE_FORGE_LORE_REMOTE")] + lore_remote: Option, } /// Whether a request is gRPC, which goes to Lore's directory services rather than the web @@ -157,12 +231,25 @@ fn is_grpc(request: &axum::extract::Request) -> bool { .is_some_and(|value| value.starts_with("application/grpc")) } +/// The key that encrypts the token signing keys: `LORE_FORGE_SECRET_KEY`, the file +/// `LORE_FORGE_SECRET_KEY_FILE` names, or the systemd credential `secret-key`. fn secret_key() -> anyhow::Result { - let text = std::env::var("LORE_FORGE_SECRET_KEY").context( - "LORE_FORGE_SECRET_KEY is not set. It encrypts the token signing keys; create one with \ - `lore-forge generate-secret-key` and keep it outside the data directory", - )?; - SecretKey::from_base64(&text).context("LORE_FORGE_SECRET_KEY") + if let Ok(text) = std::env::var("LORE_FORGE_SECRET_KEY") { + return SecretKey::from_base64(text.trim()).context("LORE_FORGE_SECRET_KEY"); + } + let file = std::env::var_os("LORE_FORGE_SECRET_KEY_FILE").map(PathBuf::from).or_else(|| { + std::env::var_os("CREDENTIALS_DIRECTORY").map(|dir| PathBuf::from(dir).join("secret-key")) + }); + if let Some(path) = file { + let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?; + return SecretKey::from_base64(text.trim()).with_context(|| format!("the secret key in {}", path.display())); + } + bail!( + "neither LORE_FORGE_SECRET_KEY nor LORE_FORGE_SECRET_KEY_FILE is set, and there is no \ + systemd credential `secret-key`. The key encrypts the \ + token signing keys; create one with `lore-forge generate-secret-key` and keep it outside \ + the data directory" + ) } async fn serve(args: ServeArgs) -> anyhow::Result<()> { @@ -190,7 +277,8 @@ async fn serve(args: ServeArgs) -> anyhow::Result<()> { let grpc = Directory::new(pool.clone(), issuer.clone()).routes().into_axum_router(); let lore = forge_lore::reader::Lore::new(&args.lore_grpc_url, &args.lore_http_url).map_err(anyhow::Error::msg)?; - let web = forge_web::router(forge_web::AppState::new(pool, issuer.clone(), oauth, lore)); + let remote = args.lore_remote.unwrap_or_else(|| forge_web::default_lore_remote(&issuer.config().lore_url)); + let web = forge_web::router(forge_web::AppState::new(pool, issuer.clone(), oauth, lore, remote)); let app = axum::Router::new() .fallback_service(tower::service_fn(move |request: axum::extract::Request| { let target = if is_grpc(&request) { grpc.clone() } else { web.clone() }; @@ -209,13 +297,37 @@ async fn serve(args: ServeArgs) -> anyhow::Result<()> { ); axum::serve(listener, app) .with_graceful_shutdown(async { - let _ = tokio::signal::ctrl_c().await; + stop_signal().await; tracing::info!("shutting down"); }) .await?; Ok(()) } +/// Ctrl-C, or SIGTERM, which service managers send. +async fn stop_signal() { + #[cfg(unix)] + { + use tokio::signal::unix::SignalKind; + use tokio::signal::unix::signal; + match signal(SignalKind::terminate()) { + Ok(mut term) => { + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = term.recv() => {} + } + } + Err(_) => { + let _ = tokio::signal::ctrl_c().await; + } + } + } + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; + } +} + #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() @@ -226,15 +338,13 @@ async fn main() -> anyhow::Result<()> { .init(); match Cli::parse().command { Command::Serve(args) => serve(args).await, - Command::LoreserverConfig(urls) => { - print!("{}", forge_lore::loreserver_config(&urls.issuer_config()?)); - Ok(()) - } + Command::LoreserverConfig(args) => loreserver_config(args), Command::GenerateSecretKey => { println!("{}", SecretKey::generate_base64()); Ok(()) } Command::CreateUser(args) => create_user(args).await, Command::RotateSigningKey(args) => rotate_signing_key(args).await, + Command::BackupDatabase(args) => backup_database(args).await, } } diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..b643227 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,130 @@ +# Deploying lore-forge + +This sets up lore-forge and an unmodified `loreserver` on one Linux machine with systemd, +behind Caddy, under one public hostname with a Let's Encrypt certificate. Design notes are in +[../.ai/designs/deployment.md](../.ai/designs/deployment.md). + +``` + browsers, Lore CLI ──443/tcp──▶ Caddy ──h2c──▶ lore-forge 127.0.0.1:8080 + (lores://host:41337) ▲ keys, registry, names + Lore CLI, desktop ──41337 udp+tcp, TLS──▶ loreserver ┘ (via https://host) + └ 127.0.0.1:41339 (file content, for lore-forge) +``` + +Status: the units and `install.sh` are written to this design but **not yet run on a Linux +machine**. What they wire together is tested on macOS by `scripts/e2e-lore.sh`: QUIC and gRPC +over TLS with an EC key in the form Caddy writes, `lores://` clients, the browser reading over +TLS, and a backup and restore. + +## Before you start + +- A Linux server (x86_64 or aarch64) with systemd 247 or later: Debian 12, Ubuntu 22.04 or + newer. +- A DNS name pointing at it, for example `lore.example.com`. The server must be able to reach + itself at that name, since loreserver fetches lore-forge's keys through Caddy. Where the + network does not loop back, add `127.0.0.1 lore.example.com` to `/etc/hosts`. +- Ports 80/tcp and 443/tcp (Caddy, including certificate issuance) and 41337/tcp and + 41337/udp (loreserver) open to your users. +- Caddy from its package (), rsync, and to build: + Rust, `protoc`, curl and tar. + +## Install + +As your own user, in a checkout of this repository on the server: + +```bash +cargo build --release -p lore-forge +scripts/fetch-lore.sh +``` + +Then as root: + +```bash +sudo deploy/install.sh lore.example.com you@example.com +``` + +It installs: + +| Path | What | +| --- | --- | +| `/opt/lore-forge/bin/` | `lore-forge`, the pinned `loreserver` and `lore`, `lore-forge-certs` | +| `/opt/lore-forge/scripts/` | `backup.sh`, `restore.sh` | +| `/etc/lore-forge/lore-forge.env` | Settings for both services, written once from [lore-forge.env](lore-forge.env) | +| `/etc/lore-forge/secret.key` | The key that encrypts the token signing keys (root only, handed to lore-forge as a systemd credential) | +| `/etc/loreserver/tls/` | loreserver's copy of Caddy's certificate | +| `/etc/caddy/lore-forge.caddy` | The Caddy site, imported from `/etc/caddy/Caddyfile` | +| `/var/lib/lore-forge/` | lore-forge's database | +| `/var/lib/loreserver/store/` | Every repository's data | +| `/var/backups/lore-forge/` | Nightly backups | + +**Copy `/etc/lore-forge/secret.key` somewhere safe and separate now.** Without it a backup +cannot be restored, and with it and the database anyone can mint access to every repository. + +Then open `https://lore.example.com` to create the owner account, and sign the CLI in: + +```bash +lore auth login lores://lore.example.com:41337 +``` + +Clone URLs on the forge's pages use the `lores://` remote. Never give people a `lore://` +remote: it accepts any certificate and sends tokens over unencrypted gRPC. + +## How the pieces start + +- `lore-forge.service` runs `lore-forge serve` as the `lore-forge` user. +- `loreserver.service` runs as `loreserver`. Before each start it copies Caddy's certificate + (`lore-forge-certs`) and writes its configuration with `lore-forge loreserver-config`, so the + TLS, store and trust settings come from one tested place. Until Caddy has obtained the first + certificate, the start fails and systemd retries every 10 seconds. +- `lore-forge-certs.path` notices Caddy renewing the certificate and restarts loreserver. +- `lore-forge-backup.timer` runs the backup at 04:30. + +Restarting lore-forge leaves loreserver running. Restarting loreserver, for an upgrade, a +certificate renewal or a backup, **releases every file lock**: Lore keeps locks in memory. + +## Backups + +`scripts/backup.sh` copies loreserver's store while it runs, stops loreserver for a second +copy of what changed and for a snapshot of the database, and starts it again; the outage is +usually seconds. Each backup is a directory under `/var/backups/lore-forge/`, with unchanged +store files hard-linked to the previous one. It keeps 14 (`KEEP`). + +- Copy `/var/backups/lore-forge` off the machine (rsync, restic, rclone). A backup on the same + disk does not survive the disk. +- The secret key is not in the backups, on purpose; keep it apart. +- Run one by hand with `systemctl start lore-forge-backup`, and see past runs with + `journalctl -u lore-forge-backup`. + +### Restoring + +```bash +sudo systemctl stop loreserver lore-forge +sudo /opt/lore-forge/scripts/restore.sh /var/backups/lore-forge/latest +sudo systemctl start lore-forge loreserver +``` + +The current database and store are moved aside (`*.before-restore-