Dungeon: invites are minted on a 0600 Unix socket; the HTTP router has no invite path
The peer-loopback gate on /admin/invite was open behind nginx, where every request has a loopback peer. The mint moves to invite.rs: a socket under the state root, and 'ghostlight-dungeon invite --state-root PATH HOURS' asks it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
588b0cca8f
commit
920bb3d289
4 changed files with 236 additions and 59 deletions
|
|
@ -11,7 +11,7 @@ use crate::{
|
|||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{ConnectInfo, DefaultBodyLimit, Path, State},
|
||||
extract::{DefaultBodyLimit, Path, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||||
response::{
|
||||
IntoResponse, Response,
|
||||
|
|
@ -23,7 +23,7 @@ use chrono::{DateTime, Utc};
|
|||
use ghostlight::{CommandId, VerifiedPrincipalEvidence};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{convert::Infallible, net::SocketAddr, time::Duration};
|
||||
use std::{convert::Infallible, time::Duration};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
pub(crate) const COOKIE_NAME: &str = "ghostlight_session";
|
||||
|
|
@ -49,7 +49,6 @@ pub(crate) fn router() -> Router<AppState> {
|
|||
.route("/api/auth/begin", post(auth_begin))
|
||||
.route("/api/auth/complete", post(auth_complete))
|
||||
.route("/api/auth/logout", post(auth_logout))
|
||||
.route("/admin/invite", post(mint_invite))
|
||||
.layer(DefaultBodyLimit::max(BODY_LIMIT))
|
||||
}
|
||||
|
||||
|
|
@ -564,39 +563,6 @@ async fn auth_logout(headers: HeaderMap, State(state): State<AppState>) -> Respo
|
|||
response
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct InviteBody {
|
||||
hours: u32,
|
||||
}
|
||||
|
||||
/// The operator's mint: loopback only, like the daemon's other service doors.
|
||||
/// Returns the token once; the catalog keeps only its hash.
|
||||
async fn mint_invite(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<AppState>,
|
||||
Json(body): Json<InviteBody>,
|
||||
) -> Response {
|
||||
if !peer.ip().is_loopback() {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
if body.hours == 0 || body.hours > 24 * 30 {
|
||||
return refuse(StatusCode::BAD_REQUEST, "an invite lives between 1 hour and 30 days");
|
||||
}
|
||||
match state
|
||||
.catalog
|
||||
.lock()
|
||||
.await
|
||||
.mint_invite(Utc::now(), chrono::Duration::hours(i64::from(body.hours)))
|
||||
{
|
||||
Ok(token) => reply(StatusCode::OK, json!({"invite": token})),
|
||||
Err(error) => {
|
||||
tracing::error!(%error, "an invite could not be minted");
|
||||
refuse(StatusCode::INTERNAL_SERVER_ERROR, "the invite could not be minted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -961,30 +927,28 @@ mod tests {
|
|||
assert_eq!(response.headers()[header::CONTENT_TYPE], "text/event-stream");
|
||||
}
|
||||
|
||||
/// Invites are minted on the operator's socket; the HTTP router has no
|
||||
/// invite path, from any peer, so the reverse proxy has nothing to forward.
|
||||
#[tokio::test]
|
||||
async fn the_invite_mint_is_loopback_only_and_its_token_enrols_once() {
|
||||
async fn no_http_path_mints_an_invite_even_from_loopback() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let mint = |peer: &str| {
|
||||
let mut request = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/admin/invite")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(json!({"hours": 2}).to_string()))
|
||||
.unwrap();
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap()));
|
||||
request
|
||||
};
|
||||
let refused = app.router.clone().oneshot(mint("203.0.113.9:1234")).await.unwrap();
|
||||
assert_eq!(refused.status(), StatusCode::FORBIDDEN);
|
||||
let minted = app.router.clone().oneshot(mint("127.0.0.1:1234")).await.unwrap();
|
||||
assert_eq!(minted.status(), StatusCode::OK);
|
||||
let body: Value = serde_json::from_slice(&to_bytes(minted.into_body(), 1 << 20).await.unwrap()).unwrap();
|
||||
let token = body["invite"].as_str().unwrap();
|
||||
let mut catalog = app.state.catalog.lock().await;
|
||||
assert!(catalog.sign_in("google:deru", Some(token), Utc::now()).unwrap().is_ok());
|
||||
assert!(catalog.sign_in("google:other", Some(token), Utc::now()).unwrap().is_err());
|
||||
for peer in ["127.0.0.1:1234", "203.0.113.9:1234"] {
|
||||
for uri in ["/admin/invite", "/invite", "/api/invite", "/api/admin/invite", "/admin"] {
|
||||
for method in [Method::POST, Method::GET] {
|
||||
let mut request = Request::builder()
|
||||
.method(method.clone())
|
||||
.uri(uri)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(json!({"hours": 2}).to_string()))
|
||||
.unwrap();
|
||||
request.extensions_mut().insert(axum::extract::ConnectInfo(
|
||||
peer.parse::<std::net::SocketAddr>().unwrap(),
|
||||
));
|
||||
let response = app.router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{method} {uri} from {peer}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
202
crates/ghostlight-dungeon/src/invite.rs
Normal file
202
crates/ghostlight-dungeon/src/invite.rs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
//! The operator's invite mint.
|
||||
//!
|
||||
//! Invites are minted on a Unix domain socket owned by the service user, mode
|
||||
//! 0600, under the state root. The HTTP router has no invite path, so the
|
||||
//! reverse proxy has nothing to forward: reaching the mint takes a local
|
||||
//! process running as the service user, not a peer-address test.
|
||||
//!
|
||||
//! Wire: the client writes one line, the number of hours. The daemon answers
|
||||
//! one JSON line, `{"invite": "<token>"}` or `{"error": "<why>"}`.
|
||||
|
||||
use crate::catalog::Catalog;
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use chrono::Utc;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
os::unix::{
|
||||
fs::{FileTypeExt, PermissionsExt},
|
||||
net::UnixStream as StdUnixStream,
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
|
||||
net::{UnixListener, UnixStream},
|
||||
sync::Mutex,
|
||||
};
|
||||
|
||||
/// An invite lives between one hour and thirty days.
|
||||
const MAX_HOURS: u32 = 24 * 30;
|
||||
const REQUEST_LIMIT: u64 = 32;
|
||||
|
||||
pub(crate) fn socket_path(runtime_root: &Path) -> PathBuf {
|
||||
runtime_root.join("service").join("invite.sock")
|
||||
}
|
||||
|
||||
/// Binds the mint socket, replacing a stale socket left by a previous run and
|
||||
/// refusing anything else at the path. The socket is created under a 0177 umask
|
||||
/// so it is never visible with wider permissions.
|
||||
pub(crate) fn bind(path: &Path) -> anyhow::Result<UnixListener> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) => {
|
||||
ensure!(
|
||||
metadata.file_type().is_socket(),
|
||||
"{} exists and is not a socket",
|
||||
path.display()
|
||||
);
|
||||
std::fs::remove_file(path).context("removing a stale invite socket")?;
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error).context("inspecting the invite socket path"),
|
||||
}
|
||||
// SAFETY: umask only swaps the process file-creation mask.
|
||||
let previous = unsafe { libc::umask(0o177) };
|
||||
let bound = UnixListener::bind(path);
|
||||
unsafe { libc::umask(previous) };
|
||||
let listener = bound.with_context(|| format!("binding {}", path.display()))?;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
|
||||
Ok(listener)
|
||||
}
|
||||
|
||||
pub(crate) async fn serve(listener: UnixListener, catalog: Arc<Mutex<Catalog>>) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await.context("accepting on the invite socket")?;
|
||||
let catalog = catalog.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = answer(stream, &catalog).await {
|
||||
tracing::warn!(%error, "an invite request failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn answer(stream: UnixStream, catalog: &Mutex<Catalog>) -> anyhow::Result<()> {
|
||||
let (read, mut write) = stream.into_split();
|
||||
let mut line = String::new();
|
||||
BufReader::new(read.take(REQUEST_LIMIT)).read_line(&mut line).await?;
|
||||
let reply = match mint(catalog, line.trim()).await {
|
||||
Ok(token) => json!({"invite": token}),
|
||||
Err(message) => json!({"error": message}),
|
||||
};
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mint(catalog: &Mutex<Catalog>, hours: &str) -> Result<String, String> {
|
||||
let hours: u32 = hours
|
||||
.parse()
|
||||
.map_err(|_| "the request is a whole number of hours".to_owned())?;
|
||||
if hours == 0 || hours > MAX_HOURS {
|
||||
return Err("an invite lives between 1 hour and 30 days".into());
|
||||
}
|
||||
catalog
|
||||
.lock()
|
||||
.await
|
||||
.mint_invite(Utc::now(), chrono::Duration::hours(i64::from(hours)))
|
||||
.map_err(|error| {
|
||||
tracing::error!(%error, "an invite could not be minted");
|
||||
"the invite could not be minted".to_owned()
|
||||
})
|
||||
}
|
||||
|
||||
/// The operator command: asks the running daemon at `runtime_root` for an invite.
|
||||
pub(crate) fn request(runtime_root: &Path, hours: u32) -> anyhow::Result<String> {
|
||||
use std::io::{BufRead, Write};
|
||||
let path = socket_path(runtime_root);
|
||||
let mut stream = StdUnixStream::connect(&path)
|
||||
.with_context(|| format!("no daemon is listening at {}", path.display()))?;
|
||||
writeln!(stream, "{hours}")?;
|
||||
let mut reply = String::new();
|
||||
std::io::BufReader::new(stream).read_line(&mut reply)?;
|
||||
let reply: Value = serde_json::from_str(&reply).context("the daemon's answer is not JSON")?;
|
||||
match (reply["invite"].as_str(), reply["error"].as_str()) {
|
||||
(Some(token), _) => Ok(token.to_owned()),
|
||||
(None, Some(error)) => bail!("{error}"),
|
||||
(None, None) => bail!("the daemon's answer names neither an invite nor an error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
fn catalog(directory: &Path) -> Arc<Mutex<Catalog>> {
|
||||
Arc::new(Mutex::new(Catalog::open(directory.join("catalog.cc")).unwrap()))
|
||||
}
|
||||
|
||||
async fn serving(root: &Path) -> Arc<Mutex<Catalog>> {
|
||||
std::fs::create_dir_all(root.join("service")).unwrap();
|
||||
let catalog = catalog(root);
|
||||
let listener = bind(&socket_path(root)).unwrap();
|
||||
tokio::spawn(serve(listener, catalog.clone()));
|
||||
catalog
|
||||
}
|
||||
|
||||
async fn ask(root: &Path, hours: u32) -> anyhow::Result<String> {
|
||||
let root = root.to_owned();
|
||||
tokio::task::spawn_blocking(move || request(&root, hours)).await.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_socket_is_private_and_its_token_enrols_exactly_once() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let catalog = serving(directory.path()).await;
|
||||
let mode = std::fs::metadata(socket_path(directory.path())).unwrap().mode();
|
||||
assert_eq!(mode & 0o777, 0o600, "mode {mode:o}");
|
||||
let token = ask(directory.path(), 2).await.unwrap();
|
||||
let mut catalog = catalog.lock().await;
|
||||
assert!(catalog.sign_in("google:deru", Some(&token), Utc::now()).unwrap().is_ok());
|
||||
assert!(catalog.sign_in("google:other", Some(&token), Utc::now()).unwrap().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_invite_lives_one_hour_to_thirty_days_and_expires_at_its_hours() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let catalog = serving(directory.path()).await;
|
||||
for hours in [0, 24 * 30 + 1] {
|
||||
let error = ask(directory.path(), hours).await.unwrap_err();
|
||||
assert!(error.to_string().contains("between 1 hour and 30 days"), "{hours}: {error}");
|
||||
}
|
||||
let longest = ask(directory.path(), 24 * 30).await.unwrap();
|
||||
let shortest = ask(directory.path(), 1).await.unwrap();
|
||||
let mut catalog = catalog.lock().await;
|
||||
let in_two_hours = Utc::now() + chrono::Duration::hours(2);
|
||||
assert!(catalog.sign_in("a", Some(&shortest), in_two_hours).unwrap().is_err());
|
||||
let in_thirty_days = Utc::now() + chrono::Duration::days(30) - chrono::Duration::minutes(1);
|
||||
assert!(catalog.sign_in("b", Some(&longest), in_thirty_days).unwrap().is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn binding_replaces_a_stale_socket_and_refuses_a_regular_file() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("invite.sock");
|
||||
drop(bind(&path).unwrap());
|
||||
assert!(path.exists(), "the dropped listener leaves its socket file");
|
||||
drop(bind(&path).unwrap());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::write(&path, "not a socket").unwrap();
|
||||
assert!(bind(&path).is_err());
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "not a socket");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_request_that_is_not_hours_mints_nothing() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let catalog = serving(directory.path()).await;
|
||||
let root = directory.path().to_owned();
|
||||
let reply = tokio::task::spawn_blocking(move || {
|
||||
use std::io::{Read, Write};
|
||||
let mut stream = StdUnixStream::connect(socket_path(&root)).unwrap();
|
||||
writeln!(stream, "soon").unwrap();
|
||||
let mut reply = String::new();
|
||||
stream.read_to_string(&mut reply).unwrap();
|
||||
reply
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(reply.contains("error"), "{reply}");
|
||||
assert!(catalog.lock().await.sign_in("x", Some("anything"), Utc::now()).unwrap().is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ mod begin;
|
|||
mod catalog;
|
||||
mod heimdall;
|
||||
mod idunn_health;
|
||||
mod invite;
|
||||
mod play;
|
||||
mod runtime;
|
||||
mod session_refresh;
|
||||
|
|
@ -17,9 +18,14 @@ use std::path::PathBuf;
|
|||
async fn main() -> anyhow::Result<()> {
|
||||
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
|
||||
let state_root = match args.as_slice() {
|
||||
[command, flag, path, hours] if command == "invite" && flag == "--state-root" => {
|
||||
let hours = hours.to_string_lossy().parse::<u32>()?;
|
||||
println!("{}", invite::request(&PathBuf::from(path), hours)?);
|
||||
return Ok(());
|
||||
}
|
||||
[flag, path] if flag == "--state-root" => Some(PathBuf::from(path)),
|
||||
[] => None,
|
||||
_ => bail!("usage: ghostlight-dungeon [--state-root PATH]"),
|
||||
_ => bail!("usage: ghostlight-dungeon [--state-root PATH] | ghostlight-dungeon invite --state-root PATH HOURS"),
|
||||
};
|
||||
runtime::run(state_root).await
|
||||
}
|
||||
|
|
|
|||
|
|
@ -242,6 +242,7 @@ pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<(
|
|||
(None, None) => None,
|
||||
_ => bail!("managed runtime health authority is partial"),
|
||||
};
|
||||
let invite_socket = crate::invite::bind(&crate::invite::socket_path(&runtime_root))?;
|
||||
let app = service_router(state.clone());
|
||||
tracing::info!(address = %bound_address, "Ghostlight Dungeon serving");
|
||||
let server = axum::serve(
|
||||
|
|
@ -250,6 +251,10 @@ pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<(
|
|||
);
|
||||
tokio::select! {
|
||||
result = server => result.context("Ghostlight HTTP server stopped"),
|
||||
result = crate::invite::serve(invite_socket, state.catalog.clone()) => {
|
||||
result?;
|
||||
bail!("invite socket owner stopped while the daemon was serving")
|
||||
}
|
||||
result = maintain_runtime_health(state.clone()) => {
|
||||
result?;
|
||||
bail!("runtime readiness owner stopped while the daemon was serving")
|
||||
|
|
|
|||
Loading…
Reference in a new issue