sysknife-daemon 0.15.0

Policy-enforced, audit-logged Linux action daemon for SysKnife
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
//! Coverage-gap tests for the daemon.
//!
//! Covers: TransactionStore limit capping, combined filters, empty-hash
//! rejection, ListJobHistory via handle_query_action, bad params for
//! ListJobHistory, non-Observer action blocked by query_action, and
//! execute path authorization checks.

use std::io;
use std::sync::Arc;

use serde_json::{json, Value};
use sysknife_daemon::actions::ActionSpec;
use sysknife_daemon::dispatcher::connection_handler_with_executor;
use sysknife_daemon::executor::{ActionExecutor, ExecutionOutput, ExecutorError};
use sysknife_daemon::state::{DaemonConfig, DaemonState};
use sysknife_daemon::state_collector::CommandRunner;
use sysknife_daemon::transactions::{NewTransaction, TransactionStore};
use sysknife_daemon::transport::{framing::FramedStream, listen::ListenTarget};
use sysknife_types::{CallerRole, JobState, RiskLevel};
use tempfile::tempdir;
use tokio::net::UnixStream;

// ---------------------------------------------------------------------------
// Test doubles
// ---------------------------------------------------------------------------

struct MockRunner;

impl CommandRunner for MockRunner {
    fn run(&self, _program: &str, _args: &[&str]) -> Result<String, io::Error> {
        Ok(String::new())
    }
}

struct MockExecutor {
    exit_code: i32,
}

