clash 0.5.3

Command Line Agent Safety Harness — permission policies for coding agents
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use serde::Deserialize;
use tracing::{info, warn};

fn default_timeout_secs() -> u64 {
    120
}

// ---------------------------------------------------------------------------
// Configuration types (parsed from policy.yaml root-level `notifications:` key)
// ---------------------------------------------------------------------------

/// Top-level notification configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct NotificationConfig {
    /// Enable desktop notifications for permission prompts and idle events.
    #[serde(default)]
    pub desktop: bool,

    /// Timeout in seconds for interactive desktop notification prompts.
    #[serde(default = "default_timeout_secs")]
    pub desktop_timeout_secs: u64,

    /// Zulip bot configuration for remote permission resolution.
    #[serde(default)]
    pub zulip: Option<ZulipConfig>,
}

impl Default for NotificationConfig {
    fn default() -> Self {
        Self {
            desktop: false,
            desktop_timeout_secs: default_timeout_secs(),
            zulip: None,
        }
    }
}

/// Zulip bot configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct ZulipConfig {
    /// Zulip server URL (e.g., "https://your-org.zulipchat.com").
    pub server_url: String,
    /// Bot email address.
    pub bot_email: String,
    /// Bot API key.
    pub bot_api_key: String,
    /// Stream (channel) to post messages to.
    pub stream: String,
    /// Topic within the stream.
    #[serde(default = "default_topic")]
    pub topic: String,
    /// Timeout in seconds to wait for a Zulip response on permission requests.
    #[serde(default = "default_timeout_secs")]
    pub timeout_secs: u64,
}

fn default_topic() -> String {
    "permissions".into()
}

// ---------------------------------------------------------------------------
// Zulip bot client
// ---------------------------------------------------------------------------

/// Details of a permission request, passed to external resolvers.
pub struct PermissionRequest {
    pub tool_name: String,
    pub tool_input: serde_json::Value,
    pub session_id: String,
    pub cwd: String,
}

/// Response from an external permission resolver.
pub enum PermissionResponse {
    Approve,
    Deny(String),
}

// ---------------------------------------------------------------------------
// Keyword constants for approval/denial matching
// ---------------------------------------------------------------------------

/// Keywords that trigger approval when found anywhere in the message (substring match).
const APPROVE_KEYWORDS: &[&str] = &["approve", "allow"];
/// Keywords that trigger approval only when they are the entire message (exact match).
const APPROVE_EXACT: &[&str] = &["yes", "y"];

/// Keywords that trigger denial when found anywhere in the message (substring match).
const DENY_KEYWORDS: &[&str] = &["deny", "reject"];
/// Keywords that trigger denial only when they are the entire message (exact match).
const DENY_EXACT: &[&str] = &["no", "n"];

/// Check whether `content` (already lowercased and trimmed) is an approval response.
fn is_approval_response(content: &str) -> bool {
    APPROVE_KEYWORDS.iter().any(|kw| content.contains(kw)) || APPROVE_EXACT.contains(&content)
}

/// Check whether `content` (already lowercased and trimmed) is a denial response.
fn is_denial_response(content: &str) -> bool {
    DENY_KEYWORDS.iter().any(|kw| content.contains(kw)) || DENY_EXACT.contains(&content)
}

/// Synchronous Zulip API client.
pub struct ZulipClient<'a> {
    config: &'a ZulipConfig,
}

impl<'a> ZulipClient<'a> {
    pub fn new(config: &'a ZulipConfig) -> Self {
        Self { config }
    }

    /// Send a permission request to Zulip and poll for a user response.
    ///
    /// Returns `Some(PermissionResponse)` if a user responds before the timeout,
    /// or `None` if the timeout elapses without a response.
    pub fn resolve_permission(
        &self,
        request: &PermissionRequest,
    ) -> anyhow::Result<Option<PermissionResponse>> {
        let message = format_permission_message(request);
        let msg_id = self.send_message(&message)?;

        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(self.config.timeout_secs);
        let poll_interval = std::time::Duration::from_secs(2);

        while start.elapsed() < timeout {
            std::thread::sleep(poll_interval);

            match self.check_for_response(msg_id) {
                Ok(Some(response)) => return Ok(Some(response)),
                Ok(None) => continue,
                Err(e) => {
                    warn!(error = %e, "Error polling Zulip for response");
                    // Keep polling despite transient errors.
                    continue;
                }
            }
        }

        info!(
            timeout_secs = self.config.timeout_secs,
            "Zulip permission request timed out"
        );
        Ok(None)
    }

