Harden lore-forge for a production deployment

TLS on every Lore port, a Linux deployment behind Caddy, and backups.

- lore-forge loreserver-config writes loreserver's whole config:
  the certificate on QUIC and gRPC, store paths, ports, and the HTTP
  port bound to 127.0.0.1. --output writes it atomically. start.sh,
  the e2e test and the systemd units all use it.
- The repository browser reaches Lore's gRPC over TLS for https URLs.
  Pages show lores:// remotes (lore:// for loopback hosts), with
  LORE_FORGE_LORE_REMOTE to override.
- serve stops cleanly on SIGTERM, and reads the secret key from
  LORE_FORGE_SECRET_KEY_FILE or a systemd credential as well.
- backup-database snapshots the database with VACUUM INTO on a
  read-only connection and checks the copy.
- scripts/backup.sh copies the store live, stops loreserver briefly to
  copy it again with the database, and keeps hard-linked snapshots.
  scripts/restore.sh puts one back and moves the current state aside.
- deploy/: install.sh, systemd units for lore-forge, loreserver,
  certificate copying and nightly backups, the Caddy site, the
  settings template and an operator README. Not yet run on Linux.
- e2e: TLS by default with a CA made for the run (NO_TLS=1 for
  lore://); untrusting and lore:// clients are refused; ends with a
  backup, a push and a restore.
- Docs: deployment.md, Lore's transport security, backups in storage,
  and the overview's decisions and status.
This commit is contained in:
Peterino 2026-11-26 17:20:53 -07:00
parent 0e8e4a601a
commit 695bc5f141
29 changed files with 1349 additions and 112 deletions

View File

@ -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

84
.ai/designs/deployment.md Normal file
View File

@ -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://<Lore URL host>`, 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/<host>/`.
- 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.

View File

@ -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

View File

@ -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 <file>` 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

View File

@ -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

69
Cargo.lock generated
View File

@ -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",

View File

@ -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

View File

@ -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<Vec<u8>> {
.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<PathBuf>,
/// 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<u16>,
/// The HTTP port, 41339 by default. It is plaintext and bound to loopback.
pub http_port: Option<u16>,
}
/// 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"));
}
}

View File

@ -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<Self, String> {
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();

View File

@ -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(&copy).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(), &copy).await.unwrap();
assert!(super::backup_database(store.dir(), &copy).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"));
}
}

View File

@ -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<Issuer>, oauth: OAuth, lore: forge_lore::reader::Lore) -> Self {
pub fn new(
pool: SqlitePool,
issuer: Arc<Issuer>,
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.

View File

@ -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 ------------------------------------------------------------------------------

View File

@ -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");
}

View File

@ -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<PathBuf>,
/// 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<PathBuf>,
/// The certificate's PEM private key.
#[arg(long, env = "LORE_FORGE_LORESERVER_TLS_KEY", requires = "tls_cert")]
tls_key: Option<PathBuf>,
/// loreserver's QUIC and gRPC port (default 41337).
#[arg(long)]
port: Option<u16>,
/// loreserver's HTTP port (default 41339), bound to loopback.
#[arg(long)]
http_port: Option<u16>,
/// Write the configuration to this file instead of standard output.
#[arg(long)]
output: Option<PathBuf>,
}
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<String>,
}
/// 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<SecretKey> {
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,
}
}

130
deploy/README.md Normal file
View File

@ -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 (<https://caddyserver.com/docs/install>), 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-<time>`), not deleted.
Everything after the backup is gone, and people whose login began or refreshed after it sign
in again. The secret key must be the one in use when the backup was made.
Try a restore once on a spare machine before relying on the backups.
## Upgrading
Pull, rebuild, and run the installer again; it keeps the settings, the key and the data:
```bash
git pull && cargo build --release -p lore-forge && scripts/fetch-lore.sh
sudo deploy/install.sh lore.example.com
```
Moving to a new Lore release changes the format loreserver keeps on disk. Back up first, and
try the new release on a copy of the store before upgrading the real one.
## Checking on it
```bash
systemctl status lore-forge loreserver caddy
journalctl -u loreserver -f
systemctl list-timers lore-forge-backup
```

126
deploy/install.sh Normal file
View File

