Skip to main content

orch/channels/
slack.rs

1//! Slack channel — receives commands and streams agent output.
2//!
3//! Uses the Slack Web API with HTTP polling (conversations.history) to receive
4//! messages and the chat.postMessage API to send responses.
5//!
6//! Configuration in `~/.orch/config.yml`:
7//! ```yaml
8//! channels:
9//!   slack:
10//!     bot_token: "xoxb-..."       # Bot User OAuth Token
11//!     channel_id: "C1234567890"   # Channel to monitor and post to
12//!     allowed_user_ids: ["U1234567890"]  # required: other senders are dropped
13//! ```
14//!
15//! The bot token requires the following OAuth scopes:
16//! - `channels:history` / `groups:history` — read messages
17//! - `chat:write` — post messages
18//! - `channels:read` — health check
19
20use super::access::Access;
21use super::{Channel, IncomingMessage, OutgoingMessage};
22use anyhow::Context;
23use async_trait::async_trait;
24use chrono::{DateTime, Utc};
25use reqwest::Client;
26use serde::Deserialize;
27use sha2::{Digest, Sha256};
28use std::fmt;
29use std::fmt::Debug;
30use std::fmt::Formatter;
31use std::fmt::Write as _;
32use std::sync::Arc;
33use std::time::Duration;
34use tokio::sync::Mutex;
35use tokio::sync::mpsc;
36use tokio::sync::mpsc::Receiver;
37use tokio::time;
38
39pub struct SlackChannel {
40    pub bot_token: String,
41    pub client: Client,
42    pub channel_id: Option<String>,
43    /// Cursor tracking the latest message timestamp seen (Slack uses `ts` as cursor).
44    pub last_ts: Arc<Mutex<Option<String>>>,
45    access: Access,
46}
47
48impl Debug for SlackChannel {
49    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
50        f.debug_struct("SlackChannel")
51            .field("channel_id", &self.channel_id)
52            .finish_non_exhaustive()
53    }
54}
55
56#[derive(Deserialize)]
57struct SlackMessage {
58    #[serde(rename = "type")]
59    msg_type: Option<String>,
60    ts: String,
61    /// Absent for bot-posted messages; present for human users.
62    user: Option<String>,
63    /// Present for bot messages.
64    bot_id: Option<String>,
65    text: Option<String>,
66}
67
68#[derive(Deserialize)]
69struct ResponseMetadata {
70    next_cursor: Option<String>,
71}
72
73#[derive(Deserialize)]
74struct ConversationsHistoryResponse {
75    ok: bool,
76    messages: Option<Vec<SlackMessage>>,
77    error: Option<String>,
78    has_more: Option<bool>,
79    response_metadata: Option<ResponseMetadata>,
80}
81
82#[derive(Deserialize)]
83struct PostMessageResponse {
84    ok: bool,
85    error: Option<String>,
86}
87
88#[derive(Deserialize)]
89struct AuthTestResponse {
90    ok: bool,
91    error: Option<String>,
92}
93
94impl SlackChannel {
95    pub fn new(bot_token: String, channel_id: Option<String>) -> anyhow::Result<Self> {
96        let client = Client::builder()
97            .timeout(Duration::from_secs(30))
98            .build()
99            .context("failed to build HTTP client")?;
100
101        Ok(Self {
102            bot_token,
103            client,
104            channel_id,
105            last_ts: Arc::new(Mutex::new(None)),
106            access: Access::default(),
107        })
108    }
109
110    /// Restrict incoming messages to `channel_id`, `extra_channels` and the given user IDs.
111    /// With no channel or no user, every incoming message is dropped
112    #[must_use]
113    pub fn with_access(mut self, extra_channels: Vec<String>, user_ids: Vec<String>) -> Self {
114        let channels = self.channel_id.iter().cloned().chain(extra_channels);
115        self.access = Access::new(channels, user_ids);
116        self
117    }
118
119    fn api_url(method: &str) -> String {
120        format!("https://slack.com/api/{method}")
121    }
122
123    /// Fetch messages newer than `oldest` from a channel
124    ///
125    /// `oldest` is the Slack `ts` of the last processed message (exclusive lower bound).
126    /// With a cursor, pages until `has_more` is false. With none, one newest-first page seeds the cursor
127    async fn get_messages(
128        &self,
129        channel_id: &str,
130        oldest: Option<String>,
131    ) -> anyhow::Result<Vec<SlackMessage>> {
132        let mut all_messages: Vec<SlackMessage> = Vec::new();
133        let mut cursor: Option<String> = None;
134
135        loop {
136            let mut params = vec![
137                ("channel", channel_id.to_string()),
138                ("limit", "200".to_string()),
139            ];
140
141            if let Some(ref ts) = oldest {
142                params.push(("oldest", ts.clone()));
143            }
144
145            if let Some(ref c) = cursor {
146                params.push(("cursor", c.clone()));
147            }
148
149            let response = self
150                .client
151                .get(Self::api_url("conversations.history"))
152                .bearer_auth(&self.bot_token)
153                .query(&params)
154                .send()
155                .await?;
156
157            if !response.status().is_success() {
158                let body = response.text().await.unwrap_or_default();
159                anyhow::bail!("slack API HTTP error: {body}");
160            }
161
162            let result: ConversationsHistoryResponse = response.json().await?;
163
164            if !result.ok {
165                let err = result.error.as_deref().unwrap_or("unknown");
166                anyhow::bail!("slack conversations.history error: {err}");
167            }
168
169            all_messages.extend(result.messages.unwrap_or_default());
170
171            if oldest.is_none() {
172                break;
173            }
174
175            let has_more = result.has_more.unwrap_or(false);
176            let next_cursor = result
177                .response_metadata
178                .and_then(|m| m.next_cursor)
179                .filter(|c| !c.is_empty());
180
181            if !has_more || next_cursor.is_none() {
182                break;
183            }
184
185            cursor = next_cursor;
186        }
187
188        Ok(all_messages)
189    }
190
191    async fn send_message(&self, channel_id: &str, text: &str) -> anyhow::Result<()> {
192        let response = self
193            .client
194            .post(Self::api_url("chat.postMessage"))
195            .bearer_auth(&self.bot_token)
196            .json(&serde_json::json!({
197                "channel": channel_id,
198                "text": text,
199                "mrkdwn": true
200            }))
201            .send()
202            .await?;
203
204        if !response.status().is_success() {
205            let body = response.text().await.unwrap_or_default();
206            anyhow::bail!("slack API HTTP error: {body}");
207        }
208
209        let result: PostMessageResponse = response.json().await?;
210
211        if !result.ok {
212            let err = result.error.as_deref().unwrap_or("unknown");
213            anyhow::bail!("slack chat.postMessage error: {err}");
214        }
215
216        Ok(())
217    }
218}
219
220fn slack_ts_now() -> String {
221    let now = Utc::now();
222    format!("{}.{:06}", now.timestamp(), now.timestamp_subsec_micros())
223}
224
225/// First poll (`last_ts` is None) seeds the cursor from the newest ts or `now_ts` and emits nothing
226fn ingest_poll(
227    last_ts: &mut Option<String>,
228    messages: &[SlackMessage],
229    channel_id: &str,
230    now_ts: &str,
231    access: &Access,
232) -> Vec<IncomingMessage> {
233    if last_ts.is_none() {
234        let seed = messages
235            .iter()
236            .map(|msg| msg.ts.as_str())
237            .max()
238            .unwrap_or(now_ts);
239        tracing::info!(ts = %seed, "slack poller seeded cursor, skipping channel backlog");
240        *last_ts = Some(seed.to_string());
241        return Vec::new();
242    }
243
244    let mut incoming = Vec::new();
245    for msg in messages.iter().rev() {
246        if msg.msg_type.as_deref() != Some("message") {
247            continue;
248        }
249        if msg.bot_id.is_some() {
250            continue;
251        }
252        let text = msg.text.as_deref().unwrap_or_default();
253        if text.is_empty() {
254            continue;
255        }
256
257        if last_ts
258            .as_ref()
259            .is_none_or(|prev: &String| msg.ts.as_str() > prev.as_str())
260        {
261            *last_ts = Some(msg.ts.clone());
262        }
263
264        if !access.allows(channel_id, msg.user.as_deref().unwrap_or_default()) {
265            tracing::warn!(
266                channel_id = %channel_id,
267                user = msg.user.as_deref().unwrap_or("unknown"),
268                "slack message from a user not in allowed_user_ids, dropped"
269            );
270            continue;
271        }
272
273        let author = msg.user.as_deref().unwrap_or("unknown").to_string();
274        let timestamp = msg
275            .ts
276            .split('.')
277            .next()
278            .and_then(|s| s.parse::<i64>().ok())
279            .and_then(|secs| DateTime::from_timestamp(secs, 0))
280            .unwrap_or_else(Utc::now);
281
282        incoming.push(IncomingMessage {
283            channel: "slack".to_string(),
284            id: msg.ts.clone(),
285            thread_id: channel_id.to_string(),
286            author,
287            body: text.to_string(),
288            timestamp,
289            metadata: serde_json::json!({ "channel_id": channel_id }),
290            topic_id: None,
291        });
292    }
293    incoming
294}
295
296#[async_trait]
297impl Channel for SlackChannel {
298    fn name(&self) -> &'static str {
299        "slack"
300    }
301
302    async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
303        let (tx, rx) = mpsc::channel(64);
304
305        // If no channel_id configured we can't poll
306        if self.channel_id.is_none() {
307            tracing::warn!("slack channel_id not configured, skipping message polling");
308            return Ok(rx);
309        }
310
311        let bot_token = self.bot_token.clone();
312        let client = self.client.clone();
313        let Some(channel_id) = self.channel_id.clone() else {
314            // Defensive: is_none() early-return above should prevent reaching here
315            tracing::error!("slack channel_id unexpectedly None after guard check");
316            return Ok(rx);
317        };
318        let last_ts = Arc::clone(&self.last_ts);
319        let access = self.access.clone();
320        access.warn_if_closed("slack");
321
322        let token_fingerprint = {
323            let mut hasher = Sha256::new();
324            hasher.update(bot_token.as_bytes());
325            let hash = hasher.finalize();
326            let hex = hash[..8].iter().fold(String::new(), |mut out, b| {
327                let _ = write!(out, "{b:02x}");
328                out
329            });
330            format!("sha256:{hex}")
331        };
332
333        tracing::info!(
334            token_fingerprint = %token_fingerprint,
335            channel_id = %channel_id,
336            "slack channel started"
337        );
338
339        tokio::spawn(async move {
340            let polling_interval = Duration::from_secs(5);
341
342            loop {
343                time::sleep(polling_interval).await;
344
345                let channel = SlackChannel {
346                    bot_token: bot_token.clone(),
347                    client: client.clone(),
348                    channel_id: Some(channel_id.clone()),
349                    last_ts: Arc::clone(&last_ts),
350                    access: access.clone(),
351                };
352
353                // Snapshot the cursor once so all pagination pages use the same lower bound.
354                let oldest = last_ts.lock().await.clone();
355
356                let messages = match channel.get_messages(&channel_id, oldest).await {
357                    Ok(m) => m,
358                    Err(e) => {
359                        tracing::warn!(?e, "failed to get slack messages");
360                        continue;
361                    }
362                };
363
364                let incoming = {
365                    let mut last = last_ts.lock().await;
366                    ingest_poll(&mut last, &messages, &channel_id, &slack_ts_now(), &access)
367                };
368
369                for msg in incoming {
370                    if tx.send(msg).await.is_err() {
371                        tracing::debug!("slack channel receiver dropped");
372                        return;
373                    }
374                }
375            }
376        });
377
378        Ok(rx)
379    }
380
381    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
382        let channel_id = self
383            .channel_id
384            .as_ref()
385            .ok_or_else(|| anyhow::anyhow!("slack channel_id not configured"))?;
386
387        self.send_message(channel_id, &msg.body).await
388    }
389
390    async fn health_check(&self) -> anyhow::Result<()> {
391        let response = self
392            .client
393            .get(Self::api_url("auth.test"))
394            .bearer_auth(&self.bot_token)
395            .send()
396            .await?;
397
398        if !response.status().is_success() {
399            let body = response.text().await.unwrap_or_default();
400            anyhow::bail!("slack health check HTTP error: {body}");
401        }
402
403        let result: AuthTestResponse = response.json().await?;
404
405        if !result.ok {
406            let err = result.error.as_deref().unwrap_or("unknown");
407            anyhow::bail!("slack auth.test failed: {err}");
408        }
409
410        tracing::info!("slack bot health check passed");
411        Ok(())
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    #[test]
420    fn slack_channel_name() {
421        let ch = SlackChannel::new("xoxb-test".to_string(), None).unwrap();
422        assert_eq!(ch.name(), "slack");
423    }
424
425    #[test]
426    fn access_allows_listed_user_only() {
427        let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string()))
428            .unwrap()
429            .with_access(vec![], vec!["U1".to_string()]);
430        assert!(ch.access.allows("C1", "U1"));
431        assert!(!ch.access.allows("C1", "U2"));
432        assert!(!ch.access.allows("C1", ""));
433    }
434
435    #[test]
436    fn access_includes_mapped_channels() {
437        let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string()))
438            .unwrap()
439            .with_access(vec!["C2".to_string()], vec!["U1".to_string()]);
440        assert!(ch.access.allows("C2", "U1"));
441        assert!(!ch.access.allows("C3", "U1"));
442    }
443
444    #[test]
445    fn empty_policy_drops_everything() {
446        let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string())).unwrap();
447        assert!(!ch.access.allows("C1", "U1"));
448        let ch = ch.with_access(vec![], vec![]);
449        assert!(!ch.access.allows("C1", "U1"));
450    }
451
452    #[test]
453    fn slack_api_url() {
454        assert_eq!(
455            SlackChannel::api_url("auth.test"),
456            "https://slack.com/api/auth.test"
457        );
458        assert_eq!(
459            SlackChannel::api_url("chat.postMessage"),
460            "https://slack.com/api/chat.postMessage"
461        );
462    }
463
464    #[test]
465    fn slack_ts_comparison_is_lexicographic() {
466        // Slack ts values are strings like "1700000000.123456"
467        // Lexicographic comparison works because the integer part is the same width
468        let older = "1700000000.000100".to_string();
469        let newer = "1700000001.000000".to_string();
470        assert!(newer > older);
471    }
472
473    #[test]
474    fn conversations_history_response_deserializes_pagination_fields() {
475        // Response with more pages available
476        let json = r#"{
477            "ok": true,
478            "messages": [{"type": "message", "ts": "1700000001.000000", "text": "hello"}],
479            "has_more": true,
480            "response_metadata": {"next_cursor": "bmV4dF90czoxNzAwMDAwMDAxLjAwMDAwMA=="}
481        }"#;
482        let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
483        assert!(resp.ok);
484        assert_eq!(resp.has_more, Some(true));
485        let meta = resp.response_metadata.unwrap();
486        assert_eq!(
487            meta.next_cursor.as_deref(),
488            Some("bmV4dF90czoxNzAwMDAwMDAxLjAwMDAwMA==")
489        );
490    }
491
492    #[test]
493    fn conversations_history_response_last_page_has_no_cursor() {
494        // Final page: has_more=false, empty next_cursor
495        let json = r#"{
496            "ok": true,
497            "messages": [{"type": "message", "ts": "1700000002.000000", "text": "last"}],
498            "has_more": false,
499            "response_metadata": {"next_cursor": ""}
500        }"#;
501        let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
502        assert_eq!(resp.has_more, Some(false));
503        let next = resp
504            .response_metadata
505            .and_then(|m| m.next_cursor)
506            .filter(|c| !c.is_empty());
507        assert!(
508            next.is_none(),
509            "empty next_cursor should be treated as no more pages"
510        );
511    }
512
513    #[test]
514    fn conversations_history_response_missing_pagination_fields() {
515        // Older API responses may omit has_more and response_metadata entirely
516        let json = r#"{"ok": true, "messages": []}"#;
517        let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
518        assert_eq!(resp.has_more, None);
519        assert!(resp.response_metadata.is_none());
520        // has_more defaults to false — no pagination loop
521        assert!(!resp.has_more.unwrap_or(false));
522    }
523
524    fn slack_msg(ts: &str, text: &str) -> SlackMessage {
525        SlackMessage {
526            msg_type: Some("message".into()),
527            ts: ts.into(),
528            user: Some("U1".into()),
529            bot_id: None,
530            text: Some(text.into()),
531        }
532    }
533
534    fn open_access() -> Access {
535        Access::new(["C123".to_string()], ["U1".to_string()])
536    }
537
538    #[test]
539    fn first_poll_with_no_cursor_does_not_emit_historical_messages() {
540        let mut last_ts = None;
541        let messages = [
542            slack_msg("1700000002.000000", "newest"),
543            slack_msg("1700000001.000000", "older"),
544            slack_msg("1700000000.000000", "oldest"),
545        ];
546        let incoming = ingest_poll(
547            &mut last_ts,
548            &messages,
549            "C123",
550            "1700000099.000000",
551            &open_access(),
552        );
553        assert!(
554            incoming.is_empty(),
555            "first poll must not replay channel history"
556        );
557        assert_eq!(last_ts.as_deref(), Some("1700000002.000000"));
558    }
559
560    #[test]
561    fn first_poll_with_empty_history_seeds_from_now() {
562        let mut last_ts = None;
563        let incoming = ingest_poll(
564            &mut last_ts,
565            &[],
566            "C123",
567            "1700000099.000000",
568            &open_access(),
569        );
570        assert!(incoming.is_empty());
571        assert_eq!(last_ts.as_deref(), Some("1700000099.000000"));
572    }
573
574    #[test]
575    fn later_poll_emits_messages_newer_than_cursor() {
576        let mut last_ts = Some("1700000002.000000".into());
577        let messages = [slack_msg("1700000003.000000", "hello")];
578        let incoming = ingest_poll(
579            &mut last_ts,
580            &messages,
581            "C123",
582            "1700000099.000000",
583            &open_access(),
584        );
585        assert_eq!(incoming.len(), 1);
586        assert_eq!(incoming[0].body, "hello");
587        assert_eq!(incoming[0].id, "1700000003.000000");
588        assert_eq!(last_ts.as_deref(), Some("1700000003.000000"));
589    }
590
591    #[test]
592    fn later_poll_drops_unlisted_users_and_advances_cursor() {
593        let mut last_ts = Some("1700000002.000000".into());
594        let mut other = slack_msg("1700000003.000000", "nope");
595        other.user = Some("U2".into());
596        let messages = [other, slack_msg("1700000004.000000", "hello")];
597        let incoming = ingest_poll(
598            &mut last_ts,
599            &messages,
600            "C123",
601            "1700000099.000000",
602            &open_access(),
603        );
604        assert_eq!(incoming.len(), 1);
605        assert_eq!(incoming[0].body, "hello");
606        assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
607    }
608}