Skip to main content

ironflow_api/routes/api_keys/
available_scopes.rs

1//! `GET /api/v1/api-keys/scopes` -- List available scopes for the current user.
2
3use axum::response::IntoResponse;
4use ironflow_auth::extractor::AuthenticatedUser;
5use ironflow_store::entities::ApiKeyScope;
6use serde::Serialize;
7
8use crate::error::ApiError;
9use crate::response::ok;
10
11/// A scope entry with its machine name and human-readable label.
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[derive(Debug, Serialize)]
14pub struct ScopeEntry {
15    /// Machine-readable scope value (e.g. "runs_read").
16    pub value: String,
17    /// Human-readable label (e.g. "Runs Read").
18    pub label: String,
19    /// Short description.
20    pub description: String,
21}
22
23/// Return the list of scopes the current user is allowed to assign to API keys.
24///
25/// Admins get all scopes, members only get read-only scopes.
26#[cfg_attr(
27    feature = "openapi",
28    utoipa::path(
29        get,
30        path = "/api/v1/api-keys/scopes",
31        tags = ["api-keys"],
32        responses(
33            (status = 200, description = "List of available scopes", body = Vec<ScopeEntry>),
34            (status = 401, description = "Unauthorized")
35        ),
36        security(("Bearer" = []))
37    )
38)]
39pub async fn available_scopes(user: AuthenticatedUser) -> Result<impl IntoResponse, ApiError> {
40    let scopes = if user.is_admin {
41        ApiKeyScope::all_non_admin()
42    } else {
43        ApiKeyScope::member_allowed().to_vec()
44    };
45
46    let entries: Vec<ScopeEntry> = scopes
47        .into_iter()
48        .map(|s| {
49            let (label, description) = scope_metadata(&s);
50            ScopeEntry {
51                value: s.to_string(),
52                label: label.to_string(),
53                description: description.to_string(),
54            }
55        })
56        .collect();
57
58    Ok(ok(entries))
59}
60
61fn scope_metadata(scope: &ApiKeyScope) -> (&'static str, &'static str) {
62    match scope {
63        ApiKeyScope::WorkflowsRead => ("Workflows Read", "Read workflow definitions"),
64        ApiKeyScope::RunsRead => ("Runs Read", "Read runs and their steps"),
65        ApiKeyScope::RunsWrite => ("Runs Write", "Create new runs"),
66        ApiKeyScope::RunsManage => ("Runs Manage", "Cancel, approve, reject, retry runs"),
67        ApiKeyScope::StatsRead => ("Stats Read", "Read aggregated statistics"),
68        ApiKeyScope::Admin => ("Admin", "Full access to all operations"),
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use axum::Router;
75    use axum::body::Body;
76    use axum::http::{Request, StatusCode};
77    use axum::routing::get;
78    use http_body_util::BodyExt;
79    use ironflow_auth::jwt::{AccessToken, JwtConfig};
80    use ironflow_core::providers::claude::ClaudeCodeProvider;
81    use ironflow_engine::context::WorkflowContext;
82    use ironflow_engine::engine::Engine;
83    use ironflow_engine::handler::{HandlerFuture, WorkflowHandler};
84    use ironflow_engine::notify::Event;
85    use ironflow_store::memory::InMemoryStore;
86    use serde_json::Value as JsonValue;
87    use std::sync::Arc;
88    use tokio::sync::broadcast;
89    use tower::ServiceExt;
90    use uuid::Uuid;
91
92    use crate::state::AppState;
93
94    use super::*;
95
96    struct TestWorkflow;
97
98    impl WorkflowHandler for TestWorkflow {
99        fn name(&self) -> &str {
100            "test-workflow"
101        }
102
103        fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
104            Box::pin(async move { Ok(()) })
105        }
106    }
107
108    fn test_jwt_config() -> Arc<JwtConfig> {
109        Arc::new(JwtConfig {
110            secret: "test-secret-for-scope-tests".to_string(),
111            access_token_ttl_secs: 900,
112            refresh_token_ttl_secs: 604800,
113            cookie_domain: None,
114            cookie_secure: false,
115        })
116    }
117
118    fn test_state() -> AppState {
119        let store = Arc::new(InMemoryStore::new());
120        let provider = Arc::new(ClaudeCodeProvider::new());
121        let mut engine = Engine::new(store.clone(), provider);
122        engine
123            .register(TestWorkflow)
124            .expect("failed to register test workflow");
125        let (event_sender, _) = broadcast::channel::<Event>(1);
126        AppState::new(
127            store,
128            Arc::new(engine),
129            test_jwt_config(),
130            "test-worker-token".to_string(),
131            event_sender,
132        )
133    }
134
135    fn make_auth_header(is_admin: bool, state: &AppState) -> String {
136        let user_id = Uuid::now_v7();
137        let token =
138            AccessToken::for_user(user_id, "testuser", is_admin, &state.jwt_config).unwrap();
139        format!("Bearer {}", token.0)
140    }
141
142    #[tokio::test]
143    async fn admin_gets_all_non_admin_scopes() {
144        let state = test_state();
145        let auth_header = make_auth_header(true, &state);
146        let app = Router::new()
147            .route("/", get(available_scopes))
148            .with_state(state);
149
150        let req = Request::builder()
151            .uri("/")
152            .header("authorization", auth_header)
153            .body(Body::empty())
154            .unwrap();
155
156        let resp = app.oneshot(req).await.unwrap();
157        assert_eq!(resp.status(), StatusCode::OK);
158
159        let body = resp.into_body().collect().await.unwrap().to_bytes();
160        let json: JsonValue = serde_json::from_slice(&body).unwrap();
161        let scopes = json["data"].as_array().unwrap();
162        assert_eq!(scopes.len(), 5);
163
164        let values: Vec<&str> = scopes
165            .iter()
166            .map(|s| s["value"].as_str().unwrap())
167            .collect();
168        assert!(values.contains(&"runs_write"));
169        assert!(values.contains(&"runs_manage"));
170    }
171
172    #[tokio::test]
173    async fn member_gets_read_only_scopes() {
174        let state = test_state();
175        let auth_header = make_auth_header(false, &state);
176        let app = Router::new()
177            .route("/", get(available_scopes))
178            .with_state(state);
179
180        let req = Request::builder()
181            .uri("/")
182            .header("authorization", auth_header)
183            .body(Body::empty())
184            .unwrap();
185
186        let resp = app.oneshot(req).await.unwrap();
187        assert_eq!(resp.status(), StatusCode::OK);
188
189        let body = resp.into_body().collect().await.unwrap().to_bytes();
190        let json: JsonValue = serde_json::from_slice(&body).unwrap();
191        let scopes = json["data"].as_array().unwrap();
192        assert_eq!(scopes.len(), 3);
193
194        let values: Vec<&str> = scopes
195            .iter()
196            .map(|s| s["value"].as_str().unwrap())
197            .collect();
198        assert!(values.contains(&"workflows_read"));
199        assert!(values.contains(&"runs_read"));
200        assert!(values.contains(&"stats_read"));
201        assert!(!values.contains(&"runs_write"));
202        assert!(!values.contains(&"runs_manage"));
203    }
204}