Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/api/messaging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ pub(super) async fn toggle_platform(
let adapter = crate::messaging::webhook::WebhookAdapter::new(
webhook_config.port,
&webhook_config.bind,
webhook_config.auth_token.clone(),
);
if let Err(error) = manager.register_and_start(adapter).await {
tracing::error!(%error, "failed to start webhook adapter on toggle");
Expand Down
34 changes: 33 additions & 1 deletion src/api/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ use super::{
providers, settings, skills, system, webchat,
};

use axum::Json;
use axum::extract::Request;
use axum::Router;
use axum::http::{StatusCode, Uri, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{delete, get, post, put};
use rust_embed::Embed;
use serde_json::json;
use tower_http::cors::{Any, CorsLayer};

use std::net::SocketAddr;
Expand Down Expand Up @@ -131,7 +135,11 @@ pub async fn start_http_server(
)
.route("/update/apply", post(settings::update_apply))
.route("/webchat/send", post(webchat::webchat_send))
.route("/webchat/history", get(webchat::webchat_history));
.route("/webchat/history", get(webchat::webchat_history))
.layer(middleware::from_fn_with_state(
state.clone(),
api_auth_middleware,
));

let app = Router::new()
.nest("/api", api_routes)
Expand All @@ -157,6 +165,30 @@ pub async fn start_http_server(
Ok(handle)
}

async fn api_auth_middleware(state: Arc<ApiState>, request: Request, next: Next) -> Response {
let Some(expected_token) = state.auth_token.as_deref() else {
return next.run(request).await;
};

let path = request.uri().path();
if path == "/api/health" || path == "/health" {
return next.run(request).await;
}

let is_authorized = request
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.is_some_and(|token| token == expected_token);

if is_authorized {
next.run(request).await
} else {
(StatusCode::UNAUTHORIZED, Json(json!({"error": "unauthorized"}))).into_response()
}
}

async fn static_handler(uri: Uri) -> Response {
let path = uri.path().trim_start_matches('/');

Expand Down
2 changes: 2 additions & 0 deletions src/api/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub struct AgentInfo {
/// State shared across all API handlers.
pub struct ApiState {
pub started_at: Instant,
pub auth_token: Option<String>,
/// Aggregated event stream from all agents. SSE clients subscribe here.
pub event_tx: broadcast::Sender<ApiEvent>,
/// Per-agent SQLite pools for querying channel/conversation data.
Expand Down Expand Up @@ -182,6 +183,7 @@ impl ApiState {
let (event_tx, _) = broadcast::channel(512);
Self {
started_at: Instant::now(),
auth_token: None,
event_tx,
agent_pools: arc_swap::ArcSwap::from_pointee(HashMap::new()),
agent_configs: arc_swap::ArcSwap::from_pointee(Vec::new()),
Expand Down
9 changes: 9 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub struct ApiConfig {
pub port: u16,
/// Address to bind the HTTP server on.
pub bind: String,
pub auth_token: Option<String>,
}

impl Default for ApiConfig {
Expand All @@ -68,6 +69,7 @@ impl Default for ApiConfig {
enabled: true,
port: 19898,
bind: "127.0.0.1".into(),
auth_token: None,
}
}
}
Expand Down Expand Up @@ -1072,6 +1074,7 @@ pub struct WebhookConfig {
pub enabled: bool,
pub port: u16,
pub bind: String,
pub auth_token: Option<String>,
}

// -- TOML deserialization types --
Expand Down Expand Up @@ -1112,6 +1115,8 @@ struct TomlApiConfig {
port: u16,
#[serde(default = "default_api_bind")]
bind: String,
#[serde(default)]
auth_token: Option<String>,
}

impl Default for TomlApiConfig {
Expand All @@ -1120,6 +1125,7 @@ impl Default for TomlApiConfig {
enabled: default_api_enabled(),
port: default_api_port(),
bind: default_api_bind(),
auth_token: None,
}
}
}
Expand Down Expand Up @@ -1509,6 +1515,7 @@ struct TomlWebhookConfig {
port: u16,
#[serde(default = "default_webhook_bind")]
bind: String,
auth_token: Option<String>,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -2670,6 +2677,7 @@ impl Config {
enabled: w.enabled,
port: w.port,
bind: w.bind,
auth_token: w.auth_token.as_deref().and_then(resolve_env_value),
}),
twitch: toml.messaging.twitch.and_then(|t| {
let username = t
Expand Down Expand Up @@ -2711,6 +2719,7 @@ impl Config {
enabled: toml.api.enabled,
port: toml.api.port,
bind: hosted_api_bind(toml.api.bind),
auth_token: toml.api.auth_token.as_deref().and_then(resolve_env_value),
};

let metrics = MetricsConfig {
Expand Down
7 changes: 5 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,11 +607,13 @@ async fn run(
let (agent_remove_tx, mut agent_remove_rx) = mpsc::channel::<String>(8);

// Start HTTP API server if enabled
let api_state = Arc::new(spacebot::api::ApiState::new_with_provider_sender(
let mut api_state = spacebot::api::ApiState::new_with_provider_sender(
provider_tx,
agent_tx,
agent_remove_tx,
));
);
api_state.auth_token = config.api.auth_token.clone();
let api_state = Arc::new(api_state);

// Start background update checker
spacebot::update::spawn_update_checker(api_state.update_status.clone());
Expand Down Expand Up @@ -1432,6 +1434,7 @@ async fn initialize_agents(
let adapter = spacebot::messaging::webhook::WebhookAdapter::new(
webhook_config.port,
&webhook_config.bind,
webhook_config.auth_token.clone(),
);
new_messaging_manager.register(adapter).await;
}
Expand Down
59 changes: 50 additions & 9 deletions src/messaging/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,26 @@
//! the integration point for scripts, CI pipelines, and other programs
//! that need to interact with Spacebot programmatically.

use crate::messaging::traits::{InboundStream, Messaging};
use crate::{InboundMessage, MessageContent, OutboundResponse};
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::Context as _;
use axum::Router;
use axum::extract::{Json, State};
use axum::http::StatusCode;
use axum::http::header::AUTHORIZATION;
use axum::http::{HeaderMap, StatusCode};
use axum::routing::{get, post};
use serde::{Deserialize, Serialize};

use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{RwLock, mpsc};

use crate::messaging::traits::{InboundStream, Messaging};
use crate::{InboundMessage, MessageContent, OutboundResponse};

/// Webhook adapter state.
pub struct WebhookAdapter {
port: u16,
bind: String,
auth_token: Option<String>,
inbound_tx: Arc<RwLock<Option<mpsc::Sender<InboundMessage>>>>,
/// Buffered responses per conversation_id, waiting to be polled.
response_buffers: Arc<RwLock<HashMap<String, Vec<WebhookResponse>>>>,
Expand All @@ -34,6 +36,7 @@ pub struct WebhookAdapter {
struct AppState {
inbound_tx: Arc<RwLock<Option<mpsc::Sender<InboundMessage>>>>,
response_buffers: Arc<RwLock<HashMap<String, Vec<WebhookResponse>>>>,
auth_token: Option<String>,
}

/// Inbound webhook request body.
Expand Down Expand Up @@ -72,10 +75,11 @@ struct PollResponse {
}

impl WebhookAdapter {
pub fn new(port: u16, bind: impl Into<String>) -> Self {
pub fn new(port: u16, bind: impl Into<String>, auth_token: Option<String>) -> Self {
Self {
port,
bind: bind.into(),
auth_token,
inbound_tx: Arc::new(RwLock::new(None)),
response_buffers: Arc::new(RwLock::new(HashMap::new())),
shutdown_tx: Arc::new(RwLock::new(None)),
Expand All @@ -98,8 +102,15 @@ impl Messaging for WebhookAdapter {
let state = AppState {
inbound_tx: self.inbound_tx.clone(),
response_buffers: self.response_buffers.clone(),
auth_token: self.auth_token.clone(),
};

if self.auth_token.is_none() {
tracing::warn!(
"webhook authentication is disabled because no auth token is configured"
);
}

let app = Router::new()
.route("/send", post(handle_send))
.route("/poll/{conversation_id}", get(handle_poll))
Expand Down Expand Up @@ -226,9 +237,14 @@ impl Messaging for WebhookAdapter {
// -- Axum handlers --

async fn handle_send(
headers: HeaderMap,
State(state): State<AppState>,
Json(request): Json<WebhookRequest>,
) -> Result<StatusCode, (StatusCode, String)> {
if !is_authorized(&headers, state.auth_token.as_deref()) {
return Err((StatusCode::UNAUTHORIZED, "unauthorized".into()));
}

let tx = state.inbound_tx.read().await;
let Some(tx) = tx.as_ref() else {
return Err((
Expand Down Expand Up @@ -269,9 +285,14 @@ async fn handle_send(
}

async fn handle_poll(
headers: HeaderMap,
State(state): State<AppState>,
axum::extract::Path(conversation_id): axum::extract::Path<String>,
) -> Json<PollResponse> {
) -> Result<Json<PollResponse>, (StatusCode, String)> {
if !is_authorized(&headers, state.auth_token.as_deref()) {
return Err((StatusCode::UNAUTHORIZED, "unauthorized".into()));
}

let key = format!("webhook:{conversation_id}");
let messages = state
.response_buffers
Expand All @@ -280,9 +301,29 @@ async fn handle_poll(
.remove(&key)
.unwrap_or_default();

Json(PollResponse { messages })
Ok(Json(PollResponse { messages }))
}

async fn handle_health() -> StatusCode {
StatusCode::OK
}

fn is_authorized(headers: &HeaderMap, expected_token: Option<&str>) -> bool {
let Some(expected_token) = expected_token else {
return true;
};

if headers
.get("x-webhook-token")
.and_then(|value| value.to_str().ok())
.is_some_and(|token| token == expected_token)
{
return true;
}

headers
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.is_some_and(|token| token == expected_token)
}
Loading
Loading