feat(auth): add DB-based token authentication for dashboard-created clients
Add client_tokens table with auto-generated sk-{hex} tokens so clients
created in the dashboard get working API keys. Auth flow: DB token lookup
first, then env token fallback, then permissive mode. Includes token
management CRUD endpoints and copy-once reveal modal in the frontend.
This commit is contained in:
@@ -6,6 +6,7 @@ use axum::{
|
||||
routing::{get, post},
|
||||
};
|
||||
use futures::stream::StreamExt;
|
||||
use sqlx;
|
||||
use std::sync::Arc;
|
||||
use tracing::{info, warn};
|
||||
use uuid::Uuid;
|
||||
@@ -119,13 +120,34 @@ async fn chat_completions(
|
||||
auth: AuthenticatedClient,
|
||||
Json(mut request): Json<ChatCompletionRequest>,
|
||||
) -> Result<axum::response::Response, AppError> {
|
||||
// Validate token against configured auth tokens
|
||||
if !state.auth_tokens.is_empty() && !state.auth_tokens.contains(&auth.token) {
|
||||
// Resolve client_id: try DB token first, then env tokens, then permissive fallback
|
||||
let db_client_id: Option<String> = sqlx::query_scalar::<_, String>(
|
||||
"SELECT client_id FROM client_tokens WHERE token = ? AND is_active = TRUE",
|
||||
)
|
||||
.bind(&auth.token)
|
||||
.fetch_optional(&state.db_pool)
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
|
||||
let client_id = if let Some(cid) = db_client_id {
|
||||
// Update last_used_at in background (fire-and-forget)
|
||||
let pool = state.db_pool.clone();
|
||||
let token = auth.token.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = sqlx::query("UPDATE client_tokens SET last_used_at = CURRENT_TIMESTAMP WHERE token = ?")
|
||||
.bind(&token)
|
||||
.execute(&pool)
|
||||
.await;
|
||||
});
|
||||
cid
|
||||
} else if state.auth_tokens.is_empty() || state.auth_tokens.contains(&auth.token) {
|
||||
// Env token match or permissive mode (no env tokens configured)
|
||||
auth.client_id.clone()
|
||||
} else {
|
||||
return Err(AppError::AuthError("Invalid authentication token".to_string()));
|
||||
}
|
||||
};
|
||||
|
||||
let start_time = std::time::Instant::now();
|
||||
let client_id = auth.client_id.clone();
|
||||
let model = request.model.clone();
|
||||
|
||||
info!("Chat completion request from client {} for model {}", client_id, model);
|
||||
|
||||
Reference in New Issue
Block a user