From 2bc656f8f1dadd622c3496006322f4a9f276b1ac Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Fri, 9 Oct 2026 21:59:54 +0200 Subject: [PATCH] Tidy clippy findings in MCP-related server code Collapse nested ifs with let chains in token_scope, jobs, entry visibility and run-link helpers; move test module to the end of test_support.rs; drop needless borrows in routes tests. Co-Authored-By: Claude Sonnet 5.5 --- crates/archivr-core/src/capture.rs | 8 +- crates/archivr-server/src/jobs.rs | 12 +- crates/archivr-server/src/routes.rs | 15 +- crates/archivr-server/src/test_support.rs | 198 +++++++++++----------- crates/archivr-server/src/token_scope.rs | 30 ++-- 5 files changed, 130 insertions(+), 133 deletions(-) diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index 67ab805..58a4091 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -1224,10 +1224,10 @@ fn fail_run( /// Records `run_uid` on the capture job (if any) the moment the run exists. Best effort: a /// failure must never fail the capture itself, it only delays the link until the job ends. fn link_job_to_run(conn: &rusqlite::Connection, job_uid: Option<&str>, run_uid: &str) { - if let Some(job_uid) = job_uid { - if let Err(e) = database::link_capture_job_run(conn, job_uid, run_uid) { - eprintln!("warn: could not link capture job {job_uid} to run {run_uid}: {e:#}"); - } + if let Some(job_uid) = job_uid + && let Err(e) = database::link_capture_job_run(conn, job_uid, run_uid) + { + eprintln!("warn: could not link capture job {job_uid} to run {run_uid}: {e:#}"); } } diff --git a/crates/archivr-server/src/jobs.rs b/crates/archivr-server/src/jobs.rs index cd8f25b..eab359a 100644 --- a/crates/archivr-server/src/jobs.rs +++ b/crates/archivr-server/src/jobs.rs @@ -67,12 +67,12 @@ async fn list_capture_jobs_handler( Query(q): Query, ) -> Result>, ApiError> { auth.require_role(ROLE_USER)?; - if let Some(status) = q.status.as_deref() { - if !capture_jobs::JOB_STATUSES.contains(&status) { - return Err(ApiError::bad_request( - "invalid status: must be pending, running, completed, or failed", - )); - } + if let Some(status) = q.status.as_deref() + && !capture_jobs::JOB_STATUSES.contains(&status) + { + return Err(ApiError::bad_request( + "invalid status: must be pending, running, completed, or failed", + )); } let limit = parse_int_param("limit", q.limit.as_deref())? .unwrap_or(capture_jobs::JOB_LIST_DEFAULT_LIMIT); diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 87eca4b..f0a5559 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -3294,12 +3294,11 @@ pub(crate) fn ensure_entry_visible( auth: &AuthUser, entry_uid: &str, ) -> Result<(), ApiError> { - if let AuthUser::Authenticated { role_bits, .. } = auth { - if role_bits & (ROLE_ADMIN | ROLE_OWNER) == 0 - && !database::caller_can_access_entry(conn, entry_uid, *role_bits)? - { - return Err(ApiError::not_found("entry not found")); - } + if let AuthUser::Authenticated { role_bits, .. } = auth + && role_bits & (ROLE_ADMIN | ROLE_OWNER) == 0 + && !database::caller_can_access_entry(conn, entry_uid, *role_bits)? + { + return Err(ApiError::not_found("entry not found")); } Ok(()) } @@ -7863,7 +7862,7 @@ mod tests { .oneshot( Request::builder() .method("PATCH") - .uri(&format!("/api/archives/test/entries/{}", entry.entry_uid)) + .uri(format!("/api/archives/test/entries/{}", entry.entry_uid)) .header("content-type", "application/json") .header("cookie", &session_cookie) .body(Body::from(r#"{"title":"Renamed Title"}"#)) @@ -7877,7 +7876,7 @@ mod tests { let get_resp = app(registry, auth_path) .oneshot( Request::builder() - .uri(&format!("/api/archives/test/entries/{}", entry.entry_uid)) + .uri(format!("/api/archives/test/entries/{}", entry.entry_uid)) .header("cookie", &session_cookie) .body(Body::empty()) .unwrap(), diff --git a/crates/archivr-server/src/test_support.rs b/crates/archivr-server/src/test_support.rs index b61f761..dcdb583 100644 --- a/crates/archivr-server/src/test_support.rs +++ b/crates/archivr-server/src/test_support.rs @@ -5,6 +5,9 @@ use std::path::{Path, PathBuf}; use archivr_core::database; use axum::body::Body; +use axum::{Router, http::{Request, StatusCode}}; +use serde_json::{Value, json}; +use tower::ServiceExt; use crate::auth; use crate::registry::{MountedArchive, ServerRegistry}; @@ -157,108 +160,9 @@ pub(crate) fn json_body(payload: &serde_json::Value) -> Body { Body::from(serde_json::to_vec(payload).unwrap()) } -#[cfg(test)] -mod tests { - use super::*; - use crate::routes::app; - use axum::http::{Request, StatusCode}; - use tower::ServiceExt; - - #[tokio::test] - async fn session_helpers_and_bearer_token_authenticate() { - let dir = tempfile::tempdir().unwrap(); - let (registry, _, auth_path) = make_test_registry(&dir); - let owner = owner_session(&auth_path); - let admin = admin_session(&auth_path); - let user = user_session(&auth_path); - let guest = guest_session(&auth_path); - let token = make_api_token(&auth_path, "test-user", None, "full"); - - let me = |cookie: Option, bearer: Option| { - let registry = registry.clone(); - let auth_path = auth_path.clone(); - async move { - let mut b = Request::builder().uri("/api/auth/me"); - if let Some(c) = cookie { - b = b.header("cookie", c); - } - if let Some(t) = bearer { - b = b.header("authorization", format!("Bearer {t}")); - } - let resp = app(registry, auth_path) - .oneshot(b.body(Body::empty()).unwrap()) - .await - .unwrap(); - let status = resp.status(); - (status, body_json(resp).await) - } - }; - for (cookie, role_bit) in [(owner, 8u64), (admin, 4), (user, 2), (guest, 1)] { - let (status, body) = me(Some(cookie), None).await; - assert_eq!(status, StatusCode::OK); - assert!(body["role_bits"].as_u64().unwrap() & role_bit != 0, "{body}"); - } - let (status, body) = me(None, Some(token)).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(body["username"], "test-user"); - - // Back-dated token expiry is rejected as unauthenticated. - let past = (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339(); - let expired = make_api_token(&auth_path, "test-user", Some(&past), "full"); - let (status, _) = me(None, Some(expired)).await; - assert_eq!(status, StatusCode::UNAUTHORIZED); - } - - // Axum 0.7.9 `Router::merge` semantics, pinned for the stream modules. - async fn status_of(router: axum::Router, method: &str, uri: &str) -> StatusCode { - router - .oneshot( - Request::builder() - .method(method) - .uri(uri) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap() - .status() - } - - #[tokio::test] - async fn merge_adds_new_methods_to_an_existing_path() { - use axum::routing::{delete, get, post}; - let base = axum::Router::new().route("/api/auth/tokens", get(|| async { "list" }).post(|| async { "create" })); - // A merged router adding DELETE (a new method) on the same path: fine. - let extra = axum::Router::new().route("/api/auth/tokens", delete(|| async { "revoke-all" })); - let merged = base.merge(extra); - assert_eq!(status_of(merged.clone(), "GET", "/api/auth/tokens").await, StatusCode::OK); - assert_eq!(status_of(merged.clone(), "POST", "/api/auth/tokens").await, StatusCode::OK); - assert_eq!(status_of(merged.clone(), "DELETE", "/api/auth/tokens").await, StatusCode::OK); - assert_eq!(status_of(merged, "PUT", "/api/auth/tokens").await, StatusCode::METHOD_NOT_ALLOWED); - // Same for routes registered by two merged routers on one new path. - let a = axum::Router::new().route("/x", get(|| async { "a" })); - let b = axum::Router::new().route("/x", post(|| async { "b" })); - let merged = a.merge(b); - assert_eq!(status_of(merged.clone(), "GET", "/x").await, StatusCode::OK); - assert_eq!(status_of(merged, "POST", "/x").await, StatusCode::OK); - } - - #[test] - #[should_panic(expected = "Overlapping method route")] - fn merge_panics_when_the_same_method_is_registered_twice() { - use axum::routing::get; - let base = axum::Router::<()>::new().route("/api/auth/tokens", get(|| async { "list" })); - let extra = axum::Router::new().route("/api/auth/tokens", get(|| async { "dup" })); - let _ = base.merge(extra); - } -} // ---- HTTP fixture shared by router-level tests ---- -use axum::{Router, http::{Request, StatusCode}}; -use serde_json::{Value, json}; -use tower::ServiceExt; - pub(crate) struct Fixture { pub(crate) _dir: tempfile::TempDir, pub(crate) router: Router, @@ -393,3 +297,99 @@ pub(crate) async fn send_json( let (status, bytes) = send(router, method, uri, cookie, payload).await; (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::routes::app; + use axum::http::{Request, StatusCode}; + use tower::ServiceExt; + + #[tokio::test] + async fn session_helpers_and_bearer_token_authenticate() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let owner = owner_session(&auth_path); + let admin = admin_session(&auth_path); + let user = user_session(&auth_path); + let guest = guest_session(&auth_path); + let token = make_api_token(&auth_path, "test-user", None, "full"); + + let me = |cookie: Option, bearer: Option| { + let registry = registry.clone(); + let auth_path = auth_path.clone(); + async move { + let mut b = Request::builder().uri("/api/auth/me"); + if let Some(c) = cookie { + b = b.header("cookie", c); + } + if let Some(t) = bearer { + b = b.header("authorization", format!("Bearer {t}")); + } + let resp = app(registry, auth_path) + .oneshot(b.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = resp.status(); + (status, body_json(resp).await) + } + }; + for (cookie, role_bit) in [(owner, 8u64), (admin, 4), (user, 2), (guest, 1)] { + let (status, body) = me(Some(cookie), None).await; + assert_eq!(status, StatusCode::OK); + assert!(body["role_bits"].as_u64().unwrap() & role_bit != 0, "{body}"); + } + let (status, body) = me(None, Some(token)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["username"], "test-user"); + + // Back-dated token expiry is rejected as unauthenticated. + let past = (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339(); + let expired = make_api_token(&auth_path, "test-user", Some(&past), "full"); + let (status, _) = me(None, Some(expired)).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + + // Axum 0.7.9 `Router::merge` semantics, pinned for the stream modules. + async fn status_of(router: axum::Router, method: &str, uri: &str) -> StatusCode { + router + .oneshot( + Request::builder() + .method(method) + .uri(uri) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap() + .status() + } + + #[tokio::test] + async fn merge_adds_new_methods_to_an_existing_path() { + use axum::routing::{delete, get, post}; + let base = axum::Router::new().route("/api/auth/tokens", get(|| async { "list" }).post(|| async { "create" })); + // A merged router adding DELETE (a new method) on the same path: fine. + let extra = axum::Router::new().route("/api/auth/tokens", delete(|| async { "revoke-all" })); + let merged = base.merge(extra); + assert_eq!(status_of(merged.clone(), "GET", "/api/auth/tokens").await, StatusCode::OK); + assert_eq!(status_of(merged.clone(), "POST", "/api/auth/tokens").await, StatusCode::OK); + assert_eq!(status_of(merged.clone(), "DELETE", "/api/auth/tokens").await, StatusCode::OK); + assert_eq!(status_of(merged, "PUT", "/api/auth/tokens").await, StatusCode::METHOD_NOT_ALLOWED); + // Same for routes registered by two merged routers on one new path. + let a = axum::Router::new().route("/x", get(|| async { "a" })); + let b = axum::Router::new().route("/x", post(|| async { "b" })); + let merged = a.merge(b); + assert_eq!(status_of(merged.clone(), "GET", "/x").await, StatusCode::OK); + assert_eq!(status_of(merged, "POST", "/x").await, StatusCode::OK); + } + + #[test] + #[should_panic(expected = "Overlapping method route")] + fn merge_panics_when_the_same_method_is_registered_twice() { + use axum::routing::get; + let base = axum::Router::<()>::new().route("/api/auth/tokens", get(|| async { "list" })); + let extra = axum::Router::new().route("/api/auth/tokens", get(|| async { "dup" })); + let _ = base.merge(extra); + } +} diff --git a/crates/archivr-server/src/token_scope.rs b/crates/archivr-server/src/token_scope.rs index 873ecc6..d477929 100644 --- a/crates/archivr-server/src/token_scope.rs +++ b/crates/archivr-server/src/token_scope.rs @@ -31,22 +31,20 @@ pub async fn enforce_read_scope( .get("Authorization") .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")); - if let Some(raw_token) = raw_token { - if let Ok(conn) = database::open_auth_db(&state.auth_db_path) { - let jar = CookieJar::from_headers(req.headers()); - let cookie_session_valid = jar - .get("session") - .map(|c| matches!(database::get_session(&conn, c.value()), Ok(Some(_)))) - .unwrap_or(false); - if !cookie_session_valid { - if let Ok(Some(scope)) = - auth_credentials::token_scope_for_hash(&conn, &hash_token(raw_token)) - { - if scope == "read" { - return ApiError::forbidden("read-only token").into_response(); - } - } - } + if let Some(raw_token) = raw_token + && let Ok(conn) = database::open_auth_db(&state.auth_db_path) + { + let jar = CookieJar::from_headers(req.headers()); + let cookie_session_valid = jar + .get("session") + .map(|c| matches!(database::get_session(&conn, c.value()), Ok(Some(_)))) + .unwrap_or(false); + if !cookie_session_valid + && let Ok(Some(scope)) = + auth_credentials::token_scope_for_hash(&conn, &hash_token(raw_token)) + && scope == "read" + { + return ApiError::forbidden("read-only token").into_response(); } } next.run(req).await