From 0a9cd1eea712fd463cd87069c55879774cb6844a Mon Sep 17 00:00:00 2001 From: Aljaz Date: Thu, 29 May 2025 10:12:12 +0200 Subject: [PATCH] api: return 401 for invalid api key --- crates/goose-api/src/main.rs | 59 ++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/goose-api/src/main.rs b/crates/goose-api/src/main.rs index 9a68f872..71660b33 100644 --- a/crates/goose-api/src/main.rs +++ b/crates/goose-api/src/main.rs @@ -1,5 +1,6 @@ -use warp::{Filter, Rejection}; +use warp::{Filter, Rejection, Reply}; use warp::http::HeaderValue; +use std::convert::Infallible; use serde::{Deserialize, Serialize}; use std::sync::LazyLock; use goose::config::{Config, ExtensionEntry}; @@ -463,6 +464,24 @@ async fn remove_extension_handler( Ok(warp::reply::json(&resp)) } +#[derive(Debug)] +struct Unauthorized; + +impl warp::reject::Reject for Unauthorized {} + +async fn handle_rejection(err: Rejection) -> Result { + if err.find::().is_some() { + Ok(warp::reply::with_status("UNAUTHORIZED", warp::http::StatusCode::UNAUTHORIZED)) + } else if err.is_not_found() { + Ok(warp::reply::with_status("NOT_FOUND", warp::http::StatusCode::NOT_FOUND)) + } else { + Ok(warp::reply::with_status( + "INTERNAL_SERVER_ERROR", + warp::http::StatusCode::INTERNAL_SERVER_ERROR, + )) + } +} + fn with_api_key(api_key: String) -> impl Filter + Clone { warp::header::value("x-api-key") .and_then(move |header_api_key: HeaderValue| { @@ -471,12 +490,45 @@ fn with_api_key(api_key: String) -> impl Filter std::result::Result { let config_path = std::env::var("GOOSE_CONFIG").unwrap_or_else(|_| "config".to_string()); @@ -671,7 +723,8 @@ async fn main() -> Result<(), anyhow::Error> { .or(list_extensions) .or(add_extension) .or(remove_extension) - .or(get_provider_config); + .or(get_provider_config) + .recover(handle_rejection); // Get bind address from configuration or use default let host = std::env::var("GOOSE_API_HOST")