|
| 1 | +use axum::{ |
| 2 | + extract::{State, Form}, |
| 3 | + response::{IntoResponse, Json}, |
| 4 | + http::StatusCode, |
| 5 | +}; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use serde_json::json; |
| 8 | +use pangolin_store::CatalogStore; |
| 9 | +// Removed Signer import as we implement signing locally |
| 10 | +use pangolin_core::user::{User, UserRole, UserSession, ServiceUser}; |
| 11 | +use chrono::{Utc, Duration}; |
| 12 | +use anyhow::Context; |
| 13 | +use uuid::Uuid; |
| 14 | +use bcrypt::verify; |
| 15 | +use jsonwebtoken::{encode, EncodingKey, Header}; |
| 16 | +use crate::auth::Claims; |
| 17 | + |
| 18 | +// Internal imports |
| 19 | +use crate::error::ApiError; |
| 20 | +use crate::iceberg::AppState; |
| 21 | + |
| 22 | +#[derive(Deserialize)] |
| 23 | +pub struct OAuthTokenRequest { |
| 24 | + grant_type: String, |
| 25 | + client_id: String, |
| 26 | + client_secret: String, |
| 27 | + scope: Option<String>, |
| 28 | +} |
| 29 | + |
| 30 | +#[derive(Serialize)] |
| 31 | +pub struct OAuthTokenResponse { |
| 32 | + access_token: String, |
| 33 | + token_type: String, |
| 34 | + expires_in: u64, |
| 35 | + issued_token_type: String, |
| 36 | +} |
| 37 | + |
| 38 | +/// Handler for the standard OAuth2 client_credentials flow |
| 39 | +/// |
| 40 | +/// This endpoint accepts `application/x-www-form-urlencoded` data |
| 41 | +/// to support standard libraries like PyIceberg/REST Catalog. |
| 42 | +/// |
| 43 | +/// It maps: |
| 44 | +/// - `client_id` -> Service User ID (UUID) |
| 45 | +/// - `client_secret` -> Service User API Key |
| 46 | +/// |
| 47 | +/// If valid, it returns a standard Pangolin JWT signed by the server key. |
| 48 | +pub async fn handle_oauth_token( |
| 49 | + State(store): State<AppState>, |
| 50 | + Form(payload): Form<OAuthTokenRequest>, |
| 51 | +) -> Result<impl IntoResponse, ApiError> { |
| 52 | + // 1. Validate Grant Type |
| 53 | + if payload.grant_type != "client_credentials" { |
| 54 | + return Err(ApiError::bad_request("Unsupported grant_type. exact 'client_credentials' required.")); |
| 55 | + } |
| 56 | + |
| 57 | + // 2. Parse Client ID as UUID |
| 58 | + let service_user_id = Uuid::parse_str(&payload.client_id) |
| 59 | + .map_err(|_| ApiError::bad_request("Invalid client_id format. Must be a valid UUID."))?; |
| 60 | + |
| 61 | + // 3. Retrieve Service User |
| 62 | + let store_ref = &*store; |
| 63 | + let service_user_result: anyhow::Result<Option<ServiceUser>> = store_ref.get_service_user(service_user_id).await; |
| 64 | + let service_user = service_user_result |
| 65 | + .map_err(|e| ApiError::InternalError(e))? |
| 66 | + .ok_or_else(|| ApiError::unauthorized("Invalid client_id"))?; |
| 67 | + |
| 68 | + // 4. Verify Active Status |
| 69 | + if !service_user.active { |
| 70 | + return Err(ApiError::unauthorized("Client is inactive")); |
| 71 | + } |
| 72 | + |
| 73 | + // 5. Verify Secret (API Key) |
| 74 | + // The stored hash is bcrypt |
| 75 | + let valid_secret = verify(&payload.client_secret, &service_user.api_key_hash) |
| 76 | + .map_err(|e| ApiError::InternalError(anyhow::anyhow!("Crypto failure: {}", e)))?; |
| 77 | + |
| 78 | + if !valid_secret { |
| 79 | + return Err(ApiError::unauthorized("Invalid client_secret")); |
| 80 | + } |
| 81 | + |
| 82 | + // 6. Generate Session/Token |
| 83 | + // We reuse the standard JWT generation logic used for users |
| 84 | + let now = Utc::now(); |
| 85 | + let expires_in_seconds = 3600; // 1 hour default |
| 86 | + let expires_at = now + Duration::seconds(expires_in_seconds as i64); |
| 87 | + |
| 88 | + let token_id = Uuid::new_v4(); |
| 89 | + let secret = std::env::var("PANGOLIN_JWT_SECRET").unwrap_or_else(|_| "default_secret_for_dev".to_string()); |
| 90 | + |
| 91 | + let claims = Claims { |
| 92 | + sub: service_user.id.to_string(), |
| 93 | + jti: Some(token_id.to_string()), |
| 94 | + username: service_user.name.clone(), |
| 95 | + tenant_id: Some(service_user.tenant_id.to_string()), |
| 96 | + role: service_user.role.clone(), |
| 97 | + exp: expires_at.timestamp(), |
| 98 | + iat: now.timestamp(), |
| 99 | + }; |
| 100 | + |
| 101 | + // We need to sign this. |
| 102 | + let token = encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_bytes())) |
| 103 | + .map_err(|e| ApiError::InternalError(anyhow::anyhow!("Token generation failed: {}", e)))?; |
| 104 | + |
| 105 | + // 7. Update Last Used |
| 106 | + // Best effort - don't fail auth if this fails |
| 107 | + let _ = store_ref.update_service_user_last_used(service_user.id, now).await; |
| 108 | + |
| 109 | + // 8. Return Response |
| 110 | + Ok(Json(OAuthTokenResponse { |
| 111 | + access_token: token, |
| 112 | + token_type: "Bearer".to_string(), |
| 113 | + expires_in: expires_in_seconds, |
| 114 | + issued_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(), |
| 115 | + })) |
| 116 | +} |
0 commit comments