@ -0,0 +1,126 @@
#!/usr/bin/env bash
# Installs or upgrades lore-forge and loreserver as systemd services on Linux, behind Caddy.
#
# sudo deploy/install.sh <hostname> [<email for Let's Encrypt>]
#
# Run it from a checkout of this repository on the server, after building and fetching as your
# own user:
#
# cargo build --release -p lore-forge
# scripts/fetch-lore.sh
#
# It installs the binaries and scripts under /opt/lore-forge, creates the `lore-forge` and
# `loreserver` system users, writes /etc/lore-forge/lore-forge.env and the secret key if they
# do not exist yet, installs the units and Caddy's site, and (re)starts everything. Running it
# again upgrades the binaries and units and keeps the settings, the key and all data.
# deploy/README.md describes the whole setup.
set -euo pipefail
say() { echo "install: $*" >&2; }
die() { say "$*"; exit 1; }
[ "$(uname -s)" = Linux ] || die "this installs systemd services on Linux"
[ "$(id -u)" = 0 ] || die "run it as root: sudo $0 $*"
[ $# -ge 1 ] && [ $# -le 2 ] || die "usage: $0 <hostname> [<email for Let's Encrypt>]"
HOST=$1
EMAIL=${2:-}
case "$HOST" in
*[!A-Za-z0-9.-]* | .* | *. | '') die "$HOST is not a hostname" ;;
localhost | *.local) die "use a public hostname that Let's Encrypt can reach" ;;
esac
command -v systemctl >/dev/null || die "systemd is required"
command -v caddy >/dev/null || die "install Caddy first: https://caddyserver.com/docs/install"
command -v rsync >/dev/null || die "install rsync first (the nightly backup needs it)"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
FORGE_BUILD="$ROOT/target/release/lore-forge"
[ -x "$FORGE_BUILD" ] || die "build lore-forge first, as your user: cargo build --release -p lore-forge"
# Prints the directory of the pinned, checksummed release, fetching it only if it is missing.
LORE_DIR="$(sudo -u "${SUDO_USER:-root}" "$ROOT/scripts/fetch-lore.sh")" || die "scripts/fetch-lore.sh failed"
for bin in lore loreserver; do [ -x "$LORE_DIR/$bin" ] || die "no $bin in $LORE_DIR"; done
ENV_FILE=/etc/lore-forge/lore-forge.env
if [ -f "$ENV_FILE" ]; then
current=$(sed -n 's/^LORE_FORGE_HOST=//p' "$ENV_FILE")
[ "$current" = "$HOST" ] || die "$ENV_FILE is for $current, not $HOST. The public URL must not change once people have logged in; edit the file by hand if you mean it"
fi
say "users"
for user in lore-forge loreserver; do
id "$user" >/dev/null 2>&1 || useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin "$user"
done
say "binaries and scripts in /opt/lore-forge"
install -d -m 0755 /opt/lore-forge /opt/lore-forge/bin /opt/lore-forge/scripts
install -m 0755 "$FORGE_BUILD" /opt/lore-forge/bin/lore-forge.new
install -m 0755 "$LORE_DIR/loreserver" /opt/lore-forge/bin/loreserver.new
install -m 0755 "$LORE_DIR/lore" /opt/lore-forge/bin/lore.new
for bin in lore-forge loreserver lore; do mv -f "/opt/lore-forge/bin/$bin.new" "/opt/lore-forge/bin/$bin"; done
install -m 0755 "$ROOT/deploy/lore-forge-certs" /opt/lore-forge/bin/lore-forge-certs
install -m 0755 "$ROOT/scripts/backup.sh" "$ROOT/scripts/restore.sh" /opt/lore-forge/scripts/
install -m 0644 "$ROOT/deploy/README.md" /opt/lore-forge/README.md
ln -sfn /opt/lore-forge/bin/lore /usr/local/bin/lore
say "settings in /etc/lore-forge"
install -d -m 0755 /etc/lore-forge
if [ ! -f "$ENV_FILE" ]; then
sed "s/@HOST@/$HOST/g" "$ROOT/deploy/lore-forge.env" >"$ENV_FILE"
chmod 0644 "$ENV_FILE"
say "wrote $ENV_FILE"
fi
if [ ! -s /etc/lore-forge/secret.key ]; then
(umask 077 && /opt/lore-forge/bin/lore-forge generate-secret-key >/etc/lore-forge/secret.key)
say "generated /etc/lore-forge/secret.key. COPY IT SOMEWHERE SAFE, apart from the backups:"
say "a restore needs it, and nothing else can decrypt the token signing keys"
fi
chown root:root /etc/lore-forge/secret.key
chmod 0400 /etc/lore-forge/secret.key
install -d -m 0750 -o root -g loreserver /etc/loreserver /etc/loreserver/tls
install -d -m 0700 /var/backups/lore-forge
say "systemd units"
CADDY_CERTIFICATES=$(sed -n 's/^CADDY_CERTIFICATES=//p' "$ENV_FILE")
for unit in lore-forge.service loreserver.service lore-forge-certs.service lore-forge-backup.service lore-forge-backup.timer; do
install -m 0644 "$ROOT/deploy/systemd/$unit" "/etc/systemd/system/$unit"
done
sed "s|@CERT@|$CADDY_CERTIFICATES/$HOST/$HOST.crt|" "$ROOT/deploy/systemd/lore-forge-certs.path" \
>/etc/systemd/system/lore-forge-certs.path
systemctl daemon-reload
say "Caddy site"
if [ -n "$EMAIL" ]; then email_line="email $EMAIL"; else email_line="# no email given"; fi
sed -e "s/@HOST@/$HOST/g" -e "s/@EMAIL@/$email_line/" "$ROOT/deploy/lore-forge.caddy" >/etc/caddy/lore-forge.caddy
if ! grep -qxF "import /etc/caddy/lore-forge.caddy" /etc/caddy/Caddyfile 2>/dev/null; then
printf '\nimport /etc/caddy/lore-forge.caddy\n' >>/etc/caddy/Caddyfile
say "added an import of /etc/caddy/lore-forge.caddy to /etc/caddy/Caddyfile"
fi
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null || die "Caddy rejects /etc/caddy/Caddyfile"
say "starting"
systemctl enable caddy lore-forge.service loreserver.service lore-forge-certs.path lore-forge-backup.timer >/dev/null
systemctl reload-or-restart caddy
systemctl restart lore-forge.service
for _ in $(seq 1 50); do
curl -fsS http://127.0.0.1:8080/.well-known/openid-configuration >/dev/null 2>&1 && break
sleep 0.2
done
curl -fsS http://127.0.0.1:8080/.well-known/openid-configuration >/dev/null 2>&1 \
|| die "lore-forge did not start: journalctl -u lore-forge"
systemctl start lore-forge-certs.path
# Until Caddy has the certificate loreserver fails to start and systemd retries every 10 s.
systemctl restart loreserver.service || true
cat >&2 <<EOF
lore-forge is installed for $HOST.
- Open these ports: 80/tcp and 443/tcp (Caddy), 41337/tcp and 41337/udp (loreserver).
With ufw: ufw allow 80,443/tcp && ufw allow 41337
- Check loreserver once Caddy has its certificate: systemctl status loreserver
- Open https://$HOST to create the owner account (first visit only).
- Sign the Lore CLI in: lore auth login lores://$HOST:41337
- Backups run nightly into /var/backups/lore-forge (systemctl list-timers lore-forge-backup).
Copy them off this machine, and keep /etc/lore-forge/secret.key somewhere else again.
EOF

30
deploy/lore-forge-certs Executable file
View File

