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(
174            "/runs/pending-count",
175            get(internal::count_pending_runs::count_pending_runs),
176        )
177        .route(
178            "/runs/{id}",
179            get(internal::get_run::get_run).put(internal::update_run::update_run),
180        )
181        .route(
182            "/runs/{id}/status",
183            put(internal::update_run_status::update_run_status),
184        )
185        .route("/runs/{id}/logs", post(internal::push_logs::push_logs))
186        .route("/runs/{id}/lease", post(internal::renew_lease::renew_lease))
187        .route(
188            "/runs/{id}/descendants",
189            get(internal::list_descendants::list_descendants),
190        )
191        .route(
192            "/runs/{id}/artifacts",
193            get(internal::list_artifacts::list_artifacts),
194        )
195        .route("/steps", post(internal::create_step::create_step))
196        .route("/steps/{id}", put(internal::update_step::update_step))
197        .route(
198            "/step-dependencies",
199            post(internal::create_step_dependencies::create_step_dependencies),
200        )
201        .route("/secrets/{*key}", get(internal::get_secret::get_secret))
202        .route("/signals", get(internal::signals::list_signals_for_key))
203        .route(
204            "/steps/{id}/signal-resolution",
205            post(internal::signals::resolve_signal_step),
206        )
207        .route(
208            "/runs/{id}/signal-suspension",
209            post(internal::signals::suspend_run_on_signal),
210        )
211        .route(
212            "/provider-accounts/candidates",
213            get(internal::provider_accounts::list_candidates),
214        )
215        .route(
216            "/provider-accounts/{id}/observations",
217            post(internal::provider_accounts::record_observation),
218        )
219        .layer(axum_mw::from_fn(worker_token_auth))
220        .layer(Extension(WorkerToken(state.worker_token.clone())))
221        .with_state(state.clone());
222
223    // Artifact uploads carry file payloads, so they sit outside the 2 MiB
224    // limit that guards every JSON route and get their own, larger ceiling.
225    let artifact_upload_routes = Router::new()
226        .route(
227            "/api/v1/internal/runs/{id}/steps/{step_id}/artifacts/{name}",
228            post(internal::upload_artifact::upload_artifact),
229        )
230        .layer(axum_mw::from_fn(worker_token_auth))
231        .layer(Extension(WorkerToken(state.worker_token.clone())))
232        .layer(RequestBodyLimitLayer::new(MAX_ARTIFACT_BODY_SIZE))
233        .with_state(state.clone());
234
235    // Auth credential routes (rate-limited when configured). Password change
236    // sits here too: it checks the current password, so it is a guessing oracle.
237    #[allow(unused_mut)]
238    let mut auth_credential_routes = Router::new();
239
240    #[cfg(feature = "sign-up")]
241    {
242        auth_credential_routes =
243            auth_credential_routes.route("/sign-up", post(auth::sign_up::sign_up));
244    }
245
246    #[cfg(not(feature = "sign-up"))]
247    {
248        auth_credential_routes = auth_credential_routes.route("/sign-up", post(sign_up_disabled));
249    }
250
251    let mut auth_credential_routes = auth_credential_routes
252        .route("/sign-in", post(auth::sign_in::sign_in))
253        .route("/password", patch(auth::change_password::change_password));
254
255    if let Some(rpm) = config.rate_limit_auth {
256        let ctx = RateLimitContext {
257            store: state.store.clone(),
258            jwt_config: state.jwt_config.clone(),
259            limiter: per_minute(rpm),
260            trusted_proxies: config.trusted_proxies.clone(),
261            account_limit: AccountLimit::ByEmail,
262        };
263        auth_credential_routes = auth_credential_routes
264            .layer(axum_mw::from_fn(rate_limit))
265            .layer(Extension(ctx));
266    }
267
268    // Auth session routes (no strict rate limiting, covered by general limiter)
269    let auth_session_routes = Router::new()
270        .route("/refresh", post(auth::refresh::refresh))
271        .route("/sign-out", post(auth::sign_out::sign_out))
272        .route("/me", get(auth::me::me));
273
274    // Public + user-authenticated routes (rate-limited when configured)
275    #[allow(unused_mut)]
276    let mut api_v1 = Router::new()
277        .route("/health-check", get(health_check::health_check))
278        .route("/openapi.json", get(openapi_spec::openapi_spec))
279        .route(
280            "/runs",
281            get(list_runs::list_runs).post(create_run::create_run),
282        )
283        .route("/runs/{id}", get(get_run::get_run))
284        .route("/runs/{id}/logs", get(get_run_logs::get_run_logs))
285        .route("/runs/{id}/cancel", post(cancel_run::cancel_run))
286        .route("/runs/{id}/pause", post(pause_run::pause_run))
287        .route("/runs/{id}/resume", post(pause_run::resume_run))
288        .route("/runs/{id}/approve", post(approve_run::approve_run))
289        .route("/runs/{id}/reject", post(approve_run::reject_run))
290        .route("/runs/{id}/retry", post(retry_run::retry_run))
291        .route("/runs/{id}/replay", post(replay_run::replay_run))
292        .route("/runs/{id}/events", get(run_events::run_events))
293        .route(
294            "/runs/{id}/steps/{step_id}/artifacts/{name}",
295            get(download_artifact::download_artifact),
296        )
297        .route(
298            "/runs/{id}/steps/{step_id}/input",
299            post(human_input::submit_human_input),
300        )
301        .route(
302            "/runs/{id}/steps/{step_id}/reject",
303            post(human_input::reject_human_input),
304        )
305        .route("/workflows", get(list_workflows::list_workflows))
306        .route("/workflows/{name}", get(get_workflow::get_workflow))
307        .route("/workflows/{name}/plan", post(plan_workflow::plan_workflow))
308        .route(
309            "/workflows/{name}/pause",
310            post(pause_workflow::pause_workflow),
311        )
312        .route(
313            "/workflows/{name}/resume",
314            post(pause_workflow::resume_workflow),
315        )
316        .route("/stats", get(get_stats::get_stats))
317        .route(
318            "/stats/agent-roles",
319            get(get_agent_role_stats::get_agent_role_stats),
320        )
321        .route("/stats/history", get(get_stats_history::get_stats_history))
322        .route("/steps", get(list_steps::list_steps))
323        .route("/audit-logs", get(audit_logs::list_audit_logs))
324        .route("/events", get(events::events))
325        .route(
326            "/api-keys",
327            get(api_keys::list::list_api_keys).post(api_keys::create::create_api_key),
328        )
329        .route(
330            "/api-keys/scopes",
331            get(api_keys::available_scopes::available_scopes),
332        )
333        .route("/api-keys/{id}", delete(api_keys::delete::delete_api_key))
334        .route(
335            "/users",
336            get(users::list::list_users).post(users::create::create_user),
337        )
338        .route("/users/{id}", delete(users::delete::delete_user))
339        .route("/users/{id}/role", patch(users::update_role::update_role))
340        .route(
341            "/users/{id}/groups",
342            get(users::groups::get_user_groups).put(users::groups::update_user_groups),
343        )
344        .route(
345            "/secrets",
346            get(secrets::list::list_secrets).post(secrets::create::create_secret),
347        )
348        // Registered before the catch-all below: a static segment wins over
349        // the wildcard, so `rotate` is never read as a secret key.
350        .route("/secrets/rotate", post(secrets::rotate::rotate_secrets))
351        .route(
352            "/secrets/key-versions",
353            get(secrets::key_versions::secret_key_versions),
354        )
355        .route(
356            "/secrets/{*key}",
357            put(secrets::update::update_secret).delete(secrets::delete::delete_secret),
358        )
359        .route(
360            "/provider-accounts",
361            get(provider_accounts::list::list_provider_accounts)
362                .post(provider_accounts::create::create_provider_account),
363        )
364        // Registered before `{id}`: a static segment wins, so `kinds` is never
365        // read as an account name.
366        .route(
367            "/provider-accounts/kinds",
368            get(provider_accounts::kinds::list_account_kinds),
369        )
370        .route(
371            "/provider-accounts/{id}",
372            get(provider_accounts::get::get_provider_account)
373                .patch(provider_accounts::update::update_provider_account)
374                .delete(provider_accounts::delete::delete_provider_account),
375        )
376        .route(
377            "/provider-accounts/{id}/test",
378            post(provider_accounts::test::test_provider_account),
379        )
380        .route(
381            "/provider-accounts/{id}/usage",
382            get(provider_accounts::usage::provider_account_usage),
383        )
384        .route(
385            "/approval-delegations",
386            get(approval_delegations::list::list_approval_delegations)
387                .post(approval_delegations::create::create_approval_delegation),
388        )
389        .route(
390            "/approval-delegations/{id}",
391            delete(approval_delegations::delete::delete_approval_delegation),
392        )
393        .route(
394            "/schedules",
395            get(schedules::list::list_schedules).post(schedules::create::create_schedule),
396        )
397        .route(
398            "/schedules/{id}",
399            get(schedules::get::get_schedule).delete(schedules::delete::delete_schedule),
400        )
401        .route(
402            "/schedules/{id}/pause",
403            post(schedules::pause_resume::pause_schedule),
404        )
405        .route(
406            "/schedules/{id}/resume",
407            post(schedules::pause_resume::resume_schedule),
408        )
409        .route(
410            "/schedules/{id}/trigger",
411            post(schedules::trigger::trigger_schedule),
412        )
413        .route(
414            "/signals",
415            get(signals::list::list_signals).post(signals::send::send_signal),
416        )
417        .route(
418            "/templates/registry",
419            get(templates::list_registry_templates),
420        );
421
422    #[cfg(feature = "prometheus")]
423    {
424        api_v1 = api_v1.route("/metrics", get(metrics::metrics));
425    }
426
427    let mut api_v1 = api_v1
428        .nest("/auth", auth_credential_routes)
429        .nest("/auth", auth_session_routes);
430
431    if let Some(rpm) = config.rate_limit_general {
432        let ctx = RateLimitContext {
433            store: state.store.clone(),
434            jwt_config: state.jwt_config.clone(),
435            limiter: per_minute(rpm),
436            trusted_proxies: config.trusted_proxies.clone(),
437            account_limit: AccountLimit::Off,
438        };
439        api_v1 = api_v1
440            .layer(axum_mw::from_fn(rate_limit))
441            .layer(Extension(ctx));
442    }
443
444    let api_v1 = api_v1.with_state(state.clone());
445
446    let mut app = Router::new()
447        .nest("/api/v1/internal", internal_routes)
448        .nest("/api/v1", api_v1)
449        .with_state(state)
450        .layer(RequestBodyLimitLayer::new(MAX_API_BODY_BYTES))
451        .merge(artifact_upload_routes);
452
453    // Before the dashboard fallback: metrics are labelled by matched route,
454    // and every unknown URL falls through to the dashboard, which is not
455    // metered.
456    #[cfg(feature = "prometheus")]
457    {
458        app = app.layer(axum_mw::from_fn(crate::middleware::request_metrics));
459    }
460
461    // `Router::layer` only wraps what the router already holds: the dashboard
462    // fallback goes in first so the HTTPS redirect and the security headers
463    // cover it too.
464    app = match config.dashboard_dir {
465        Some(dir) => {
466            let index = dir.join("index.html");
467            let serve = ServeDir::new(dir).fallback(ServeFile::new(index));
468            app.fallback_service(serve)
469        }
470        #[cfg(feature = "dashboard")]
471        None => app.fallback_service(crate::dashboard::EmbeddedDashboard),
472        #[cfg(not(feature = "dashboard"))]
473        None => app,
474    };
475
476    if config.enforce_https {
477        if config.trusted_proxies.is_empty() {
478            warn!(
479                "enforce_https is set but TRUSTED_PROXIES is empty: X-Forwarded-Proto is never \
480                 believed, so no request is redirected to HTTPS"
481            );
482        }
483        app = app.layer(axum_mw::from_fn_with_state(
484            config.trusted_proxies.clone(),
485            https_redirect,
486        ));
487    }
488
489    app.layer(axum_mw::from_fn(security_headers))
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495    use crate::routes::test_helpers::create_user_auth_header;
496    use axum::body::Body;
497    use axum::http::{Request, StatusCode};
498    use http_body_util::BodyExt;
499    use ironflow_core::providers::claude::ClaudeCodeProvider;
500    use ironflow_engine::engine::Engine;
501    use ironflow_engine::notify::Event;
502    use ironflow_store::memory::InMemoryStore;
503    use std::sync::Arc;
504    use tokio::sync::broadcast;
505    use tower::ServiceExt;
506    fn test_state() -> AppState {
507        let store = Arc::new(InMemoryStore::new());
508        let provider = Arc::new(ClaudeCodeProvider::new());
509        let engine = Arc::new(Engine::new(store.clone(), provider));
510        let jwt_config = Arc::new(ironflow_auth::jwt::JwtConfig {
511            secret: "test-secret".to_string(),
512            access_token_ttl_secs: 900,
513            refresh_token_ttl_secs: 604800,
514            cookie_domain: None,
515            cookie_secure: false,
516        });
517        let (event_sender, _) = broadcast::channel::<Event>(1);
518        AppState::new(
519            store,
520            engine,
521            jwt_config,
522            "test-worker-token".to_string(),
523            event_sender,
524        )
525    }
526
527    #[tokio::test]
528    async fn health_check_route() {
529        let state = test_state();
530        let app = create_router(state, RouterConfig::default());
531
532        let req = Request::builder()
533            .uri("/api/v1/health-check")
534            .body(Body::empty())
535            .unwrap();
536
537        let resp = app.oneshot(req).await.unwrap();
538        assert_eq!(resp.status(), StatusCode::OK);
539
540        let body = resp.into_body().collect().await.unwrap().to_bytes();
541        assert_eq!(&body[..], b"OK");
542    }
543
544    #[tokio::test]
545    async fn runs_route_exists() {
546        let state = test_state();
547        let app = create_router(state.clone(), RouterConfig::default());
548        let auth_header = create_user_auth_header(&state, "testuser", false).await;
549
550        let req = Request::builder()
551            .uri("/api/v1/runs?page=1&per_page=20")
552            .header("authorization", auth_header)
553            .body(Body::empty())
554            .unwrap();
555
556        let resp = app.oneshot(req).await.unwrap();
557        assert_eq!(resp.status(), StatusCode::OK);
558    }
559
560    #[tokio::test]
561    async fn stats_route_exists() {
562        let state = test_state();
563        let app = create_router(state.clone(), RouterConfig::default());
564        let auth_header = create_user_auth_header(&state, "testuser", false).await;
565
566        let req = Request::builder()
567            .uri("/api/v1/stats")
568            .header("authorization", auth_header)
569            .body(Body::empty())
570            .unwrap();
571
572        let resp = app.oneshot(req).await.unwrap();
573        assert_eq!(resp.status(), StatusCode::OK);
574    }
575
576    #[tokio::test]
577    async fn responses_include_security_headers() {
578        let state = test_state();
579        let app = create_router(state, RouterConfig::default());
580
581        let req = Request::builder()
582            .uri("/api/v1/health-check")
583            .body(Body::empty())
584            .unwrap();
585
586        let resp = app.oneshot(req).await.unwrap();
587
588        assert_eq!(
589            resp.headers().get("x-content-type-options").unwrap(),
590            "nosniff"
591        );
592        assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
593        assert_eq!(
594            resp.headers().get("x-xss-protection").unwrap(),
595            "1; mode=block"
596        );
597        assert_eq!(
598            resp.headers().get("strict-transport-security").unwrap(),
599            "max-age=63072000; includeSubDomains"
600        );
601        assert!(
602            resp.headers()
603                .get("content-security-policy")
604                .unwrap()
605                .to_str()
606                .unwrap()
607                .contains("default-src 'self'")
608        );
609    }
610
611    #[tokio::test]
612    async fn body_size_limit_rejects_oversized_payload() {
613        let state = test_state();
614        let app = create_router(state.clone(), RouterConfig::default());
615        let auth_header = create_user_auth_header(&state, "testuser", false).await;
616
617        // 3 MiB payload — exceeds the 2 MiB limit
618        let oversized = vec![0u8; 3 * 1024 * 1024];
619
620        let req = Request::builder()
621            .method("POST")
622            .uri("/api/v1/runs")
623            .header("content-type", "application/json")
624            .header("authorization", auth_header)
625            .body(Body::from(oversized))
626            .unwrap();
627
628        let resp = app.oneshot(req).await.unwrap();
629        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
630    }
631}