ironflow_api/routes/api_keys/
list.rs1use 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#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
17#[derive(Debug, Serialize)]
18pub struct ApiKeyResponse {
19 pub id: Uuid,
21 pub name: String,
23 pub key_prefix: String,
25 pub scopes: Vec<ApiKeyScope>,
27 pub is_active: bool,
29 pub expires_at: Option<DateTime<Utc>>,
31 pub last_used_at: Option<DateTime<Utc>>,
33 pub created_at: DateTime<Utc>,
35 pub rate_limit_override: Option<u32>,
37}
38
39#[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 use uuid::Uuid;
102
103 use super::*;
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 user_id = Uuid::now_v7();
146 let token = AccessToken::for_user(user_id, "testuser", false, &state.jwt_config).unwrap();
147 let auth_header = format!("Bearer {}", token.0);
148
149 let app = Router::new()
150 .route("/", get(list_api_keys))
151 .with_state(state);
152
153 let req = Request::builder()
154 .uri("/")
155 .method("GET")
156 .header("authorization", auth_header)
157 .body(Body::empty())
158 .unwrap();
159
160 let resp = app.oneshot(req).await.unwrap();
161 assert_eq!(resp.status(), StatusCode::OK);
162
163 let body = resp.into_body().collect().await.unwrap().to_bytes();
164 let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
165 assert_eq!(json_val["data"].as_array().unwrap().len(), 0);
166 }
167
168 #[tokio::test]
169 async fn list_api_keys_returns_user_keys() {
170 let state = test_state();
171 let user = state
172 .store
173 .create_user(NewUser {
174 email: "test@example.com".to_string(),
175 username: "testuser".to_string(),
176 password_hash: "hash".to_string(),
177 is_admin: None,
178 })
179 .await
180 .unwrap();
181
182 let _key1 = state
183 .store
184 .create_api_key(NewApiKey {
185 user_id: user.id,
186 name: "key1".to_string(),
187 key_hash: "hash".to_string(),
188 key_prefix: "sk_".to_string(),
189 scopes: vec![],
190 expires_at: None,
191 rate_limit_override: None,
192 })
193 .await
194 .unwrap();
195
196 let _key2 = state
197 .store
198 .create_api_key(NewApiKey {
199 user_id: user.id,
200 name: "key2".to_string(),
201 key_hash: "hash".to_string(),
202 key_prefix: "sk_".to_string(),
203 scopes: vec![],
204 expires_at: None,
205 rate_limit_override: None,
206 })
207 .await
208 .unwrap();
209
210 let token = AccessToken::for_user(user.id, "testuser", false, &state.jwt_config).unwrap();
211 let auth_header = format!("Bearer {}", token.0);
212
213 let app = Router::new()
214 .route("/", get(list_api_keys))
215 .with_state(state);
216
217 let req = Request::builder()
218 .uri("/")
219 .method("GET")
220 .header("authorization", auth_header)
221 .body(Body::empty())
222 .unwrap();
223
224 let resp = app.oneshot(req).await.unwrap();
225 assert_eq!(resp.status(), StatusCode::OK);
226
227 let body = resp.into_body().collect().await.unwrap().to_bytes();
228 let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
229 assert_eq!(json_val["data"].as_array().unwrap().len(), 2);
230 }
231
232 #[tokio::test]
233 async fn list_api_keys_does_not_leak_other_users_keys() {
234 let state = test_state();
235 let user1 = state
236 .store
237 .create_user(NewUser {
238 email: "user1@example.com".to_string(),
239 username: "user1".to_string(),
240 password_hash: "hash".to_string(),
241 is_admin: None,
242 })
243 .await
244 .unwrap();
245
246 let user2 = state
247 .store
248 .create_user(NewUser {
249 email: "user2@example.com".to_string(),
250 username: "user2".to_string(),
251 password_hash: "hash".to_string(),
252 is_admin: None,
253 })
254 .await
255 .unwrap();
256
257 state
258 .store
259 .create_api_key(NewApiKey {
260 user_id: user1.id,
261 name: "user1-key".to_string(),
262 key_hash: "hash".to_string(),
263 key_prefix: "sk_".to_string(),
264 scopes: vec![],
265 expires_at: None,
266 rate_limit_override: None,
267 })
268 .await
269 .unwrap();
270
271 state
272 .store
273 .create_api_key(NewApiKey {
274 user_id: user2.id,
275 name: "user2-key".to_string(),
276 key_hash: "hash".to_string(),
277 key_prefix: "sk_".to_string(),
278 scopes: vec![],
279 expires_at: None,
280 rate_limit_override: None,
281 })
282 .await
283 .unwrap();
284
285 let token = AccessToken::for_user(user1.id, "user1", false, &state.jwt_config).unwrap();
286 let auth_header = format!("Bearer {}", token.0);
287
288 let app = Router::new()
289 .route("/", get(list_api_keys))
290 .with_state(state);
291
292 let req = Request::builder()
293 .uri("/")
294 .method("GET")
295 .header("authorization", auth_header)
296 .body(Body::empty())
297 .unwrap();
298
299 let resp = app.oneshot(req).await.unwrap();
300 assert_eq!(resp.status(), StatusCode::OK);
301
302 let body = resp.into_body().collect().await.unwrap().to_bytes();
303 let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
304 let keys = json_val["data"].as_array().unwrap();
305 assert_eq!(keys.len(), 1);
306 assert_eq!(keys[0]["name"], "user1-key");
307 }
308}