@ -0,0 +1,30 @@
#!/bin/sh
# Copies Caddy's certificate for LORE_FORGE_HOST to /etc/loreserver/tls, where loreserver reads
# it. loreserver.service runs this before each start; lore-forge-certs.path runs it, and
# restarts loreserver, when Caddy renews the certificate.
#
# Settings come from /etc/lore-forge/lore-forge.env: LORE_FORGE_HOST and CADDY_CERTIFICATES.
set -eu
ENV_FILE=/etc/lore-forge/lore-forge.env
if [ -z "${LORE_FORGE_HOST:-}" ] && [ -r "$ENV_FILE" ]; then
# Plain KEY=VALUE lines, as systemd reads them.
eval "$(grep -E '^(LORE_FORGE_HOST|CADDY_CERTIFICATES)=' "$ENV_FILE")"
fi
: "${LORE_FORGE_HOST:?set LORE_FORGE_HOST in $ENV_FILE}"
: "${CADDY_CERTIFICATES:?set CADDY_CERTIFICATES in $ENV_FILE}"
SOURCE="$CADDY_CERTIFICATES/$LORE_FORGE_HOST"
TARGET=/etc/loreserver/tls
if [ ! -s "$SOURCE/$LORE_FORGE_HOST.crt" ] || [ ! -s "$SOURCE/$LORE_FORGE_HOST.key" ]; then
echo "lore-forge-certs: Caddy has no certificate for $LORE_FORGE_HOST in $SOURCE yet" >&2
echo "lore-forge-certs: is the DNS record in place and ports 80 and 443 open? journalctl -u caddy" >&2
exit 1
fi
install -d -m 0750 -o root -g loreserver "$TARGET"
install -m 0644 -o root -g loreserver "$SOURCE/$LORE_FORGE_HOST.crt" "$TARGET/cert.pem.new"
install -m 0640 -o root -g loreserver "$SOURCE/$LORE_FORGE_HOST.key" "$TARGET/key.pem.new"
mv -f "$TARGET/cert.pem.new" "$TARGET/cert.pem"
mv -f "$TARGET/key.pem.new" "$TARGET/key.pem"
echo "lore-forge-certs: installed the certificate for $LORE_FORGE_HOST, $(openssl x509 -noout -enddate -in "$TARGET/cert.pem" 2>/dev/null || echo 'expiry unknown')"

16
deploy/lore-forge.caddy Normal file
View File

@ -0,0 +1,16 @@
# lore-forge behind Caddy, written by deploy/install.sh and imported from /etc/caddy/Caddyfile.
@HOST@ {
tls {
# Let's Encrypt with a P-256 key, so lore-forge-certs finds the certificate in
# CADDY_CERTIFICATES and loreserver can read the key.
issuer acme {
@EMAIL@
}
key_type p256
}
# HTTP/2 without TLS to lore-forge, so gRPC (Lore's user directory and registry) passes
# through with the pages. Streams are flushed as they come.
reverse_proxy h2c://127.0.0.1:8080 {
flush_interval -1
}
}

31
deploy/lore-forge.env Normal file
View File

@ -0,0 +1,31 @@
# lore-forge and loreserver settings, read by both systemd units and by lore-forge-certs.
# deploy/install.sh writes this file once, for the hostname it is given; it never overwrites it.
# The one public hostname. lore-forge's pages (443, through Caddy) and loreserver's QUIC and
# gRPC endpoints (41337, UDP and TCP) share it and its Let's Encrypt certificate.
LORE_FORGE_HOST=@HOST@
# lore-forge's canonical URL. It is the token issuer loreserver trusts and Lore's user
# directory, so it must not change once people have logged in.
LORE_FORGE_PUBLIC_URL=https://@HOST@
# The tokens' audience. Its host is the one Lore clients connect to.
LORE_FORGE_LORE_URL=https://@HOST@
# The remote people give the Lore CLI and the desktop client, shown on the forge's pages.
# lores:// checks the certificate; lore:// would send tokens unencrypted.
LORE_FORGE_LORE_REMOTE=lores://@HOST@:41337
# Where lore-forge listens; only Caddy reaches it.
LORE_FORGE_LISTEN=127.0.0.1:8080
# How lore-forge's repository browser reaches loreserver: gRPC over TLS by the public name,
# which the certificate covers, and file content over loopback HTTP.
LORE_FORGE_LORE_GRPC_URL=https://@HOST@:41337
LORE_FORGE_LORE_HTTP_URL=http://127.0.0.1:41339
# Where Caddy keeps the certificate it obtains for LORE_FORGE_HOST. lore-forge-certs copies it
# for loreserver from here.
CADDY_CERTIFICATES=/var/lib/caddy/.local/share/caddy/certificates/acme-v02.api.letsencrypt.org-directory
RUST_LOG=info,sqlx=warn,tower_http=info

View File

@ -0,0 +1,10 @@
[Unit]
Description=Back up lore-forge and loreserver
After=lore-forge.service loreserver.service
[Service]
Type=oneshot
# Stops loreserver for a few seconds; see the script.
ExecStart=/opt/lore-forge/scripts/backup.sh /var/backups/lore-forge
Nice=10
IOSchedulingClass=idle

View File

@ -0,0 +1,9 @@
[Unit]
Description=Back up lore-forge and loreserver every night
[Timer]
OnCalendar=*-*-* 04:30
Persistent=true
[Install]
WantedBy=timers.target

View File

@ -0,0 +1,10 @@
[Unit]
Description=Watch Caddy's certificate for lore-forge's host
[Path]
# deploy/install.sh fills in the path from CADDY_CERTIFICATES and LORE_FORGE_HOST.
PathChanged=@CERT@
Unit=lore-forge-certs.service
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,8 @@
[Unit]
Description=Hand Caddy's renewed certificate to loreserver
[Service]
Type=oneshot
# loreserver reads its certificate at startup, and its start copies the new one. A restart
# releases every file lock, which Lore keeps in memory; renewals come about every 60 days.
ExecStart=/bin/systemctl try-restart loreserver.service

View File

