openlatch-client 0.0.1

The open-source security layer for AI agents — client forwarder
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
/// Integration tests for the OpenLatch daemon HTTP server.
///
/// Each test starts a daemon on a random port (port 0 → OS-assigned), exercises
/// the endpoints via an HTTP client, and verifies responses, headers, and log output.
///
/// Per testing.md: all tests use port 0 to avoid conflicts in parallel CI runs.
use std::time::Duration;

use openlatch_client::{config::Config, daemon};
use tokio::net::TcpListener;

// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------

/// A live daemon bound to a random port for integration testing.
struct TestDaemon {
    /// The OS-assigned port the daemon is listening on.
    port: u16,
    /// Bearer token for authenticated requests.
    token: String,
    /// Shared HTTP client.
    client: reqwest::Client,
    /// Temporary directory holding logs (kept alive for the test's lifetime).
    _temp_dir: tempfile::TempDir,
    /// Path to the log directory (for log content assertions).
    log_dir: std::path::PathBuf,
}

impl TestDaemon {
    fn base_url(&self) -> String {
        format!("http://127.0.0.1:{}", self.port)
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}", self.base_url(), path)
    }

    fn auth_header(&self) -> String {
        format!("Bearer {}", self.token)
    }
}

/// Starts a test daemon on a random OS-assigned port.
///
/// Returns a [`TestDaemon`] with the port, token, and HTTP client pre-configured.
/// The daemon runs in a background tokio task and will be shut down when the
/// returned `TestDaemon` is used to call POST /shutdown.
async fn start_test_daemon() -> TestDaemon {
    let temp_dir = tempfile::tempdir().expect("tempdir must be created");
    let log_dir = temp_dir.path().join("logs");
    std::fs::create_dir_all(&log_dir).expect("log dir must be created");

    let token = "test-integration-token-abcdef1234567890".to_string();

    let cfg = Config {
        port: 0, // port 0 → OS picks a free port
        log_dir: log_dir.clone(),
        log_level: "info".into(),
        retention_days: 30,
        extra_patterns: vec![],
        foreground: true,
        update: openlatch_client::config::UpdateConfig::default(),
    };

    // Bind to port 0 so OS assigns a random free port
    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind to port 0 must succeed");
    let port = listener
        .local_addr()
        .expect("local_addr must return address")
        .port();

    let token_clone = token.clone();
    tokio::spawn(async move {
        daemon::start_server_with_listener(listener, cfg, token_clone)
            .await
            .ok(); // errors are expected when the test shuts down the daemon
    });

    // Give the daemon a moment to start accepting connections
    tokio::time::sleep(Duration::from_millis(50)).await;

    TestDaemon {
        port,
        token,
        client: reqwest::Client::new(),
        _temp_dir: temp_dir,
        log_dir,
    }
}

/// A valid Claude Code PreToolUse event body for testing.
fn test_event() -> serde_json::Value {
    serde_json::json!({
        "session_id": "test-session-abc",
        "tool_name": "bash",
        "tool_input": {
            "command": "ls -la"
        }
    })
}

