/* * Author: Ruben Fiszel * Copyright: Windmill Labs, Inc 2026 * This file and its contents are licensed under the AGPLv3 License. * Please see the included NOTICE for copyright information and * LICENSE-AGPL for a copy of the license. */ use axum::http::header; use windmill_common::error::Error; use windmill_common::users::COOKIE_NAME; /// For a GET route that acts (posts a message, signs a link) rather than reads: refuses a /// request that would authenticate on the session cookie, which a browser attaches to a /// cross-site navigation. Its callers are jobs and scripts, which send a bearer header. pub async fn require_explicit_credential( req: axum::extract::Request, next: axum::middleware::Next, ) -> axum::response::Response { use axum::response::IntoResponse; if authenticates_on_session_cookie(req.headers()) { return Error::PermissionDenied( "this route does not accept the session cookie: pass a token in the \ `Authorization` header" .to_string(), ) .into_response(); } next.run(req).await } /// Mirrors `extract_token`: a bearer header wins, and otherwise a session cookie is used /// before any `token` query parameter. fn authenticates_on_session_cookie(headers: &axum::http::HeaderMap) -> bool { let has_bearer = headers .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .is_some_and(|v| v.starts_with("Bearer ")); !has_bearer && headers .get_all(header::COOKIE) .iter() .filter_map(|h| h.to_str().ok()) .flat_map(|h| h.split(';')) .filter_map(|c| tower_cookies::Cookie::parse_encoded(c.trim()).ok()) .any(|c| c.name() == COOKIE_NAME) } #[cfg(test)] mod tests { use super::authenticates_on_session_cookie; use axum::http::HeaderMap; fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { let mut map = HeaderMap::new(); for (k, v) in pairs { map.append(*k, v.parse().unwrap()); } map } #[test] fn session_cookie_is_refused_unless_a_bearer_header_wins() { let cookie = |pairs: &[(&'static str, &str)]| authenticates_on_session_cookie(&headers(pairs)); assert!(cookie(&[("cookie", "a=b; token=abc")])); assert!(!cookie(&[ ("cookie", "token=abc"), ("authorization", "Bearer xyz") ])); assert!(!cookie(&[("cookie", "other=abc")])); assert!(!cookie(&[("authorization", "Bearer xyz")])); assert!(!cookie(&[])); } }