@ -0,0 +1,44 @@
[Unit]
Description=lore-forge: accounts, tokens and the forge for Lore
Documentation=file:///opt/lore-forge/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=lore-forge
Group=lore-forge
EnvironmentFile=/etc/lore-forge/lore-forge.env
Environment=LORE_FORGE_DATA_DIR=/var/lib/lore-forge
# The key that encrypts the token signing keys, handed over as a credential so the service
# user cannot read the file itself. lore-forge finds it in $CREDENTIALS_DIRECTORY.
LoadCredential=secret-key:/etc/lore-forge/secret.key
ExecStart=/opt/lore-forge/bin/lore-forge serve
Restart=on-failure
RestartSec=5
StateDirectory=lore-forge
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=yes
CapabilityBoundingSet=
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,54 @@
[Unit]
Description=loreserver (Lore), trusting lore-forge
Documentation=file:///opt/lore-forge/README.md
# loreserver fetches lore-forge's signing keys at startup, through Caddy at the public URL. It
# only wants lore-forge, so restarting lore-forge for an upgrade leaves loreserver, and the
# file locks it holds in memory, alone.
After=network-online.target lore-forge.service caddy.service
Wants=network-online.target lore-forge.service
# Until Caddy has its first certificate, starting fails; keep retrying.
StartLimitIntervalSec=0
[Service]
Type=simple
User=loreserver
Group=loreserver
EnvironmentFile=/etc/lore-forge/lore-forge.env
RuntimeDirectory=loreserver
StateDirectory=loreserver
StateDirectoryMode=0700
UMask=0077
# Copy Caddy's certificate (as root), then write the configuration that trusts lore-forge.
ExecStartPre=+/opt/lore-forge/bin/lore-forge-certs
ExecStartPre=/opt/lore-forge/bin/lore-forge loreserver-config \
--store /var/lib/loreserver/store \
--tls-cert /etc/loreserver/tls/cert.pem --tls-key /etc/loreserver/tls/key.pem \
--output /run/loreserver/forge.toml
ExecStart=/opt/lore-forge/bin/loreserver --config /run/loreserver --env forge
Restart=on-failure
RestartSec=10
# loreserver waits 5 s for connections and 25 s for its runtime after a stop signal.
TimeoutStopSec=45
LimitNOFILE=65536
NoNewPrivileges=yes
CapabilityBoundingSet=
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target

113
scripts/backup.sh Executable file
View File

@ -0,0 +1,113 @@
#!/usr/bin/env bash
# Backs up a lore-forge deployment: lore-forge's database and loreserver's repository store,
# taken at the same moment.
#
# scripts/backup.sh <backup directory>
#
# Each run writes <backup directory>/<UTC time>/ holding lore-forge.sqlite, lore-store/ and a
# MANIFEST, then points <backup directory>/latest at it. Store files that have not changed
# since the previous backup are hard links into it, so a run costs about what changed. Only the
# newest KEEP backups are kept.
#
# loreserver writes its store to disk in the background and has no documented way to copy it
# while it runs, so the store is copied once while loreserver runs, then loreserver is stopped
# for a second copy of what changed meanwhile and for the database, and started again. The
# outage lasts the second copy, usually seconds. Stopping loreserver releases every file lock,
# which Lore keeps only in memory.
#
# The secret key is not copied: keep it apart from these backups, since the database holds the
# token signing keys it encrypts. A restore needs both. See scripts/restore.sh.
#
# Settings, from the environment; the defaults match the layout deploy/install.sh makes:
#
# LORE_FORGE_DATA_DIR lore-forge's data directory /var/lib/lore-forge
# LORE_STORE loreserver's store /var/lib/loreserver/store
# LORE_FORGE_BIN the lore-forge binary /opt/lore-forge/bin/lore-forge
# LORESERVER_BIN loreserver, for its version /opt/lore-forge/bin/loreserver
# LORESERVER_STOP command that stops loreserver systemctl stop loreserver
# LORESERVER_START command that starts it systemctl start loreserver
# KEEP backups to keep 14
#
# Needs rsync.
set -euo pipefail
say() { echo "backup: $*" >&2; }
die() { say "$*"; exit 1; }
[ $# -eq 1 ] || die "usage: $0 <backup directory>"
DEST=$1
DATA_DIR="${LORE_FORGE_DATA_DIR:-/var/lib/lore-forge}"
STORE="${LORE_STORE:-/var/lib/loreserver/store}"
FORGE_BIN="${LORE_FORGE_BIN:-/opt/lore-forge/bin/lore-forge}"
LORESERVER_BIN="${LORESERVER_BIN:-/opt/lore-forge/bin/loreserver}"
STOP="${LORESERVER_STOP:-systemctl stop loreserver}"
START="${LORESERVER_START:-systemctl start loreserver}"
KEEP="${KEEP:-14}"
command -v rsync >/dev/null || die "rsync is not installed"
[ -x "$FORGE_BIN" ] || die "no lore-forge binary at $FORGE_BIN (set LORE_FORGE_BIN)"
[ -f "$DATA_DIR/lore-forge.sqlite" ] || die "no database in $DATA_DIR (set LORE_FORGE_DATA_DIR)"
[ -d "$STORE" ] || die "no loreserver store at $STORE (set LORE_STORE)"
case "$KEEP" in '' | *[!0-9]* | 0) die "KEEP must be a positive number" ;; esac
mkdir -p "$DEST"
DEST="$(cd "$DEST" && pwd)"
NAME="$(date -u +%Y%m%dT%H%M%SZ)"
[ ! -e "$DEST/$NAME" ] || die "$DEST/$NAME already exists"
# Written under a temporary name, so a failed run never looks like a backup.
PARTIAL="$DEST/.partial-$NAME"
rm -rf "$PARTIAL"
mkdir -p "$PARTIAL"
LINK=()
if [ -d "$DEST/latest/lore-store" ]; then
LINK=(--link-dest="$(cd "$DEST/latest/lore-store" && pwd)")
fi
copy_store() { rsync -a --delete ${LINK[@]+"${LINK[@]}"} "$STORE/" "$PARTIAL/lore-store/"; }
say "copying the store while loreserver runs"
copy_store
STOPPED=""
restart() {
if [ -n "$STOPPED" ]; then
say "starting loreserver"
sh -c "$START" || say "STARTING LORESERVER FAILED; start it by hand"
STOPPED=""
fi
}
trap 'restart; rm -rf "$PARTIAL"' EXIT
say "stopping loreserver"
STOPPED=1
sh -c "$STOP"
started=$(date +%s)
copy_store
"$FORGE_BIN" backup-database --data-dir "$DATA_DIR" "$PARTIAL/lore-forge.sqlite" >/dev/null
restart
say "loreserver was stopped for $(($(date +%s) - started)) s"
{
echo "backup $NAME"
echo "lore-forge $("$FORGE_BIN" --version | awk '{print $2}')"
if [ -x "$LORESERVER_BIN" ]; then echo "loreserver $("$LORESERVER_BIN" --version | awk '{print $2}')"; fi
echo "store $STORE"
echo "data $DATA_DIR"
} >"$PARTIAL/MANIFEST"
mv "$PARTIAL" "$DEST/$NAME"
trap - EXIT
ln -sfn "$NAME" "$DEST/latest.new" && mv -f "$DEST/latest.new" "$DEST/latest"
# The newest KEEP backups stay; names sort by time.
all=$(find "$DEST" -mindepth 1 -maxdepth 1 -type d -name '[0-9]*T[0-9]*Z' | sort)
count=$(printf '%s\n' "$all" | grep -c . || true)
if [ "$count" -gt "$KEEP" ]; then
for dir in $(printf '%s\n' "$all" | head -n $((count - KEEP))); do
say "removing old backup $(basename "$dir")"
rm -rf "$dir"
done
fi
echo "$DEST/$NAME"

