ironflow-api 2.40.0

REST API for ironflow run management and observability
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! `POST /api/v1/runs/:id/steps/:step_id/input` -- Answer a human input step.
//!
//! `POST /api/v1/runs/:id/steps/:step_id/reject` -- Reject a human input step.

use axum::Json;
use axum::extract::{Path, State};
use axum::response::IntoResponse;
use chrono::Utc;
use ironflow_auth::extractor::Authenticated;
use ironflow_engine::config::HUMAN_INPUT_SCHEMA_KEY;
use ironflow_store::models::{
    Run, RunStatus, Step, StepApproval, StepKind, StepStatus, StepUpdate,
};
use jsonschema::validator_for;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::spawn;
use tracing::error;
use uuid::Uuid;

use crate::entities::RunResponse;
use crate::error::ApiError;
use crate::response::ok;
use crate::routes::approve_run::authorize_gate;
use crate::state::AppState;

/// Request body for rejecting a human input step.
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct RejectHumanInputRequest {
    /// Why the input is refused. Passed to the handler.
    #[serde(default)]
    pub reason: Option<String>,
}

/// Answer a human input step with a value matching its JSON schema.
///
/// The answer is validated against the schema stored on the step. The caller
/// must be allowed to resolve the step like an approval gate (admin, approver
/// groups, assignee or delegation). The first valid answer wins: the step
/// completes, the run moves from `AwaitingApproval` back to `Running` and
/// resumes, and the handler receives the typed answer.
///
/// # Errors
///
/// - 400 if the step is not a human input or is not awaiting input
/// - 403 if the caller may not answer the step
/// - 404 if the run or the step does not exist
/// - 409 if the input was already answered or rejected
/// - 422 if the answer does not match the schema
#[cfg_attr(
    feature = "openapi",
    utoipa::path(
        post,
        path = "/api/v1/runs/{id}/steps/{step_id}/input",
        tags = ["runs"],
        params(
            ("id" = Uuid, Path, description = "Run ID"),
            ("step_id" = Uuid, Path, description = "Step ID")
        ),
        request_body(content = Value, content_type = "application/json", description = "Answer matching the JSON schema stored on the step"),
        responses(
            (status = 200, description = "Answer recorded, the run resumes", body = RunResponse),
            (status = 400, description = "Step is not a human input awaiting input"),
            (status = 401, description = "Unauthorized"),
            (status = 403, description = "Forbidden"),
            (status = 404, description = "Run or step not found"),
            (status = 409, description = "Input already answered or rejected"),
            (status = 422, description = "Answer does not match the schema")
        ),
        security(("Bearer" = []))
    )
)]
pub async fn submit_human_input(
    auth: Authenticated,
    State(state): State<AppState>,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
    Json(answer): Json<Value>,
) -> Result<impl IntoResponse, ApiError> {
    let (run, step) = open_input_step(&state, id, step_id).await?;
    let actor = authorize_gate(&auth, &state, &run, &step).await?;
    validate_answer(step.input.as_ref(), &answer)?;

    // Like approve, two concurrent answers are not serialized: both may pass
    // the status check above before either is written. This is an accepted
    // limitation of the gate routes.
    let now = Utc::now();
    state
        .store
        .record_step_approval(
            step.id,
            StepApproval {
                user_id: auth.user_id,
                approved_by: actor,
                at: now,
            },
        )
        .await?;
    state
        .store
        .update_step(
            step.id,
            StepUpdate {
                status: Some(StepStatus::Completed),
                output: Some(answer),
                completed_at: Some(now),
                clear_approval_deadline: true,
                ..StepUpdate::default()
            },
        )
        .await?;
    state
        .store
        .update_run_status(id, RunStatus::Running)
        .await?;

    resume_in_background(&state, id);

    Ok(ok(RunResponse::from(state.get_run_or_404(id).await?)))
}