    // -- internal helpers --

    /// Return the `Authorization` header value for HTTP Basic auth.
    fn auth_header(&self) -> String {
        format!(
            "Basic {}",
            base64_auth(&self.config.bot_email, &self.config.bot_api_key)
        )
    }

    /// Return the Zulip messages API endpoint URL.
    fn messages_url(&self) -> String {
        format!(
            "{}/api/v1/messages",
            self.config.server_url.trim_end_matches('/')
        )
    }

    /// Post a message to the configured stream/topic. Returns the message ID.
    fn send_message(&self, content: &str) -> anyhow::Result<u64> {
        let url = self.messages_url();
        let auth_header = self.auth_header();

        let resp = ureq::post(&url)
            .set("Authorization", &auth_header)
            .send_form(&[
                ("type", "stream"),
                ("to", &self.config.stream),
                ("topic", &self.config.topic),
                ("content", content),
            ])?;

        let body = resp.into_string()?;
        let json: serde_json::Value = serde_json::from_str(&body)?;

        let msg_id = json["id"]
            .as_u64()
            .ok_or_else(|| anyhow::anyhow!("Zulip API did not return a message id: {}", body))?;

        info!(msg_id, stream = %self.config.stream, topic = %self.config.topic, "Sent Zulip message");
        Ok(msg_id)
    }

    /// Poll for new messages in the topic after `after_msg_id`.
    fn check_for_response(&self, after_msg_id: u64) -> anyhow::Result<Option<PermissionResponse>> {
        let url = self.messages_url();
        let auth_header = self.auth_header();

        let narrow = serde_json::json!([
            {"operator": "stream", "operand": &self.config.stream},
            {"operator": "topic", "operand": &self.config.topic},
        ]);

        let resp = ureq::get(&url)
            .set("Authorization", &auth_header)
            .query("anchor", &after_msg_id.to_string())
            .query("num_before", "0")
            .query("num_after", "100")
            .query("narrow", &narrow.to_string())
            .call()?;

        let body = resp.into_string()?;
        let json: serde_json::Value = serde_json::from_str(&body)?;

        if let Some(messages) = json["messages"].as_array() {
            for msg in messages {
                // Skip our own bot messages.
                let sender_email = msg["sender_email"].as_str().unwrap_or("");
                if sender_email == self.config.bot_email {
                    continue;
                }

                // Skip the anchor message itself and anything before it.
                let msg_id = msg["id"].as_u64().unwrap_or(0);
                if msg_id <= after_msg_id {
                    continue;
                }

                let content = msg["content"].as_str().unwrap_or("").to_lowercase();
                let content = content.trim();

                if is_approval_response(content) {
                    info!(
                        sender = sender_email,
                        msg_id, "Permission approved via Zulip"
                    );
                    return Ok(Some(PermissionResponse::Approve));
                }

                if is_denial_response(content) {
                    let reason = format!("Denied via Zulip by {}", sender_email);
                    info!(sender = sender_email, msg_id, "Permission denied via Zulip");
                    return Ok(Some(PermissionResponse::Deny(reason)));
                }
            }
        }

        Ok(None)
    }
}

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

/// Format a permission request as a Zulip-friendly markdown message.
fn format_permission_message(request: &PermissionRequest) -> String {
    let noun = crate::permissions::extract_noun(&request.tool_name, &request.tool_input);

    let tool_detail = match request.tool_name.as_str() {
        "Bash" => format!("**Command:** `{}`", noun),
        "Read" | "Write" | "Edit" => format!("**File:** `{}`", noun),
        _ => format!("**Resource:** `{}`", noun),
    };

    format!(
        "**Permission Request**\n\n\
         **Tool:** {}\n\
         {}\n\
         **CWD:** `{}`\n\
         **Session:** `{}`\n\n\
         Reply **approve** or **deny**.",
        request.tool_name, tool_detail, request.cwd, request.session_id,
    )
}

