1mod api;
7mod auth;
8mod wire;
9
10use std::collections::{HashMap, HashSet, VecDeque};
11use std::fmt;
12use std::sync::{Arc, Mutex, PoisonError};
13
14use adk_core::{AdkError, ErrorCategory, ErrorComponent};
15use adk_kernel::KernelError;
16use adk_kernel::channels::{
17 ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
18 StopNotice,
19};
20use async_trait::async_trait;
21use axum::Json;
22use axum::body::Bytes;
23use axum::extract::State;
24use axum::http::{HeaderMap, StatusCode, header};
25use axum::response::{IntoResponse, Response};
26use axum::routing::post;
27use chrono::Utc;
28use serde_json::Value;
29use tokio::sync::mpsc;
30
31use super::shared::{
32 ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
33 PressedCard, Taker, Update, checked_base, checked_token, dispatch, kit_builder, notice_words,
34 patient, stopped_words,
35};
36use crate::error::{Result, SurfaceError};
37use api::{ConnectorApi, TokenSource};
38use auth::{ConnectorAuth, Refusal};
39
40pub const TEAMS_CHANNEL: &str = "teams";
43
44pub const TEAMS: &str = "Microsoft Teams";
47
48const DEFAULT_SERVICE_URL: &str = "https://smba.trafficmanager.net/teams/";
51const DEFAULT_LOGIN_BASE: &str = "https://login.microsoftonline.com";
53const SEEN_KEPT: usize = 4096;
55const ANSWER_RECEIVED: &str = "Answer received.";
58
59#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
74#[non_exhaustive]
75pub enum TeamsError {
76 #[error(
79 "Microsoft Teams refused the bot's credentials: check TEAMS_APP_ID and \
80 TEAMS_APP_PASSWORD (a client secret of the bot's app registration), and TEAMS_TENANT_ID \
81 for a single-tenant bot"
82 )]
83 Unauthorized,
84 #[error(
87 "Microsoft Teams refused the message (HTTP 403): {message}; the person may have blocked or removed the app"
88 )]
89 Forbidden {
90 message: String,
92 },
93 #[error("Microsoft Teams throttled the bot (HTTP {status}): try again later")]
96 RateLimited {
97 status: u16,
99 },
100 #[error("Microsoft Teams refused the message (HTTP {status}): {message}")]
103 Refused {
104 status: u16,
106 message: String,
108 },
109 #[error("Microsoft Teams could not be reached: {reason}; check the network")]
111 Unreachable {
112 reason: String,
114 },
115 #[error("Microsoft Teams' answer could not be read: {reason}")]
117 InvalidResponse {
118 reason: String,
120 },
121}
122
123impl TeamsError {
124 pub fn code(&self) -> &'static str {
127 match self {
128 Self::Unauthorized => "surface.teams.unauthorized",
129 Self::Forbidden { .. } => "surface.teams.forbidden",
130 Self::RateLimited { .. } => "surface.teams.rate_limited",
131 Self::Refused { .. } => "surface.teams.refused",
132 Self::Unreachable { .. } => "surface.teams.unreachable",
133 Self::InvalidResponse { .. } => "surface.teams.invalid_response",
134 }
135 }
136}
137
138impl From<TeamsError> for AdkError {
139 fn from(error: TeamsError) -> Self {
140 let category = match &error {
141 TeamsError::Unauthorized => ErrorCategory::Unauthorized,
142 TeamsError::Forbidden { .. } => ErrorCategory::Forbidden,
143 TeamsError::RateLimited { .. } => ErrorCategory::RateLimited,
144 TeamsError::Refused { .. } => ErrorCategory::InvalidInput,
145 TeamsError::Unreachable { .. } => ErrorCategory::Unavailable,
146 TeamsError::InvalidResponse { .. } => ErrorCategory::Internal,
147 };
148 AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
149 .with_provider("teams")
150 }
151}
152
153impl From<TeamsError> for KernelError {
154 fn from(error: TeamsError) -> Self {
155 Self::Core(error.into())
156 }
157}
158
159pub struct TeamsAdapterBuilder {
161 app_id: String,
162 password: String,
163 tenant: Option<String>,
164 service_url: String,
165 login_base: String,
166 openid_configuration: String,
167 issuer: String,
168 kit: Kit,
169}
170
171impl fmt::Debug for TeamsAdapterBuilder {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 f.debug_struct("TeamsAdapterBuilder")
174 .field("app_id", &self.app_id)
175 .field("tenant", &self.tenant)
176 .field("service_url", &self.service_url)
177 .finish_non_exhaustive()
178 }
179}
180
181impl TeamsAdapterBuilder {
182 #[must_use]
186 pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
187 self.tenant = Some(tenant.into());
188 self
189 }
190
191 #[must_use]
198 pub fn service_url(mut self, url: impl Into<String>) -> Self {
199 self.service_url = url.into();
200 self
201 }
202
203 #[must_use]
206 pub fn login_base(mut self, url: impl Into<String>) -> Self {
207 self.login_base = url.into();
208 self
209 }
210
211 #[must_use]
216 pub fn openid_configuration(mut self, url: impl Into<String>) -> Self {
217 self.openid_configuration = url.into();
218 self
219 }
220
221 #[must_use]
225 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
226 self.issuer = issuer.into();
227 self
228 }
229
230 kit_builder!("Microsoft Teams");
231
232 pub fn build(self) -> Result<TeamsAdapter> {
239 checked_token(&self.app_id, "the bot's app id (TEAMS_APP_ID)")
240 .map_err(SurfaceError::Invalid)?;
241 if self.password.is_empty() || self.password.chars().any(char::is_control) {
242 return Err(SurfaceError::Invalid(
243 "the bot's password (TEAMS_APP_PASSWORD) is empty or malformed: copy the client \
244 secret's value again from the app registration"
245 .into(),
246 ));
247 }
248 if let Some(tenant) = &self.tenant {
249 checked_token(tenant, "the tenant id (TEAMS_TENANT_ID)")
250 .map_err(SurfaceError::Invalid)?;
251 }
252 let service_url = checked_base(&self.service_url, "the Bot Connector address", false)
253 .map_err(SurfaceError::Invalid)?;
254 let client = reqwest::Client::builder().build().map_err(|error| {
255 SurfaceError::Invalid(format!(
256 "the Teams HTTP client could not be built: {}",
257 error.without_url()
258 ))
259 })?;
260 let tokens = TokenSource::new(
261 client.clone(),
262 &self.login_base,
263 self.tenant.as_deref(),
264 &self.app_id,
265 &self.password,
266 )
267 .map_err(SurfaceError::Invalid)?;
268 let auth = ConnectorAuth::new(
269 client.clone(),
270 &self.openid_configuration,
271 &self.issuer,
272 &self.app_id,
273 )
274 .map_err(SurfaceError::Invalid)?;
275 Ok(TeamsAdapter {
276 inner: Arc::new(Inner {
277 api: ConnectorApi::new(client, tokens),
278 auth,
279 kit: self.kit,
280 app_id: self.app_id,
281 tenant: self.tenant,
282 service_url,
283 state: Mutex::default(),
284 }),
285 })
286 }
287}
288
289#[derive(Clone)]
329pub struct TeamsAdapter {
330 inner: Arc<Inner>,
331}
332
333struct Inner {
334 api: ConnectorApi,
335 auth: ConnectorAuth,
336 kit: Kit,
337 app_id: String,
338 tenant: Option<String>,
339 service_url: String,
340 state: Mutex<Conversations>,
341}
342
343#[derive(Default)]
345struct Conversations {
346 service_urls: HashMap<String, String>,
347 seen: HashSet<String>,
348 order: VecDeque<String>,
349}
350
351impl Conversations {
352 fn first_time(&mut self, id: &str) -> bool {
354 if !self.seen.insert(id.to_string()) {
355 return false;
356 }
357 self.order.push_back(id.to_string());
358 while self.order.len() > SEEN_KEPT {
359 if let Some(oldest) = self.order.pop_front() {
360 self.seen.remove(&oldest);
361 }
362 }
363 true
364 }
365}
366
367impl fmt::Debug for TeamsAdapter {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 f.debug_struct("TeamsAdapter")
370 .field("channel", &TEAMS_CHANNEL)
371 .field("app_id", &self.inner.app_id)
372 .finish_non_exhaustive()
373 }
374}
375
376#[derive(Debug)]
379pub struct TeamsWebhook {
380 router: axum::Router,
381 connection: ChannelConnection<TeamsError>,
382}
383
384impl TeamsWebhook {
385 pub fn router(&self) -> axum::Router {
388 self.router.clone()
389 }
390
391 pub fn stop(&self) {
394 self.connection.stop();
395 }
396
397 pub fn is_finished(&self) -> bool {
399 self.connection.is_finished()
400 }
401
402 pub async fn join(self) -> std::result::Result<(), TeamsError> {
408 drop(self.router);
409 self.connection.join().await
410 }
411}
412
413struct Hook {
415 adapter: TeamsAdapter,
416 sender: mpsc::UnboundedSender<Update<Carried>>,
417}
418
419pub(crate) struct Carried {
421 card: Option<String>,
422}
423
424enum Delivery {
426 Queued,
428 Again,
430 Closed,
432}
433
434impl TeamsAdapter {
435 pub fn builder(app_id: impl Into<String>, password: impl Into<String>) -> TeamsAdapterBuilder {
438 TeamsAdapterBuilder {
439 app_id: app_id.into(),
440 password: password.into(),
441 tenant: None,
442 service_url: DEFAULT_SERVICE_URL.to_string(),
443 login_base: DEFAULT_LOGIN_BASE.to_string(),
444 openid_configuration: auth::OPENID_CONFIGURATION.to_string(),
445 issuer: auth::ISSUER.to_string(),
446 kit: Kit::default(),
447 }
448 }
449
450 pub fn inbound(&self, activity: &Value) -> Option<ChannelInbound> {
473 wire::parse(activity).and_then(|received| received.inbound)
474 }
475
476 pub fn start(&self, gateway: ChannelGateway) -> TeamsWebhook {
485 let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
486 let hook = Arc::new(Hook { adapter: self.clone(), sender });
487 let router = axum::Router::new().route("/", post(receive)).with_state(hook);
488 let connection = ChannelConnection::spawn(async move {
489 let mut dispatcher = AbortOnDrop(task);
490 let _ = (&mut dispatcher.0).await;
491 Ok(())
492 });
493 TeamsWebhook { router, connection }
494 }
495
496 fn take(
498 &self,
499 received: wire::Received,
500 sender: &mpsc::UnboundedSender<Update<Carried>>,
501 ) -> Delivery {
502 {
503 let mut state = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
504 state.service_urls.insert(received.thread.clone(), received.service_url.clone());
505 if !state.first_time(&received.id) {
506 return Delivery::Again;
507 }
508 }
509 let Some(inbound) = received.inbound else { return Delivery::Queued };
510 let update =
511 Update { inbound: Some(inbound), press: Some(Carried { card: received.card }) };
512 if sender.send(update).is_err() { Delivery::Closed } else { Delivery::Queued }
513 }
514
515 fn service_url(&self, thread: &str) -> String {
518 let state = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
519 state.service_urls.get(thread).cloned().unwrap_or_else(|| self.inner.service_url.clone())
520 }
521
522 async fn send(
524 &self,
525 thread: &str,
526 reply_to: Option<&str>,
527 activity: &Value,
528 ) -> adk_kernel::Result<String> {
529 let service = self.service_url(thread);
530 let patient = patient(TEAMS_CHANNEL, thread);
532 Ok(self.inner.api.post(&service, thread, reply_to, activity, patient).await?)
533 }
534}
535
536fn refused(refusal: &Refusal) -> Response {
538 let status = match refusal {
539 Refusal::Unauthenticated(_) => StatusCode::UNAUTHORIZED,
540 Refusal::Forbidden(_) => StatusCode::FORBIDDEN,
541 Refusal::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
542 };
543 status.into_response()
544}
545
546async fn receive(State(hook): State<Arc<Hook>>, headers: HeaderMap, body: Bytes) -> Response {
548 let authorization = headers.get(header::AUTHORIZATION).and_then(|value| value.to_str().ok());
549 let verified = match hook.adapter.inner.auth.verify(authorization).await {
550 Ok(verified) => verified,
551 Err(refusal) => {
552 tracing::warn!(reason = ?refusal, "a teams activity without a valid bot connector token was refused");
553 return refused(&refusal);
554 }
555 };
556 let Ok(activity) = serde_json::from_slice::<Value>(&body) else {
557 return StatusCode::BAD_REQUEST.into_response();
558 };
559 let channel = activity["channelId"].as_str().unwrap_or_default();
560 let service_url = activity["serviceUrl"].as_str().unwrap_or_default();
561 if let Err(refusal) = verified.vouches_for(channel, service_url) {
562 tracing::warn!(reason = ?refusal, "a teams activity its token does not vouch for was refused");
563 return refused(&refusal);
564 }
565 if checked_base(service_url, "the activity's serviceUrl", false).is_err() {
567 tracing::warn!("a teams activity naming a service address that is not https was refused");
568 return StatusCode::FORBIDDEN.into_response();
569 }
570 let Some(received) = wire::parse(&activity) else { return StatusCode::OK.into_response() };
571 if let Some(tenant) = &hook.adapter.inner.tenant
572 && received.tenant.as_deref() != Some(tenant.as_str())
573 {
574 tracing::warn!("a teams activity from another tenant was refused");
575 return StatusCode::FORBIDDEN.into_response();
576 }
577 let invoke = received.invoke;
578 let answers = received
579 .inbound
580 .as_ref()
581 .is_some_and(|inbound| matches!(inbound.body, InboundBody::Answer { .. }));
582 match hook.adapter.take(received, &hook.sender) {
583 Delivery::Closed => StatusCode::SERVICE_UNAVAILABLE.into_response(),
584 Delivery::Queued | Delivery::Again if invoke && answers => {
585 Json(wire::invoke_message(ANSWER_RECEIVED)).into_response()
586 }
587 Delivery::Queued | Delivery::Again if invoke => {
588 Json(wire::invoke_refused("this card action is not one of the agents' answers"))
589 .into_response()
590 }
591 Delivery::Queued | Delivery::Again => StatusCode::OK.into_response(),
592 }
593}
594
595#[async_trait]
596impl Taker for TeamsAdapter {
597 type Press = Carried;
599
600 fn channel_name(&self) -> &'static str {
601 TEAMS_CHANNEL
602 }
603
604 async fn take(
605 &self,
606 gateway: &ChannelGateway,
607 update: &Update<Carried>,
608 paired: bool,
609 ) -> adk_kernel::Result<()> {
610 let Some(inbound) = update.inbound.clone() else { return Ok(()) };
611 let card = match &inbound.body {
612 InboundBody::Answer { decision, .. } => Some(PressedCard {
613 card: update.press.as_ref().and_then(|carried| carried.card.clone()),
614 decision: decision.clone(),
615 }),
616 _ => None,
617 };
618 let handling = Handling::of(TEAMS_CHANNEL, gateway, &inbound, paired, card);
619 HANDLING.scope(handling, gateway.receive(inbound)).await.map(drop)
620 }
621
622 async fn not_taken(&self, update: &Update<Carried>) {
623 let Some(inbound) = &update.inbound else { return };
624 let card = update.press.as_ref().and_then(|carried| carried.card.as_deref());
625 let (text, reply_to) = match card {
626 Some(card) => (ANSWER_NOT_TAKEN, Some(card)),
627 None => (MESSAGE_NOT_TAKEN, Some(inbound.message_id.as_str())),
628 };
629 if let Err(error) = self.send(&inbound.thread, reply_to, &wire::text(text)).await {
630 tracing::debug!(error = %error, "a person could not be told their message was not taken");
631 }
632 }
633}
634
635#[async_trait]
636impl ChannelSink for TeamsAdapter {
637 fn channel(&self) -> &str {
638 TEAMS_CHANNEL
639 }
640
641 async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
642 for activity in wire::plain(text) {
643 self.send(thread, None, &activity).await?;
644 }
645 Ok(())
646 }
647
648 async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
649 let (heading, card) = self.inner.kit.prepare(card).await;
650 let activity = wire::card(&card, &heading, self.inner.kit.offset);
651 self.send(thread, None, &activity).await.map(drop)
652 }
653
654 async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
655 self.send(thread, None, &wire::message(&stopped_words(notice))).await.map(drop)
656 }
657
658 async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
661 let card = self.inner.kit.before_notice(TEAMS_CHANNEL, TEAMS, thread, notice).await;
662 let card = card.filter(|card| !card.is_empty());
663 let words = notice_words(notice, self.inner.kit.offset, Utc::now(), card.is_some());
664 self.send(thread, card.as_deref(), &wire::message(&words)).await.map(drop)
665 }
666}
667
668#[cfg(test)]
669mod tests {
670 use super::*;
671
672 const APP_ID: &str = "00000000-0000-0000-0000-000000000001";
673
674 #[test]
675 fn errors_say_what_to_do_and_keep_their_category() {
676 let error: AdkError = TeamsError::Unauthorized.into();
677 assert_eq!(error.category, ErrorCategory::Unauthorized);
678 assert_eq!(error.code, "surface.teams.unauthorized");
679 let throttled: AdkError = TeamsError::RateLimited { status: 429 }.into();
680 assert!(throttled.is_retryable());
681 let blocked: AdkError =
682 TeamsError::Forbidden { message: "MessageWritesBlocked".into() }.into();
683 assert_eq!(blocked.category, ErrorCategory::Forbidden);
684 }
685
686 #[test]
687 fn the_builder_checks_its_inputs_and_never_echoes_the_password() {
688 let adapter = TeamsAdapter::builder(APP_ID, "s3cret~pass").build().unwrap();
689 assert!(!format!("{adapter:?}").contains("s3cret"));
690 assert!(!format!("{:?}", TeamsAdapter::builder(APP_ID, "s3cret~pass")).contains("s3cret"));
691 assert_eq!(ChannelSink::channel(&adapter), "teams");
692 let empty = TeamsAdapter::builder(APP_ID, "").build().unwrap_err();
693 assert!(empty.to_string().contains("TEAMS_APP_PASSWORD"), "{empty}");
694 let id = TeamsAdapter::builder("app id", "p").build().unwrap_err();
695 assert!(id.to_string().contains("TEAMS_APP_ID"), "{id}");
696 let plain = TeamsAdapter::builder(APP_ID, "p")
697 .service_url("http://smba.example/teams")
698 .build()
699 .unwrap_err();
700 assert!(plain.to_string().contains("https"), "{plain}");
701 assert!(TeamsAdapter::builder(APP_ID, "p").tenant("a tenant").build().is_err());
702 }
703
704 #[test]
705 fn a_conversation_is_answered_where_it_last_wrote_from() {
706 let adapter = TeamsAdapter::builder(APP_ID, "p").build().unwrap();
707 assert_eq!(adapter.service_url("a:1"), "https://smba.trafficmanager.net/teams");
708 let (sender, _receiver) = mpsc::unbounded_channel();
709 let received = wire::Received {
710 id: "1".into(),
711 thread: "a:1".into(),
712 service_url: "https://smba.trafficmanager.net/emea/".into(),
713 tenant: None,
714 inbound: None,
715 card: None,
716 invoke: false,
717 };
718 assert!(matches!(adapter.take(received.clone(), &sender), Delivery::Queued));
719 assert!(matches!(adapter.take(received, &sender), Delivery::Again));
720 assert_eq!(adapter.service_url("a:1"), "https://smba.trafficmanager.net/emea/");
721 let mut state = Conversations::default();
722 assert!(state.first_time("x") && !state.first_time("x"));
723 for index in 0..SEEN_KEPT + 1 {
724 state.first_time(&format!("y{index}"));
725 }
726 assert!(state.first_time("x"), "forgotten after {SEEN_KEPT}");
727 }
728}