#[async_trait::async_trait]
impl ActionExecutor for MockExecutor {
    async fn execute(&self, _spec: &ActionSpec) -> Result<ExecutionOutput, ExecutorError> {
        Ok(ExecutionOutput {
            stdout: String::new(),
            stderr: String::new(),
            exit_code: self.exit_code,
        })
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn test_state(dir: &tempfile::TempDir) -> DaemonState {
    let db_path = dir.path().join("test.db");
    let sock_path = dir.path().join("test.sock");
    let config = DaemonConfig::new(ListenTarget::Unix(sock_path), db_path);
    DaemonState::open(config).unwrap()
}

async fn spawn_handler_with_role(state: DaemonState, role: CallerRole) -> FramedStream<UnixStream> {
    let (client, server) = UnixStream::pair().unwrap();
    let runner: Arc<dyn CommandRunner + Send + Sync> = Arc::new(MockRunner);
    let executor: Arc<dyn ActionExecutor> = Arc::new(MockExecutor { exit_code: 0 });
    tokio::spawn(async move {
        connection_handler_with_executor(server, state, runner, executor, uid_caller(role)).await;
    });
    FramedStream::new(client)
}

async fn query_action(
    framed: &mut FramedStream<UnixStream>,
    action_name: &str,
    params: Value,
    request_id: &str,
) -> Value {
    let req = json!({
        "type": "query_action",
        "request_id": request_id,
        "action_name": action_name,
        "params": params,
    });
    framed
        .send(&serde_json::to_vec(&req).unwrap())
        .await
        .unwrap();
    let raw = framed.recv().await.unwrap();
    serde_json::from_slice(&raw).unwrap()
}

fn make_transaction(action: &str) -> NewTransaction {
    NewTransaction {
        request_id: format!("req-{action}"),
        request_hash: format!("hash-{action}"),
        action_name: action.to_string(),
        risk_level: RiskLevel::High,
        summary: format!("Test {action}"),
        warnings: vec![],
        caller_role: CallerRole::Dev,
        caller_principal: sysknife_daemon::auth::CallerPrincipal::Uid(1000),
    }
}

// ---------------------------------------------------------------------------
// TransactionStore: limit capping
// ---------------------------------------------------------------------------

#[test]
fn list_transactions_limit_is_capped_at_100() {
    let dir = tempdir().unwrap();
    let store = TransactionStore::open(dir.path().join("tx.sqlite")).expect("open store");

    // Insert 110 transactions.
    for i in 0..110 {
        store
            .record(NewTransaction {
                request_id: format!("req-{i}"),
                request_hash: format!("hash-{i}"),
                action_name: "UpdateSystem".into(),
                risk_level: RiskLevel::High,
                summary: format!("tx {i}"),
                warnings: vec![],
                caller_role: CallerRole::Dev,
                caller_principal: sysknife_daemon::auth::CallerPrincipal::Uid(1000),
            })
            .expect("record tx");
    }

    // Request 200 — must be capped to 100.
    let rows = store
        .list_transactions(200, None, None, None)
        .expect("list");
    assert!(
        rows.len() <= 100,
        "expected at most 100 rows (cap), got {}",
        rows.len()
    );
    assert_eq!(rows.len(), 100, "should return exactly 100 when 110 exist");
}

// ---------------------------------------------------------------------------
// TransactionStore: combined filter
// ---------------------------------------------------------------------------

#[test]
fn list_transactions_combined_action_and_status_filter() {
    let dir = tempdir().unwrap();
    let store = TransactionStore::open(dir.path().join("tx-filter.sqlite")).expect("open store");

    // Insert different actions with default Queued status.
    store.record(make_transaction("UpdateSystem")).unwrap();
    store.record(make_transaction("UpdateSystem")).unwrap();
    store.record(make_transaction("RebootSystem")).unwrap();

    // Promote one UpdateSystem to Succeeded via update_status.
    let recs = store.list_transactions(10, None, None, None).unwrap();
    let update_id = recs
        .iter()
        .find(|r| r.action_name == "UpdateSystem")
        .unwrap()
        .transaction_id
        .clone();
    store.update_status(&update_id, JobState::Running).unwrap();
    store
        .update_status(&update_id, JobState::Succeeded)
        .unwrap();

    // Filter: action=UpdateSystem + status=succeeded → exactly 1 row.
    let filtered = store
        .list_transactions(100, Some("succeeded"), Some("UpdateSystem"), None)
        .expect("list filtered");
    assert_eq!(filtered.len(), 1, "expected 1 succeeded UpdateSystem");
    assert_eq!(filtered[0].action_name, "UpdateSystem");
    assert_eq!(filtered[0].status, JobState::Succeeded);
}

// ---------------------------------------------------------------------------
// ListJobHistory via handle_query_action (integration)
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_job_history_returns_recorded_transactions() {
    let dir = tempdir().unwrap();
    let state = test_state(&dir);

    // Insert a transaction directly before spawning the handler.
    state
        .audit
        .record(NewTransaction {
            request_id: "req-history".into(),
            request_hash: "hash-history".into(),
            action_name: "UpdateSystem".into(),
            risk_level: RiskLevel::High,
            summary: "Stage system update".into(),
            warnings: vec![],
            caller_role: CallerRole::Dev,
            caller_principal: sysknife_daemon::auth::CallerPrincipal::Uid(1000),
        })
        .await
        .expect("record tx");

    let mut framed = spawn_handler_with_role(state, CallerRole::Observer).await;
    let resp = query_action(
        &mut framed,
        "ListJobHistory",
        json!({ "limit": 10 }),
        "history-req",
    )
    .await;

    assert_eq!(
        resp["type"], "query_action_response",
        "expected query_action_response, got: {resp}"
    );
    let output = resp["output"].as_str().unwrap();
    assert!(
        output.contains("UpdateSystem"),
        "history output should mention UpdateSystem: {output}"
    );
}

// ---------------------------------------------------------------------------
// ListJobHistory: bad params rejected with validation_failure
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_job_history_rejects_non_integer_limit() {
    let dir = tempdir().unwrap();
    let state = test_state(&dir);
    let mut framed = spawn_handler_with_role(state, CallerRole::Observer).await;
    let resp = query_action(
        &mut framed,
        "ListJobHistory",
        json!({ "limit": "not-a-number" }),
        "bad-limit-req",
    )
    .await;

    assert_eq!(
        resp["type"], "error_response",
        "expected error_response for bad limit, got: {resp}"
    );
    assert_eq!(
        resp["category"], "validation_failure",
        "expected validation_failure category, got: {resp}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_job_history_rejects_non_integer_since_hours() {
    let dir = tempdir().unwrap();
    let state = test_state(&dir);
    let mut framed = spawn_handler_with_role(state, CallerRole::Observer).await;
    let resp = query_action(
        &mut framed,
        "ListJobHistory",
        json!({ "since_hours": "yesterday" }),
        "bad-since-req",
    )
    .await;

    assert_eq!(
        resp["type"], "error_response",
        "expected error_response for bad since_hours, got: {resp}"
    );
    assert_eq!(resp["category"], "validation_failure");
}

// ---------------------------------------------------------------------------
// query_action blocks every action that requires approval
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn query_action_rejects_actions_that_require_approval() {
    // An action can require approval either because its risk tier is above Low,
    // or because it mutates the host despite being Low/Observer-callable. Even
    // an Admin caller must not bypass preview + approval through query_action.
    let dir = tempdir().unwrap();
    let mut state = test_state(&dir);
    state.host_distro = Some(sysknife_core::distro::DistroId::Ubuntu {
        major: 24,
        minor: 4,
    });
    let mut framed = spawn_handler_with_role(state, CallerRole::Admin).await;

    for (action_name, request_id) in [
        ("UpdateSystem", "non-observer-req"),
        ("AptUpdate", "observer-mutation-req"),
    ] {
        let resp = query_action(&mut framed, action_name, json!({}), request_id).await;
        assert_eq!(
            resp["type"], "error_response",
            "expected error_response for approval-gated {action_name}, got: {resp}"
        );
        assert_eq!(
            resp["category"], "authorization_failure",
            "approval-gated {action_name} must return authorization_failure, got: {resp}"
        );
    }
}

// ---------------------------------------------------------------------------
// handle_execute: authorization check on execute path
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn execute_rejects_observer_for_admin_action() {
    // Observer role cannot execute RebootSystem (Admin-only).
    // Authorization is checked before the preview/hash check, so we can send
    // any transaction/receipt and still get authorization_failure first.
    let dir = tempdir().unwrap();
    let state = test_state(&dir);
    let mut framed = spawn_handler_with_role(state, CallerRole::Observer).await;

    let req = json!({
        "type": "execute",
        "request_id": "auth-test",
        "transaction_id": "any-transaction",
        "action_name": "RebootSystem",
        "params": {},
        "approval_receipt": "any-receipt"
    });
    framed
        .send(&serde_json::to_vec(&req).unwrap())
        .await
        .unwrap();

    let raw = framed.recv().await.unwrap();
    let resp: Value = serde_json::from_slice(&raw).unwrap();

    assert_eq!(
        resp["type"], "error_response",
        "expected error_response for insufficient role, got: {resp}"
    );
    assert_eq!(
        resp["category"], "authorization_failure",
        "Observer executing Admin action must get authorization_failure, got: {resp}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn execute_rejects_dev_for_admin_action() {
    // Dev role cannot execute SetKernelArguments (Admin-only).
    let dir = tempdir().unwrap();
    let state = test_state(&dir);
    let mut framed = spawn_handler_with_role(state, CallerRole::Dev).await;

    let req = json!({
        "type": "execute",
        "request_id": "dev-auth-test",
        "transaction_id": "any-transaction",
        "action_name": "SetKernelArguments",
        "params": { "add": [], "remove": [] },
        "approval_receipt": "any-receipt"
    });
    framed
        .send(&serde_json::to_vec(&req).unwrap())
        .await
        .unwrap();

    let raw = framed.recv().await.unwrap();
    let resp: Value = serde_json::from_slice(&raw).unwrap();

    assert_eq!(
        resp["type"], "error_response",
        "expected error_response for Dev on Admin action, got: {resp}"
    );
    assert_eq!(resp["category"], "authorization_failure");
}

// ---------------------------------------------------------------------------
// MD-8 — `cleanup_stale_queued` must not clobber non-Queued rows even when
// they share a backdated `created_at` with the row we want to cancel.
// ---------------------------------------------------------------------------

#[test]
fn cleanup_stale_queued_does_not_clobber_running_rows() {
    use rusqlite::params;

    let dir = tempdir().unwrap();
    let store = TransactionStore::open(dir.path().join("tx.sqlite")).expect("open store");

    // Insert two rows: both will be backdated to 30 minutes ago, but only
    // one is left in `Queued` state. The other is promoted to `Running`
    // before the cleanup runs — which would normally collide with the TTL
    // window if the WHERE clause didn't pin `status = Queued`.
    let queued = store.record(make_transaction("queued-old")).unwrap();
    let promoted = store.record(make_transaction("promoted-old")).unwrap();
    store
        .update_status(&promoted.transaction_id, JobState::Running)
        .unwrap();

    // Reach into the SQLite file directly to backdate both rows so the TTL
    // window matches them. Going through the public API would require time
    // manipulation; this is a coverage-gap test, so the surgical approach
    // is fine and exercises exactly the predicate that `cleanup_stale_queued`
    // applies in production.
    {
        let conn = rusqlite::Connection::open(dir.path().join("tx.sqlite")).unwrap();
        conn.execute(
            "UPDATE transactions \
             SET created_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-30 minutes')",
            params![],
        )
        .unwrap();
    }

    let canceled = store.cleanup_stale_queued().unwrap();
    assert_eq!(
        canceled, 1,
        "expected exactly the queued row to be canceled, got {canceled}"
    );

    // Re-read: queued should now be Canceled, running should still be Running.
    assert_eq!(
        store.get(&queued.transaction_id).unwrap().unwrap().status,
        JobState::Canceled
    );
    let history = store.list_transactions(10, None, None, None).unwrap();
    let queued_status = history
        .iter()
        .find(|r| r.transaction_id == queued.transaction_id)
        .map(|r| r.status);
    let promoted_status = history
        .iter()
        .find(|r| r.transaction_id == promoted.transaction_id)
        .map(|r| r.status);
    assert_eq!(queued_status, Some(JobState::Canceled));
    assert_eq!(promoted_status, Some(JobState::Running));
}

/// A caller attributed to a uid, as a Unix-socket connection would be.
fn uid_caller(role: sysknife_types::CallerRole) -> sysknife_daemon::auth::CallerAttribution {
    sysknife_daemon::auth::CallerAttribution::from_peer_uid(1000, role)
}