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