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