kranz-server 0.4.2

REST and WebSocket mission host for Kranz.
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
//! `POST /api/hooks/github` end-to-end (design D-F, ticket
//! `trigger-ci-pr-fix-mission`): signature verification, repo matching, the
//! event allowlist, dedup, consent-gated queueing, and the never-land
//! invariant — driven through the real router (mutation-token gate ARMED;
//! hook requests authenticate via HMAC instead) with the engine's mock
//! backend, mirroring the wiring conventions of `tickets_host.rs`. All tests
//! are `ghook_`-prefixed for the contract filter.

use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::response::Response;
use axum::Router;
use http_body_util::BodyExt;
use kranz_engine::backend::AgentBackend;
use kranz_engine::backend_mock::{mock_init, mock_result_text, mock_text, MockBackend, MockScript};
use kranz_engine::event_log::EventLog;
use kranz_engine::paths::MissionPaths;
use kranz_engine::ticket::{Ticket, TicketState};
use kranz_engine::types::MissionStatus;
use kranz_server::MissionHost;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Once};
use std::time::{Duration, Instant};
use tempfile::TempDir;
use tower::ServiceExt;

const SECRET: &str = "whsec-test";

// ---------------------------------------------------------------------------
// Git fixtures (same isolation discipline as tickets_host.rs)
// ---------------------------------------------------------------------------

static ENV_ISOLATION: Once = Once::new();

fn isolate_git_env() {
    ENV_ISOLATION.call_once(|| {
        let missing = std::env::temp_dir().join(format!(
            "kranz-hooks-server-test-no-config-{}",
            std::process::id()
        ));
        std::env::set_var("GIT_CONFIG_GLOBAL", &missing);
        std::env::set_var("GIT_CONFIG_SYSTEM", &missing);
        if let Ok(ceiling) = std::fs::canonicalize(std::env::temp_dir()) {
            std::env::set_var("GIT_CEILING_DIRECTORIES", ceiling);
        }
        // Keep the real ~/.kranz/config.json (and its potential `hooks` key)
        // out of load_hooks.
        let home = std::env::temp_dir().join(format!(
            "kranz-hooks-server-test-home-{}",
            std::process::id()
        ));
        let _ = std::fs::create_dir_all(&home);
        std::env::set_var(if cfg!(windows) { "USERPROFILE" } else { "HOME" }, &home);
    });
}