/// Base64-encode `email:api_key` for HTTP Basic auth.
fn base64_auth(email: &str, api_key: &str) -> String {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", email, api_key))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_permission_message_bash() {
        let req = PermissionRequest {
            tool_name: "Bash".into(),
            tool_input: serde_json::json!({"command": "rm -rf /tmp/test"}),
            session_id: "sess-123".into(),
            cwd: "/home/user/project".into(),
        };
        let msg = format_permission_message(&req);
        assert!(msg.contains("**Tool:** Bash"));
        assert!(msg.contains("**Command:** `rm -rf /tmp/test`"));
        assert!(msg.contains("**Session:** `sess-123`"));
        assert!(msg.contains("approve"));
        assert!(msg.contains("deny"));
    }

    #[test]
    fn test_format_permission_message_read() {
        let req = PermissionRequest {
            tool_name: "Read".into(),
            tool_input: serde_json::json!({"file_path": "/etc/passwd"}),
            session_id: "sess-456".into(),
            cwd: "/home/user".into(),
        };
        let msg = format_permission_message(&req);
        assert!(msg.contains("**Tool:** Read"));
        assert!(msg.contains("**File:** `/etc/passwd`"));
    }

    #[test]
    fn test_format_permission_message_unknown_tool() {
        let req = PermissionRequest {
            tool_name: "CustomTool".into(),
            tool_input: serde_json::json!({"key": "value"}),
            session_id: "sess-789".into(),
            cwd: "/tmp".into(),
        };
        let msg = format_permission_message(&req);
        assert!(msg.contains("**Tool:** CustomTool"));
        assert!(msg.contains("**Resource:** `customtool`"));
    }

    #[test]
    fn test_base64_auth() {
        let encoded = base64_auth("bot@example.com", "secret123");
        // base64("bot@example.com:secret123")
        assert!(!encoded.is_empty());

        // Decode and verify
        use base64::Engine;
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(&encoded)
            .unwrap();
        assert_eq!(
            String::from_utf8(decoded).unwrap(),
            "bot@example.com:secret123"
        );
    }

    #[test]
    fn test_notification_config_defaults() {
        let config: NotificationConfig = serde_json::from_str("{}").unwrap();
        assert!(!config.desktop);
        assert!(config.zulip.is_none());
    }

    #[test]
    fn test_notification_config_full() {
        let json = r#"{
            "desktop": true,
            "zulip": {
                "server_url": "https://chat.example.com",
                "bot_email": "bot@example.com",
                "bot_api_key": "abc123",
                "stream": "clash",
                "topic": "perms",
                "timeout_secs": 60
            }
        }"#;
        let config: NotificationConfig = serde_json::from_str(json).unwrap();
        assert!(config.desktop);
        let zulip = config.zulip.unwrap();
        assert_eq!(zulip.server_url, "https://chat.example.com");
        assert_eq!(zulip.bot_email, "bot@example.com");
        assert_eq!(zulip.bot_api_key, "abc123");
        assert_eq!(zulip.stream, "clash");
        assert_eq!(zulip.topic, "perms");
        assert_eq!(zulip.timeout_secs, 60);
    }

    #[test]
    fn test_zulip_config_defaults() {
        let json = r#"{
            "server_url": "https://chat.example.com",
            "bot_email": "bot@example.com",
            "bot_api_key": "abc123",
            "stream": "clash"
        }"#;
        let config: ZulipConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.topic, "permissions");
        assert_eq!(config.timeout_secs, 120);
    }

    // -----------------------------------------------------------------------
    // HTTP integration tests using mockito
    // -----------------------------------------------------------------------

    /// Create a ZulipConfig pointing at the given mock server URL.
    fn mock_zulip_config(server_url: &str, timeout_secs: u64) -> ZulipConfig {
        ZulipConfig {
            server_url: server_url.to_string(),
            bot_email: "bot@example.com".to_string(),
            bot_api_key: "test-api-key".to_string(),
            stream: "test-stream".to_string(),
            topic: "permissions".to_string(),
            timeout_secs,
        }
    }

    /// Create a sample permission request for tests.
    fn sample_permission_request() -> PermissionRequest {
        PermissionRequest {
            tool_name: "Bash".into(),
            tool_input: serde_json::json!({"command": "ls -la"}),
            session_id: "test-session-123".into(),
            cwd: "/tmp/test".into(),
        }
    }

    #[test]
    fn test_send_message_returns_message_id() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        let mock = server
            .mock("POST", "/api/v1/messages")
            .match_header(
                "Authorization",
                mockito::Matcher::Regex("^Basic .+".to_string()),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"id": 42, "result": "success"}"#)
            .create();

        let msg_id = client.send_message("Hello, world!").unwrap();
        assert_eq!(msg_id, 42);
        mock.assert();
    }

    #[test]
    fn test_send_message_propagates_http_error() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        let mock = server
            .mock("POST", "/api/v1/messages")
            .with_status(401)
            .with_body(r#"{"result": "error", "msg": "Invalid API key"}"#)
            .create();

        let result = client.send_message("Hello");
        assert!(result.is_err());
        mock.assert();
    }

    #[test]
    fn test_send_message_errors_on_missing_id() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        let mock = server
            .mock("POST", "/api/v1/messages")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"result": "success"}"#)
            .create();

        let result = client.send_message("Hello");
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("did not return a message id"),
            "unexpected error: {}",
            err_msg
        );
        mock.assert();
    }

    #[test]
    fn test_check_for_response_approve() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        let mock = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::AllOf(vec![
                mockito::Matcher::UrlEncoded("anchor".to_string(), "100".to_string()),
                mockito::Matcher::UrlEncoded("num_before".to_string(), "0".to_string()),
                mockito::Matcher::UrlEncoded("num_after".to_string(), "100".to_string()),
            ]))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 101,
                            "sender_email": "user@example.com",
                            "content": "approve"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let response = client.check_for_response(100).unwrap();
        assert!(response.is_some());
        assert!(matches!(response.unwrap(), PermissionResponse::Approve));
        mock.assert();
    }

    #[test]
    fn test_check_for_response_deny() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        let mock = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::AllOf(vec![
                mockito::Matcher::UrlEncoded("anchor".to_string(), "100".to_string()),
                mockito::Matcher::UrlEncoded("num_before".to_string(), "0".to_string()),
                mockito::Matcher::UrlEncoded("num_after".to_string(), "100".to_string()),
            ]))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 101,
                            "sender_email": "user@example.com",
                            "content": "deny"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let response = client.check_for_response(100).unwrap();
        assert!(response.is_some());
        match response.unwrap() {
            PermissionResponse::Deny(reason) => {
                assert!(
                    reason.contains("user@example.com"),
                    "deny reason should include sender: {}",
                    reason
                );
            }
            PermissionResponse::Approve => panic!("Expected Deny, got Approve"),
        }
        mock.assert();
    }

    #[test]
    fn test_check_for_response_no_relevant_messages() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        // Return messages, but only from the bot itself (should be skipped)
        // and messages at or before the anchor (should be skipped).
        let mock = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 100,
                            "sender_email": "bot@example.com",
                            "content": "Permission Request..."
                        },
                        {
                            "id": 99,
                            "sender_email": "user@example.com",
                            "content": "approve"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let response = client.check_for_response(100).unwrap();
        assert!(response.is_none());
        mock.assert();
    }

    #[test]
    fn test_check_for_response_empty_messages() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        let mock = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": []
                })
                .to_string(),
            )
            .create();

        let response = client.check_for_response(100).unwrap();
        assert!(response.is_none());
        mock.assert();
    }

    #[test]
    fn test_check_for_response_skips_bot_messages() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        // Bot message with "approve" should be ignored; only user messages count.
        let mock = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 101,
                            "sender_email": "bot@example.com",
                            "content": "approve"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let response = client.check_for_response(100).unwrap();
        assert!(response.is_none());
        mock.assert();
    }

    #[test]
    fn test_check_for_response_ignores_irrelevant_content() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 120);
        let client = ZulipClient::new(&config);

        // A user message that doesn't match any approve/deny keywords.
        let mock = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 101,
                            "sender_email": "user@example.com",
                            "content": "What is this about?"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let response = client.check_for_response(100).unwrap();
        assert!(response.is_none());
        mock.assert();
    }

    #[test]
    fn test_check_for_response_various_approve_keywords() {
        // Test all the different approval keywords: "approve", "allow", "yes", "y"
        for keyword in &["approve", "allow", "yes", "y"] {
            let mut server = mockito::Server::new();
            let config = mock_zulip_config(&server.url(), 120);
            let client = ZulipClient::new(&config);

            let mock = server
                .mock("GET", "/api/v1/messages")
                .match_query(mockito::Matcher::Any)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(
                    serde_json::json!({
                        "result": "success",
                        "messages": [
                            {
                                "id": 101,
                                "sender_email": "user@example.com",
                                "content": keyword
                            }
                        ]
                    })
                    .to_string(),
                )
                .create();

            let response = client.check_for_response(100).unwrap();
            assert!(
                matches!(response, Some(PermissionResponse::Approve)),
                "keyword '{}' should be recognized as approval",
                keyword
            );
            mock.assert();
        }
    }

    #[test]
    fn test_check_for_response_various_deny_keywords() {
        // Test all the different denial keywords: "deny", "reject", "no", "n"
        for keyword in &["deny", "reject", "no", "n"] {
            let mut server = mockito::Server::new();
            let config = mock_zulip_config(&server.url(), 120);
            let client = ZulipClient::new(&config);

            let mock = server
                .mock("GET", "/api/v1/messages")
                .match_query(mockito::Matcher::Any)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(
                    serde_json::json!({
                        "result": "success",
                        "messages": [
                            {
                                "id": 101,
                                "sender_email": "user@example.com",
                                "content": keyword
                            }
                        ]
                    })
                    .to_string(),
                )
                .create();

            let response = client.check_for_response(100).unwrap();
            assert!(
                matches!(response, Some(PermissionResponse::Deny(_))),
                "keyword '{}' should be recognized as denial",
                keyword
            );
            mock.assert();
        }
    }

    #[test]
    fn test_resolve_permission_timeout() {
        // Use timeout_secs=0 so resolve_permission returns None immediately
        // without entering the polling loop.
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 0);
        let client = ZulipClient::new(&config);

        let mock_post = server
            .mock("POST", "/api/v1/messages")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"id": 42, "result": "success"}"#)
            .create();

        let request = sample_permission_request();
        let result = client.resolve_permission(&request).unwrap();
        assert!(result.is_none(), "Expected None (timeout), got a response");
        mock_post.assert();
    }

    #[test]
    fn test_resolve_permission_approve_end_to_end() {
        // Use timeout_secs=10 to allow one poll cycle (sleep 2s then poll).
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 10);
        let client = ZulipClient::new(&config);

        // Mock the initial POST to send the message.
        let mock_post = server
            .mock("POST", "/api/v1/messages")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"id": 42, "result": "success"}"#)
            .create();

        // Mock the GET poll to return an approval.
        let mock_get = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 43,
                            "sender_email": "reviewer@example.com",
                            "content": "approve"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let request = sample_permission_request();
        let result = client.resolve_permission(&request).unwrap();
        assert!(matches!(result, Some(PermissionResponse::Approve)));
        mock_post.assert();
        mock_get.assert();
    }

    #[test]
    fn test_resolve_permission_deny_end_to_end() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 10);
        let client = ZulipClient::new(&config);

        let mock_post = server
            .mock("POST", "/api/v1/messages")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"id": 42, "result": "success"}"#)
            .create();

        let mock_get = server
            .mock("GET", "/api/v1/messages")
            .match_query(mockito::Matcher::Any)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "result": "success",
                    "messages": [
                        {
                            "id": 43,
                            "sender_email": "reviewer@example.com",
                            "content": "deny"
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let request = sample_permission_request();
        let result = client.resolve_permission(&request).unwrap();
        match result {
            Some(PermissionResponse::Deny(reason)) => {
                assert!(reason.contains("reviewer@example.com"));
            }
            other => panic!("Expected Some(Deny), got {:?}", other.map(|_| "something")),
        }
        mock_post.assert();
        mock_get.assert();
    }

    #[test]
    fn test_resolve_permission_send_failure() {
        let mut server = mockito::Server::new();
        let config = mock_zulip_config(&server.url(), 10);
        let client = ZulipClient::new(&config);

        // The POST fails, so resolve_permission should propagate the error.
        let mock_post = server
            .mock("POST", "/api/v1/messages")
            .with_status(500)
            .with_body(r#"{"result": "error", "msg": "Internal error"}"#)
            .create();

        let request = sample_permission_request();
        let result = client.resolve_permission(&request);
        assert!(result.is_err());
        mock_post.assert();
    }
}