This repository has been archived on 2026-10-08. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
maestro/crates/maestro-registry/src/token.rs
T
naps62-yolo 094cd1ffce
ci / rust (pull_request) Successful in 4m13s
fix(maestro): drop SHARED_ prefix from [shared] env vars
The shared section is the implicit global scope, so its fields use
the bare `MAESTRO_<FIELD>` env-var spelling. Only `[daemon]` and
`[registry]` sections get section-prefixed env vars.

Renames:
- MAESTRO_SHARED_TOKEN        → MAESTRO_TOKEN
- MAESTRO_SHARED_REGISTRY_URL → MAESTRO_REGISTRY_URL

`MAESTRO_DAEMON_*` and `MAESTRO_REGISTRY_BIND_ADDR` are unchanged.

This restores the canonical spec name (`MAESTRO_TOKEN`) that operators
already use in their deployment scripts — NAP-233 had renamed it to
`MAESTRO_SHARED_TOKEN`, which silently broke daemon auth against
existing registry deployments still setting `MAESTRO_TOKEN` in env.

Constants renamed alongside: `ENV_SHARED_TOKEN` → `ENV_TOKEN`,
`ENV_SHARED_REGISTRY_URL` → `ENV_REGISTRY_URL`. `EnvOverrides` fields
shed their `shared_` prefix to match.

Touches: daemon/cli/registry crates, e2e harness, design spec.
2026-05-26 13:24:29 +00:00

298 lines
9.3 KiB
Rust