fn git_available() -> bool {
    Command::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn setup() -> bool {
    isolate_git_env();
    if git_available() {
        true
    } else {
        kranz_engine::test_capability::skip(
            kranz_engine::test_capability::capability::GIT,
            "git is not on PATH",
        );
        false
    }
}

fn raw_git(dir: &Path, args: &[&str]) {
    let out = Command::new("git")
        .args(args)
        .current_dir(dir)
        .output()
        .expect("spawn git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Fresh repo on `main` with one seed commit and an `origin` remote pointing
/// at `octo/hello` on GitHub (the identity the hook route matches against).
fn init_repo() -> (TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("create tempdir");
    let init = Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(dir.path())
        .output()
        .expect("spawn git init");
    if !init.status.success() {
        raw_git(dir.path(), &["init"]);
        raw_git(dir.path(), &["symbolic-ref", "HEAD", "refs/heads/main"]);
    }
    raw_git(dir.path(), &["config", "user.name", "test"]);
    raw_git(dir.path(), &["config", "user.email", "test@example.com"]);
    std::fs::write(dir.path().join("README.md"), "seed\n").unwrap();
    raw_git(dir.path(), &["add", "-A"]);
    raw_git(dir.path(), &["commit", "-m", "seed"]);
    let root = std::fs::canonicalize(dir.path()).expect("canonicalize repo root");
    raw_git(
        &root,
        &["remote", "add", "origin", "git@github.com:octo/hello.git"],
    );
    (dir, root)
}

/// Repo + `hooks.secret` config; `None` leaves the route unconfigured (the
/// refuse-closed case).
fn init_hook_repo(secret: Option<&str>) -> (TempDir, PathBuf) {
    let (dir, root) = init_repo();
    if let Some(secret) = secret {
        let kranz = root.join(".kranz");
        std::fs::create_dir_all(&kranz).unwrap();
        std::fs::write(
            kranz.join("config.json"),
            json!({ "hooks": { "secret": secret, "allowUsers": ["reviewer"] } }).to_string(),
        )
        .unwrap();
    }
    (dir, root)
}

// ---------------------------------------------------------------------------
// Router harness (mutation token ARMED; hook requests carry no token)
// ---------------------------------------------------------------------------

fn orch_script(replies: Vec<String>) -> MockScript {
    MockScript::streaming(vec![mock_init("orch-session"), mock_result_text("ready")]).responding(
        replies
            .iter()
            .map(|reply| vec![mock_text(reply), mock_result_text(reply)])
            .collect(),
    )
}

fn plan_json(goal: &str) -> String {
    json!({
        "goal": goal,
        "validationContract": [],
        "milestones": [{
            "title": "M1",
            "features": [{
                "title": "F1",
                "spec": "do it",
                "validationCriteria": ["works"]
            }]
        }]
    })
    .to_string()
}

/// One scripted draft (planning turn + plan) per hook call the test makes.
fn hook_app(root: &Path, drafts: usize) -> Router {
    let scripts: Vec<MockScript> = (0..drafts)
        .map(|_| {
            orch_script(vec![
                "seeded, thinking...".to_string(),
                plan_json("fix the trigger"),
            ])
        })
        .collect();
    let backend: Arc<dyn AgentBackend> = Arc::new(MockBackend::with_scripts(scripts));
    let host = MissionHost::with_backend(root.to_path_buf(), backend);
    kranz_server::router_with_host(
        host,
        None,
        kranz_server::MutationAuthority::new("tok").unwrap(),
    )
}

// ---------------------------------------------------------------------------
// Request helpers — note: NO x-kranz-token is ever set on hook requests
// ---------------------------------------------------------------------------

fn sign(secret: &str, body: &str) -> String {
    format!(
        "sha256={}",
        kranz_engine::hooks::hmac_sha256_hex(secret.as_bytes(), body.as_bytes())
    )
}

fn hook_post(event: &str, sign_with: Option<&str>, body: &Value) -> Request<Body> {
    let text = body.to_string();
    let mut builder = Request::builder()
        .method("POST")
        .uri("/api/hooks/github")
        .header("content-type", "application/json")
        .header("x-github-event", event);
    if let Some(secret) = sign_with {
        builder = builder.header("x-hub-signature-256", sign(secret, &text));
    }
    builder.body(Body::from(text)).unwrap()
}

async fn body_json(response: Response) -> Value {
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    serde_json::from_slice(&bytes).unwrap()
}

/// Wait for the background draft to reach a terminal ticket state (Review /
/// Queued / NeedsContext …). A draft that errors rolls back to New; the
/// deadline returns that honestly instead of hanging.
async fn wait_ticket_terminal(root: &Path, slug: &str) -> TicketState {
    let deadline = Instant::now() + Duration::from_secs(30);
    loop {
        let state = Ticket::read_state(root, slug);
        if !matches!(state, TicketState::New | TicketState::Drafting) || Instant::now() >= deadline
        {
            return state;
        }
        tokio::time::sleep(Duration::from_millis(25)).await;
    }
}

fn trigger_tickets_in(repo: &Path) -> Vec<String> {
    Ticket::list(repo)
        .iter()
        .map(|t| t.slug.clone())
        .filter(|s| s.starts_with("trigger-"))
        .collect()
}

fn mission_status(repo: &Path, mission_id: &str) -> MissionStatus {
    let paths = MissionPaths::new(repo, mission_id);
    let events = EventLog::read_events(&paths.events_file()).unwrap();
    kranz_engine::reducer::fold(&events).unwrap().mission.status
}

// ---------------------------------------------------------------------------
// Payload fixtures
// ---------------------------------------------------------------------------

fn workflow_run_payload(conclusion: &str, head_branch: &str) -> Value {
    json!({
        "action": "completed",
        "workflow_run": {
            "id": 9876543210_u64,
            "name": "gates",
            "head_branch": head_branch,
            "head_repository": { "full_name": "octo/hello" },
            "head_sha": "0123456789abcdef0123456789abcdef01234567",
            "conclusion": conclusion,
            "html_url": "https://github.com/octo/hello/actions/runs/9876543210",
            "actor": { "login": "octocat" }
        },
        "repository": { "full_name": "octo/hello", "default_branch": "main" },
        "sender": { "login": "octocat" }
    })
}

fn pr_comment_payload(body: &str) -> Value {
    json!({
        "action": "created",
        "issue": { "number": 42, "pull_request": { "html_url": "https://github.com/octo/hello/pull/42" } },
        "comment": {
            "body": body,
            "html_url": "https://github.com/octo/hello/pull/42#issuecomment-7",
            "user": { "login": "reviewer" }
        },
        "repository": { "full_name": "octo/hello", "default_branch": "main" },
        "sender": { "login": "reviewer" }
    })
}

// ---------------------------------------------------------------------------
// Accepted triggers
// ---------------------------------------------------------------------------

#[tokio::test]
async fn ghook_ci_failure_drafts_one_ticket_and_second_event_dedupes() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 1);
    let payload = workflow_run_payload("failure", "main");

    let response = app
        .clone()
        .oneshot(hook_post("workflow_run", Some(SECRET), &payload))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    let body = body_json(response).await;
    assert_eq!(body["outcome"], "drafted");
    assert_eq!(body["ticketSlug"], "trigger-ci-9876543210");
    assert_eq!(body["queued"], false);
    let mission_id = body["missionId"].as_str().unwrap().to_string();

    // The draft runs through the normal pipeline and parks for review.
    let slug = "trigger-ci-9876543210";
    assert_eq!(wait_ticket_terminal(&root, slug).await, TicketState::Review);
    assert_eq!(mission_status(&root, &mission_id), MissionStatus::Approved);

    // Provenance: frontmatter trigger field + body source/actor/consent.
    let ticket = Ticket::load(&Ticket::tickets_dir(&root).join(format!("{slug}.md"))).unwrap();
    assert_eq!(ticket.trigger.as_deref(), Some("ci-failure"));
    assert!(ticket
        .raw_body
        .contains("Source: https://github.com/octo/hello/actions/runs/9876543210"));
    assert!(ticket.raw_body.contains("Actor: octocat"));
    assert!(ticket.raw_body.contains("Consent: draft-only"));

    // A second event for the same run is a no-op: no second ticket, no
    // second mission.
    let response = app
        .oneshot(hook_post("workflow_run", Some(SECRET), &payload))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    let body = body_json(response).await;
    assert_eq!(body["outcome"], "duplicate");
    assert_eq!(body["ticketSlug"], slug);
    assert!(body.get("missionId").is_none());

    assert_eq!(trigger_tickets_in(&root), vec![slug.to_string()]);
    assert_eq!(MissionPaths::list_missions(&root), vec![mission_id]);
}

#[tokio::test]
async fn ghook_signed_outsider_comment_cannot_draft_or_queue_work() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 0);
    let mut payload = pr_comment_payload("kranz:fix-and-queue");
    payload["comment"]["user"]["login"] = json!("outsider");
    payload["comment"]["author_association"] = json!("NONE");
    let response = app
        .oneshot(hook_post("issue_comment", Some(SECRET), &payload))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    assert_eq!(body_json(response).await["outcome"], "ignored");
    assert!(trigger_tickets_in(&root).is_empty());
    assert!(MissionPaths::list_missions(&root).is_empty());
    assert!(kranz_engine::queue::list(&root).is_empty());
}