/// Reject a human input step.
///
/// The step is marked `Rejected` with the reason, the run moves from
/// `AwaitingApproval` back to `Running` and resumes: the handler receives a
/// `HumanInputRejected` error and decides what happens next. The body is
/// optional; without a reason, one naming the caller is recorded.
///
/// # Errors
///
/// - 400 if the step is not a human input or is not awaiting input
/// - 403 if the caller may not resolve the step
/// - 404 if the run or the step does not exist
/// - 409 if the input was already answered or rejected
#[cfg_attr(
    feature = "openapi",
    utoipa::path(
        post,
        path = "/api/v1/runs/{id}/steps/{step_id}/reject",
        tags = ["runs"],
        params(
            ("id" = Uuid, Path, description = "Run ID"),
            ("step_id" = Uuid, Path, description = "Step ID")
        ),
        request_body(content = RejectHumanInputRequest, description = "Optional rejection reason"),
        responses(
            (status = 200, description = "Input rejected, the run resumes", body = RunResponse),
            (status = 400, description = "Step is not a human input awaiting input"),
            (status = 401, description = "Unauthorized"),
            (status = 403, description = "Forbidden"),
            (status = 404, description = "Run or step not found"),
            (status = 409, description = "Input already answered or rejected")
        ),
        security(("Bearer" = []))
    )
)]
pub async fn reject_human_input(
    auth: Authenticated,
    State(state): State<AppState>,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
    body: Option<Json<RejectHumanInputRequest>>,
) -> Result<impl IntoResponse, ApiError> {
    let (run, step) = open_input_step(&state, id, step_id).await?;
    let actor = authorize_gate(&auth, &state, &run, &step).await?;

    let reason = body
        .and_then(|Json(b)| b.reason)
        .filter(|r| !r.trim().is_empty())
        .unwrap_or_else(|| format!("input rejected by {actor}"));

    state
        .store
        .update_step(
            step.id,
            StepUpdate {
                status: Some(StepStatus::Rejected),
                error: Some(reason),
                completed_at: Some(Utc::now()),
                clear_approval_deadline: true,
                ..StepUpdate::default()
            },
        )
        .await?;
    state
        .store
        .update_run_status(id, RunStatus::Running)
        .await?;

    resume_in_background(&state, id);

    Ok(ok(RunResponse::from(state.get_run_or_404(id).await?)))
}

/// Load the run and the human input step, and check the step can be resolved.
///
/// A resolved step returns 409 whatever the run status, so replaying an
/// accepted request is reported as a conflict rather than a bad request.
async fn open_input_step(
    state: &AppState,
    run_id: Uuid,
    step_id: Uuid,
) -> Result<(Run, Step), ApiError> {
    let run = state.get_run_or_404(run_id).await?;
    let step = state
        .store
        .get_step(step_id)
        .await?
        .filter(|s| s.run_id == run_id)
        .ok_or(ApiError::StepNotFound(step_id))?;

    if step.kind != StepKind::HumanInput {
        return Err(ApiError::BadRequest(
            "step does not wait for input".to_string(),
        ));
    }

    match step.status.state {
        StepStatus::Completed => {
            return Err(ApiError::Conflict("input already provided".to_string()));
        }
        StepStatus::Rejected => {
            return Err(ApiError::Conflict("input already rejected".to_string()));
        }
        _ => {}
    }

    if step.status.state != StepStatus::AwaitingApproval
        || run.status.state != RunStatus::AwaitingApproval
    {
        return Err(ApiError::BadRequest(
            "step is not awaiting input".to_string(),
        ));
    }

    Ok((run, step))
}

/// Validate `answer` against the JSON schema stored in the step input.
fn validate_answer(input: Option<&Value>, answer: &Value) -> Result<(), ApiError> {
    let schema = input
        .and_then(|i| i.get(HUMAN_INPUT_SCHEMA_KEY))
        .ok_or_else(|| ApiError::Internal("input step has no stored schema".to_string()))?;
    let validator = validator_for(schema)
        .map_err(|e| ApiError::Internal(format!("input step has an invalid schema: {e}")))?;

    let errors: Vec<String> = validator
        .iter_errors(answer)
        .map(|e| e.to_string())
        .collect();
    if errors.is_empty() {
        Ok(())
    } else {
        Err(ApiError::InvalidInput(errors))
    }
}

