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