//! Registry view over the unified Maestro config + first-run token bootstrap.
//!
//! On startup the registry looks for the unified file at
//! `~/.config/maestro/config.toml`:
//!
//! - If `[shared].token` is present, loads it.
//! - If absent, generates a 256-bit random token, prints it once to stderr,
//! and persists it back to the same file via read-modify-write (so any
//! `[cli]` / `[daemon]` sections from a co-located host stay intact).
//! Subsequent runs are silent.
//!
//! Env-var overrides (applied by [`load_config`]):
//!
//! - `MAESTRO_TOKEN` — when set, bypasses the file entirely (no read,
//! no write). Lets the binary run in a container with no writable volume.
//! - `MAESTRO_REGISTRY_BIND_ADDR` — when set, overrides `bind_addr`.
//!
//! Default config path: `~/.config/maestro/config.toml` (override via
//! `$MAESTRO_CONFIG`).
use std::net::SocketAddr;
use std::path::Path;
use maestro_config::MaestroConfigFile;
use rand::RngCore;
pub use maestro_config::{default_config_path, resolve_config_path, CONFIG_PATH_ENV};
/// Default `bind_addr` when neither file nor env specify one.
pub const DEFAULT_BIND_ADDR: &str = "127.0.0.1:8080";
/// Env var that overrides `[shared].token`.
pub const ENV_TOKEN: &str = "MAESTRO_TOKEN";
/// Env var that overrides `[registry].bind_addr`.
pub const ENV_REGISTRY_BIND_ADDR: &str = "MAESTRO_REGISTRY_BIND_ADDR";
fn default_bind_addr() -> SocketAddr {
DEFAULT_BIND_ADDR.parse().expect("valid default bind_addr")
}
#[derive(Debug, thiserror::Error)]
pub enum TokenError {
#[error(transparent)]
Inner(#[from] maestro_config::ConfigError),
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("invalid {env} ({input:?}): {source}")]
InvalidBindAddr {
env: &'static str,
input: String,
source: std::net::AddrParseError,
},
}
/// Resolved registry config: the token to sign JWTs with and the address
/// to bind on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegistryConfig {
pub token: String,
pub bind_addr: SocketAddr,
}
/// Load `[shared].token` (or generate one and persist it). Returns the
/// resolved [`RegistryConfig`] populated with `[registry].bind_addr` when
/// present, else the default.
///
/// On first run (no `[shared].token` in the file) this prints the freshly
/// generated token to stderr so the operator can copy it to every daemon.
pub fn ensure_token(config_path: &Path) -> Result<RegistryConfig, TokenError> {
let mut file = MaestroConfigFile::load_or_default(config_path)?;
let bind_addr = file.registry.bind_addr.unwrap_or_else(default_bind_addr);
if let Some(token) = file.shared.token.clone() {
return Ok(RegistryConfig { token, bind_addr });
}
let token = generate_token();
file.shared.token = Some(token.clone());
file.save(config_path)?;
eprintln!(
"maestro-registry: generated new MAESTRO_TOKEN; deploy this to every daemon:\n {token}"
);
Ok(RegistryConfig { token, bind_addr })
}
/// Resolve the runtime config, applying env-var overrides on top of (or
/// instead of) the on-disk config file.
///
/// Precedence per field: env > file > default.
///
/// `env_token` (`MAESTRO_TOKEN`): when `Some`, the file is neither
/// read nor created — useful in container deployments without a writable
/// volume.
/// `env_bind_addr` (`MAESTRO_REGISTRY_BIND_ADDR`): when `Some`, overrides
/// the bind address.
///
/// Pass real env values from `main`; tests pass explicit `Option`s.
pub fn load_config(
config_path: &Path,
env_token: Option<String>,
env_bind_addr: Option<&str>,
) -> Result<RegistryConfig, TokenError> {
let mut cfg = match env_token {
Some(token) => RegistryConfig {
token,
bind_addr: default_bind_addr(),
},
None => ensure_token(config_path)?,
};
if let Some(raw) = env_bind_addr {
cfg.bind_addr = raw.parse().map_err(|source| TokenError::InvalidBindAddr {
env: ENV_REGISTRY_BIND_ADDR,
input: raw.to_string(),
source,
})?;
}
Ok(cfg)
}
fn generate_token() -> String {
let mut bytes = [0u8; 32];
rand::thread_rng().fill_bytes(&mut bytes);
hex_encode(&bytes)
}
fn hex_encode(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0xf) as usize] as char);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_run_generates_persistent_token_in_shared_section() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let cfg = ensure_token(&path).unwrap();
assert_eq!(cfg.token.len(), 64); // 32 bytes hex-encoded
assert_eq!(cfg.bind_addr, default_bind_addr());
let again = ensure_token(&path).unwrap();
assert_eq!(cfg, again, "second call must return same token");
let file = MaestroConfigFile::load(&path).unwrap();
assert_eq!(file.shared.token.as_deref(), Some(cfg.token.as_str()));
}
#[test]
fn first_run_preserves_other_sections() {
// A host running both daemon and registry already has the daemon's
// config in the file. Registry's first-run token gen must not lose
// [daemon] or [shared].registry_url.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
r#"
[shared]
registry_url = "https://r.example"
[daemon]
daemon_url = "ws://laptop:7070"
"#,
)
.unwrap();
let cfg = ensure_token(&path).unwrap();
assert_eq!(cfg.token.len(), 64);
let file = MaestroConfigFile::load(&path).unwrap();
assert_eq!(
file.shared.registry_url.as_deref(),
Some("https://r.example")
);
assert_eq!(file.shared.token.as_deref(), Some(cfg.token.as_str()));
assert_eq!(file.daemon.daemon_url.as_deref(), Some("ws://laptop:7070"));
}
#[test]
fn creates_parent_directory() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested/here/config.toml");
let cfg = ensure_token(&path).unwrap();
assert!(path.exists());
assert_eq!(cfg.token.len(), 64);
}
#[test]
fn existing_token_is_loaded_as_is() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
r#"
[shared]
token = "abcd"
"#,
)
.unwrap();
let cfg = ensure_token(&path).unwrap();
assert_eq!(cfg.token, "abcd");
assert_eq!(cfg.bind_addr, default_bind_addr());
}
#[test]
fn custom_bind_addr_is_preserved() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
r#"
[shared]
token = "x"
[registry]
bind_addr = "0.0.0.0:9999"
"#,
)
.unwrap();
let cfg = ensure_token(&path).unwrap();
assert_eq!(cfg.bind_addr, "0.0.0.0:9999".parse().unwrap());
}
#[test]
fn env_token_bypasses_file_entirely() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let cfg = load_config(&path, Some("envtoken".into()), None).unwrap();
assert_eq!(cfg.token, "envtoken");
assert_eq!(cfg.bind_addr, default_bind_addr());
assert!(
!path.exists(),
"no file should be created when env token is set"
);
}
#[test]
fn env_bind_addr_overrides_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
r#"
[shared]
token = "file"
[registry]
bind_addr = "127.0.0.1:1"
"#,
)
.unwrap();
let cfg = load_config(&path, None, Some("0.0.0.0:9090")).unwrap();
assert_eq!(cfg.token, "file");
assert_eq!(cfg.bind_addr, "0.0.0.0:9090".parse().unwrap());
}
#[test]
fn env_token_and_env_bind_addr_combined() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let cfg = load_config(&path, Some("t".into()), Some("0.0.0.0:7777")).unwrap();
assert_eq!(cfg.token, "t");
assert_eq!(cfg.bind_addr, "0.0.0.0:7777".parse().unwrap());
assert!(!path.exists());
}
#[test]
fn invalid_env_bind_addr_returns_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let err = load_config(&path, Some("t".into()), Some("not-an-addr")).unwrap_err();
match err {
TokenError::InvalidBindAddr { input, env, .. } => {
assert_eq!(input, "not-an-addr");
assert_eq!(env, ENV_REGISTRY_BIND_ADDR);
}
other => panic!("expected InvalidBindAddr, got {other:?}"),
}
}
#[test]
fn no_env_falls_through_to_ensure_token() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let cfg = load_config(&path, None, None).unwrap();
assert_eq!(cfg.token.len(), 64);
assert!(path.exists());
}
}