All checks were successful
PR Checks / rust-gates (pull_request) Successful in 59s
Completes the command surface INSTALL.md §2 published before the binary
existed. With this, `edge` cuts a binary that does everything that guide
describes.
doctor (src/doctor.rs)
Reads only. Every row is answered by asking the thing itself — the
installed binary (--version, --print-config), the service manager, and
the sidecar's /health — because the record says what `install` did,
which is a different question from what is true now. --print-config is
run ONLY when the config already exists: that flag provisions, and a
diagnosis must not create the state it reports on. It is also run under
the environment the service pins (UOLINK_DB_PATH), so the config and
database it names are the ones the service opens, not the ones the
binary would pick on its own.
Exit 1 when any row failed, so a monitoring script can read it; a ⚠
never does that. A stopped shard is therefore a ⚠, not a ✗ — "you have
not started it" and "it is running and the bridge is dead" are
different problems and only the second is broken. Offline is a ⚠ too:
a shard host with no route to Gitea is a supported way to run this.
The patch row re-resolves each recorded patch against the tree from the
cached .patch, so a core upgrade or a restored backup that silently
removed the tier's edits is caught — nothing else here would notice.
update (src/update.rs, install.rs::Mode)
The same pipeline as install, not a second one: PLAN.md describes it as
"re-resolve the bundle, then move both components to it", which is what
an install over an existing deployment already does. Writing it twice
would give the sync rules and the protocol cross-checks two places to
disagree. What differs is small and lives in Mode — a prior record is
required, the tree comes from that record rather than detection, the
patch tier's scope narrows, and the close is a diff instead of a
handoff.
The token is not reprinted: it has not changed and the website has it.
A changed protocol number IS called out, because a stale value in
Admin → Shard is answered with 409 and looks like the shard going
offline.
Tier scope: features an earlier run recorded are re-resolved without
asking again (the record is the evidence of consent, including on an
unsupported ServUO); anything new the release offers is named but not
applied without --patches. A shard that declined stays declined.
uninstall (src/uninstall.rs, service::remove)
Removes the binary, the service and install.json; prints the overlay
files and the exact hunks, rendered from the cached patches with the
rung each landed at. Files edited since deployment are flagged so
nobody deletes their own work blind. The report is also written to a
file in the working directory — it is the only thing still needed after
the command exits, and it arrives at the end of the longest output this
tool produces.
Two deviations from PLAN.md §5, both deliberate:
- The cached patch set and patches/originals/ SURVIVE. That table put
them under "removed", but the report tells the operator to diff
against those originals — advice the same command would have made
impossible to follow. --purge removes them, with the config and the
database.
- --yes means yes here, not "take the default". The prompt defaults to
no (destructive), but the operator typed the verb; reading --yes as
"no" would leave an unattended uninstall unable to express itself,
and a script that appears to succeed while removing nothing is the
worse failure.
Exit 1 if a step could not be carried out — everything else still was.
Verified on this machine against a scratch tree built from the real
ServUO 57.4 files: a healthy doctor (exit 0), one with a deleted overlay
file, an edited one and a reverted patch (all three found, exit 1), a
--verify update that wrote nothing, a real update that repaired all three
and left install.json byte-identical, uninstall with and without --purge,
a second uninstall, and doctor/update on a host with no record. Linux
fmt/clippy/tests run in Docker as well as the Windows host.
Co-Authored-By: Claude <noreply@anthropic.com>
129 lines
5.2 KiB
Rust
129 lines
5.2 KiB
Rust
//! HTTP fetches and verified downloads.
|
|
//!
|
|
//! Everything this module pulls comes from a public Gitea repo over anonymous HTTPS — the shard
|
|
//! host has no Gitea credentials and needs none (PLAN.md §1). The one rule that matters:
|
|
//! **nothing downloaded is used before its SHA256 has been checked against the bundle.** The
|
|
//! artifacts are deliberately unsigned (§3), so the checksum is the entire trust anchor, and a
|
|
//! download that "mostly worked" is exactly the case that must not proceed.
|
|
|
|
use std::fs::File;
|
|
use std::io::{self, BufWriter};
|
|
use std::path::Path;
|
|
use std::time::Duration;
|
|
|
|
use anyhow::{anyhow, bail, Context, Result};
|
|
|
|
use crate::util::HashingWriter;
|
|
|
|
/// Identifies the tool and its version in Gitea's logs — worth having when an operator reports that
|
|
/// a fetch failed and nobody can tell which build made the request.
|
|
fn user_agent() -> String {
|
|
format!("runicgateway-installer/{}", env!("CARGO_PKG_VERSION"))
|
|
}
|
|
|
|
/// The default global timeout. Generous because the overlay tarball travels over whatever link the
|
|
/// shard host has, and a slow VPS is not a failure. It exists so a black-holed connection ends the
|
|
/// run with a message instead of hanging an operator's terminal indefinitely.
|
|
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
|
|
|
|
/// One agent per call is fine at this volume, and it keeps the timeouts in one place.
|
|
fn agent(timeout: Duration) -> ureq::Agent {
|
|
ureq::Agent::config_builder()
|
|
.user_agent(user_agent())
|
|
.timeout_global(Some(timeout))
|
|
.build()
|
|
.into()
|
|
}
|
|
|
|
/// Fetches a small text document (the bundle manifest).
|
|
pub fn get_text(url: &str) -> Result<String> {
|
|
get_text_within(url, DEFAULT_TIMEOUT)
|
|
}
|
|
|
|
/// Fetches a small text document, giving up after `timeout`.
|
|
///
|
|
/// `doctor` uses this for both of its network calls, and the short timeout is the point: every one
|
|
/// of its rows is optional context around local state, so a host with no route out must produce a
|
|
/// report a few seconds later rather than a terminal that appears to have hung. The install path
|
|
/// keeps [`DEFAULT_TIMEOUT`], where a slow answer is still worth waiting for.
|
|
pub fn get_text_within(url: &str, timeout: Duration) -> Result<String> {
|
|
let mut response = agent(timeout)
|
|
.get(url)
|
|
.call()
|
|
.with_context(|| format!("cannot reach {url}"))?;
|
|
let status = response.status();
|
|
if !status.is_success() {
|
|
bail!("{url} returned HTTP {}", status.as_u16());
|
|
}
|
|
response
|
|
.body_mut()
|
|
.read_to_string()
|
|
.with_context(|| format!("cannot read the response from {url}"))
|
|
}
|
|
|
|
/// Downloads `url` to `dest`, verifying SHA256 **while writing**.
|
|
///
|
|
/// On mismatch the partial file is removed before returning: leaving a wrong-hash artifact on disk
|
|
/// invites a later step — or a puzzled operator — to use it anyway.
|
|
pub fn download_verified(url: &str, dest: &Path, expected_sha256: &str) -> Result<()> {
|
|
let expected = expected_sha256.trim().to_ascii_lowercase();
|
|
if expected.len() != 64 || !expected.chars().all(|c| c.is_ascii_hexdigit()) {
|
|
bail!("refusing to download {url}: the bundle records an unusable SHA256 ({expected_sha256:?})");
|
|
}
|
|
|
|
let mut response = agent(DEFAULT_TIMEOUT)
|
|
.get(url)
|
|
.call()
|
|
.with_context(|| format!("cannot reach {url}"))?;
|
|
let status = response.status();
|
|
if !status.is_success() {
|
|
bail!("{url} returned HTTP {}", status.as_u16());
|
|
}
|
|
|
|
let file = File::create(dest).with_context(|| format!("cannot create {}", dest.display()))?;
|
|
let mut writer = HashingWriter::new(BufWriter::new(file));
|
|
io::copy(&mut response.body_mut().as_reader(), &mut writer)
|
|
.with_context(|| format!("download of {url} failed"))?;
|
|
let actual = writer.finish();
|
|
|
|
if actual != expected {
|
|
let _ = std::fs::remove_file(dest);
|
|
return Err(anyhow!(
|
|
"checksum mismatch for {url}\n expected {expected}\n got {actual}\n\
|
|
These artifacts are unsigned, so the checksum is the only thing vouching for them. \
|
|
Refusing to use this download."
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::util::TempDir;
|
|
|
|
#[test]
|
|
fn the_user_agent_names_the_build() {
|
|
let ua = user_agent();
|
|
assert!(ua.starts_with("runicgateway-installer/"), "{ua}");
|
|
assert!(ua.len() > "runicgateway-installer/".len(), "{ua}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_malformed_expected_hash_is_refused_before_any_request() {
|
|
// A bundle whose sha256 field is truncated, uppercase-garbled or empty must stop the run
|
|
// rather than download something that can then only be compared against nonsense. The URL
|
|
// is unroutable on purpose: reaching the network at all would be the bug.
|
|
let dir = TempDir::new("rg-test-net").unwrap();
|
|
let dest = dir.path().join("artifact");
|
|
for bad in ["", "abc", &"z".repeat(64)] {
|
|
let err = download_verified("http://127.0.0.1:1/artifact", &dest, bad).unwrap_err();
|
|
assert!(
|
|
err.to_string().contains("unusable SHA256"),
|
|
"expected a pre-flight refusal, got: {err}"
|
|
);
|
|
}
|
|
assert!(!dest.exists());
|
|
}
|
|
}
|