//! The admin token file, and the CLI side of the admin routes on the internal socket. //! //! While the server runs it writes `data_dir/run/admin.token` (mode 0600, directory 0700) and //! serves `/internal/admin/*` on `data_dir/internal.sock`. The socket is 0600 and sits in the //! 0700 data dir, so only this user can reach it. Those routes also need the token. An `admin` //! command runs through the server when the socket answers, and runs against the database //! directly when it does not. use std::io::Write; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use forge_core::{Config, Error, Result}; use serde::de::DeserializeOwned; use serde_json::Value; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::UnixStream; /// Header carrying the admin token on `/internal/admin/*`. pub const ADMIN_TOKEN_HEADER: &str = "x-forge-admin-token"; const RUN_DIR: &str = "run"; const TOKEN_FILE: &str = "admin.token"; const SOCKET_FILE: &str = "internal.sock"; /// Writes the per-boot admin token to `data_dir/run/admin.token`, replacing any earlier file. /// The file is created with mode 0600 and its directory is 0700. pub fn write_admin_token(data_dir: &Path, token: &str) -> Result<()> { let run = data_dir.join(RUN_DIR); std::fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(&run)?; std::fs::set_permissions(&run, std::fs::Permissions::from_mode(0o700))?; let path = run.join(TOKEN_FILE); match std::fs::remove_file(&path) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(e.into()), } let mut file = std::fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(&path)?; file.write_all(token.as_bytes())?; file.sync_all()?; Ok(()) } /// Path of the admin token file for `data_dir`. pub fn admin_token_path(data_dir: &Path) -> PathBuf { data_dir.join(RUN_DIR).join(TOKEN_FILE) } /// A server that answers on the internal socket. pub struct AdminClient { socket: PathBuf, token: String, } /// The running server, if one answers on its internal socket. `None` means nothing is listening /// (no socket, or a stale one), and the caller should work on the database directly. An error /// means a server is running but the CLI cannot talk to it. pub async fn running_server(config: &Config) -> Result> { let socket = config.data_dir.join(SOCKET_FILE); if !socket.exists() { return Ok(None); } match UnixStream::connect(&socket).await { Ok(stream) => drop(stream), Err(e) if matches!( e.kind(), std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound ) => { return Ok(None); } Err(e) => return Err(e.into()), } let path = admin_token_path(&config.data_dir); let token = std::fs::read_to_string(&path).map_err(|e| { Error::Config(format!( "a server is running, but its admin token at {} cannot be read: {e}", path.display() )) })?; Ok(Some(AdminClient { socket, token: token.trim().to_owned(), })) } #[derive(serde::Deserialize)] struct ErrorBody { error: String, } impl AdminClient { /// Sends `body` as JSON to `path` and decodes the JSON answer. A refusal from the server /// comes back as the matching error: 403 forbidden, 409 conflict, 400 invalid. pub async fn post(&self, path: &str, body: &Value) -> Result { let payload = body.to_string(); let mut stream = UnixStream::connect(&self.socket).await?; let head = format!( "POST {path} HTTP/1.1\r\n\ Host: forge-internal\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ {ADMIN_TOKEN_HEADER}: {}\r\n\ Connection: close\r\n\r\n", payload.len(), self.token ); stream.write_all(head.as_bytes()).await?; stream.write_all(payload.as_bytes()).await?; stream.flush().await?; let mut raw = Vec::new(); stream.read_to_end(&mut raw).await?; let (status, bytes) = crate::hook_cmd::parse_response(&raw)?; if status == 200 { return serde_json::from_slice(&bytes) .map_err(|e| Error::Invalid(format!("unexpected answer from the server: {e}"))); } let message = serde_json::from_slice::(&bytes) .map(|b| b.error) .unwrap_or_else(|_| String::from_utf8_lossy(&bytes).trim().to_owned()); Err(match status { 403 => Error::Forbidden(message), 409 => Error::Conflict(message), 400 => Error::Invalid(message), _ => Error::Git(format!("server answered {status}: {message}")), }) } } #[cfg(test)] mod tests { use super::*; use crate::backup::FsckSummary; use crate::test_support::{ADMIN_TOKEN, test_config, test_state}; use topcoat::router::RouterService; #[test] fn token_file_is_private_and_replaced_on_each_boot() { let dir = tempfile::tempdir().expect("tempdir"); write_admin_token(dir.path(), "first").expect("write"); let path = admin_token_path(dir.path()); assert_eq!(std::fs::read_to_string(&path).expect("read"), "first"); assert_eq!( std::fs::metadata(&path).expect("meta").permissions().mode() & 0o777, 0o600 ); assert_eq!( std::fs::metadata(path.parent().expect("run dir")) .expect("meta") .permissions() .mode() & 0o777, 0o700 ); write_admin_token(dir.path(), "second").expect("rewrite"); assert_eq!(std::fs::read_to_string(&path).expect("read"), "second"); } #[tokio::test] async fn no_socket_means_no_server() { let dir = tempfile::tempdir().expect("tempdir"); let config = crate::test_support::test_config(dir.path()); assert!(running_server(&config).await.expect("probe").is_none()); } #[tokio::test] async fn stale_socket_means_no_server() { let dir = tempfile::tempdir().expect("tempdir"); let config = crate::test_support::test_config(dir.path()); // A socket file with no listener behind it, left by a crashed server. let listener = std::os::unix::net::UnixListener::bind(dir.path().join(SOCKET_FILE)).expect("bind"); drop(listener); assert!(running_server(&config).await.expect("probe").is_none()); } /// Serves the internal router on a real unix socket, as boot does, and talks to it through /// the client. Checks the answer, a refusal with the wrong token, and the no-server path. #[tokio::test] async fn client_talks_to_the_server_over_the_socket() { let dir = tempfile::tempdir().expect("tempdir"); let data_dir = dir.path().join("data"); std::fs::create_dir_all(&data_dir).expect("data dir"); let state = test_state(&data_dir).await; write_admin_token(&data_dir, ADMIN_TOKEN).expect("token"); let listener = tokio::net::UnixListener::bind(data_dir.join(SOCKET_FILE)).expect("bind"); let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); let server = tokio::spawn(topcoat::serve_until( listener, RouterService::new(crate::internal::router(state)), async move { let _ = stop_rx.await; }, )); let config = test_config(&data_dir); let client = running_server(&config) .await .expect("probe") .expect("the server is up"); let summary: FsckSummary = client .post( "/internal/admin/fsck", &serde_json::json!({ "full": false }), ) .await .expect("fsck through the socket"); assert!(summary.is_ok()); assert_eq!(summary.repos, 0); // The same route with a token that is not the admin token is refused. let wrong = AdminClient { socket: data_dir.join(SOCKET_FILE), token: "not-the-token".into(), }; let refused: Result = wrong .post("/internal/admin/fsck", &serde_json::json!({})) .await; assert!(matches!(refused, Err(Error::Forbidden(_))), "{refused:?}"); let _ = stop_tx.send(()); let _ = server.await; } }