diff --git a/swarm-authelia-bridge-sock/src/lib.rs b/swarm-authelia-bridge-sock/src/lib.rs index 4a373eb4d..137a02fb6 100644 --- a/swarm-authelia-bridge-sock/src/lib.rs +++ b/swarm-authelia-bridge-sock/src/lib.rs @@ -25,9 +25,16 @@ //! file blob — that would invite a last-writer-wins race between independent //! callers and duplicate the rendering logic on both sides of the wire. +use std::time::Duration; + use hive_types::Ident; use serde::{Deserialize, Serialize}; +/// How long a caller waits for one bridge call, body included. The bridge's +/// own bounds (token introspection, lock wait, hash) sum to less than this, so +/// an answer arrives before the caller stops listening. +pub const BRIDGE_CALL_TIMEOUT: Duration = Duration::from_secs(30); + /// A request to the bridge — see the module doc for why this isn't a /// file-replace API. #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/swarm-authelia-bridge/README.md b/swarm-authelia-bridge/README.md index ef29bde48..06e30c78f 100644 --- a/swarm-authelia-bridge/README.md +++ b/swarm-authelia-bridge/README.md @@ -54,7 +54,9 @@ What still has to hold, since two processes share the file: - **One lock around read → write.** Both take an exclusive `flock` on `users.yml.lock`, a sibling file in the same directory, before loading and - hold it until the rename lands, waiting at most 10 seconds. Reading the + hold it until the rename lands. `swarmctl` waits at most 10 seconds for it; + the bridge waits at most 5 seconds for it and for the bridge's own write + lock together, then answers `503`. Reading the file first is not enough: both writers spend about a second minting a password between load and write, and the second rename would drop the first writer's user. The lock file is opened `O_NOFOLLOW`, so a symlink diff --git a/swarm-authelia-bridge/src/introspect.rs b/swarm-authelia-bridge/src/introspect.rs index 4616d9fc0..8aaa88ff7 100644 --- a/swarm-authelia-bridge/src/introspect.rs +++ b/swarm-authelia-bridge/src/introspect.rs @@ -27,15 +27,11 @@ use std::time::Duration; use serde::Deserialize; -/// One attempt, no retry. authelia's introspection endpoint takes up to -/// ~19s when its host is overloaded, and this covers that. It must stay -/// below the controller's 30s bound on a whole bridge call -/// (`swarm-controller`'s `auth::HTTP_TIMEOUT`), or the controller gives up -/// on the bridge before the bridge has answered. A timeout is still -/// [`Verdict::Unavailable`], never an admission. -pub const INTROSPECTION_TIMEOUT: Duration = Duration::from_secs(20); - -const _: () = assert!(INTROSPECTION_TIMEOUT.as_secs() < 30); +/// One attempt, no retry. A slower answer is [`Verdict::Unavailable`], which +/// the controller retries; it is never an admission. This is one leg of the +/// bridge's worst case, which `main`'s budget assertion holds below +/// [`swarm_authelia_bridge_sock::BRIDGE_CALL_TIMEOUT`]. +pub const INTROSPECTION_TIMEOUT: Duration = Duration::from_secs(15); /// `active` decides whether to admit; `client_id` says as whom, which is /// what lets one verb be scoped to a single client. Same two fields, for the diff --git a/swarm-authelia-bridge/src/main.rs b/swarm-authelia-bridge/src/main.rs index dc7e2050c..f81639bd7 100644 --- a/swarm-authelia-bridge/src/main.rs +++ b/swarm-authelia-bridge/src/main.rs @@ -32,6 +32,7 @@ mod introspect; mod store; use std::sync::Arc; +use std::time::Duration; use anyhow::{Context, Result, bail}; use axum::body::Bytes; @@ -103,8 +104,49 @@ struct AppState { /// in `generate_password` and `publish`. It covers this process only; /// `store::lock_users_file` is the lock against `swarmctl`. write_lock: tokio::sync::Mutex<()>, + bounds: Bounds, } +/// How long one `EnsureAgentIdentity` may wait on things it does not control. +#[derive(Debug, Clone, Copy)] +struct Bounds { + /// Total wait for the in-process write lock and the `users.yml` `flock` + /// together: one deadline, not one per lock. + lock_wait: Duration, + /// How long the authelia hash child may run before it is killed. + hash_timeout: Duration, +} + +impl Bounds { + const PRODUCTION: Self = Self { + lock_wait: store::USERS_LOCK_WAIT, + hash_timeout: HASH_TIMEOUT, + }; +} + +/// Longest the `authelia crypto hash` child runs while the locks are held. +/// A hash takes well under a second on an idle host. +const HASH_TIMEOUT: Duration = Duration::from_secs(6); + +/// Slack between the bridge's worst case and the controller's call budget, +/// for the work with no bound of its own: parsing, the file write, the reply. +const BUDGET_MARGIN: Duration = Duration::from_secs(2); + +/// The longest a request spends in the bridge: the bearer token's +/// introspection, then the lock wait, then the hash. +const fn worst_case_millis() -> u128 { + introspect::INTROSPECTION_TIMEOUT.as_millis() + + store::USERS_LOCK_WAIT.as_millis() + + HASH_TIMEOUT.as_millis() +} + +// The controller gives up on a call after `BRIDGE_CALL_TIMEOUT` and does not +// retry it, while the bridge may still go on to create the identity. +const _: () = assert!( + worst_case_millis() + BUDGET_MARGIN.as_millis() + < swarm_authelia_bridge_sock::BRIDGE_CALL_TIMEOUT.as_millis() +); + #[tokio::main] async fn main() -> Result<()> { let stop = swarm_secret_client::shutdown_signal(); @@ -122,6 +164,7 @@ async fn main() -> Result<()> { config, http: reqwest::Client::new(), write_lock: tokio::sync::Mutex::new(()), + bounds: Bounds::PRODUCTION, }); let app = router(Arc::clone(&state)); @@ -187,7 +230,7 @@ fn bind_socket(path: &std::path::Path) -> Result { /// alone. async fn handle_request(State(state): State>, body: Bytes) -> Response { match serde_json::from_slice(&body) { - Ok(req) => respond(&state.config, &state.write_lock, req).await, + Ok(req) => respond(&state.config, &state.write_lock, state.bounds, req).await, Err(e) => unreadable(&e), } } @@ -244,31 +287,78 @@ fn unreadable(e: &serde_json::Error) -> Response { .into_response() } -/// Everything after authentication: the operation itself. Takes the config -/// and the write lock rather than [`AppState`], whose HTTP client only -/// [`authorize`] uses. +/// Everything after authentication: the operation itself. Takes the config, +/// the write lock and the bounds rather than [`AppState`], whose HTTP client +/// only [`authorize`] uses. async fn respond( config: &Config, write_lock: &tokio::sync::Mutex<()>, + bounds: Bounds, req: BridgeRequest, ) -> Response { let (op, result) = match req { - BridgeRequest::EnsureAgentIdentity { name } => { - ("ensure_identity", handle(config, write_lock, name).await) + BridgeRequest::EnsureAgentIdentity { name } => ( + "ensure_identity", + handle(config, write_lock, bounds, name).await, + ), + BridgeRequest::ListAgentIdentities => { + ("list_identities", list(config).map_err(HandleError::from)) } - BridgeRequest::ListAgentIdentities => ("list_identities", list(config)), - BridgeRequest::ListOperators => ("list_operators", list_operators(config)), + BridgeRequest::ListOperators => ( + "list_operators", + list_operators(config).map_err(HandleError::from), + ), }; match result { Ok(body) => (StatusCode::OK, Json(body)).into_response(), Err(e) => { - let detail = format!("{e:#}"); + let detail = format!("{:#}", e.cause()); tracing::warn!(op, error = %detail, "request failed"); - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(BridgeResponse::Error { message: detail }), - ) - .into_response() + (e.status(), Json(BridgeResponse::Error { message: detail })).into_response() + } + } +} + +/// Why an operation failed, by what the caller can do about it. +#[derive(Debug)] +enum HandleError { + /// A bound on a wait expired (a lock, the hash child). The same request + /// can succeed later: `503`, which `swarm-controller` retries. + Transient(anyhow::Error), + /// The request itself is unacceptable (an invalid or reserved name): + /// `400`. Repeating it cannot help. + Caller(anyhow::Error), + /// Anything else: `500`. + Internal(anyhow::Error), +} + +impl HandleError { + fn status(&self) -> StatusCode { + match self { + HandleError::Transient(_) => StatusCode::SERVICE_UNAVAILABLE, + HandleError::Caller(_) => StatusCode::BAD_REQUEST, + HandleError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, + } + } + + fn cause(&self) -> &anyhow::Error { + match self { + HandleError::Transient(e) | HandleError::Caller(e) | HandleError::Internal(e) => e, + } + } +} + +impl From for HandleError { + fn from(e: anyhow::Error) -> Self { + HandleError::Internal(e) + } +} + +impl From for HandleError { + fn from(e: store::LockError) -> Self { + match e { + store::LockError::TimedOut(_) => HandleError::Transient(e.into()), + store::LockError::Failed(_) => HandleError::Internal(e.into()), } } } @@ -398,31 +488,47 @@ fn refuse(refusal: Refusal) -> Response { async fn handle( cfg: &Config, write_lock: &tokio::sync::Mutex<()>, + bounds: Bounds, name: String, -) -> Result { +) -> Result { // The rule the roster reads with: `list` keeps only subjects that parse as // an `Ident`, so a name the store would accept but `Ident` refuses (an // uppercase letter, `.`, `_`) would be written, then dropped from the // roster for good. Refused here, before the store is touched. - hive_types::Ident::parse(&name).map_err(|e| { - anyhow::anyhow!("{name:?} is not an agent name (lower-case a-z, 0-9, `-`): {e}") - })?; - store::validate_username(&name)?; + hive_types::Ident::parse(&name) + .map_err(|e| { + anyhow::anyhow!("{name:?} is not an agent name (lower-case a-z, 0-9, `-`): {e}") + }) + .map_err(HandleError::Caller)?; + store::validate_username(&name).map_err(HandleError::Caller)?; // After the charset check and before anything touches the store: a // reserved name is refused on its own terms, not as a side effect of a // collision with whatever happens to be in the file today. - store::reject_reserved_name(&name)?; + store::reject_reserved_name(&name).map_err(HandleError::Caller)?; // Held across the whole load → insert → publish sequence, not just the // write — two concurrent `EnsureAgentIdentity` calls must not both read // the same on-disk snapshot before either publishes. See the field's // doc comment on `AppState::write_lock` for why this is reachable in // practice, not just theoretically. - let _write_guard = write_lock.lock().await; + let deadline = tokio::time::Instant::now() + bounds.lock_wait; + let _write_guard = tokio::time::timeout_at(deadline, write_lock.lock()) + .await + .map_err(|_| { + HandleError::Transient(anyhow::anyhow!( + "timed out after {:?} waiting for another identity request to finish", + bounds.lock_wait + )) + })?; // The in-process lock does not cover `swarmctl`, which rewrites the same // file from the host: the `flock` does, and is held to the end of the - // function like the guard above. - let _file_lock = store::lock_users_file(&cfg.users_file, store::USERS_LOCK_WAIT).await?; + // function like the guard above. It waits only for what is left of the + // one deadline. + let _file_lock = store::lock_users_file( + &cfg.users_file, + deadline.saturating_duration_since(tokio::time::Instant::now()), + ) + .await?; let mut user_store = store::load_store(&cfg.users_file)?; if user_store.users.contains_key(&name) { @@ -448,7 +554,7 @@ async fn handle( } return Ok(BridgeResponse::AlreadyExists); } - let generated = generate_password(&cfg.authelia_bin).await?; + let generated = generate_password(&cfg.authelia_bin, bounds.hash_timeout).await?; user_store.users.insert( name.clone(), store::User { @@ -519,9 +625,26 @@ fn list_operators(config: &Config) -> Result { /// plaintext is generated and immediately discarded, since nothing reads /// it back today (still an open question what an agent's login actually /// uses this for). -async fn generate_password(bin: &std::path::Path) -> Result { +/// +/// The child is killed when `timeout` passes, which is a +/// [`HandleError::Transient`], and when the caller's future is dropped. +async fn generate_password( + bin: &std::path::Path, + timeout: Duration, +) -> Result { + match tokio::time::timeout(timeout, run_hash(bin)).await { + Ok(hashed) => hashed.map_err(HandleError::Internal), + Err(_) => Err(HandleError::Transient(anyhow::anyhow!( + "{} did not finish within {timeout:?}", + bin.display() + ))), + } +} + +async fn run_hash(bin: &std::path::Path) -> Result { let out = tokio::process::Command::new(bin) .args(["crypto", "hash", "generate", "argon2", "--random"]) + .kill_on_drop(true) .output() .await .with_context(|| format!("running {}", bin.display()))?; @@ -558,8 +681,9 @@ mod tests { use axum::routing::post; use super::{ - AppState, BridgeRequest, Config, Refusal, StatusCode, bind_socket, classify, handle, - handle_request, introspect::Verdict, protect, respond, router, routes, + AppState, Bounds, BridgeRequest, BridgeResponse, Config, Duration, HASH_TIMEOUT, Refusal, + StatusCode, bind_socket, classify, handle, handle_request, introspect::Verdict, protect, + respond, router, routes, worst_case_millis, }; const CONTROLLER: &str = "swarm-controller"; @@ -694,6 +818,7 @@ mod tests { config: config_with_one_operator(), http: reqwest::Client::new(), write_lock: tokio::sync::Mutex::new(()), + bounds: PATIENT, }) } @@ -781,7 +906,7 @@ mod tests { async fn the_operator_list_is_the_operator_groups_members() { let config = config_with_one_operator(); let lock = tokio::sync::Mutex::new(()); - let answered = respond(&config, &lock, BridgeRequest::ListOperators).await; + let answered = respond(&config, &lock, PATIENT, BridgeRequest::ListOperators).await; assert_eq!(answered.status(), StatusCode::OK); let body = axum::body::to_bytes(answered.into_body(), usize::MAX) .await @@ -830,13 +955,12 @@ mod tests { let write_lock = tokio::sync::Mutex::new(()); for name in ["Atlas", "at_las", "at.las", "ATLAS"] { - let err = handle(&config, &write_lock, name.to_owned()) + let err = handle(&config, &write_lock, PATIENT, name.to_owned()) .await .expect_err(name); - assert!( - format!("{err:#}").contains("not an agent name"), - "{name}: {err:#}" - ); + assert_eq!(err.status(), StatusCode::BAD_REQUEST, "{name}"); + let cause = format!("{:#}", err.cause()); + assert!(cause.contains("not an agent name"), "{name}: {cause}"); assert_eq!( std::fs::read_to_string(&config.users_file).unwrap(), before, @@ -845,7 +969,7 @@ mod tests { } // The control: a legal name is created, so the refusals above are the // check and not a broken fixture. - handle(&config, &write_lock, "atlas".to_owned()) + handle(&config, &write_lock, PATIENT, "atlas".to_owned()) .await .expect("a legal name is created"); assert_ne!(std::fs::read_to_string(&config.users_file).unwrap(), before); @@ -924,7 +1048,7 @@ mod tests { let users_file = config.users_file.clone(); ( tokio::spawn(async move { - handle(&config, &write_lock, "atlas".to_owned()) + handle(&config, &write_lock, PATIENT, "atlas".to_owned()) .await .map(|_| ()) }), @@ -949,4 +1073,196 @@ mod tests { ); let _ = std::fs::remove_dir_all(users_file.parent().unwrap()); } + + /// Bounds long enough that no test trips them by accident. + const PATIENT: Bounds = Bounds { + lock_wait: Duration::from_secs(5), + hash_timeout: Duration::from_secs(5), + }; + + const PRINTS_A_DIGEST: &str = + "#!/bin/sh\nprintf 'Random Password: pw\\nDigest: $argon2id$x\\n'\n"; + + fn ensure(name: &str) -> BridgeRequest { + BridgeRequest::EnsureAgentIdentity { + name: name.to_owned(), + } + } + + /// The status and the decoded body of an answer. + async fn read(answered: axum::response::Response) -> (StatusCode, BridgeResponse) { + let status = answered.status(); + let body = axum::body::to_bytes(answered.into_body(), usize::MAX) + .await + .unwrap(); + (status, serde_json::from_slice(&body).unwrap()) + } + + /// A config whose `authelia` is the script `body`, next to the users file. + fn config_with_authelia(body: &str) -> Config { + let mut config = config_with_one_operator(); + let authelia = config.users_file.with_file_name("authelia"); + write_executable(&authelia, body); + config.authelia_bin = authelia; + config + } + + fn is_running(pid: &str) -> bool { + std::fs::read_to_string(format!("/proc/{pid}/stat")) + .is_ok_and(|stat| !stat.rsplit(") ").next().unwrap_or("").starts_with('Z')) + } + + /// A hash child that outlives its bound is killed and answered `503`, and + /// neither lock stays held: the next request goes through. + #[tokio::test] + async fn a_hash_that_outlives_its_bound_is_a_503_and_frees_the_locks() { + let mut config = config_with_one_operator(); + let pidfile = config.users_file.with_file_name("hash.pid"); + config.authelia_bin = config.users_file.with_file_name("authelia"); + write_executable( + &config.authelia_bin, + &format!( + "#!/bin/sh\necho $$ > {}\nexec sleep 30\n", + pidfile.display() + ), + ); + let users_file = config.users_file.clone(); + let write_lock = tokio::sync::Mutex::new(()); + + let slow = Bounds { + hash_timeout: Duration::from_secs(1), + ..PATIENT + }; + let (status, body) = read(respond(&config, &write_lock, slow, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(matches!(body, BridgeResponse::Error { .. }), "{body:?}"); + + let pid = std::fs::read_to_string(&pidfile) + .expect("the stub ran") + .trim() + .to_owned(); + let mut waited = 0; + while is_running(&pid) && waited < 50 { + tokio::time::sleep(Duration::from_millis(100)).await; + waited += 1; + } + assert!( + !is_running(&pid), + "the timed-out hash child is still running" + ); + + drop(write_lock.try_lock().expect("the write lock is free")); + drop( + crate::store::lock_users_file(&users_file, Duration::from_millis(100)) + .await + .expect("the users file lock is free"), + ); + assert!( + !crate::store::load_store(&users_file) + .unwrap() + .users + .contains_key("atlas"), + "a timed-out request must not create the identity" + ); + + write_executable( + &config.users_file.with_file_name("authelia-ok"), + PRINTS_A_DIGEST, + ); + config.authelia_bin = config.users_file.with_file_name("authelia-ok"); + let (status, body) = + read(respond(&config, &write_lock, PATIENT, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::OK); + assert!(matches!(body, BridgeResponse::Created), "{body:?}"); + let _ = std::fs::remove_dir_all(users_file.parent().unwrap()); + } + + /// The `users.yml` lock held past the wait is a `503`, not a final `500`; + /// once it is released the same request succeeds. + #[tokio::test] + async fn a_users_file_lock_held_past_the_wait_is_a_503() { + let config = config_with_authelia(PRINTS_A_DIGEST); + let write_lock = tokio::sync::Mutex::new(()); + let held = crate::store::lock_users_file(&config.users_file, Duration::from_secs(1)) + .await + .unwrap(); + let short = Bounds { + lock_wait: Duration::from_millis(200), + ..PATIENT + }; + let (status, body) = + read(respond(&config, &write_lock, short, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(matches!(body, BridgeResponse::Error { .. }), "{body:?}"); + + drop(held); + let (status, _) = read(respond(&config, &write_lock, short, ensure("atlas")).await).await; + assert_eq!( + status, + StatusCode::OK, + "control: the released lock is granted" + ); + let _ = std::fs::remove_dir_all(config.users_file.parent().unwrap()); + } + + /// The in-process write lock held past the wait is a `503` too. + #[tokio::test] + async fn a_write_lock_held_past_the_wait_is_a_503() { + let config = config_with_authelia(PRINTS_A_DIGEST); + let write_lock = tokio::sync::Mutex::new(()); + let short = Bounds { + lock_wait: Duration::from_millis(200), + ..PATIENT + }; + let guard = write_lock.lock().await; + let (status, _) = read(respond(&config, &write_lock, short, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + + drop(guard); + let (status, _) = read(respond(&config, &write_lock, short, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::OK, "control: the free lock is taken"); + let _ = std::fs::remove_dir_all(config.users_file.parent().unwrap()); + } + + /// A name the caller chose badly is a `400`; a failure of the bridge's + /// own is a `500`. The valid-name request is the control for both. + #[tokio::test] + async fn a_bad_name_is_a_400_and_an_internal_failure_a_500() { + let mut config = config_with_authelia(PRINTS_A_DIGEST); + let write_lock = tokio::sync::Mutex::new(()); + for name in ["operator", "bad name"] { + let (status, body) = + read(respond(&config, &write_lock, PATIENT, ensure(name)).await).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{name:?}"); + assert!(matches!(body, BridgeResponse::Error { .. }), "{body:?}"); + } + + config.authelia_bin = config.users_file.with_file_name("no-such-authelia"); + let (status, _) = read(respond(&config, &write_lock, PATIENT, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + + config.authelia_bin = config.users_file.with_file_name("authelia"); + let (status, _) = read(respond(&config, &write_lock, PATIENT, ensure("atlas")).await).await; + assert_eq!(status, StatusCode::OK, "control: a valid name is created"); + let _ = std::fs::remove_dir_all(config.users_file.parent().unwrap()); + } + + /// The whole worst case, not one leg of it, fits in the controller's call + /// budget with the margin to spare. + #[test] + fn the_worst_case_fits_in_the_controllers_budget() { + let worst = worst_case_millis(); + for leg in [ + crate::introspect::INTROSPECTION_TIMEOUT, + crate::store::USERS_LOCK_WAIT, + HASH_TIMEOUT, + ] { + assert!(worst > leg.as_millis(), "control: the sum covers {leg:?}"); + } + assert!( + worst + super::BUDGET_MARGIN.as_millis() + < swarm_authelia_bridge_sock::BRIDGE_CALL_TIMEOUT.as_millis(), + "{worst} ms of bridge timeouts leave no room in the controller's call budget" + ); + } } diff --git a/swarm-authelia-bridge/src/store.rs b/swarm-authelia-bridge/src/store.rs index a6972e2e3..be7349bf5 100644 --- a/swarm-authelia-bridge/src/store.rs +++ b/swarm-authelia-bridge/src/store.rs @@ -319,8 +319,35 @@ fn fill_missing_emails(store: &mut UserStore) { } } -/// How long a writer waits for the other process's `users.yml` update. -pub const USERS_LOCK_WAIT: Duration = Duration::from_secs(10); +/// How long one request waits for the in-process write lock and the other +/// process's `users.yml` update, together. +pub const USERS_LOCK_WAIT: Duration = Duration::from_secs(5); + +/// Why [`lock_users_file`] did not return the lock. +#[derive(Debug)] +pub enum LockError { + /// Another holder kept the lock for the whole wait. + TimedOut(String), + /// The lock file could not be opened, checked or locked. + Failed(anyhow::Error), +} + +impl std::fmt::Display for LockError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + LockError::TimedOut(message) => f.write_str(message), + LockError::Failed(e) => write!(f, "{e:#}"), + } + } +} + +impl std::error::Error for LockError {} + +impl From for LockError { + fn from(e: anyhow::Error) -> Self { + LockError::Failed(e) + } +} /// Take the exclusive `flock` on `.lock`, held until the /// returned file drops. @@ -334,7 +361,12 @@ pub const USERS_LOCK_WAIT: Duration = Duration::from_secs(10); /// because `write_atomic` replaces that inode on every write. It is opened /// `O_NOFOLLOW` and `O_NONBLOCK` (a planted symlink or FIFO cannot redirect or /// hang it) and must be a regular file; no ownership is touched by path. -pub async fn lock_users_file(users_file: &Path, wait: Duration) -> Result { +/// +/// # Errors +/// +/// [`LockError::TimedOut`] when `wait` passes with the lock still held; +/// [`LockError::Failed`] for anything else. +pub async fn lock_users_file(users_file: &Path, wait: Duration) -> Result { let dir = users_file .parent() .with_context(|| format!("{} has no parent directory", users_file.display()))?; @@ -364,7 +396,7 @@ pub async fn lock_users_file(users_file: &Path, wait: Duration) -> Result .with_context(|| format!("stat {}", lock_path.display()))? .is_file() { - bail!("{} is not a regular file", lock_path.display()); + return Err(anyhow::anyhow!("{} is not a regular file", lock_path.display()).into()); } let deadline = tokio::time::Instant::now() + wait; @@ -376,14 +408,18 @@ pub async fn lock_users_file(users_file: &Path, wait: Duration) -> Result { tokio::time::sleep(Duration::from_millis(50)).await; } - Err(e) if e == rustix::io::Errno::WOULDBLOCK => bail!( - "timed out after {wait:?} waiting for {}: another process (`swarmctl user`) \ - is updating {}", - lock_path.display(), - users_file.display() - ), + Err(e) if e == rustix::io::Errno::WOULDBLOCK => { + return Err(LockError::TimedOut(format!( + "timed out after {wait:?} waiting for {}: another process (`swarmctl user`) \ + is updating {}", + lock_path.display(), + users_file.display() + ))); + } Err(e) => { - return Err(e).with_context(|| format!("locking {}", lock_path.display())); + return Err(anyhow::Error::new(e) + .context(format!("locking {}", lock_path.display())) + .into()); } } } diff --git a/swarm-controller/src/auth.rs b/swarm-controller/src/auth.rs index 0a4e2240a..51e8052d8 100644 --- a/swarm-controller/src/auth.rs +++ b/swarm-controller/src/auth.rs @@ -25,10 +25,9 @@ use swarm_authelia_bridge_sock::{BridgeRequest, BridgeResponse}; /// Bound on reaching the bridge. const HTTP_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); -/// Bound on one whole bridge call, body included. Ensuring an identity has -/// the bridge shell out to `authelia` for an argon2 hash before it answers, -/// so this is looser than a plain API call needs. -const HTTP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +/// Bound on one whole bridge call, body included. Shared with the bridge, +/// whose worst case is held below it. +const HTTP_TIMEOUT: std::time::Duration = swarm_authelia_bridge_sock::BRIDGE_CALL_TIMEOUT; /// A configured connection to `swarm-authelia-bridge`. #[derive(Clone)] @@ -140,9 +139,13 @@ const RETRY_BACKOFF: &[std::time::Duration] = &[ /// POST `req` to the bridge, retrying a `503` or a failure to connect after /// each wait in `backoff`. /// -/// `503` is the bridge saying it could not get an answer out of authelia, so -/// the token was never evaluated; the same call usually succeeds once -/// authelia recovers. `401` and `403` are verdicts on the token and are +/// `503` is the bridge saying the call is worth repeating, for one of three +/// reasons: it could not get an answer out of authelia, so the token was never +/// evaluated; or, after the token was admitted, a lock stayed held past the +/// bridge's wait, or the password hash outlived its bound. The first usually +/// clears once authelia recovers. The other two act on an admitted request, so +/// the retry may find the identity already created, which the idempotent +/// ensure answers. `401` and `403` are verdicts on the token and are /// final, as is any other status. A timeout after the connection was made /// is not retried: the request may have been acted on, and a whole attempt /// already took [`HTTP_TIMEOUT`]. Every bridge request is safe to repeat