#[tokio::test]
async fn ghook_fix_label_comment_drafts_ticket_for_review() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 1);

    let response = app
        .oneshot(hook_post(
            "issue_comment",
            Some(SECRET),
            &pr_comment_payload("kranz:fix the flaky test"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    let body = body_json(response).await;
    assert_eq!(body["outcome"], "drafted");
    assert_eq!(body["ticketSlug"], "trigger-pr-42");
    assert_eq!(body["queued"], false);

    let slug = "trigger-pr-42";
    assert_eq!(wait_ticket_terminal(&root, slug).await, TicketState::Review);
    // Draft-only consent: nothing is queued.
    assert!(kranz_engine::queue::list(&root).is_empty());

    let ticket = Ticket::load(&Ticket::tickets_dir(&root).join(format!("{slug}.md"))).unwrap();
    assert_eq!(ticket.trigger.as_deref(), Some("pr-comment"));
    assert!(ticket
        .raw_body
        .contains("Source: https://github.com/octo/hello/pull/42#issuecomment-7"));
    assert!(ticket.raw_body.contains("Actor: reviewer"));
    assert!(ticket.raw_body.contains("Consent: draft-only"));
}

#[tokio::test]
async fn ghook_fix_and_queue_label_drafts_and_queues_without_running() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 1);

    let response = app
        .oneshot(hook_post(
            "issue_comment",
            Some(SECRET),
            &pr_comment_payload("kranz:fix-and-queue the flaky test"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    let body = body_json(response).await;
    assert_eq!(body["outcome"], "drafted");
    assert_eq!(body["queued"], true);
    let mission_id = body["missionId"].as_str().unwrap().to_string();

    let slug = "trigger-pr-42";
    assert_eq!(wait_ticket_terminal(&root, slug).await, TicketState::Queued);

    // The queue holds exactly the drafted mission…
    let entries = kranz_engine::queue::list(&root);
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].mission_id, mission_id);
    assert_eq!(entries[0].ticket_slug.as_deref(), Some(slug));

    // …and the mission is NOT running: plan approved (through the normal
    // draft-time approval), but no run activity — only `kranz work` starts
    // it.
    assert_eq!(mission_status(&root, &mission_id), MissionStatus::Approved);

    // Pre-consent is on the record.
    let ticket = Ticket::load(&Ticket::tickets_dir(&root).join(format!("{slug}.md"))).unwrap();
    assert!(ticket.raw_body.contains("Consent: fix-and-queue"));
}

// ---------------------------------------------------------------------------
// Refusals (closed) and ignores
// ---------------------------------------------------------------------------

#[tokio::test]
async fn ghook_bad_signature_is_401_and_drafts_nothing() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 0);

    let response = app
        .oneshot(hook_post(
            "workflow_run",
            Some("whsec-WRONG"),
            &workflow_run_payload("failure", "main"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert!(trigger_tickets_in(&root).is_empty());
    assert!(MissionPaths::list_missions(&root).is_empty());
}

#[tokio::test]
async fn ghook_absent_secret_refuses_closed_403() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(None);
    let app = hook_app(&root, 0);

    // Even a well-formed signature header cannot open an unconfigured route.
    let response = app
        .clone()
        .oneshot(hook_post(
            "workflow_run",
            Some(SECRET),
            &workflow_run_payload("failure", "main"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);

    // …and an unsigned request gets the same closed refusal.
    let response = app
        .oneshot(hook_post(
            "workflow_run",
            None,
            &workflow_run_payload("failure", "main"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);

    assert!(trigger_tickets_in(&root).is_empty());
    assert!(MissionPaths::list_missions(&root).is_empty());
}

#[tokio::test]
async fn ghook_wrong_repo_is_403_and_drafts_nothing() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 0);

    let mut payload = workflow_run_payload("failure", "main");
    payload["repository"]["full_name"] = json!("octo/other");
    let response = app
        .oneshot(hook_post("workflow_run", Some(SECRET), &payload))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    assert!(trigger_tickets_in(&root).is_empty());
    assert!(MissionPaths::list_missions(&root).is_empty());
}

#[tokio::test]
async fn ghook_unallowlisted_event_and_non_failure_run_are_202_ignored() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 0);

    // A `push` event is not in the allowlist.
    let response = app
        .clone()
        .oneshot(hook_post(
            "push",
            Some(SECRET),
            &json!({ "ref": "refs/heads/main", "repository": { "full_name": "octo/hello" } }),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    assert_eq!(body_json(response).await["outcome"], "ignored");

    // A successful workflow run matches no trigger rule.
    let response = app
        .oneshot(hook_post(
            "workflow_run",
            Some(SECRET),
            &workflow_run_payload("success", "main"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);
    assert_eq!(body_json(response).await["outcome"], "ignored");

    assert!(trigger_tickets_in(&root).is_empty());
    assert!(MissionPaths::list_missions(&root).is_empty());
}

// ---------------------------------------------------------------------------
// Authority and the never-land invariant
// ---------------------------------------------------------------------------

#[tokio::test]
async fn ghook_token_gate_still_arms_every_other_post_route() {
    if !setup() {
        return;
    }
    let (_dir, root) = init_hook_repo(Some(SECRET));
    let app = hook_app(&root, 1);

    // The hook route passes WITHOUT the mutation token (HMAC is its
    // authority)…
    let response = app
        .clone()
        .oneshot(hook_post(
            "workflow_run",
            Some(SECRET),
            &workflow_run_payload("failure", "main"),
        ))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::ACCEPTED);

    // …while a tokenless POST to any other route is still refused.
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/tickets")
                .header("content-type", "application/json")
                .body(Body::from(json!({"slug":"x","title":"y"}).to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[test]
fn ghook_handler_source_has_no_git_mutation_paths() {
    // The hook handler drafts/queues tickets and nothing more: it must never
    // reference a git-mutation entry point or raw mutation command (the
    // repo's never-land-from-automation invariant, asserted at source level).
    const NEEDLES: [&str; 8] = [
        "git push",
        "git merge",
        "git publish",
        "push_mission",
        "merge_mission",
        "merge_no_ff",
        "fast_forward",
        "publish",
    ];
    let source = include_str!("../src/hooks.rs");
    for needle in NEEDLES {
        assert!(
            !source.contains(needle),
            "crates/server/src/hooks.rs must not reference '{needle}'"
        );
    }
}