/// Resume the run in the background; the handler replays up to the input.
fn resume_in_background(state: &AppState, id: Uuid) {
    let engine = state.engine.clone();
    spawn(async move {
        if let Err(err) = engine.resume_run(id).await {
            error!(run_id = %id, error = %err, "failed to resume run after human input");
        }
    });
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::Arc;

    use axum::Router;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::routing::post;
    use http_body_util::BodyExt;
    use ironflow_auth::jwt::{AccessToken, JwtConfig};
    use ironflow_auth::password;
    use ironflow_core::providers::claude::ClaudeCodeProvider;
    use ironflow_engine::engine::Engine;
    use ironflow_engine::handler::input_schema_for;
    use ironflow_engine::notify::Event;
    use ironflow_store::memory::InMemoryStore;
    use ironflow_store::models::{
        Assignee, NewRun, NewStep, NewUser, TriggerKind, User, step_trace_id,
    };
    use ironflow_store::store::RunStore;
    use ironflow_store::user_store::UserStore;
    use schemars::JsonSchema;
    use serde_json::{from_slice, json};
    use tokio::sync::broadcast;
    use tower::ServiceExt;

    use super::*;

    /// The answer type the test steps ask for.
    #[allow(dead_code)]
    #[derive(Deserialize, JsonSchema)]
    struct Answers {
        answers: Vec<String>,
    }

    /// An answer type whose schema carries a `$defs` reference.
    #[allow(dead_code)]
    #[derive(Deserialize, JsonSchema)]
    struct Nested {
        target: Target,
    }

    #[allow(dead_code)]
    #[derive(Deserialize, JsonSchema)]
    struct Target {
        env: String,
    }

    fn test_state(store: Arc<InMemoryStore>) -> AppState {
        let provider = Arc::new(ClaudeCodeProvider::new());
        let engine = Arc::new(Engine::new(store.clone(), provider));
        let jwt_config = Arc::new(JwtConfig {
            secret: "test-secret".to_string(),
            access_token_ttl_secs: 900,
            refresh_token_ttl_secs: 604800,
            cookie_domain: None,
            cookie_secure: false,
        });
        let (event_sender, _) = broadcast::channel::<Event>(1);
        AppState::new(
            store,
            engine,
            jwt_config,
            "test-worker-token".to_string(),
            event_sender,
        )
    }

    fn admin_header(state: &AppState) -> String {
        let token =
            AccessToken::for_user(Uuid::now_v7(), "admin", true, &state.jwt_config).unwrap();
        format!("Bearer {}", token.0)
    }

    async fn member(store: &Arc<InMemoryStore>, username: &str) -> User {
        let password_hash = password::hash("password123").expect("hash");
        store
            .create_user(NewUser {
                email: format!("{username}@example.com"),
                username: username.to_string(),
                password_hash,
                // The first user would otherwise become an implicit admin.
                is_admin: Some(false),
            })
            .await
            .expect("create user")
    }

    fn member_header(user: &User, state: &AppState) -> String {
        let token = AccessToken::for_user(user.id, &user.username, false, &state.jwt_config)
            .expect("token");
        format!("Bearer {}", token.0)
    }

    async fn awaiting_run(store: &Arc<InMemoryStore>) -> Uuid {
        let run = store
            .create_run(NewRun {
                created_by: None,
                workflow_name: "test".to_string(),
                trigger: TriggerKind::Manual,
                payload: json!({}),
                max_retries: 0,
                handler_version: None,
                labels: HashMap::new(),
                scheduled_at: None,
                idempotency_key: None,
                max_cost_usd: None,
            })
            .await
            .unwrap()
            .into_run();
        store
            .update_run_status(run.id, RunStatus::Running)
            .await
            .unwrap();
        store
            .update_run_status(run.id, RunStatus::AwaitingApproval)
            .await
            .unwrap();
        run.id
    }

    /// A step of `kind` awaiting approval on `run_id`.
    async fn awaiting_step(
        store: &Arc<InMemoryStore>,
        run_id: Uuid,
        kind: StepKind,
        assignee: Option<Assignee>,
    ) -> Uuid {
        let step = store
            .create_step(NewStep {
                run_id,
                trace_id: step_trace_id(run_id, "clarify", 0),
                name: "clarify".to_string(),
                kind,
                position: 0,
                input: Some(json!({
                    "message": "Answer the questions",
                    HUMAN_INPUT_SCHEMA_KEY: input_schema_for::<Answers>(),
                })),
                is_error_handler: false,
            })
            .await
            .unwrap();
        store
            .update_step(
                step.id,
                StepUpdate {
                    status: Some(StepStatus::Running),
                    ..StepUpdate::default()
                },
            )
            .await
            .unwrap();
        store
            .update_step(
                step.id,
                StepUpdate {
                    status: Some(StepStatus::AwaitingApproval),
                    approval_assignee: assignee,
                    ..StepUpdate::default()
                },
            )
            .await
            .unwrap();
        step.id
    }

    /// A run awaiting a human input step, with an admin header.
    async fn setup() -> (Arc<InMemoryStore>, AppState, Uuid, Uuid) {
        let store = Arc::new(InMemoryStore::new());
        let run_id = awaiting_run(&store).await;
        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, None).await;
        let state = test_state(store.clone());
        (store, state, run_id, step_id)
    }

    fn app(state: AppState) -> Router {
        Router::new()
            .route("/{id}/steps/{step_id}/input", post(submit_human_input))
            .route("/{id}/steps/{step_id}/reject", post(reject_human_input))
            .with_state(state)
    }

    /// POST `body` (or nothing) to `/{run_id}/steps/{step_id}/{verb}`.
    async fn call(
        state: &AppState,
        auth: &str,
        run_id: Uuid,
        step_id: Uuid,
        verb: &str,
        body: Option<Value>,
    ) -> (StatusCode, Value) {
        let builder = Request::builder()
            .method("POST")
            .uri(format!("/{run_id}/steps/{step_id}/{verb}"))
            .header("authorization", auth);
        let req = match body {
            Some(body) => builder
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
            None => builder.body(Body::empty()).unwrap(),
        };

        let resp = app(state.clone()).oneshot(req).await.unwrap();
        let status = resp.status();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let json_val = if bytes.is_empty() {
            Value::Null
        } else {
            from_slice(&bytes).unwrap()
        };
        (status, json_val)
    }

    #[tokio::test]
    async fn human_input_submit_valid_answer_resumes_the_run() {
        let (store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);
        let answer = json!({"answers": ["staging"]});

        let (status, body) = call(
            &state,
            &auth,
            run_id,
            step_id,
            "input",
            Some(answer.clone()),
        )
        .await;

        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["data"]["status"], "running");
        let step = store.get_step(step_id).await.unwrap().unwrap();
        assert_eq!(step.status.state, StepStatus::Completed);
        assert_eq!(step.output, Some(answer));
        assert_eq!(step.approvals.len(), 1);
        assert_eq!(step.approvals[0].approved_by, "admin");
    }

    #[tokio::test]
    async fn human_input_submit_invalid_answer_returns_422() {
        let (store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        for answer in [json!({"answers": 3}), json!({})] {
            let (status, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;

            assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
            assert_eq!(body["error"]["code"], "INVALID_INPUT");
            let errors = body["error"]["details"]["errors"]
                .as_array()
                .expect("errors array");
            assert!(!errors.is_empty());
        }

        let step = store.get_step(step_id).await.unwrap().unwrap();
        assert_eq!(step.status.state, StepStatus::AwaitingApproval);
        let run = store.get_run(run_id).await.unwrap().unwrap();
        assert_eq!(run.status.state, RunStatus::AwaitingApproval);
    }

    #[tokio::test]
    async fn human_input_submit_twice_returns_409() {
        let (_store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);
        let answer = json!({"answers": ["yes"]});

        let (first, _) = call(
            &state,
            &auth,
            run_id,
            step_id,
            "input",
            Some(answer.clone()),
        )
        .await;
        assert_eq!(first, StatusCode::OK);

        let (second, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
        assert_eq!(second, StatusCode::CONFLICT);
        assert_eq!(body["error"]["message"], "input already provided");
    }

    #[tokio::test]
    async fn human_input_submit_on_an_approval_step_returns_400() {
        let store = Arc::new(InMemoryStore::new());
        let run_id = awaiting_run(&store).await;
        let step_id = awaiting_step(&store, run_id, StepKind::Approval, None).await;
        let state = test_state(store);
        let auth = admin_header(&state);

        let answer = json!({"answers": []});
        let (status, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn human_input_submit_on_a_run_not_awaiting_returns_400() {
        let (store, state, run_id, step_id) = setup().await;
        store
            .update_run_status(run_id, RunStatus::Running)
            .await
            .unwrap();
        let auth = admin_header(&state);

        let answer = json!({"answers": []});
        let (status, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn human_input_unknown_step_or_step_of_another_run_returns_404() {
        let (store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);
        let answer = json!({"answers": []});

        let unknown = Uuid::now_v7();
        let (status, body) = call(
            &state,
            &auth,
            run_id,
            unknown,
            "input",
            Some(answer.clone()),
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(body["error"]["code"], "STEP_NOT_FOUND");

        let other_run = awaiting_run(&store).await;
        let (status, _) = call(&state, &auth, other_run, step_id, "input", Some(answer)).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn human_input_unknown_run_returns_404() {
        let (_store, state, _run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        let answer = json!({"answers": []});
        let (status, body) = call(
            &state,
            &auth,
            Uuid::now_v7(),
            step_id,
            "input",
            Some(answer),
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(body["error"]["code"], "RUN_NOT_FOUND");
    }

    #[tokio::test]
    async fn human_input_non_admin_non_assignee_is_forbidden() {
        let store = Arc::new(InMemoryStore::new());
        let alice = member(&store, "alice").await;
        let bob = member(&store, "bob").await;
        let run_id = awaiting_run(&store).await;
        let assignee = Some(Assignee::user(&alice.username));
        let step_id = awaiting_step(&store, run_id, StepKind::HumanInput, assignee).await;
        let state = test_state(store.clone());

        let answer = json!({"answers": ["yes"]});
        let bob_auth = member_header(&bob, &state);
        let (status, _) = call(
            &state,
            &bob_auth,
            run_id,
            step_id,
            "input",
            Some(answer.clone()),
        )
        .await;
        assert_eq!(status, StatusCode::FORBIDDEN);

        let alice_auth = member_header(&alice, &state);
        let (status, _) = call(&state, &alice_auth, run_id, step_id, "input", Some(answer)).await;
        assert_eq!(status, StatusCode::OK);
        let step = store.get_step(step_id).await.unwrap().unwrap();
        assert_eq!(step.approvals[0].user_id, alice.id);
    }

    #[tokio::test]
    async fn human_input_reject_marks_the_step_and_resumes_the_run() {
        let (store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        let body = json!({"reason": "out of scope"});
        let (status, resp) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;

        assert_eq!(status, StatusCode::OK);
        assert_eq!(resp["data"]["status"], "running");
        let step = store.get_step(step_id).await.unwrap().unwrap();
        assert_eq!(step.status.state, StepStatus::Rejected);
        assert_eq!(step.error.as_deref(), Some("out of scope"));
        assert!(step.approval_deadline_at.is_none());
    }

    #[tokio::test]
    async fn human_input_reject_without_body_uses_the_default_reason() {
        let (store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        let (status, _) = call(&state, &auth, run_id, step_id, "reject", None).await;

        assert_eq!(status, StatusCode::OK);
        let step = store.get_step(step_id).await.unwrap().unwrap();
        assert_eq!(step.error.as_deref(), Some("input rejected by admin"));
    }

    #[tokio::test]
    async fn human_input_reject_with_a_blank_reason_uses_the_default_reason() {
        let (store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        let body = json!({"reason": "   "});
        let (status, _) = call(&state, &auth, run_id, step_id, "reject", Some(body)).await;

        assert_eq!(status, StatusCode::OK);
        let step = store.get_step(step_id).await.unwrap().unwrap();
        assert_eq!(step.error.as_deref(), Some("input rejected by admin"));
    }

    #[tokio::test]
    async fn human_input_reject_after_submit_returns_409() {
        let (_store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        let answer = json!({"answers": ["yes"]});
        let (first, _) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
        assert_eq!(first, StatusCode::OK);

        let (second, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
        assert_eq!(second, StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn human_input_submit_after_reject_returns_409() {
        let (_store, state, run_id, step_id) = setup().await;
        let auth = admin_header(&state);

        let (first, _) = call(&state, &auth, run_id, step_id, "reject", None).await;
        assert_eq!(first, StatusCode::OK);

        let answer = json!({"answers": ["yes"]});
        let (second, body) = call(&state, &auth, run_id, step_id, "input", Some(answer)).await;
        assert_eq!(second, StatusCode::CONFLICT);
        assert_eq!(body["error"]["message"], "input already rejected");
    }

    #[test]
    fn human_input_validate_answer_without_a_schema_is_internal() {
        let err = validate_answer(Some(&json!({"message": "Answer?"})), &json!({}))
            .expect_err("no schema");
        assert!(matches!(err, ApiError::Internal(_)), "got {err:?}");

        let err = validate_answer(None, &json!({})).expect_err("no input");
        assert!(matches!(err, ApiError::Internal(_)), "got {err:?}");
    }

    #[test]
    fn human_input_validate_answer_resolves_defs_references() {
        let schema = input_schema_for::<Nested>();
        assert!(schema.get("$defs").is_some(), "schema: {schema}");
        let input = json!({ HUMAN_INPUT_SCHEMA_KEY: schema });

        let valid = validate_answer(Some(&input), &json!({"target": {"env": "prod"}}));
        assert!(valid.is_ok(), "got {valid:?}");

        let err = validate_answer(Some(&input), &json!({"target": {"env": 1}}))
            .expect_err("wrong nested type");
        match err {
            ApiError::InvalidInput(errors) => assert_eq!(errors.len(), 1, "got {errors:?}"),
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }
}