1use 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 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 user: Option<String>,
63 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 #[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 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(¶ms)
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
225fn ingest_poll(
228 last_ts: &mut Option<String>,
229 messages: &[SlackMessage],
230 channel_id: &str,
231 now_ts: &str,
232 access: &Access,
233) -> Vec<IncomingMessage> {
234 let newest = messages.iter().map(|msg| msg.ts.as_str()).max();
235
236 if last_ts.is_none() {
237 let seed = newest.unwrap_or(now_ts);
238 tracing::info!(ts = %seed, "slack poller seeded cursor, skipping channel backlog");
239 *last_ts = Some(seed.to_string());
240 return Vec::new();
241 }
242
243 if let Some(ts) = newest
244 && last_ts.as_deref().is_none_or(|prev| ts > prev)
245 {
246 *last_ts = Some(ts.to_string());
247 }
248
249 let mut incoming = Vec::new();
250 for msg in messages.iter().rev() {
251 if msg.msg_type.as_deref() != Some("message") {
252 continue;
253 }
254 if msg.bot_id.is_some() {
255 continue;
256 }
257 let text = msg.text.as_deref().unwrap_or_default();
258 if text.is_empty() {
259 continue;
260 }
261
262 if !access.allows(channel_id, msg.user.as_deref().unwrap_or_default()) {
263 tracing::warn!(
264 channel_id = %channel_id,
265 user = msg.user.as_deref().unwrap_or("unknown"),
266 "slack message from a user not in allowed_user_ids, dropped"
267 );
268 continue;
269 }
270
271 let author = msg.user.as_deref().unwrap_or("unknown").to_string();
272 let timestamp = msg
273 .ts
274 .split('.')
275 .next()
276 .and_then(|s| s.parse::<i64>().ok())
277 .and_then(|secs| DateTime::from_timestamp(secs, 0))
278 .unwrap_or_else(Utc::now);
279
280 incoming.push(IncomingMessage {
281 channel: "slack".to_string(),
282 id: msg.ts.clone(),
283 thread_id: channel_id.to_string(),
284 author,
285 body: text.to_string(),
286 timestamp,
287 metadata: serde_json::json!({ "channel_id": channel_id }),
288 topic_id: None,
289 });
290 }
291 incoming
292}
293
294#[async_trait]
295impl Channel for SlackChannel {
296 fn name(&self) -> &'static str {
297 "slack"
298 }
299
300 async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
301 let (tx, rx) = mpsc::channel(64);
302
303 if self.channel_id.is_none() {
305 tracing::warn!("slack channel_id not configured, skipping message polling");
306 return Ok(rx);
307 }
308
309 let bot_token = self.bot_token.clone();
310 let client = self.client.clone();
311 let Some(channel_id) = self.channel_id.clone() else {
312 tracing::error!("slack channel_id unexpectedly None after guard check");
314 return Ok(rx);
315 };
316 let last_ts = Arc::clone(&self.last_ts);
317 let access = self.access.clone();
318 access.warn_if_closed("slack");
319
320 let token_fingerprint = {
321 let mut hasher = Sha256::new();
322 hasher.update(bot_token.as_bytes());
323 let hash = hasher.finalize();
324 let hex = hash[..8].iter().fold(String::new(), |mut out, b| {
325 let _ = write!(out, "{b:02x}");
326 out
327 });
328 format!("sha256:{hex}")
329 };
330
331 tracing::info!(
332 token_fingerprint = %token_fingerprint,
333 channel_id = %channel_id,
334 "slack channel started"
335 );
336
337 tokio::spawn(async move {
338 let polling_interval = Duration::from_secs(5);
339
340 loop {
341 time::sleep(polling_interval).await;
342
343 let channel = SlackChannel {
344 bot_token: bot_token.clone(),
345 client: client.clone(),
346 channel_id: Some(channel_id.clone()),
347 last_ts: Arc::clone(&last_ts),
348 access: access.clone(),
349 };
350
351 let oldest = last_ts.lock().await.clone();
353
354 let messages = match channel.get_messages(&channel_id, oldest).await {
355 Ok(m) => m,
356 Err(e) => {
357 tracing::warn!(?e, "failed to get slack messages");
358 continue;
359 }
360 };
361
362 let incoming = {
363 let mut last = last_ts.lock().await;
364 ingest_poll(&mut last, &messages, &channel_id, &slack_ts_now(), &access)
365 };
366
367 for msg in incoming {
368 if tx.send(msg).await.is_err() {
369 tracing::debug!("slack channel receiver dropped");
370 return;
371 }
372 }
373 }
374 });
375
376 Ok(rx)
377 }
378
379 async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
380 let channel_id = self
381 .channel_id
382 .as_ref()
383 .ok_or_else(|| anyhow::anyhow!("slack channel_id not configured"))?;
384
385 self.send_message(channel_id, &msg.body).await
386 }
387
388 async fn health_check(&self) -> anyhow::Result<()> {
389 let response = self
390 .client
391 .get(Self::api_url("auth.test"))
392 .bearer_auth(&self.bot_token)
393 .send()
394 .await?;
395
396 if !response.status().is_success() {
397 let body = response.text().await.unwrap_or_default();
398 anyhow::bail!("slack health check HTTP error: {body}");
399 }
400
401 let result: AuthTestResponse = response.json().await?;
402
403 if !result.ok {
404 let err = result.error.as_deref().unwrap_or("unknown");
405 anyhow::bail!("slack auth.test failed: {err}");
406 }
407
408 tracing::info!("slack bot health check passed");
409 Ok(())
410 }
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 #[test]
418 fn slack_channel_name() {
419 let ch = SlackChannel::new("xoxb-test".to_string(), None).unwrap();
420 assert_eq!(ch.name(), "slack");
421 }
422
423 #[test]
424 fn access_allows_listed_user_only() {
425 let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string()))
426 .unwrap()
427 .with_access(vec![], vec!["U1".to_string()]);
428 assert!(ch.access.allows("C1", "U1"));
429 assert!(!ch.access.allows("C1", "U2"));
430 assert!(!ch.access.allows("C1", ""));
431 }
432
433 #[test]
434 fn access_includes_mapped_channels() {
435 let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string()))
436 .unwrap()
437 .with_access(vec!["C2".to_string()], vec!["U1".to_string()]);
438 assert!(ch.access.allows("C2", "U1"));
439 assert!(!ch.access.allows("C3", "U1"));
440 }
441
442 #[test]
443 fn empty_policy_drops_everything() {
444 let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string())).unwrap();
445 assert!(!ch.access.allows("C1", "U1"));
446 let ch = ch.with_access(vec![], vec![]);
447 assert!(!ch.access.allows("C1", "U1"));
448 }
449
450 #[test]
451 fn slack_api_url() {
452 assert_eq!(
453 SlackChannel::api_url("auth.test"),
454 "https://slack.com/api/auth.test"
455 );
456 assert_eq!(
457 SlackChannel::api_url("chat.postMessage"),
458 "https://slack.com/api/chat.postMessage"
459 );
460 }
461
462 #[test]
463 fn slack_ts_comparison_is_lexicographic() {
464 let older = "1700000000.000100".to_string();
467 let newer = "1700000001.000000".to_string();
468 assert!(newer > older);
469 }
470
471 #[test]
472 fn conversations_history_response_deserializes_pagination_fields() {
473 let json = r#"{
475 "ok": true,
476 "messages": [{"type": "message", "ts": "1700000001.000000", "text": "hello"}],
477 "has_more": true,
478 "response_metadata": {"next_cursor": "bmV4dF90czoxNzAwMDAwMDAxLjAwMDAwMA=="}
479 }"#;
480 let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
481 assert!(resp.ok);
482 assert_eq!(resp.has_more, Some(true));
483 let meta = resp.response_metadata.unwrap();
484 assert_eq!(
485 meta.next_cursor.as_deref(),
486 Some("bmV4dF90czoxNzAwMDAwMDAxLjAwMDAwMA==")
487 );
488 }
489
490 #[test]
491 fn conversations_history_response_last_page_has_no_cursor() {
492 let json = r#"{
494 "ok": true,
495 "messages": [{"type": "message", "ts": "1700000002.000000", "text": "last"}],
496 "has_more": false,
497 "response_metadata": {"next_cursor": ""}
498 }"#;
499 let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
500 assert_eq!(resp.has_more, Some(false));
501 let next = resp
502 .response_metadata
503 .and_then(|m| m.next_cursor)
504 .filter(|c| !c.is_empty());
505 assert!(
506 next.is_none(),
507 "empty next_cursor should be treated as no more pages"
508 );
509 }
510
511 #[test]
512 fn conversations_history_response_missing_pagination_fields() {
513 let json = r#"{"ok": true, "messages": []}"#;
515 let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
516 assert_eq!(resp.has_more, None);
517 assert!(resp.response_metadata.is_none());
518 assert!(!resp.has_more.unwrap_or(false));
520 }
521
522 fn slack_msg(ts: &str, text: &str) -> SlackMessage {
523 SlackMessage {
524 msg_type: Some("message".into()),
525 ts: ts.into(),
526 user: Some("U1".into()),
527 bot_id: None,
528 text: Some(text.into()),
529 }
530 }
531
532 fn bot_msg(ts: &str, text: &str) -> SlackMessage {
533 SlackMessage {
534 msg_type: Some("message".into()),
535 ts: ts.into(),
536 user: None,
537 bot_id: Some("B1".into()),
538 text: Some(text.into()),
539 }
540 }
541
542 fn open_access() -> Access {
543 Access::new(["C123".to_string()], ["U1".to_string()])
544 }
545
546 #[test]
547 fn first_poll_with_no_cursor_does_not_emit_historical_messages() {
548 let mut last_ts = None;
549 let messages = [
550 slack_msg("1700000002.000000", "newest"),
551 slack_msg("1700000001.000000", "older"),
552 slack_msg("1700000000.000000", "oldest"),
553 ];
554 let incoming = ingest_poll(
555 &mut last_ts,
556 &messages,
557 "C123",
558 "1700000099.000000",
559 &open_access(),
560 );
561 assert!(
562 incoming.is_empty(),
563 "first poll must not replay channel history"
564 );
565 assert_eq!(last_ts.as_deref(), Some("1700000002.000000"));
566 }
567
568 #[test]
569 fn first_poll_with_empty_history_seeds_from_now() {
570 let mut last_ts = None;
571 let incoming = ingest_poll(
572 &mut last_ts,
573 &[],
574 "C123",
575 "1700000099.000000",
576 &open_access(),
577 );
578 assert!(incoming.is_empty());
579 assert_eq!(last_ts.as_deref(), Some("1700000099.000000"));
580 }
581
582 #[test]
583 fn later_poll_emits_messages_newer_than_cursor() {
584 let mut last_ts = Some("1700000002.000000".into());
585 let messages = [slack_msg("1700000003.000000", "hello")];
586 let incoming = ingest_poll(
587 &mut last_ts,
588 &messages,
589 "C123",
590 "1700000099.000000",
591 &open_access(),
592 );
593 assert_eq!(incoming.len(), 1);
594 assert_eq!(incoming[0].body, "hello");
595 assert_eq!(incoming[0].id, "1700000003.000000");
596 assert_eq!(last_ts.as_deref(), Some("1700000003.000000"));
597 }
598
599 #[test]
600 fn later_poll_drops_unlisted_users_and_advances_cursor() {
601 let mut last_ts = Some("1700000002.000000".into());
602 let mut other = slack_msg("1700000003.000000", "nope");
603 other.user = Some("U2".into());
604 let messages = [other, slack_msg("1700000004.000000", "hello")];
605 let incoming = ingest_poll(
606 &mut last_ts,
607 &messages,
608 "C123",
609 "1700000099.000000",
610 &open_access(),
611 );
612 assert_eq!(incoming.len(), 1);
613 assert_eq!(incoming[0].body, "hello");
614 assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
615 }
616
617 #[test]
618 fn later_poll_advances_cursor_past_bot_messages() {
619 let mut last_ts = Some("1700000002.000000".into());
620 let messages = [
621 bot_msg("1700000004.000000", "newest bot"),
622 bot_msg("1700000003.000000", "older bot"),
623 ];
624 let incoming = ingest_poll(
625 &mut last_ts,
626 &messages,
627 "C123",
628 "1700000099.000000",
629 &open_access(),
630 );
631 assert!(
632 incoming.is_empty(),
633 "bot messages must not be emitted as incoming commands"
634 );
635 assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
636 }
637
638 #[test]
639 fn later_poll_emits_human_messages_and_advances_past_later_bots() {
640 let mut last_ts = Some("1700000002.000000".into());
641 let messages = [
642 bot_msg("1700000005.000000", "notification"),
643 slack_msg("1700000004.000000", "hello"),
644 bot_msg("1700000003.000000", "older bot"),
645 ];
646 let incoming = ingest_poll(
647 &mut last_ts,
648 &messages,
649 "C123",
650 "1700000099.000000",
651 &open_access(),
652 );
653 assert_eq!(incoming.len(), 1);
654 assert_eq!(incoming[0].body, "hello");
655 assert_eq!(last_ts.as_deref(), Some("1700000005.000000"));
656 }
657
658 #[test]
659 fn later_poll_advances_cursor_past_empty_and_non_message_events() {
660 let mut last_ts = Some("1700000002.000000".into());
661 let empty_text = SlackMessage {
662 msg_type: Some("message".into()),
663 ts: "1700000003.000000".into(),
664 user: Some("U1".into()),
665 bot_id: None,
666 text: Some(String::new()),
667 };
668 let other_type = SlackMessage {
669 msg_type: Some("desktop_notification".into()),
670 ts: "1700000004.000000".into(),
671 user: None,
672 bot_id: None,
673 text: Some("ignored".into()),
674 };
675 let messages = [other_type, empty_text];
676 let incoming = ingest_poll(
677 &mut last_ts,
678 &messages,
679 "C123",
680 "1700000099.000000",
681 &open_access(),
682 );
683 assert!(incoming.is_empty());
684 assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
685 }
686}