Skip to main content

ironflow_api/routes/api_keys/
list.rs

1//! `GET /api/v1/api-keys` -- List API keys for the authenticated user.
2
3use axum::extract::State;
4use axum::response::IntoResponse;
5use chrono::{DateTime, Utc};
6use ironflow_auth::extractor::AuthenticatedUser;
7use ironflow_store::entities::ApiKeyScope;
8use serde::Serialize;
9use uuid::Uuid;
10
11use crate::error::ApiError;
12use crate::response::ok;
13use crate::state::AppState;
14
15/// API key summary (never includes the hash or raw key).
16#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
17#[derive(Debug, Serialize)]
18pub struct ApiKeyResponse {
19    /// API key ID.
20    pub id: Uuid,
21    /// Key name.
22    pub name: String,
23    /// First characters for identification.
24    pub key_prefix: String,
25    /// Granted scopes.
26    pub scopes: Vec<ApiKeyScope>,
27    /// Whether the key is active.
28    pub is_active: bool,
29    /// Expiration date.
30    pub expires_at: Option<DateTime<Utc>>,
31    /// Last used date.
32    pub last_used_at: Option<DateTime<Utc>>,
33    /// Creation date.
34    pub created_at: DateTime<Utc>,
35    /// Per-key rate limit override (requests per minute), if set.
36    pub rate_limit_override: Option<u32>,
37}
38
39/// List all API keys for the authenticated user.
40#[cfg_attr(
41    feature = "openapi",
42    utoipa::path(
43        get,
44        path = "/api/v1/api-keys",
45        tags = ["api-keys"],
46        responses(
47            (status = 200, description = "List of API keys", body = Vec<ApiKeyResponse>),
48            (status = 401, description = "Unauthorized")
49        ),
50        security(("Bearer" = []))
51    )
52)]
53pub async fn list_api_keys(
54    user: AuthenticatedUser,
55    State(state): State<AppState>,
56) -> Result<impl IntoResponse, ApiError> {
57    let keys = state
58        .store
59        .list_api_keys_by_user(user.user_id)
60        .await
61        .map_err(ApiError::from)?;
62
63    let responses: Vec<ApiKeyResponse> = keys
64        .into_iter()
65        .map(|k| ApiKeyResponse {
66            id: k.id,
67            name: k.name,
68            key_prefix: k.key_prefix,
69            scopes: k.scopes,
70            is_active: k.is_active,
71            expires_at: k.expires_at,
72            last_used_at: k.last_used_at,
73            created_at: k.created_at,
74            rate_limit_override: k.rate_limit_override,
75        })
76        .collect();
77
78    Ok(ok(responses))
79}
80
81#[cfg(test)]
82mod tests {
83    use axum::Router;
84    use axum::body::Body;
85    use axum::http::{Request, StatusCode};
86    use axum::routing::get;
87    use http_body_util::BodyExt;
88    use ironflow_auth::jwt::{AccessToken, JwtConfig};
89    use ironflow_core::providers::claude::ClaudeCodeProvider;
90    use ironflow_engine::context::WorkflowContext;
91    use ironflow_engine::engine::Engine;
92    use ironflow_engine::handler::{HandlerFuture, WorkflowHandler};
93    use ironflow_engine::notify::Event;
94    use ironflow_store::entities::{NewApiKey, NewUser};
95    use ironflow_store::memory::InMemoryStore;
96    use ironflow_store::store::Store;
97    use serde_json::Value as JsonValue;
98    use std::sync::Arc;
99    use tokio::sync::broadcast;
100    use tower::ServiceExt;
101
102    use super::*;
103    use crate::routes::test_helpers::create_user_auth_header;
104
105    struct TestWorkflow;
106
107    impl WorkflowHandler for TestWorkflow {
108        fn name(&self) -> &str {
109            "test-workflow"
110        }
111
112        fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
113            Box::pin(async move { Ok(()) })
114        }
115    }
116
117    fn test_jwt_config() -> Arc<JwtConfig> {
118        Arc::new(JwtConfig {
119            secret: "test-secret".to_string(),
120            access_token_ttl_secs: 900,
121            refresh_token_ttl_secs: 604800,
122            cookie_domain: None,
123            cookie_secure: false,
124        })
125    }
126
127    fn test_state() -> AppState {
128        let store: Arc<dyn Store> = Arc::new(InMemoryStore::new());
129        let provider = Arc::new(ClaudeCodeProvider::new());
130        let mut engine = Engine::new(store.clone(), provider);
131        engine.register(TestWorkflow).unwrap();
132        let (event_sender, _) = broadcast::channel::<Event>(1);
133        AppState::new(
134            store,
135            Arc::new(engine),
136            test_jwt_config(),
137            "test-worker-token".to_string(),
138            event_sender,
139        )
140    }
141
142    #[tokio::test]
143    async fn list_api_keys_empty() {
144        let state = test_state();
145        let auth_header = create_user_auth_header(&state, "testuser", false).await;
146
147        let app = Router::new()
148            .route("/", get(list_api_keys))
149            .with_state(state);
150
151        let req = Request::builder()
152            .uri("/")
153            .method("GET")
154            .header("authorization", auth_header)
155            .body(Body::empty())
156            .unwrap();
157
158        let resp = app.oneshot(req).await.unwrap();
159        assert_eq!(resp.status(), StatusCode::OK);
160
161        let body = resp.into_body().collect().await.unwrap().to_bytes();
162        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
163        assert_eq!(json_val["data"].as_array().unwrap().len(), 0);
164    }
165
166    #[tokio::test]
167    async fn list_api_keys_returns_user_keys() {
168        let state = test_state();
169        let user = state
170            .store
171            .create_user(NewUser {
172                email: "test@example.com".to_string(),
173                username: "testuser".to_string(),
174                password_hash: "hash".to_string(),
175                is_admin: None,
176            })
177            .await
178            .unwrap();
179
180        let _key1 = state
181            .store
182            .create_api_key(NewApiKey {
183                user_id: user.id,
184                name: "key1".to_string(),
185                key_hash: "hash".to_string(),
186                key_prefix: "sk_".to_string(),
187                scopes: vec![],
188                expires_at: None,
189                rate_limit_override: None,
190            })
191            .await
192            .unwrap();
193
194        let _key2 = state
195            .store
196            .create_api_key(NewApiKey {
197                user_id: user.id,
198                name: "key2".to_string(),
199                key_hash: "hash".to_string(),
200                key_prefix: "sk_".to_string(),
201                scopes: vec![],
202                expires_at: None,
203                rate_limit_override: None,
204            })
205            .await
206            .unwrap();
207
208        let token = AccessToken::for_user(user.id, "testuser", false, &state.jwt_config).unwrap();
209        let auth_header = format!("Bearer {}", token.0);
210
211        let app = Router::new()
212            .route("/", get(list_api_keys))
213            .with_state(state);
214
215        let req = Request::builder()
216            .uri("/")
217            .method("GET")
218            .header("authorization", auth_header)
219            .body(Body::empty())
220            .unwrap();
221
222        let resp = app.oneshot(req).await.unwrap();
223        assert_eq!(resp.status(), StatusCode::OK);
224
225        let body = resp.into_body().collect().await.unwrap().to_bytes();
226        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
227        assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
228    }
229
230    #[tokio::test]
231    async fn list_api_keys_does_not_leak_other_users_keys() {
232        let state = test_state();
233        let user1 = state
234            .store
235            .create_user(NewUser {
236                email: "user1@example.com".to_string(),
237                username: "user1".to_string(),
238                password_hash: "hash".to_string(),
239                is_admin: None,
240            })
241            .await
242            .unwrap();
243
244        let user2 = state
245            .store
246            .create_user(NewUser {
247                email: "user2@example.com".to_string(),
248                username: "user2".to_string(),
249                password_hash: "hash".to_string(),
250                is_admin: None,
251            })
252            .await
253            .unwrap();
254
255        state
256            .store
257            .create_api_key(NewApiKey {
258                user_id: user1.id,
259                name: "user1-key".to_string(),
260                key_hash: "hash".to_string(),
261                key_prefix: "sk_".to_string(),
262                scopes: vec![],
263                expires_at: None,
264                rate_limit_override: None,
265            })
266            .await
267            .unwrap();
268
269        state
270            .store
271            .create_api_key(NewApiKey {
272                user_id: user2.id,
273                name: "user2-key".to_string(),
274                key_hash: "hash".to_string(),
275                key_prefix: "sk_".to_string(),
276                scopes: vec![],
277                expires_at: None,
278                rate_limit_override: None,
279            })
280            .await
281            .unwrap();
282
283        let token = AccessToken::for_user(user1.id, "user1", false, &state.jwt_config).unwrap();
284        let auth_header = format!("Bearer {}", token.0);
285
286        let app = Router::new()
287            .route("/", get(list_api_keys))
288            .with_state(state);
289
290        let req = Request::builder()
291            .uri("/")
292            .method("GET")
293            .header("authorization", auth_header)
294            .body(Body::empty())
295            .unwrap();
296
297        let resp = app.oneshot(req).await.unwrap();
298        assert_eq!(resp.status(), StatusCode::OK);
299
300        let body = resp.into_body().collect().await.unwrap().to_bytes();
301        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
302        let keys = json_val["data"].as_array().unwrap();
303        assert_eq!(keys.len(), 1);
304        assert_eq!(keys[0]["name"], "user1-key");
305    }
306}