View File

@ -21,6 +21,13 @@
# scripts/desktop-e2e.py: sign-in, clone, the explorer's reads, submit and sync, then locks,
# lock-on-edit and autosync against bob in his own working copy. NO_DESKTOP=1 skips that.
#
# loreserver serves QUIC and gRPC over TLS, as in a deployment, with a certificate for localhost
# from a CA made for the run; Lore's clients and lore-forge trust it through SSL_CERT_FILE and
# reach loreserver as lores://localhost. NO_TLS=1 uses lore:// and plaintext gRPC instead.
#
# Last, it backs the deployment up with scripts/backup.sh, pushes another revision, restores
# the backup with scripts/restore.sh and checks the repository is back as it was.
#
# HOLD=1 keeps both servers running after the browser checks, for a look at the pages.
#
# SMOKE=1 stops after one user's login, create and push.
@ -34,11 +41,11 @@ set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
LORE_BIN_DIR="${LORE_BIN_DIR:-$("$ROOT/scripts/fetch-lore.sh")}"
LORE="$LORE_BIN_DIR/lore"
LORE_CLI="$LORE"
LORESERVER="$LORE_BIN_DIR/loreserver"
FORGE_PORT="${FORGE_PORT:-18080}"
FORGE="http://localhost:$FORGE_PORT"
LORE_PORT="${LORE_PORT:-41337}"
LORE_REMOTE="lore://localhost:$LORE_PORT"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/lore-forge-e2e.XXXXXX")"
PIDS=()
export LORE_AUTH_STORE=fallback
@ -46,6 +53,13 @@ export LORE_AUTH_STORE=fallback
cleanup() {
local status=$?
for pid in ${PIDS[@]+"${PIDS[@]}"}; do kill "$pid" 2>/dev/null || true; done
# loreserver is not this shell's child, so `wait` does not cover it.
if [ -f "$WORK/loreserver.pid" ]; then
local lore_pid
lore_pid=$(cat "$WORK/loreserver.pid")
kill "$lore_pid" 2>/dev/null || true
for _ in $(seq 1 100); do kill -0 "$lore_pid" 2>/dev/null || break; sleep 0.1; done
fi
wait 2>/dev/null || true
if [ "$status" -ne 0 ]; then
echo "FAILED; logs and state kept in $WORK" >&2
@ -69,6 +83,38 @@ wait_for() {
fail "$what did not come up ($url)"
}
# The certificate is an EC key in SEC1 form ("EC PRIVATE KEY"), which is what Caddy writes for
# the Let's Encrypt certificates a deployment hands loreserver.
TRUST=()
TLS_ARGS=()
if [ -z "${NO_TLS:-}" ]; then
step "make a CA and a certificate for localhost"
TLS="$WORK/tls"
mkdir -p "$TLS" "$WORK/bin"
openssl ecparam -name prime256v1 -genkey -noout -out "$TLS/ca-key.pem"
openssl req -x509 -new -key "$TLS/ca-key.pem" -sha256 -days 2 -subj "/CN=lore-forge e2e CA" \
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" \
-out "$TLS/ca.pem" 2>/dev/null
openssl ecparam -name prime256v1 -genkey -noout -out "$TLS/key.pem"
openssl req -new -key "$TLS/key.pem" -subj "/CN=localhost" -out "$TLS/server.csr" 2>/dev/null
printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n' >"$TLS/ext.cnf"
openssl x509 -req -in "$TLS/server.csr" -CA "$TLS/ca.pem" -CAkey "$TLS/ca-key.pem" -CAcreateserial \
-days 2 -sha256 -extfile "$TLS/ext.cnf" -out "$TLS/cert.pem" 2>/dev/null
grep -q "BEGIN EC PRIVATE KEY" "$TLS/key.pem" || fail "openssl did not write a SEC1 key"
TRUST=(env "SSL_CERT_FILE=$TLS/ca.pem")
TLS_ARGS=(--tls-cert "$TLS/cert.pem" --tls-key "$TLS/key.pem")
# Every lore command trusts the run's CA; nothing else does, so builds still reach crates.io.
printf '#!/bin/sh\nSSL_CERT_FILE=%s exec %s "$@"\n' "$TLS/ca.pem" "$LORE_CLI" >"$WORK/bin/lore"
chmod +x "$WORK/bin/lore"
LORE="$WORK/bin/lore"
LORE_REMOTE="lores://localhost:$LORE_PORT"
export LORE_FORGE_LORE_GRPC_URL="https://localhost:$LORE_PORT"
else
LORE_REMOTE="lore://localhost:$LORE_PORT"
export LORE_FORGE_LORE_GRPC_URL="http://127.0.0.1:$LORE_PORT"
fi
export LORE_FORGE_LORE_REMOTE="$LORE_REMOTE"
step "build lore-forge"
cargo build --quiet --manifest-path "$ROOT/Cargo.toml" -p lore-forge
FORGE_BIN="$ROOT/target/debug/lore-forge"
@ -77,13 +123,17 @@ export LORE_FORGE_SECRET_KEY="$("$FORGE_BIN" generate-secret-key)"
export LORE_FORGE_PUBLIC_URL="$FORGE"
export LORE_FORGE_LORE_URL="https://localhost"
export LORE_FORGE_DATA_DIR="$WORK/forge-data"
export LORE_FORGE_LORE_GRPC_URL="http://127.0.0.1:$LORE_PORT"
export LORE_FORGE_LORE_HTTP_URL="http://127.0.0.1:$((LORE_PORT + 2))"
start_forge() {
${TRUST[@]+"${TRUST[@]}"} "$FORGE_BIN" serve --listen "127.0.0.1:$FORGE_PORT" >>"$WORK/forge.log" 2>&1 &
FORGE_PID=$!
PIDS+=("$FORGE_PID")
wait_for lore-forge "$FORGE/.well-known/openid-configuration"
}
step "start lore-forge on $FORGE"
"$FORGE_BIN" serve --listen "127.0.0.1:$FORGE_PORT" >"$WORK/forge.log" 2>&1 &
PIDS+=($!)
wait_for lore-forge "$FORGE/.well-known/openid-configuration"
start_forge
step "first-run setup in the browser flow"
JAR="$WORK/alice.cookies"
@ -101,38 +151,38 @@ printf 'bob password\n' | "$FORGE_BIN" create-user --username bob --display-name
step "start loreserver with the generated configuration"
mkdir -p "$WORK/lore-config"
{
"$FORGE_BIN" loreserver-config
cat <<EOF
[immutable_store.local]
path = "$WORK/lore-store"
[mutable_store.local]
path = "$WORK/lore-store"
[telemetry.logger]
format = "text"
[server.quic]
port = $LORE_PORT
[server.grpc]
port = $LORE_PORT
[server.http]
port = $((LORE_PORT + 2))
EOF
} >"$WORK/lore-config/forge.toml"
"$LORESERVER" --config "$WORK/lore-config" --env forge >"$WORK/loreserver.log" 2>&1 &
LORE_PID=$!
PIDS+=("$LORE_PID")
"$FORGE_BIN" loreserver-config --store "$WORK/lore-store" --port "$LORE_PORT" --http-port "$((LORE_PORT + 2))" \
${TLS_ARGS[@]+"${TLS_ARGS[@]}"} --output "$WORK/lore-config/forge.toml"
# Started and stopped through these two scripts, which backup.sh also runs. The process ID is in
# loreserver.pid, since a restart from backup.sh is not this shell's child.
export E2E_WORK="$WORK" E2E_LORESERVER="$LORESERVER" E2E_HEALTH="http://127.0.0.1:$((LORE_PORT + 2))/health_check"
cat >"$WORK/bin-start-loreserver" <<'EOF'
#!/usr/bin/env bash
set -eu
log="$E2E_WORK/loreserver.log"
from=$(($(cat "$log" 2>/dev/null | wc -l) + 1))
"$E2E_LORESERVER" --config "$E2E_WORK/lore-config" --env forge >>"$log" 2>&1 &
pid=$!
echo "$pid" >"$E2E_WORK/loreserver.pid"
for _ in $(seq 1 150); do
grep -qiE 'listening|serving|started' "$WORK/loreserver.log" && break
kill -0 "$LORE_PID" 2>/dev/null || { cat "$WORK/loreserver.log" >&2; fail "loreserver exited"; }
curl -fsS "$E2E_HEALTH" >/dev/null 2>&1 && exit 0
kill -0 "$pid" 2>/dev/null || { tail -n +"$from" "$log" >&2; echo "loreserver exited" >&2; exit 1; }
sleep 0.2
done
sleep 1
echo "loreserver did not start" >&2
exit 1
EOF
cat >"$WORK/bin-stop-loreserver" <<'EOF'
#!/usr/bin/env bash
pid=$(cat "$E2E_WORK/loreserver.pid")
kill -TERM "$pid" 2>/dev/null || exit 0
for _ in $(seq 1 300); do kill -0 "$pid" 2>/dev/null || exit 0; sleep 0.1; done
echo "loreserver did not stop" >&2
exit 1
EOF
chmod +x "$WORK/bin-start-loreserver" "$WORK/bin-stop-loreserver"
"$WORK/bin-start-loreserver" || fail "loreserver did not start"
LORE_PID=$(cat "$WORK/loreserver.pid")
# Logs `$1` (a user with cookie jar `$2`) into the Lore CLI by approving the device code.
lore_login() {
@ -175,6 +225,23 @@ mkdir -p "$WORK/alice-work"
"$LORE" push
)
if [ -z "${NO_TLS:-}" ]; then
step "alice: a client that does not trust the certificate, or skips TLS, is refused"
if (cd "$WORK" && "$LORE_CLI" clone "$LORE_REMOTE/alice/demo" untrusted-clone) >"$WORK/untrusted.log" 2>&1; then
fail "a client without the CA cloned over lores://"
fi
if (cd "$WORK" && "$LORE" clone "lore://localhost:$LORE_PORT/alice/demo" plaintext-clone) >"$WORK/plaintext.log" 2>&1; then
fail "a lore:// clone worked against loreserver's TLS gRPC endpoint"
fi
# Only TLS tells the two apart from the clones that work, but check they failed connecting,
# not over permissions. The plaintext one reports either message, run to run.
for log in untrusted plaintext; do
grep -qE "Disconnected from server|connection closed" "$WORK/$log.log" \
|| { cat "$WORK/$log.log" >&2; fail "the $log clone failed for another reason"; }
done
echo "both failed to connect"
fi
if [ -n "${SMOKE:-}" ]; then
printf '\nPASS (smoke): one login, create and push against %s\n' "$("$LORESERVER" --version 2>/dev/null || echo loreserver)"
exit 0
@ -344,6 +411,7 @@ if [ -z "${NO_DESKTOP:-}" ]; then
export LORE_FORGE_LIBLORE="$LIBLORE_DIR/$LIBLORE_FILE"
export LORE_AUTH_PATH="$WORK/auth-desktop"
export RUST_LOG="${RUST_LOG:-info,forge_service=debug}"
[ -n "${TLS:-}" ] && export SSL_CERT_FILE="$TLS/ca.pem"
exec "$ROOT/desktop/target/debug/forge-service"
) >"$WORK/desktop/stdout.log" 2>&1 &
DESKTOP_PID=$!
@ -364,9 +432,48 @@ fi
if [ -n "${HOLD:-}" ]; then
echo "holding both servers for a look: $FORGE (alice / alice password), state in $WORK; Ctrl-C ends"
wait "$LORE_PID"
while kill -0 "$(cat "$WORK/loreserver.pid")" 2>/dev/null; do sleep 1; done
fi
step "backup: back up, push another revision, restore, and the repository is as it was"
export LORE_AUTH_PATH="$WORK/auth-alice"
# A fresh clone: the desktop checks moved alice/demo on past alice-work.
(cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" backup-work) >"$WORK/backup-clone.log" 2>&1 \
|| { cat "$WORK/backup-clone.log" >&2; fail "cloning for the backup check failed"; }
(
cd "$WORK/backup-work"
echo backed up >backed.txt
"$LORE" stage backed.txt
"$LORE" commit "Pushed just before the backup"
"$LORE" push
) >"$WORK/before-backup.log" 2>&1 || { cat "$WORK/before-backup.log" >&2; fail "the push before the backup failed"; }
LORE_FORGE_BIN="$FORGE_BIN" LORE_STORE="$WORK/lore-store" LORESERVER_BIN="$LORESERVER" \
LORESERVER_STOP="$WORK/bin-stop-loreserver" LORESERVER_START="$WORK/bin-start-loreserver" \
"$ROOT/scripts/backup.sh" "$WORK/backups" | tee "$WORK/backup.log"
SNAPSHOT="$WORK/backups/$(readlink "$WORK/backups/latest")"
[ -f "$SNAPSHOT/lore-forge.sqlite" ] && [ -d "$SNAPSHOT/lore-store" ] && [ -f "$SNAPSHOT/MANIFEST" ] \
|| fail "the backup lacks the database, the store or its manifest"
(
cd "$WORK/backup-work"
echo lost >lost.txt
"$LORE" stage lost.txt
"$LORE" commit "Pushed after the backup"
"$LORE" push
) >"$WORK/after-backup.log" 2>&1 || { cat "$WORK/after-backup.log" >&2; fail "the push after the backup failed"; }
"$WORK/bin-stop-loreserver"
kill "$FORGE_PID" && wait "$FORGE_PID" 2>/dev/null || true
LORE_STORE="$WORK/lore-store" "$ROOT/scripts/restore.sh" "$SNAPSHOT" | tee "$WORK/restore.log"
start_forge
"$WORK/bin-start-loreserver" || fail "loreserver did not start on the restored store"
(cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" restored-clone) >"$WORK/restored-clone.log" 2>&1 \
|| { cat "$WORK/restored-clone.log" >&2; fail "cloning the restored repository failed"; }
[ "$(cat "$WORK/restored-clone/backed.txt")" = "backed up" ] || fail "the restore lost the revision pushed before the backup"
[ ! -e "$WORK/restored-clone/lost.txt" ] || fail "the restore kept a revision pushed after the backup"
page "$JAR" /alice/demo | grep -q '>backed.txt<' || fail "the browser does not read the restored repository"
ls -d "$WORK"/lore-store.before-restore-* "$LORE_FORGE_DATA_DIR"/lore-forge.sqlite.before-restore-* >/dev/null \
|| fail "restore did not keep what it replaced"
echo "restored $(basename "$SNAPSHOT"): backed.txt is there, lost.txt is not"
step "alice: logout revokes the CLI login"
export LORE_AUTH_PATH="$WORK/auth-alice"
(cd "$WORK/alice-work" && "$LORE" auth logout)

71
scripts/restore.sh Executable file
View File

@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Restores a backup that scripts/backup.sh wrote.
#
# scripts/restore.sh <backup>
#
# <backup> is one of its timestamped directories, or its `latest` link. Stop lore-forge and
# loreserver first (systemctl stop loreserver lore-forge). The current database and store are
# moved aside, to lore-forge.sqlite.before-restore-<time> in the data directory and
# <store>.before-restore-<time>, never deleted; remove them once the restore has checked out.
#
# The secret key is not part of a backup. The one in use must be the one that was in use when
# the backup was taken, or lore-forge cannot decrypt its signing keys and will not start.
#
# Everything after the backup is lost: revisions pushed since, accounts, grants, and logins.
# People whose login began or refreshed after the backup sign in again.
#
# Settings, from the environment, as for backup.sh:
#
# LORE_FORGE_DATA_DIR lore-forge's data directory /var/lib/lore-forge
# LORE_STORE loreserver's store /var/lib/loreserver/store
set -euo pipefail
say() { echo "restore: $*" >&2; }
die() { say "$*"; exit 1; }
[ $# -eq 1 ] || die "usage: $0 <backup>"
BACKUP="$(cd "$1" && pwd -P)" || die "no backup at $1"
DATA_DIR="${LORE_FORGE_DATA_DIR:-/var/lib/lore-forge}"
STORE="${LORE_STORE:-/var/lib/loreserver/store}"
DB=lore-forge.sqlite
[ -f "$BACKUP/MANIFEST" ] && [ -f "$BACKUP/$DB" ] && [ -d "$BACKUP/lore-store" ] \
|| die "$BACKUP is not a backup from scripts/backup.sh"
if command -v systemctl >/dev/null 2>&1; then
for unit in lore-forge loreserver; do
! systemctl is-active --quiet "$unit" || die "$unit is running; stop it first: systemctl stop loreserver lore-forge"
done
fi
say "restoring $(sed -n 's/^backup //p' "$BACKUP/MANIFEST")"
sed 's/^/ /' "$BACKUP/MANIFEST" >&2
NOW="$(date -u +%Y%m%dT%H%M%SZ)"
mkdir -p "$DATA_DIR"
if [ -e "$DATA_DIR/$DB" ]; then
mv "$DATA_DIR/$DB" "$DATA_DIR/$DB.before-restore-$NOW"
say "moved the current database to $DATA_DIR/$DB.before-restore-$NOW"
fi
# The write-ahead log belongs to the database it was beside, never to the restored one.
for suffix in -wal -shm; do
[ -e "$DATA_DIR/$DB$suffix" ] && mv "$DATA_DIR/$DB$suffix" "$DATA_DIR/$DB.before-restore-$NOW$suffix"
done
cp -p "$BACKUP/$DB" "$DATA_DIR/$DB.restoring"
mv "$DATA_DIR/$DB.restoring" "$DATA_DIR/$DB"
if [ -e "$STORE" ]; then
mv "$STORE" "$STORE.before-restore-$NOW"
say "moved the current store to $STORE.before-restore-$NOW"
fi
mkdir -p "$(dirname "$STORE")"
cp -Rp "$BACKUP/lore-store" "$STORE.restoring"
mv "$STORE.restoring" "$STORE"
if [ "$(id -u)" = 0 ]; then
# Owned as the services expect, whoever owned the copies.
id lore-forge >/dev/null 2>&1 && chown -R lore-forge:lore-forge "$DATA_DIR/$DB"
id loreserver >/dev/null 2>&1 && chown -R loreserver:loreserver "$STORE"
fi
say "done; start lore-forge, then loreserver: systemctl start lore-forge loreserver"

View File

@ -42,11 +42,14 @@ LISTEN=127.0.0.1:8080
# host Lore clients connect to.
LORE_URL=https://localhost
# How people address the Lore server from the CLI, for the instructions printed at start.
# How people address the Lore server from the CLI, shown on the forge's pages. lore:// skips
# certificate checks and sends tokens over plaintext gRPC, so use it only on this machine;
# with a certificate below, use lores://<its host>:41337.
LORE_REMOTE=lore://localhost:41337
# TLS certificate and key for loreserver's QUIC endpoint. Empty: loreserver generates a
# self-signed certificate for localhost on every start, which is fine only locally.
# TLS certificate and key for loreserver's QUIC and gRPC endpoints. Empty: QUIC uses a
# self-signed certificate made on every start and gRPC is plaintext, fine only locally. For a
# real deployment on Linux, see deploy/README.md instead of this script.
LORE_TLS_CERT=
LORE_TLS_KEY=
EOF
@ -73,6 +76,14 @@ export LORE_FORGE_SECRET_KEY="$(cat "$RUN/secret.key")"
export LORE_FORGE_PUBLIC_URL="$PUBLIC_URL"
export LORE_FORGE_LORE_URL="$LORE_URL"
export LORE_FORGE_DATA_DIR="$RUN/forge-data"
export LORE_FORGE_LORE_REMOTE="$LORE_REMOTE"
TLS_ARGS=()
if [ -n "${LORE_TLS_CERT:-}" ]; then
TLS_ARGS=(--tls-cert "$LORE_TLS_CERT" --tls-key "${LORE_TLS_KEY:?set LORE_TLS_KEY beside LORE_TLS_CERT}")
# With a certificate gRPC is TLS too, reached by the name the certificate is for.
REMOTE_HOST="${LORE_REMOTE#*://}"
export LORE_FORGE_LORE_GRPC_URL="https://${REMOTE_HOST%%/*}"
fi
FORGE_PID=""
LORE_PID=""
@ -97,40 +108,18 @@ curl -fsS "http://$LISTEN/.well-known/openid-configuration" >/dev/null 2>&1 || d
# loreserver fetches lore-forge's keys at startup, so its configuration is written and it is
# started only once lore-forge answers.
mkdir -p "$RUN/lore-config"
{
"$FORGE" loreserver-config
cat <<EOF
[immutable_store.local]
path = "$RUN/lore-store"
[mutable_store.local]
path = "$RUN/lore-store"
[telemetry.logger]
format = "text"
EOF
if [ -n "${LORE_TLS_CERT:-}" ]; then
cat <<EOF
[server.quic.certificate]
cert_file = "$LORE_TLS_CERT"
pkey_file = "$LORE_TLS_KEY"
EOF
fi
} >"$RUN/lore-config/forge.toml"
"$FORGE" loreserver-config --store "$RUN/lore-store" ${TLS_ARGS[@]+"${TLS_ARGS[@]}"} \
--output "$RUN/lore-config/forge.toml"
say "starting loreserver $("$LORE_BIN_DIR/loreserver" --version | awk '{print $2}') (logs: run/logs/loreserver.log)"
touch "$RUN/logs/loreserver.log"
LOG_FROM=$(($(wc -l <"$RUN/logs/loreserver.log") + 1))
"$LORE_BIN_DIR/loreserver" --config "$RUN/lore-config" --env forge >>"$RUN/logs/loreserver.log" 2>&1 &
LORE_PID=$!
for _ in $(seq 1 150); do
# Only lines written since this start count.
tail -n +"$LOG_FROM" "$RUN/logs/loreserver.log" | grep -qiE 'listening|serving|started' && break
curl -fsS http://127.0.0.1:41339/health_check >/dev/null 2>&1 && break
kill -0 "$LORE_PID" 2>/dev/null || { tail -20 "$RUN/logs/loreserver.log" >&2; die "loreserver exited"; }
sleep 0.2
done
curl -fsS http://127.0.0.1:41339/health_check >/dev/null 2>&1 || die "loreserver did not answer its health check"
cat >&2 <<EOF