Skip to main content

ironflow_api/routes/
mod.rs

1//! Router assembly — one module per route.
2
3pub mod api_keys;
4pub mod approval_delegations;
5pub mod approve_run;
6pub mod audit_logs;
7pub mod auth;
8pub mod cancel_run;
9pub mod create_run;
10pub mod download_artifact;
11pub mod events;
12pub mod get_agent_role_stats;
13pub mod get_run;
14pub mod get_run_logs;
15pub mod get_stats;
16pub mod get_stats_history;
17pub mod get_workflow;
18pub mod health_check;
19pub mod human_input;
20mod internal;
21pub mod list_runs;
22pub mod list_steps;
23pub mod list_workflows;
24#[cfg(feature = "prometheus")]
25pub mod metrics;
26pub mod openapi_spec;
27pub mod pause_run;
28pub mod pause_workflow;
29pub mod plan_workflow;
30pub mod provider_accounts;
31pub mod replay_run;
32pub mod retry_run;
33pub mod run_events;
34pub mod schedules;
35#[cfg(test)]
36mod scope_tests;
37pub mod secrets;
38pub mod signals;
39pub mod templates;
40#[cfg(test)]
41mod test_helpers;
42pub mod users;
43
44use std::path::PathBuf;
45
46use axum::Extension;
47use axum::Router;
48use axum::middleware as axum_mw;
49use axum::routing::{delete, get, patch, post, put};
50use ironflow_store::MAX_API_BODY_BYTES;
51use tower_http::limit::RequestBodyLimitLayer;
52use tower_http::services::{ServeDir, ServeFile};
53use tracing::warn;
54
55use crate::middleware::{WorkerToken, https_redirect, security_headers, worker_token_auth};
56use crate::rate_limit::{AccountLimit, RateLimitContext, TrustedProxies, per_minute, rate_limit};
57use crate::state::AppState;
58
59/// Maximum artifact upload size: 128 MiB.
60///
61/// A transport ceiling only, sitting slightly above the blob store's own limit
62/// so an oversized payload is refused by the store with a precise error instead
63/// of being cut off by the transport layer.
64const MAX_ARTIFACT_BODY_SIZE: usize = 128 * 1024 * 1024;
65
66/// Router-level configuration with sensible defaults.
67///
68/// Controls dashboard serving, rate limiting, and other router behaviors.
69/// Use [`Default::default()`] for production-ready defaults, then override
70/// individual fields as needed.
71///
72/// # Examples
73///
74/// ```
75/// use ironflow_api::routes::RouterConfig;
76///
77/// // All defaults: rate limiting enabled, no custom dashboard dir
78/// let config = RouterConfig::default();
79/// assert_eq!(config.rate_limit_auth, Some(10));
80/// assert!(!config.enforce_https);
81///
82/// // Disable auth rate limiting, custom dashboard
83/// let config = RouterConfig {
84///     rate_limit_auth: None,
85///     ..RouterConfig::default()
86/// };
87/// ```
88#[derive(Debug, Clone)]
89pub struct RouterConfig {
90    /// Filesystem path to dashboard assets. When set, serves the SPA
91    /// from this directory instead of the embedded build.
92    pub dashboard_dir: Option<PathBuf>,
93    /// Rate limit for auth credential routes (sign-in, sign-up, password change)
94    /// in requests per minute, applied per caller (client IP, or user for an
95    /// authenticated password change) and per targeted email.
96    /// `None` disables the limiter.
97    pub rate_limit_auth: Option<u32>,
98    /// Rate limit for general public API routes in requests per minute
99    /// per IP. `None` disables the limiter.
100    pub rate_limit_general: Option<u32>,
101    /// Reverse proxies allowed to report the client IP through the
102    /// forwarding header chosen by [`TrustedProxies::header`]. Empty by
103    /// default: the rate limiters key on the TCP peer, which requires serving
104    /// the router with `into_make_service_with_connect_info::<SocketAddr>()`.
105    ///
106    /// The forwarding headers of these proxies are also the only ones the
107    /// HTTPS redirect of [`RouterConfig::enforce_https`] reads.
108    pub trusted_proxies: TrustedProxies,
109    /// When `true`, requests carrying `X-Forwarded-Proto: http` are answered
110    /// with a `308` redirect to the HTTPS URL. Defaults to `false`.
111    ///
112    /// Only requests whose TCP peer is in [`RouterConfig::trusted_proxies`]
113    /// are redirected, so enable it behind a reverse proxy that sets
114    /// `X-Forwarded-Proto`, list that proxy in `trusted_proxies`, and serve
115    /// the router with `into_make_service_with_connect_info::<SocketAddr>()`.
116    pub enforce_https: bool,
117}
118
119impl Default for RouterConfig {
120    fn default() -> Self {
121        Self {
122            dashboard_dir: None,
123            rate_limit_auth: Some(10),
124            rate_limit_general: Some(60),
125            trusted_proxies: TrustedProxies::default(),
126            enforce_https: false,
127        }
128    }
129}
130
131/// Handler that returns a JSON 404 when the `sign-up` feature is disabled.
132#[cfg(not(feature = "sign-up"))]
133async fn sign_up_disabled() -> impl axum::response::IntoResponse {
134    crate::error::ApiError::BadRequest("sign-up is disabled".to_string())
135}
136
137/// Create the main application router.
138///
139/// # Examples
140///
141/// ```no_run
142/// use ironflow_api::routes::{RouterConfig, create_router};
143/// use ironflow_api::state::AppState;
144/// use ironflow_auth::jwt::JwtConfig;
145/// use ironflow_store::prelude::*;
146/// use ironflow_engine::engine::Engine;
147/// use ironflow_core::providers::claude::ClaudeCodeProvider;
148/// use std::sync::Arc;
149/// use tokio::sync::broadcast;
150/// use ironflow_engine::notify::Event;
151///
152/// # async fn example() {
153/// let store: Arc<dyn ironflow_store::store::Store> = Arc::new(InMemoryStore::new());
154/// let provider = Arc::new(ClaudeCodeProvider::new());
155/// let engine = Arc::new(Engine::new(store.clone(), provider));
156/// let jwt_config = Arc::new(JwtConfig {
157///     secret: "secret".to_string(),
158///     access_token_ttl_secs: 900,
159///     refresh_token_ttl_secs: 604800,
160///     cookie_domain: None,
161///     cookie_secure: false,
162/// });
163/// let (event_sender, _) = broadcast::channel::<Event>(1);
164/// let state = AppState::new(store, engine, jwt_config, "token".to_string(), event_sender);
165/// let router = create_router(state, RouterConfig::default());
166/// # }
167/// ```
168pub fn create_router(state: AppState, config: RouterConfig) -> Router {
169    // Internal routes (worker-to-API, protected by WORKER_TOKEN)
170    let internal_routes = Router::new()
171        .route("/runs", post(internal::create_run::create_run))
172        .route("/runs/next", get(internal::pick_next_run::pick_next_run))
173        .route("/runs/search", post(internal::search_runs::search_runs))
174        .route(
175            "/runs/pending-count",
176            get(internal::count_pending_runs::count_pending_runs),
177        )
178        .route(
179            "/runs/{id}",
180            get(internal::get_run::get_run).put(internal::update_run::update_run),
181        )
182        .route(
183            "/runs/{id}/status",
184            put(internal::update_run_status::update_run_status),
185        )
186        .route("/runs/{id}/logs", post(internal::push_logs::push_logs))
187        .route("/runs/{id}/lease", post(internal::renew_lease::renew_lease))
188        .route(
189            "/runs/{id}/descendants",
190            get(internal::list_descendants::list_descendants),
191        )
192        .route(
193            "/runs/{id}/artifacts",
194            get(internal::list_artifacts::list_artifacts),
195        )
196        .route("/steps", post(internal::create_step::create_step))
197        .route("/steps/{id}", put(internal::update_step::update_step))
198        .route(
199            "/step-dependencies",
200            post(internal::create_step_dependencies::create_step_dependencies),
201        )
202        .route("/secrets/{*key}", get(internal::get_secret::get_secret))
203        .route(
204            "/signals",
205            get(internal::signals::list_signals_for_key).post(internal::signals::send_signal),
206        )
207        .route(
208            "/steps/{id}/signal-resolution",
209            post(internal::signals::resolve_signal_step),
210        )
211        .route(
212            "/runs/{id}/signal-suspension",
213            post(internal::signals::suspend_run_on_signal),
214        )
215        .route(
216            "/provider-accounts/candidates",
217            get(internal::provider_accounts::list_candidates),
218        )
219        .route(
220            "/provider-accounts/{id}/observations",
221            post(internal::provider_accounts::record_observation),
222        )
223        .layer(axum_mw::from_fn(worker_token_auth))
224        .layer(Extension(WorkerToken(state.worker_token.clone())))
225        .with_state(state.clone());
226
227    // Artifact uploads carry file payloads, so they sit outside the 2 MiB
228    // limit that guards every JSON route and get their own, larger ceiling.
229    let artifact_upload_routes = Router::new()
230        .route(
231            "/api/v1/internal/runs/{id}/steps/{step_id}/artifacts/{name}",
232            post(internal::upload_artifact::upload_artifact),
233        )
234        .layer(axum_mw::from_fn(worker_token_auth))
235        .layer(Extension(WorkerToken(state.worker_token.clone())))
236        .layer(RequestBodyLimitLayer::new(MAX_ARTIFACT_BODY_SIZE))
237        .with_state(state.clone());
238
239    // Auth credential routes (rate-limited when configured). Password change
240    // sits here too: it checks the current password, so it is a guessing oracle.
241    #[allow(unused_mut)]
242    let mut auth_credential_routes = Router::new();
243
244    #[cfg(feature = "sign-up")]
245    {
246        auth_credential_routes =
247            auth_credential_routes.route("/sign-up", post(auth::sign_up::sign_up));
248    }
249
250    #[cfg(not(feature = "sign-up"))]
251    {
252        auth_credential_routes = auth_credential_routes.route("/sign-up", post(sign_up_disabled));
253    }
254
255    let mut auth_credential_routes = auth_credential_routes
256        .route("/sign-in", post(auth::sign_in::sign_in))
257        .route("/password", patch(auth::change_password::change_password));
258
259    if let Some(rpm) = config.rate_limit_auth {
260        let ctx = RateLimitContext {
261            store: state.store.clone(),
262            jwt_config: state.jwt_config.clone(),
263            limiter: per_minute(rpm),
264            trusted_proxies: config.trusted_proxies.clone(),
265            account_limit: AccountLimit::ByEmail,
266        };
267        auth_credential_routes = auth_credential_routes
268            .layer(axum_mw::from_fn(rate_limit))
269            .layer(Extension(ctx));
270    }
271
272    // Auth session routes (no strict rate limiting, covered by general limiter)
273    let auth_session_routes = Router::new()
274        .route("/refresh", post(auth::refresh::refresh))
275        .route("/sign-out", post(auth::sign_out::sign_out))
276        .route("/me", get(auth::me::me));
277
278    // Public + user-authenticated routes (rate-limited when configured)
279    #[allow(unused_mut)]
280    let mut api_v1 = Router::new()
281        .route("/health-check", get(health_check::health_check))
282        .route("/openapi.json", get(openapi_spec::openapi_spec))
283        .route(
284            "/runs",
285            get(list_runs::list_runs).post(create_run::create_run),
286        )
287        .route("/runs/{id}", get(get_run::get_run))
288        .route("/runs/{id}/logs", get(get_run_logs::get_run_logs))
289        .route("/runs/{id}/cancel", post(cancel_run::cancel_run))
290        .route("/runs/{id}/pause", post(pause_run::pause_run))
291        .route("/runs/{id}/resume", post(pause_run::resume_run))
292        .route("/runs/{id}/approve", post(approve_run::approve_run))
293        .route("/runs/{id}/reject", post(approve_run::reject_run))
294        .route("/runs/{id}/retry", post(retry_run::retry_run))
295        .route("/runs/{id}/replay", post(replay_run::replay_run))
296        .route("/runs/{id}/events", get(run_events::run_events))
297        .route(
298            "/runs/{id}/steps/{step_id}/artifacts/{name}",
299            get(download_artifact::download_artifact),
300        )
301        .route(
302            "/runs/{id}/steps/{step_id}/input",
303            post(human_input::submit_human_input),
304        )
305        .route(
306            "/runs/{id}/steps/{step_id}/reject",
307            post(human_input::reject_human_input),
308        )
309        .route("/workflows", get(list_workflows::list_workflows))
310        .route("/workflows/{name}", get(get_workflow::get_workflow))
311        .route("/workflows/{name}/plan", post(plan_workflow::plan_workflow))
312        .route(
313            "/workflows/{name}/pause",
314            post(pause_workflow::pause_workflow),
315        )
316        .route(
317            "/workflows/{name}/resume",
318            post(pause_workflow::resume_workflow),
319        )
320        .route("/stats", get(get_stats::get_stats))
321        .route(
322            "/stats/agent-roles",
323            get(get_agent_role_stats::get_agent_role_stats),
324        )
325        .route("/stats/history", get(get_stats_history::get_stats_history))
326        .route("/steps", get(list_steps::list_steps))
327        .route("/audit-logs", get(audit_logs::list_audit_logs))
328        .route("/events", get(events::events))
329        .route(
330            "/api-keys",
331            get(api_keys::list::list_api_keys).post(api_keys::create::create_api_key),
332        )
333        .route(
334            "/api-keys/scopes",
335            get(api_keys::available_scopes::available_scopes),
336        )
337        .route("/api-keys/{id}", delete(api_keys::delete::delete_api_key))
338        .route(
339            "/users",
340            get(users::list::list_users).post(users::create::create_user),
341        )
342        .route("/users/{id}", delete(users::delete::delete_user))
343        .route("/users/{id}/role", patch(users::update_role::update_role))
344        .route(
345            "/users/{id}/groups",
346            get(users::groups::get_user_groups).put(users::groups::update_user_groups),
347        )
348        .route(
349            "/secrets",
350            get(secrets::list::list_secrets).post(secrets::create::create_secret),
351        )
352        // Registered before the catch-all below: a static segment wins over
353        // the wildcard, so `rotate` is never read as a secret key.
354        .route("/secrets/rotate", post(secrets::rotate::rotate_secrets))
355        .route(
356            "/secrets/key-versions",
357            get(secrets::key_versions::secret_key_versions),
358        )
359        .route(
360            "/secrets/{*key}",
361            put(secrets::update::update_secret).delete(secrets::delete::delete_secret),
362        )
363        .route(
364            "/provider-accounts",
365            get(provider_accounts::list::list_provider_accounts)
366                .post(provider_accounts::create::create_provider_account),
367        )
368        // Registered before `{id}`: a static segment wins, so `kinds` is never
369        // read as an account name.
370        .route(
371            "/provider-accounts/kinds",
372            get(provider_accounts::kinds::list_account_kinds),
373        )
374        .route(
375            "/provider-accounts/{id}",
376            get(provider_accounts::get::get_provider_account)
377                .patch(provider_accounts::update::update_provider_account)
378                .delete(provider_accounts::delete::delete_provider_account),
379        )
380        .route(
381            "/provider-accounts/{id}/test",
382            post(provider_accounts::test::test_provider_account),
383        )
384        .route(
385            "/provider-accounts/{id}/usage",
386            get(provider_accounts::usage::provider_account_usage),
387        )
388        .route(
389            "/approval-delegations",
390            get(approval_delegations::list::list_approval_delegations)
391                .post(approval_delegations::create::create_approval_delegation),
392        )
393        .route(
394            "/approval-delegations/{id}",
395            delete(approval_delegations::delete::delete_approval_delegation),
396        )
397        .route(
398            "/schedules",
399            get(schedules::list::list_schedules).post(schedules::create::create_schedule),
400        )
401        .route(
402            "/schedules/{id}",
403            get(schedules::get::get_schedule).delete(schedules::delete::delete_schedule),
404        )
405        .route(
406            "/schedules/{id}/pause",
407            post(schedules::pause_resume::pause_schedule),
408        )
409        .route(
410            "/schedules/{id}/resume",
411            post(schedules::pause_resume::resume_schedule),
412        )
413        .route(
414            "/schedules/{id}/trigger",
415            post(schedules::trigger::trigger_schedule),
416        )
417        .route(
418            "/signals",
419            get(signals::list::list_signals).post(signals::send::send_signal),
420        )
421        .route(
422            "/templates/registry",
423            get(templates::list_registry_templates),
424        );
425
426    #[cfg(feature = "prometheus")]
427    {
428        api_v1 = api_v1.route("/metrics", get(metrics::metrics));
429    }
430
431    let mut api_v1 = api_v1
432        .nest("/auth", auth_credential_routes)
433        .nest("/auth", auth_session_routes);
434
435    if let Some(rpm) = config.rate_limit_general {
436        let ctx = RateLimitContext {
437            store: state.store.clone(),
438            jwt_config: state.jwt_config.clone(),
439            limiter: per_minute(rpm),
440            trusted_proxies: config.trusted_proxies.clone(),
441            account_limit: AccountLimit::Off,
442        };
443        api_v1 = api_v1
444            .layer(axum_mw::from_fn(rate_limit))
445            .layer(Extension(ctx));
446    }
447
448    let api_v1 = api_v1.with_state(state.clone());
449
450    let mut app = Router::new()
451        .nest("/api/v1/internal", internal_routes)
452        .nest("/api/v1", api_v1)
453        .with_state(state)
454        .layer(RequestBodyLimitLayer::new(MAX_API_BODY_BYTES))
455        .merge(artifact_upload_routes);
456
457    // Before the dashboard fallback: metrics are labelled by matched route,
458    // and every unknown URL falls through to the dashboard, which is not
459    // metered.
460    #[cfg(feature = "prometheus")]
461    {
462        app = app.layer(axum_mw::from_fn(crate::middleware::request_metrics));
463    }
464
465    // `Router::layer` only wraps what the router already holds: the dashboard
466    // fallback goes in first so the HTTPS redirect and the security headers
467    // cover it too.
468    app = match config.dashboard_dir {
469        Some(dir) => {
470            let index = dir.join("index.html");
471            let serve = ServeDir::new(dir).fallback(ServeFile::new(index));
472            app.fallback_service(serve)
473        }
474        #[cfg(feature = "dashboard")]
475        None => app.fallback_service(crate::dashboard::EmbeddedDashboard),
476        #[cfg(not(feature = "dashboard"))]
477        None => app,
478    };
479
480    if config.enforce_https {
481        if config.trusted_proxies.is_empty() {
482            warn!(
483                "enforce_https is set but TRUSTED_PROXIES is empty: X-Forwarded-Proto is never \
484                 believed, so no request is redirected to HTTPS"
485            );
486        }
487        app = app.layer(axum_mw::from_fn_with_state(
488            config.trusted_proxies.clone(),
489            https_redirect,
490        ));
491    }
492
493    app.layer(axum_mw::from_fn(security_headers))
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499    use crate::routes::test_helpers::create_user_auth_header;
500    use axum::body::Body;
501    use axum::http::{Request, StatusCode};
502    use http_body_util::BodyExt;
503    use ironflow_core::providers::claude::ClaudeCodeProvider;
504    use ironflow_engine::engine::Engine;
505    use ironflow_engine::notify::Event;
506    use ironflow_store::memory::InMemoryStore;
507    use std::sync::Arc;
508    use tokio::sync::broadcast;
509    use tower::ServiceExt;
510    fn test_state() -> AppState {
511        let store = Arc::new(InMemoryStore::new());
512        let provider = Arc::new(ClaudeCodeProvider::new());
513        let engine = Arc::new(Engine::new(store.clone(), provider));
514        let jwt_config = Arc::new(ironflow_auth::jwt::JwtConfig {
515            secret: "test-secret".to_string(),
516            access_token_ttl_secs: 900,
517            refresh_token_ttl_secs: 604800,
518            cookie_domain: None,
519            cookie_secure: false,
520        });
521        let (event_sender, _) = broadcast::channel::<Event>(1);
522        AppState::new(
523            store,
524            engine,
525            jwt_config,
526            "test-worker-token".to_string(),
527            event_sender,
528        )
529    }
530
531    #[tokio::test]
532    async fn health_check_route() {
533        let state = test_state();
534        let app = create_router(state, RouterConfig::default());
535
536        let req = Request::builder()
537            .uri("/api/v1/health-check")
538            .body(Body::empty())
539            .unwrap();
540
541        let resp = app.oneshot(req).await.unwrap();
542        assert_eq!(resp.status(), StatusCode::OK);
543
544        let body = resp.into_body().collect().await.unwrap().to_bytes();
545        assert_eq!(&body[..], b"OK");
546    }
547
548    #[tokio::test]
549    async fn runs_route_exists() {
550        let state = test_state();
551        let app = create_router(state.clone(), RouterConfig::default());
552        let auth_header = create_user_auth_header(&state, "testuser", false).await;
553
554        let req = Request::builder()
555            .uri("/api/v1/runs?page=1&per_page=20")
556            .header("authorization", auth_header)
557            .body(Body::empty())
558            .unwrap();
559
560        let resp = app.oneshot(req).await.unwrap();
561        assert_eq!(resp.status(), StatusCode::OK);
562    }
563
564    #[tokio::test]
565    async fn stats_route_exists() {
566        let state = test_state();
567        let app = create_router(state.clone(), RouterConfig::default());
568        let auth_header = create_user_auth_header(&state, "testuser", false).await;
569
570        let req = Request::builder()
571            .uri("/api/v1/stats")
572            .header("authorization", auth_header)
573            .body(Body::empty())
574            .unwrap();
575
576        let resp = app.oneshot(req).await.unwrap();
577        assert_eq!(resp.status(), StatusCode::OK);
578    }
579
580    #[tokio::test]
581    async fn responses_include_security_headers() {
582        let state = test_state();
583        let app = create_router(state, RouterConfig::default());
584
585        let req = Request::builder()
586            .uri("/api/v1/health-check")
587            .body(Body::empty())
588            .unwrap();
589
590        let resp = app.oneshot(req).await.unwrap();
591
592        assert_eq!(
593            resp.headers().get("x-content-type-options").unwrap(),
594            "nosniff"
595        );
596        assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
597        assert_eq!(
598            resp.headers().get("x-xss-protection").unwrap(),
599            "1; mode=block"
600        );
601        assert_eq!(
602            resp.headers().get("strict-transport-security").unwrap(),
603            "max-age=63072000; includeSubDomains"
604        );
605        assert!(
606            resp.headers()
607                .get("content-security-policy")
608                .unwrap()
609                .to_str()
610                .unwrap()
611                .contains("default-src 'self'")
612        );
613    }
614
615    #[tokio::test]
616    async fn body_size_limit_rejects_oversized_payload() {
617        let state = test_state();
618        let app = create_router(state.clone(), RouterConfig::default());
619        let auth_header = create_user_auth_header(&state, "testuser", false).await;
620
621        // 3 MiB payload — exceeds the 2 MiB limit
622        let oversized = vec![0u8; 3 * 1024 * 1024];
623
624        let req = Request::builder()
625            .method("POST")
626            .uri("/api/v1/runs")
627            .header("content-type", "application/json")
628            .header("authorization", auth_header)
629            .body(Body::from(oversized))
630            .unwrap();
631
632        let resp = app.oneshot(req).await.unwrap();
633        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
634    }
635}