// ---------------------------------------------------------------------------
// Test 1: GET /health returns 200 with status/version/uptime_secs
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_health_returns_200_with_status_ok() {
    let daemon = start_test_daemon().await;

    let resp = daemon
        .client
        .get(daemon.url("/health"))
        .send()
        .await
        .expect("GET /health must succeed");

    assert_eq!(resp.status(), 200);

    let body: serde_json::Value = resp.json().await.expect("health body must be JSON");
    assert_eq!(body["status"], "ok", "status field must be 'ok'");
    assert!(body["version"].is_string(), "version field must be present");
    assert!(
        body["uptime_secs"].is_number(),
        "uptime_secs field must be a number"
    );

    // Shutdown daemon
    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 2: POST /hooks/pre-tool-use without token returns 401
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_hook_without_token_returns_401() {
    let daemon = start_test_daemon().await;

    let resp = daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .json(&test_event())
        .send()
        .await
        .expect("POST without token must get a response");

    assert_eq!(
        resp.status(),
        401,
        "missing auth header must return 401 Unauthorized"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 3: POST /hooks/pre-tool-use with invalid token returns 401
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_hook_with_invalid_token_returns_401() {
    let daemon = start_test_daemon().await;

    let resp = daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", "Bearer wrong-token-xyz")
        .json(&test_event())
        .send()
        .await
        .expect("POST with wrong token must get a response");

    assert_eq!(
        resp.status(),
        401,
        "invalid bearer token must return 401 Unauthorized"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 4: POST /hooks/pre-tool-use with valid token returns 200 with "allow"
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_pre_tool_use_with_valid_token_returns_allow() {
    let daemon = start_test_daemon().await;

    let resp = daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", daemon.auth_header())
        .json(&test_event())
        .send()
        .await
        .expect("POST pre-tool-use must succeed");

    assert_eq!(resp.status(), 200);

    let body: serde_json::Value = resp.json().await.expect("body must be JSON");
    assert_eq!(
        body["verdict"], "allow",
        "pre-tool-use verdict must be 'allow'"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 5: POST /hooks/user-prompt-submit returns 200 with "allow"
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_user_prompt_submit_returns_allow() {
    let daemon = start_test_daemon().await;

    let event = serde_json::json!({
        "session_id": "test-session-prompt",
        "user_prompt": "What is the capital of France?"
    });

    let resp = daemon
        .client
        .post(daemon.url("/hooks/user-prompt-submit"))
        .header("Authorization", daemon.auth_header())
        .json(&event)
        .send()
        .await
        .expect("POST user-prompt-submit must succeed");

    assert_eq!(resp.status(), 200);

    let body: serde_json::Value = resp.json().await.expect("body must be JSON");
    assert_eq!(
        body["verdict"], "allow",
        "user-prompt-submit verdict must be 'allow'"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 6: POST /hooks/stop returns 200 with "approve"
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_stop_hook_returns_approve() {
    let daemon = start_test_daemon().await;

    let event = serde_json::json!({
        "session_id": "test-session-stop"
    });

    let resp = daemon
        .client
        .post(daemon.url("/hooks/stop"))
        .header("Authorization", daemon.auth_header())
        .json(&event)
        .send()
        .await
        .expect("POST /hooks/stop must succeed");

    assert_eq!(resp.status(), 200);

    let body: serde_json::Value = resp.json().await.expect("body must be JSON");
    assert_eq!(
        body["verdict"], "approve",
        "stop hook verdict must be 'approve'"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 7: Sending same event twice within 100ms → second gets X-OpenLatch-Dedup header
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_duplicate_event_returns_dedup_header() {
    let daemon = start_test_daemon().await;

    let event = serde_json::json!({
        "session_id": "test-session-dedup",
        "tool_name": "bash",
        "tool_input": {"command": "echo hello"}
    });

    // First request — should NOT have dedup header
    let resp1 = daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", daemon.auth_header())
        .json(&event)
        .send()
        .await
        .expect("first POST must succeed");

    assert_eq!(resp1.status(), 200);
    assert!(
        resp1.headers().get("x-openlatch-dedup").is_none(),
        "first request must NOT have dedup header"
    );

    // Second identical request within dedup TTL — should have dedup header
    let resp2 = daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", daemon.auth_header())
        .json(&event)
        .send()
        .await
        .expect("second POST must succeed");

    assert_eq!(resp2.status(), 200);
    assert_eq!(
        resp2
            .headers()
            .get("x-openlatch-dedup")
            .and_then(|v| v.to_str().ok()),
        Some("true"),
        "second identical request must have X-OpenLatch-Dedup: true header"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 8: Event appears in JSONL log file after POST
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_event_written_to_jsonl_log() {
    let daemon = start_test_daemon().await;

    let event = serde_json::json!({
        "session_id": "test-session-log",
        "tool_name": "file_read",
        "tool_input": {"path": "/etc/hosts"}
    });

    daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", daemon.auth_header())
        .json(&event)
        .send()
        .await
        .expect("POST must succeed");

    // Wait for async log writer to flush
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Find JSONL log file in the log directory
    let log_files: Vec<_> = std::fs::read_dir(&daemon.log_dir)
        .expect("log dir must be readable")
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.file_name()
                .to_str()
                .map(|n| n.starts_with("events-") && n.ends_with(".jsonl"))
                .unwrap_or(false)
        })
        .collect();

    assert!(
        !log_files.is_empty(),
        "at least one events-*.jsonl file must exist after sending an event"
    );

    // Read the log file and check for the event
    let log_path = log_files[0].path();
    let contents = std::fs::read_to_string(&log_path).expect("log file must be readable");

    assert!(
        !contents.is_empty(),
        "log file must contain at least one entry"
    );

    // Each line should be valid JSON with expected fields
    let found = contents.lines().any(|line| {
        if let Ok(entry) = serde_json::from_str::<serde_json::Value>(line) {
            entry["session_id"] == "test-session-log"
        } else {
            false
        }
    });
    assert!(
        found,
        "log must contain entry with session_id 'test-session-log'"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 9: JSONL log entry contains masked AWS key (not raw key)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_log_entry_has_masked_aws_key() {
    let daemon = start_test_daemon().await;

    let raw_key = "AKIAIOSFODNN7EXAMPLE";
    let event = serde_json::json!({
        "session_id": "test-session-mask",
        "tool_name": "bash",
        "tool_input": {
            "command": "export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE"
        }
    });

    daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", daemon.auth_header())
        .json(&event)
        .send()
        .await
        .expect("POST must succeed");

    // Wait for async log writer to flush
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Read all log files and check that the raw AWS key is not present
    let log_files: Vec<_> = std::fs::read_dir(&daemon.log_dir)
        .expect("log dir must be readable")
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.file_name()
                .to_str()
                .map(|n| n.starts_with("events-") && n.ends_with(".jsonl"))
                .unwrap_or(false)
        })
        .collect();

    assert!(
        !log_files.is_empty(),
        "log file must exist after sending event with AWS key"
    );

    let contents = std::fs::read_to_string(log_files[0].path()).expect("log file readable");
    assert!(
        !contents.contains(raw_key),
        "log must NOT contain raw AWS key '{}' — should be masked",
        raw_key
    );
    assert!(
        contents.contains("AKIA"),
        "log must contain masked AWS key with AKIA prefix preserved"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 10: GET /metrics returns event count
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_metrics_returns_event_count() {
    let daemon = start_test_daemon().await;

    // Send two events
    for _ in 0..2 {
        let event = serde_json::json!({
            "session_id": "test-session-metrics",
            "tool_name": "tool_a",
            "tool_input": {}
        });
        daemon
            .client
            .post(daemon.url("/hooks/pre-tool-use"))
            .header("Authorization", daemon.auth_header())
            .json(&event)
            .send()
            .await
            .expect("POST must succeed");
    }

    let resp = daemon
        .client
        .get(daemon.url("/metrics"))
        .send()
        .await
        .expect("GET /metrics must succeed");

    assert_eq!(resp.status(), 200);

    let body: serde_json::Value = resp.json().await.expect("metrics body must be JSON");
    assert!(
        body["events_processed"].is_number(),
        "events_processed must be a number"
    );
    // First event is counted; second is a dedup (same session+tool+input) — exactly 1 processed
    assert_eq!(
        body["events_processed"].as_u64().unwrap_or(0),
        1,
        "second identical event must be deduped — only 1 should be processed"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}

// ---------------------------------------------------------------------------
// Test 11: POST /shutdown triggers graceful shutdown
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_shutdown_endpoint_stops_daemon() {
    let daemon = start_test_daemon().await;

    // Send shutdown — should return 200
    let resp = daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .expect("POST /shutdown must get a response");

    assert_eq!(resp.status(), 200, "shutdown endpoint must return 200 OK");

    // Wait briefly for the daemon to finish shutting down
    tokio::time::sleep(Duration::from_millis(200)).await;

    // After shutdown, connections to the daemon port should fail
    let post_shutdown = daemon.client.get(daemon.url("/health")).send().await;
    assert!(
        post_shutdown.is_err(),
        "GET /health after shutdown must fail — daemon is no longer listening"
    );
}

// ---------------------------------------------------------------------------
// Test 12: Request body over 1MB returns 413
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_oversized_body_returns_413() {
    let daemon = start_test_daemon().await;

    // Build a body just over 1MB (1_048_576 bytes)
    let oversized = "x".repeat(1_100_000);
    let body = format!("{{\"data\": \"{}\"}}", oversized);

    let resp = daemon
        .client
        .post(daemon.url("/hooks/pre-tool-use"))
        .header("Authorization", daemon.auth_header())
        .header("Content-Type", "application/json")
        .body(body)
        .send()
        .await
        .expect("oversized POST must get a response");

    assert_eq!(
        resp.status(),
        413,
        "body over 1MB must return 413 Payload Too Large"
    );

    daemon
        .client
        .post(daemon.url("/shutdown"))
        .header("Authorization", daemon.auth_header())
        .send()
        .await
        .ok();
}