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