kanade-backend 0.43.1

axum + SQLite projection backend for the kanade endpoint-management system. Hosts /api/* and the embedded SPA dashboard, projects JetStream streams into SQLite, drives the cron scheduler
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
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use base64::Engine as _;
use kanade_shared::kv::{BUCKET_SCRIPT_CURRENT, OBJECT_SCRIPTS};
use kanade_shared::manifest::{FanoutPlan, Manifest};
use kanade_shared::subject;
use kanade_shared::wire::Command;
use serde::Serialize;
use tracing::{info, warn};
use uuid::Uuid;

use crate::api::AppState;
use crate::api::jobs;
use crate::audit;
use crate::audit::Caller;

#[derive(Serialize, Clone)]
pub struct ExecResponse {
    pub exec_id: String,
    pub job_id: String,
    pub version: String,
    pub target_count: u32,
    pub subjects: Vec<String>,
}

/// Core exec pipeline used by both the HTTP handler (actor = "operator")
/// and the scheduler (actor = "scheduler"). Validates the [`FanoutPlan`],
/// fans the Command out across every target subject (or schedules
/// wave-based fan-out when `rollout` is set), pins script_current,
/// records an `executions` row, and emits an audit event.
///
/// v0.18: the Manifest supplies only "what to run" (script + shell +
/// timeout + inventory hint). `target` / `rollout` / `jitter` come
/// from the caller's [`FanoutPlan`] — schedules carry one inline,
/// ad-hoc execs build one from CLI flags / SPA form input.
///
/// `caller` is `None` for the scheduler path (no HTTP request) and
/// `Some(_)` for operator-initiated execs, where the JWT subject and
/// `X-Kanade-Source` header get folded into the audit payload.
pub async fn exec_manifest(
    s: &AppState,
    manifest: Manifest,
    plan: FanoutPlan,
    actor: &str,
    caller: Option<&Caller>,
) -> Result<ExecResponse, (StatusCode, String)> {
    let has_rollout = plan
        .rollout
        .as_ref()
        .map(|r| !r.waves.is_empty())
        .unwrap_or(false);
    if !has_rollout && !plan.target.is_specified() {
        return Err((
            StatusCode::BAD_REQUEST,
            "target must specify at least one of `all` / `groups` / `pcs` (or set `rollout.waves`)"
                .into(),
        ));
    }

    // Defensive — the write paths (`POST /api/jobs`, `kanade job
    // create`) already gate every manifest through
    // `Manifest::validate()` before it lands in BUCKET_JOBS, so by
    // the time exec_manifest sees one we expect exactly one of
    // script / script_file / script_object to be set. Re-check
    // here so a hypothetical write path that bypassed validation
    // (direct NATS KV poke, downgrade-then-upgrade) bails with a
    // clear 400 instead of crashing the unwrap below.
    manifest
        .execute
        .validate_script_source()
        .map_err(|e| (StatusCode::BAD_REQUEST, e))?;
    // Resolve the manifest's script source into the wire shape the
    // agent expects:
    //   - inline `script:`     → Command { script: <body>,
    //                                      script_object: None }
    //   - `script_object: k`   → look up the OBJECT_SCRIPTS digest
    //                            for `k` and emit Command { script: "",
    //                            script_object: Some(k),
    //                            script_object_sha256: Some(<digest>) };
    //                            the agent's script_cache pulls the body
    //                            at exec time (yukimemi/kanade#210).
    // `script_file:` is operator-side only — the CLI inlines its
    // contents into `script` before POSTing, so it never reaches us
    // as an unresolved alternative.
    let (inline_script, script_object_ref) = resolve_script_source(s, &manifest).await?;

    let timeout_secs = humantime::parse_duration(&manifest.execute.timeout)
        .map_err(|e| (StatusCode::BAD_REQUEST, format!("invalid timeout: {e}")))?
        .as_secs();
    let jitter_secs = plan
        .jitter
        .as_deref()
        .map(humantime::parse_duration)
        .transpose()
        .map_err(|e| (StatusCode::BAD_REQUEST, format!("invalid jitter: {e}")))?
        .map(|d| d.as_secs());

    let exec_id = Uuid::new_v4().to_string();

    let deadline_at = plan.deadline_at;
    let make_cmd = || Command {
        id: manifest.id.clone(),
        version: manifest.version.clone(),
        request_id: Uuid::new_v4().to_string(),
        exec_id: Some(exec_id.clone()),
        shell: manifest.execute.shell.into(),
        script: inline_script.clone(),
        script_object: script_object_ref.as_ref().map(|(k, _)| k.clone()),
        script_object_sha256: script_object_ref.as_ref().map(|(_, d)| d.clone()),
        timeout_secs,
        jitter_secs,
        run_as: manifest.execute.run_as,
        cwd: manifest.execute.cwd.clone(),
        deadline_at,
        // v0.26: forward Layer 2 staleness policy to every emitted
        // Command so the agent can apply it whether it sees the live
        // publish or replays from STREAM_EXEC on reconnect.
        staleness: manifest.staleness.clone(),
        // Issue #246: forward the manifest's observability emit hint
        // so the agent can route stdout NDJSON to obs-outbox without
        // a manifest re-fetch.
        emit: manifest.emit.clone(),
    };

    let mut subjects: Vec<String> = Vec::new();
    let mut target_count: u32 = 0;

    if let Some(rollout) = plan.rollout.as_ref() {
        // Wave-based fan-out: pre-validate every delay so a bad humantime
        // string aborts the whole exec instead of silently failing on a
        // late wave inside a tokio::spawn.
        let mut delays = Vec::with_capacity(rollout.waves.len());
        for (idx, wave) in rollout.waves.iter().enumerate() {
            let d = humantime::parse_duration(&wave.delay).map_err(|e| {
                (
                    StatusCode::BAD_REQUEST,
                    format!("invalid rollout.waves[{idx}].delay: {e}"),
                )
            })?;
            delays.push(d);
        }

        for ((idx, wave), delay) in rollout.waves.iter().enumerate().zip(delays) {
            let subj = subject::commands_group(&wave.group);
            subjects.push(subj.clone());
            target_count = target_count.saturating_add(1);

            let cmd = make_cmd();
            let payload = serde_json::to_vec(&cmd)
                .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("serialize: {e}")))?;

            if delay.is_zero() {
                if let Err(e) = s.nats.publish(subj.clone(), payload.into()).await {
                    return Err((StatusCode::BAD_GATEWAY, format!("publish to {subj}: {e}")));
                }
                info!(wave = idx, subject = %subj, "wave published (immediate)");
            } else {
                let nats = s.nats.clone();
                let subj_for_spawn = subj.clone();
                tokio::spawn(async move {
                    tokio::time::sleep(delay).await;
                    match nats.publish(subj_for_spawn.clone(), payload.into()).await {
                        Ok(()) => info!(
                            wave = idx,
                            subject = %subj_for_spawn,
                            delay_secs = delay.as_secs(),
                            "wave published (delayed)",
                        ),
                        Err(e) => warn!(
                            error = %e,
                            wave = idx,
                            subject = %subj_for_spawn,
                            "delayed wave publish failed",
                        ),
                    }
                });
                info!(
                    wave = idx,
                    subject = %subj,
                    delay_secs = delay.as_secs(),
                    "wave scheduled",
                );
            }
        }
    } else {
        // Plain target-based fan-out (no rollout block).
        if plan.target.all {
            subjects.push(subject::COMMANDS_ALL.to_string());
            target_count = target_count.saturating_add(1);
        }
        for g in &plan.target.groups {
            subjects.push(subject::commands_group(g));
            target_count = target_count.saturating_add(1);
        }
        for pc in &plan.target.pcs {
            subjects.push(subject::commands_pc(pc));
            target_count = target_count.saturating_add(1);
        }

        for subj in &subjects {
            let cmd = make_cmd();
            let payload = serde_json::to_vec(&cmd)
                .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("serialize: {e}")))?;
            if let Err(e) = s.nats.publish(subj.clone(), payload.into()).await {
                warn!(error = %e, subject = %subj, "publish failed");
                return Err((StatusCode::BAD_GATEWAY, format!("publish to {subj}: {e}")));
            }
        }
    }
    let _ = s.nats.flush().await;

    match s.jetstream.get_key_value(BUCKET_SCRIPT_CURRENT).await {
        Ok(kv) => {
            if let Err(e) = kv
                .put(
                    &manifest.id,
                    bytes::Bytes::from(manifest.version.clone().into_bytes()),
                )
                .await
            {
                warn!(error = %e, cmd_id = %manifest.id, "script_current put failed");
            }
        }
        Err(e) => warn!(error = %e, "script_current KV missing; skipping version pin"),
    }

    sqlx::query(
        "INSERT INTO executions (exec_id, job_id, version, initiated_by, target_count, status)
         VALUES (?, ?, ?, ?, ?, 'pending')",
    )
    .bind(&exec_id)
    .bind(&manifest.id)
    .bind(&manifest.version)
    .bind(actor)
    .bind(target_count as i64)
    .execute(&s.pool)
    .await
    .map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("insert executions: {e}"),
        )
    })?;

    info!(
        exec_id = %exec_id,
        job_id = %manifest.id,
        version = %manifest.version,
        actor,
        target_count,
        wave_mode = has_rollout,
        subjects = ?subjects,
        "execution published",
    );

    audit::record(
        &s.nats,
        actor,
        "exec",
        Some(&manifest.id),
        caller,
        serde_json::json!({
            "exec_id": exec_id,
            "version": manifest.version,
            "target_count": target_count,
            "subjects": subjects,
            "wave_mode": has_rollout,
        }),
    )
    .await;

    Ok(ExecResponse {
        exec_id,
        job_id: manifest.id,
        version: manifest.version,
        target_count,
        subjects,
    })
}

/// `POST /api/exec/{job_id}` — fire a registered job from the
/// catalog against a caller-supplied [`FanoutPlan`]. The Manifest body
/// is never accepted inline; operators must `kanade job create` first.
/// 404 when the job isn't in `BUCKET_JOBS`.
pub async fn create(
    State(s): State<AppState>,
    Path(job_id): Path<String>,
    caller: Caller,
    Json(plan): Json<FanoutPlan>,
) -> Result<Json<ExecResponse>, (StatusCode, String)> {
    let manifest = match jobs::fetch(&s.jetstream, &job_id).await {
        Ok(Some(m)) => m,
        Ok(None) => {
            return Err((
                StatusCode::NOT_FOUND,
                format!(
                    "job '{job_id}' not found in catalog — register it first with \
                     `kanade job create <manifest.yaml>`"
                ),
            ));
        }
        Err(e) => {
            warn!(error = %e, %job_id, "exec: job catalog lookup failed");
            return Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("job catalog lookup: {e}"),
            ));
        }
    };
    exec_manifest(&s, manifest, plan, "operator", Some(&caller))
        .await
        .map(Json)
}

/// Look up the wire shape for the manifest's script source.
///
/// Returns a tuple of `(inline_body, script_object_ref)`:
///
///   * Inline path — `(body, None)`. The Command embeds the body
///     directly (matching pre-#210 wire).
///   * Object Store path — `(String::new(), Some((key, sha256)))`.
///     The agent's script_cache fetches the body keyed by `key`,
///     verifies the bytes against `sha256`, then executes.
///
/// The Object Store path snapshots the current digest at exec
/// submission. If the operator re-uploads `key` with new bytes
/// between submission and the agent's fire, the agent's sha
/// check fails and the run aborts — that's the intended safety
/// net for the "operator re-uploaded mid-rollout" case.
async fn resolve_script_source(
    s: &AppState,
    manifest: &Manifest,
) -> Result<(String, Option<(String, String)>), (StatusCode, String)> {
    if let Some(inline) = manifest.execute.script.as_deref().filter(|s| !s.is_empty()) {
        return Ok((inline.to_owned(), None));
    }

    let key = manifest.execute.script_object.as_deref().ok_or((
        StatusCode::BAD_REQUEST,
        "execute: one of `script` or `script_object` must be set \
         (Manifest::validate() should have caught this earlier)"
            .to_string(),
    ))?;

    let store = s
        .jetstream
        .get_object_store(OBJECT_SCRIPTS)
        .await
        .map_err(|e| {
            warn!(error = %e, "exec: get_object_store scripts");
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!(
                    "Object Store '{OBJECT_SCRIPTS}' missing — \
                     run `kanade jetstream setup`"
                ),
            )
        })?;
    let info = store.info(key).await.map_err(|e| {
        let msg = e.to_string();
        if msg.contains("not found") || msg.contains("no objects") {
            (
                StatusCode::NOT_FOUND,
                format!("script_object '{key}' not found in OBJECT_SCRIPTS"),
            )
        } else {
            warn!(error = %e, %key, "exec: object_store.info");
            (StatusCode::INTERNAL_SERVER_ERROR, msg)
        }
    })?;

    // NATS Object Store emits digests as `SHA-256=<base64url-no-pad>`
    // (JetStream protocol). The agent's script_cache verifies by
    // computing sha256(bytes) and hex-comparing, so re-encode to hex
    // once here — keeps the wire field operator-readable and frees
    // the agent from a base64 dep.
    let raw = info.digest.as_deref().ok_or((
        StatusCode::INTERNAL_SERVER_ERROR,
        format!(
            "script_object '{key}' has no digest metadata — \
             broker should always populate it"
        ),
    ))?;
    let b64 = raw.strip_prefix("SHA-256=").unwrap_or(raw);
    // NATS async-nats emits digests in URL-safe base64 WITH `=`
    // padding (e.g. `SHA-256=pzGZSHXYLupCjS_RB0lmdLNHpgyH53Y5vI8XYhb2H1o=`).
    // The original `URL_SAFE_NO_PAD` rejected the trailing `=` (a
    // copy-paste from a URL-safe-id case). Use an Indifferent
    // padding-mode config so a future broker emitting unpadded
    // digests doesn't break us — the crate's stock `URL_SAFE`
    // engine has `RequireCanonical` (Gemini #225) which would
    // re-introduce the same fragility in the other direction.
    // Bug surfaced during a live install-kanade-backend self-test
    // (#222 + #224 flow) as a 500 "Invalid padding" from
    // /api/exec/<job>.
    use base64::alphabet::URL_SAFE;
    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
    static DECODER: GeneralPurpose = GeneralPurpose::new(
        &URL_SAFE,
        GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
    );
    let bytes = DECODER.decode(b64).map_err(|e| {
        warn!(error = %e, %key, raw, "exec: decode object_store digest");
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("decode digest for '{key}': {e}"),
        )
    })?;
    let digest = hex_lower(&bytes);

    Ok((String::new(), Some((key.to_owned(), digest))))
}

/// Lower-case hex-encode without pulling `hex` as a fresh dep.
/// Output matches sha2's standard formatting on the agent side.
fn hex_lower(bytes: &[u8]) -> String {
    use std::fmt::Write;
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(out, "{b:02x}");
    }
    out
}