245 lines
8.9 KiB
Rust
245 lines
8.9 KiB
Rust
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
//! `ianitor-control --dev`: everything temporary, on 127.0.0.1. A fresh routes repository, a
|
|
//! state directory, a share-link key and one API token printed once. If an `ianitor-edge`
|
|
//! binary is found (`--edge-bin`, `$IANITOR_EDGE_BIN`, or next to this binary), it runs as
|
|
//! the dev proxy on 127.0.0.1:18080/18443 with an admin socket, so applies are loaded and
|
|
//! watched for real; otherwise applies are only written. Everything is removed on Ctrl-C.
|
|
|
|
use std::net::SocketAddr;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Child, Command, Stdio};
|
|
use std::time::Duration;
|
|
|
|
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
|
|
use ianitor_control::repo::Repo;
|
|
use ianitor_control::tokens::Tokens;
|
|
use ianitor_control::util::{hex, random, write_atomic};
|
|
|
|
/// A throw-away Domi root for dev mode, in `offline-root/` (its key stays in memory, like
|
|
/// on the offline machine), and the PKI password credential. Control then works like
|
|
/// production: it issues server certificates for every `tls = "domi"` host.
|
|
fn dev_pki(dir: &Path) -> Result<(String, ianitor_core::pki::KeyPair), String> {
|
|
let (root, key) = ianitor_core::pki::create_root(ianitor_control::util::now() as i64)
|
|
.map_err(|e| e.to_string())?;
|
|
std::fs::write(dir.join("offline-root/domi-root.crt"), &root).map_err(|e| e.to_string())?;
|
|
let pass = hex(&random::<24>().map_err(|e| e.to_string())?);
|
|
write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600)
|
|
.map_err(|e| e.to_string())?;
|
|
Ok((root, key))
|
|
}
|
|
|
|
const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\
|
|
[forward_auth]\nurl = \"http://127.0.0.1:9091/api/authz/forward-auth\"\n";
|
|
|
|
struct Cleanup {
|
|
dir: PathBuf,
|
|
edge: Option<Child>,
|
|
}
|
|
|
|
impl Drop for Cleanup {
|
|
fn drop(&mut self) {
|
|
if let Some(c) = &mut self.edge {
|
|
let _ = c.kill();
|
|
let _ = c.wait();
|
|
}
|
|
let _ = std::fs::remove_dir_all(&self.dir);
|
|
}
|
|
}
|
|
|
|
fn find_edge(args: &[String]) -> Option<PathBuf> {
|
|
let mut it = args.iter();
|
|
while let Some(a) = it.next() {
|
|
if a == "--edge-bin" {
|
|
return it.next().map(PathBuf::from);
|
|
}
|
|
}
|
|
if let Some(p) = std::env::var_os("IANITOR_EDGE_BIN") {
|
|
return Some(PathBuf::from(p));
|
|
}
|
|
let me = std::env::current_exe().ok()?;
|
|
let sibling = me.with_file_name(if cfg!(windows) {
|
|
"ianitor-edge.exe"
|
|
} else {
|
|
"ianitor-edge"
|
|
});
|
|
sibling.is_file().then_some(sibling)
|
|
}
|
|
|
|
fn arg(args: &[String], name: &str) -> Option<String> {
|
|
let mut it = args.iter();
|
|
while let Some(a) = it.next() {
|
|
if a == name {
|
|
return it.next().cloned();
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
pub async fn run(args: &[String]) -> Result<(), String> {
|
|
let listen: SocketAddr = arg(args, "--listen")
|
|
.unwrap_or_else(|| "127.0.0.1:7878".into())
|
|
.parse()
|
|
.map_err(|_| "--listen must be an address like 127.0.0.1:7878")?;
|
|
if !listen.ip().is_loopback() {
|
|
return Err("--dev listens on loopback only".into());
|
|
}
|
|
let dir = std::env::temp_dir().join(format!("ianitor-dev-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
let mut cleanup = Cleanup {
|
|
dir: dir.clone(),
|
|
edge: None,
|
|
};
|
|
for d in [
|
|
"state",
|
|
"edge",
|
|
"caddy",
|
|
"certs",
|
|
"creds",
|
|
"logs",
|
|
"edge-state",
|
|
"offline-root",
|
|
] {
|
|
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
|
|
}
|
|
let (root_pem, root_key) = dev_pki(&dir)?;
|
|
let key = hex(&random::<32>().map_err(|e| e.to_string())?);
|
|
write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600)
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
let edge_bin = if cfg!(unix) { find_edge(args) } else { None };
|
|
let s = |p: &str| dir.join(p).to_string_lossy().into_owned();
|
|
let cfg = Config {
|
|
listen,
|
|
allowed_hosts: Vec::new(),
|
|
state_dir: dir.join("state"),
|
|
credentials_dir: Some(dir.join("creds")),
|
|
git: PathBuf::from("git"),
|
|
watch_secs: arg(args, "--watch-secs")
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(10),
|
|
watch_every_secs: 2,
|
|
trial_margin_secs: 20,
|
|
health_poll_secs: 2,
|
|
routes: Routes {
|
|
repo: dir.join("routes.git"),
|
|
branch: "main".into(),
|
|
remote: None,
|
|
remote_name: "Gitea".into(),
|
|
push_username: "ianitor".into(),
|
|
push_credential: None,
|
|
},
|
|
edge: Edge {
|
|
config: dir.join("edge/edge.json"),
|
|
trial: None,
|
|
admin_socket: edge_bin.as_ref().map(|_| dir.join("edge/admin.sock")),
|
|
share_revocations: dir.join("edge/share-revocations.json"),
|
|
},
|
|
caddy: Caddy {
|
|
config: dir.join("caddy/caddy.json"),
|
|
},
|
|
compile: Compile {
|
|
http_listen: "127.0.0.1:18080".parse().map_err(|_| "bad address")?,
|
|
https_listen: "127.0.0.1:18443".parse().map_err(|_| "bad address")?,
|
|
cert_dir: s("certs"),
|
|
state_dir: s("edge-state"),
|
|
access_log: s("logs/access.log"),
|
|
caddy_credentials_dir: s("creds"),
|
|
caddy_admin: None,
|
|
},
|
|
compile_caddy: None,
|
|
pki: Some(ianitor_control::config::PkiConfig {
|
|
root_cert: dir.join("offline-root/domi-root.crt"),
|
|
password_credential: "pki-password".into(),
|
|
approval: "manual".into(),
|
|
kdf_iterations: 10_000,
|
|
}),
|
|
ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig {
|
|
hostname: None,
|
|
proof_credential: None,
|
|
static_dir: Some(PathBuf::from(d)),
|
|
logout_url: None,
|
|
}),
|
|
engine: None,
|
|
};
|
|
cfg.check().map_err(|e| e.to_string())?;
|
|
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
|
|
.map_err(|e| e.to_string())?;
|
|
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?;
|
|
|
|
// Control writes edge.json first; then edge can start from it.
|
|
let ctl_cfg = cfg.clone();
|
|
let opened = ianitor_control::Control::open(ctl_cfg).await?;
|
|
// Dev only: sign the first intermediate with the throw-away root at once (in production
|
|
// this is the offline step in docs/pki.md).
|
|
if let Some(p) = &opened.pki {
|
|
let now = ianitor_control::util::now();
|
|
let r = p.request_renewal(now, "dev").map_err(|e| e.to_string())?;
|
|
let signed = ianitor_core::pki::sign_intermediate(
|
|
&root_pem,
|
|
&root_key,
|
|
r.csr_pem.as_deref().unwrap_or_default(),
|
|
now as i64,
|
|
)
|
|
.map_err(|e| e.to_string())?;
|
|
p.install_intermediate(&r.id, &signed, now)
|
|
.map_err(|e| e.to_string())?;
|
|
}
|
|
drop(opened);
|
|
if let Some(bin) = &edge_bin {
|
|
cleanup.edge = Some(start_edge(bin, &dir, &cfg)?);
|
|
}
|
|
|
|
println!("Ianitor control (dev) on http://{listen}/api/v1");
|
|
println!("Routes repository: {}", cfg.routes.repo.display());
|
|
match &edge_bin {
|
|
Some(b) => println!(
|
|
"Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for any name; Domi root: {}",
|
|
b.display(),
|
|
dir.join("offline-root/domi-root.crt").display()
|
|
),
|
|
None => println!(
|
|
"No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)."
|
|
),
|
|
}
|
|
println!("API token (shown once): {token}");
|
|
println!(
|
|
"Approve a device request: ianitor-control pki approve <code> --state-dir {}",
|
|
dir.join("state").display()
|
|
);
|
|
println!("Press Ctrl-C to stop and remove {}", dir.display());
|
|
let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await;
|
|
drop(cleanup);
|
|
r
|
|
}
|
|
|
|
fn start_edge(bin: &Path, dir: &Path, cfg: &Config) -> Result<Child, String> {
|
|
let log = std::fs::File::create(dir.join("logs/edge.log")).map_err(|e| e.to_string())?;
|
|
let log2 = log.try_clone().map_err(|e| e.to_string())?;
|
|
let child = Command::new(bin)
|
|
.arg("--config")
|
|
.arg(&cfg.edge.config)
|
|
.arg("--admin-socket")
|
|
.arg(dir.join("edge/admin.sock"))
|
|
.arg("--share-revocations")
|
|
.arg(&cfg.edge.share_revocations)
|
|
.env("CREDENTIALS_DIRECTORY", dir.join("creds"))
|
|
.stdout(Stdio::from(log))
|
|
.stderr(Stdio::from(log2))
|
|
.spawn()
|
|
.map_err(|e| format!("cannot start {}: {e}", bin.display()))?;
|
|
let sock = dir.join("edge/admin.sock");
|
|
for _ in 0..100 {
|
|
if sock.exists() {
|
|
return Ok(child);
|
|
}
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
Err(format!(
|
|
"the dev proxy did not start; see {}",
|
|
dir.join("logs/edge.log").display()
|
|
))
|
|
}
|