The link both projects wrote twice
dev-updater serves APKs to a phone and ai-app runs model sessions for one. Above the waterline they share nothing. Underneath they are the same program: bound to wg0 so they are not on the LAN, presenting a certificate from a CA the app pins, answering only requests carrying a token enrolled by scanning a QR off the terminal, keeping state in owner-only files outside the repo. Three modules, each extracted only after diffing the two copies and finding nothing between them but a product name and a type parameter. netif fails closed when the tunnel is down. enroll generates, stores and compares the token, and prints the QR, with the URI scheme as the one per-project part. private owns the file modes, taken from ai-app's version because it had already factored out what dev-updater still has inline in two places. Nothing is removed from either project. This is a proposal with a working core, and the README carries the measured evidence -- the enrollment scanner activity differs by its package line and nothing else, the RON format module is byte-identical, and the two copies have each drifted into holding an improvement the other lacks, which is the cost being paid today.
This commit is contained in:
1 parent
995b29f10d
commit
7651d491ac
9 files changed
+871
No files matched your search
@@ -0,0 +1,146 @@
|
||||
//! The bearer token a phone carries, and the QR code that gets it there.
|
||||
//!
|
||||
//! Pinning authenticates the server to the phone but never the phone to
|
||||
//! the server, so the token supplies the other direction. Binding the
|
||||
//! WireGuard interface (see [`crate::netif`]) narrows who can try at all;
|
||||
//! this narrows it to who was enrolled.
|
||||
//!
|
||||
//! The token is 256 bits from the OS CSPRNG and is never typed by a
|
||||
//! human -- it travels once, in a QR code printed to the terminal -- so
|
||||
//! being unguessable costs nothing and there is no manual-entry path to
|
||||
//! design around.
|
||||
//!
|
||||
//! Only the hash is ever stored. That is what makes the plaintext a
|
||||
//! once-only artifact: it exists in the QR at generation time and nowhere
|
||||
//! afterwards, and a lost phone is answered by rotating rather than by
|
||||
//! looking the old one up.
|
||||
//!
|
||||
//! # Never log the token
|
||||
//!
|
||||
//! Nothing here, and nothing that calls it, may log the Authorization
|
||||
//! header or the token itself. Both existing projects hold a test that
|
||||
//! drives the rejection path under a capturing subscriber and asserts the
|
||||
//! token does not appear in the output; that tripwire belongs with the
|
||||
//! middleware, which stays in each project because it is generic over
|
||||
//! that project's state.
|
||||
|
||||
use std::net::IpAddr;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
/// 256 bits from the OS CSPRNG, base64url.
|
||||
pub fn generate_token() -> String {
|
||||
use rand::Rng;
|
||||
let mut bytes = [0u8; 32];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
|
||||
}
|
||||
|
||||
/// What the config stores instead of the token: hex SHA-256.
|
||||
///
|
||||
/// A plain hash, not a password KDF, and deliberately: the input is 256
|
||||
/// random bits, so there is nothing to dictionary-attack and stretching
|
||||
/// would buy only latency on every request.
|
||||
pub fn token_hash_hex(token: &str) -> String {
|
||||
Sha256::digest(token.as_bytes())
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `presented` matches any enrolled hash.
|
||||
///
|
||||
/// The fold visits every entry regardless of an earlier match, so the
|
||||
/// time taken does not say which entry matched, or whether the first one
|
||||
/// did.
|
||||
pub fn token_matches(presented: &str, stored_hashes: &[String]) -> bool {
|
||||
let presented = token_hash_hex(presented);
|
||||
stored_hashes.iter().fold(false, |matched, stored| {
|
||||
matched | bool::from(presented.as_bytes().ct_eq(stored.as_bytes()))
|
||||
})
|
||||
}
|
||||
|
||||
/// The `<scheme>://enroll?...` URI a QR code carries.
|
||||
///
|
||||
/// The scheme is the caller's because it is what routes the scan back to
|
||||
/// the right app -- `devupdater`, `aiapp` -- and it is the only part of
|
||||
/// enrollment that is per-project.
|
||||
pub fn enrollment_uri(scheme: &str, host: IpAddr, port: u16, token: &str) -> String {
|
||||
format!("{scheme}://enroll?host={host}&port={port}&token={token}")
|
||||
}
|
||||
|
||||
/// Prints the one-time enrollment QR, and the URI under it for a person
|
||||
/// who would rather paste than scan.
|
||||
///
|
||||
/// Printed to stdout rather than through `tracing`: it is for the human
|
||||
/// at the terminal, once, and a log line is the wrong shape for something
|
||||
/// that has to be photographed.
|
||||
///
|
||||
/// The QR carries no trust material. The CA is embedded in the app at
|
||||
/// build time, so photographing the terminal leaks only the token, which
|
||||
/// is rotatable.
|
||||
pub fn print_enrollment(scheme: &str, host: IpAddr, port: u16, token: &str) -> Result<()> {
|
||||
let uri = enrollment_uri(scheme, host, port, token);
|
||||
let code = qrcode::QrCode::new(uri.as_bytes()).context("render enrollment QR")?;
|
||||
let rendered = code
|
||||
.render::<qrcode::render::unicode::Dense1x2>()
|
||||
.quiet_zone(true)
|
||||
.build();
|
||||
println!("\n{rendered}\n");
|
||||
println!("Scan with the phone's camera to enroll (or paste into the app's settings):");
|
||||
println!(" {uri}");
|
||||
println!("The token is not stored in the clear and won't be shown again;");
|
||||
println!("a lost phone means re-running with --rotate-token.\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hashing_is_stable_and_tokens_verify() {
|
||||
let token = generate_token();
|
||||
assert_eq!(token_hash_hex(&token), token_hash_hex(&token));
|
||||
assert_ne!(token, generate_token(), "tokens must not repeat");
|
||||
|
||||
let hashes = vec![token_hash_hex(&token), token_hash_hex("other")];
|
||||
assert!(token_matches(&token, &hashes));
|
||||
assert!(token_matches("other", &hashes));
|
||||
assert!(!token_matches("wrong", &hashes));
|
||||
assert!(
|
||||
!token_matches(&token, &[]),
|
||||
"no enrolled token matches nothing"
|
||||
);
|
||||
}
|
||||
|
||||
/// The hash is what gets stored, so it must not be the token, and it
|
||||
/// must be the shape the config files already hold.
|
||||
#[test]
|
||||
fn the_stored_form_reveals_nothing_and_is_hex() {
|
||||
let token = generate_token();
|
||||
let hash = token_hash_hex(&token);
|
||||
assert_ne!(hash, token);
|
||||
assert_eq!(hash.len(), 64);
|
||||
assert!(
|
||||
hash.chars()
|
||||
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
|
||||
);
|
||||
}
|
||||
|
||||
/// The scheme is the only per-project part, and the app parses this
|
||||
/// back -- so the shape is a contract, not a formatting choice.
|
||||
#[test]
|
||||
fn the_enrollment_uri_carries_scheme_host_port_and_token() {
|
||||
let uri = enrollment_uri("devupdater", "10.66.0.1".parse().unwrap(), 8090, "tok");
|
||||
assert_eq!(
|
||||
uri,
|
||||
"devupdater://enroll?host=10.66.0.1&port=8090&token=tok"
|
||||
);
|
||||
let other = enrollment_uri("aiapp", "10.66.0.1".parse().unwrap(), 8443, "tok");
|
||||
assert!(other.starts_with("aiapp://enroll?"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! What dev-updater and ai-app both need in order to be reached from a
|
||||
//! phone, and nothing either of them does afterwards.
|
||||
//!
|
||||
//! Both projects are the same shape underneath: a server on a machine
|
||||
//! somebody owns, bound to a WireGuard interface so it is not on the LAN,
|
||||
//! presenting a certificate from a CA the app pins, and answering only
|
||||
//! requests carrying a bearer token that was enrolled by scanning a QR
|
||||
//! code off the terminal. None of that is about serving APKs or running
|
||||
//! model sessions -- it is the link, and it was written twice.
|
||||
//!
|
||||
//! # What belongs here
|
||||
//!
|
||||
//! Anything that would be *identical* in a third such project. The test
|
||||
//! applied to each module below was to diff the two existing copies: if
|
||||
//! the only differences were a product name and which state type the code
|
||||
//! was generic over, it came here.
|
||||
//!
|
||||
//! # What deliberately does not
|
||||
//!
|
||||
//! The API surfaces. dev-updater's routes are about projects and builds,
|
||||
//! ai-app's about sessions and providers, and their HTTP clients have
|
||||
//! diverged to 14% similarity because they are genuinely different
|
||||
//! programs. Sharing a transport is worth doing; sharing an API would mean
|
||||
//! inventing a common vocabulary neither project wants.
|
||||
//!
|
||||
//! Config *schemas*, for the same reason -- though the RON house rules
|
||||
//! that both files are written in are shared, since those were identical
|
||||
//! to the byte.
|
||||
|
||||
pub mod enroll;
|
||||
pub mod netif;
|
||||
pub mod private;
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Which address to bind, and which addresses the certificate must cover.
|
||||
//!
|
||||
//! Both projects bind the WireGuard interface and nothing else, so that
|
||||
//! neither is reachable from the LAN. That is the outer of two gates --
|
||||
//! the tunnel decides who can try, the token (see [`crate::enroll`])
|
||||
//! decides who is answered -- and it is worth having on its own account:
|
||||
//! an unenrolled scanner never reaches the token check, and a plain-HTTP
|
||||
//! bootstrap port travels inside the tunnel's encryption.
|
||||
|
||||
use std::net::IpAddr;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// The interface both projects bind. A constant rather than a parameter
|
||||
/// because a second answer would mean two ideas of what "the tunnel" is.
|
||||
pub const WG_INTERFACE: &str = "wg0";
|
||||
|
||||
/// The alias an Android emulator reaches its host by. Not a real
|
||||
/// interface anywhere, which is why it has to be added by hand.
|
||||
const EMULATOR_HOST_ALIAS: [u8; 4] = [10, 0, 2, 2];
|
||||
|
||||
/// Every address this machine answers on, for the leaf certificate's SANs
|
||||
/// -- so it covers whatever the phone actually dials without anyone
|
||||
/// maintaining a hardcoded IP.
|
||||
///
|
||||
/// Loopback is included for curl and tests, and the emulator's host alias
|
||||
/// so a debug build can reach a server running beside it.
|
||||
///
|
||||
/// Failing to enumerate is not fatal: the certificate still covers
|
||||
/// loopback, which is enough to start and to diagnose from the machine
|
||||
/// itself.
|
||||
pub fn local_addresses() -> Vec<IpAddr> {
|
||||
let mut addresses = vec![
|
||||
IpAddr::from([127, 0, 0, 1]),
|
||||
IpAddr::from(EMULATOR_HOST_ALIAS),
|
||||
];
|
||||
match if_addrs::get_if_addrs() {
|
||||
Ok(interfaces) => {
|
||||
for interface in interfaces {
|
||||
let ip = interface.ip();
|
||||
if ip.is_ipv4() && !addresses.contains(&ip) {
|
||||
addresses.push(ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => tracing::warn!("couldn't enumerate interfaces for the certificate: {err}"),
|
||||
}
|
||||
addresses
|
||||
}
|
||||
|
||||
/// The IPv4 address on the WireGuard interface, or a refusal to start.
|
||||
///
|
||||
/// Failing closed rather than falling back to 0.0.0.0 is the point. The
|
||||
/// escape hatch belongs to the caller as an explicit `--bind`, because
|
||||
/// each of these servers is also how something stranded gets recovered,
|
||||
/// and that recovery should not depend on the tunnel being healthy.
|
||||
///
|
||||
/// `product` names the binary in the failure, so the message reads as
|
||||
/// advice rather than as a library complaining.
|
||||
pub fn wg_address(product: &str) -> Result<IpAddr> {
|
||||
let interfaces = if_addrs::get_if_addrs().context("enumerate network interfaces")?;
|
||||
interfaces
|
||||
.into_iter()
|
||||
.find(|iface| iface.name == WG_INTERFACE && iface.ip().is_ipv4())
|
||||
.map(|iface| iface.ip())
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"no IPv4 address on interface {WG_INTERFACE} -- {product} binds only to the \
|
||||
WireGuard tunnel, so that only enrolled peers can reach its API. Bring the \
|
||||
tunnel up, or pass --bind 0.0.0.0 to serve the LAN while recovering."
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Whatever this machine has, the two that are not interfaces must be
|
||||
/// there -- loopback for tests and curl, the alias for an emulator --
|
||||
/// and nothing may appear twice, since these become certificate SANs.
|
||||
#[test]
|
||||
fn the_certificate_always_covers_loopback_and_the_emulator_alias() {
|
||||
let addresses = local_addresses();
|
||||
assert!(addresses.contains(&IpAddr::from([127, 0, 0, 1])));
|
||||
assert!(addresses.contains(&IpAddr::from(EMULATOR_HOST_ALIAS)));
|
||||
|
||||
let mut seen = addresses.clone();
|
||||
seen.sort();
|
||||
seen.dedup();
|
||||
assert_eq!(seen.len(), addresses.len(), "duplicate SANs: {addresses:?}");
|
||||
assert!(addresses.iter().all(|ip| ip.is_ipv4()));
|
||||
}
|
||||
|
||||
/// The failure is the thing a person reads at 2am, so it has to name
|
||||
/// the binary, the interface, and the way out.
|
||||
#[test]
|
||||
fn a_missing_tunnel_explains_itself() {
|
||||
// Only meaningful where there is no wg0; where there is one, the
|
||||
// call succeeds and there is no message to check.
|
||||
if wg_address("demo-server").is_ok() {
|
||||
return;
|
||||
}
|
||||
let err = wg_address("demo-server")
|
||||
.expect_err("no tunnel")
|
||||
.to_string();
|
||||
assert!(err.contains("demo-server"), "{err}");
|
||||
assert!(err.contains(WG_INTERFACE), "{err}");
|
||||
assert!(err.contains("--bind"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Creating files and directories this server alone can read.
|
||||
//!
|
||||
//! Everything a server writes outside its repo goes through here: the
|
||||
//! config holding token hashes, the TLS private keys, and whatever state
|
||||
//! it keeps. One module owns the modes, so "owner-only" is a property
|
||||
//! that can be checked in one place rather than re-argued at every
|
||||
//! `create`.
|
||||
//!
|
||||
//! Taken from ai-app, which had factored this out; dev-updater still has
|
||||
//! the same logic inline in two places, which is the duplication this
|
||||
//! crate exists to end.
|
||||
|
||||
use std::fs::File;
|
||||
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// Creates `dir` and its parents, owner-accessible only.
|
||||
///
|
||||
/// The mode is set again after creation, deliberately: `DirBuilder::mode`
|
||||
/// applies only when the directory is actually created, so one that
|
||||
/// already existed -- made by hand, or by an older version -- would
|
||||
/// otherwise keep whatever permissions it had while holding a private key.
|
||||
pub fn create_dir(dir: &Path) -> Result<()> {
|
||||
std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(dir)
|
||||
.with_context(|| format!("create {}", dir.display()))?;
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
|
||||
.with_context(|| format!("restrict {}", dir.display()))
|
||||
}
|
||||
|
||||
/// Writes `contents` to `path`, owner-readable only.
|
||||
///
|
||||
/// The mode is set as the file is opened rather than chmod-ed afterwards,
|
||||
/// so it is never briefly world-readable at its real path.
|
||||
pub fn write_file(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
use std::io::Write;
|
||||
let mut file = create_file(path)?;
|
||||
file.write_all(contents)
|
||||
.with_context(|| format!("write {}", path.display()))
|
||||
}
|
||||
|
||||
/// Opens `path` for writing, owner-readable only, truncating what is
|
||||
/// there. For a caller that streams rather than holding the whole body.
|
||||
pub fn create_file(path: &Path) -> Result<File> {
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.with_context(|| format!("write {}", path.display()))
|
||||
}
|
||||
|
||||
/// Opens `path` for appending, owner-readable only, creating it if needed.
|
||||
///
|
||||
/// The append case is separate because a transcript must never be
|
||||
/// truncated by being opened, and the two differ by one flag that is easy
|
||||
/// to get wrong in a hurry.
|
||||
pub fn append_file(path: &Path) -> Result<File> {
|
||||
std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.create(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.with_context(|| format!("append to {}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn mode_of(path: &Path) -> u32 {
|
||||
std::fs::metadata(path).expect("stat").permissions().mode() & 0o777
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_is_owner_only_even_if_it_already_existed() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let target = dir.path().join("state");
|
||||
|
||||
// Made by hand, wide open -- what an older version or a person
|
||||
// might leave behind.
|
||||
std::fs::create_dir(&target).expect("mkdir");
|
||||
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).expect("chmod");
|
||||
|
||||
create_dir(&target).expect("create_dir");
|
||||
assert_eq!(
|
||||
mode_of(&target),
|
||||
0o700,
|
||||
"an existing directory must be restricted too"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_are_owner_only_from_the_moment_they_exist() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
create_dir(dir.path()).expect("create_dir");
|
||||
|
||||
let written = dir.path().join("key.pem");
|
||||
write_file(&written, b"secret").expect("write");
|
||||
assert_eq!(mode_of(&written), 0o600);
|
||||
assert_eq!(std::fs::read(&written).expect("read"), b"secret");
|
||||
|
||||
let appended = dir.path().join("transcript.jsonl");
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut file = append_file(&appended).expect("append");
|
||||
file.write_all(b"one\n").expect("write");
|
||||
}
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut file = append_file(&appended).expect("append");
|
||||
file.write_all(b"two\n").expect("write");
|
||||
}
|
||||
assert_eq!(mode_of(&appended), 0o600);
|
||||
// The whole point of the separate opener: opening again must not
|
||||
// have truncated what was there.
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&appended).expect("read"),
|
||||
"one\ntwo\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user