Skip to main content

io_msgraph/v1/
send.rs

1//! HTTP/JSON transport every Microsoft Graph coroutine delegates to:
2//! builds the authorized request and parses the JSON response, or the
3//! Graph error envelope on failure.
4//!
5//! Microsoft Graph reference:
6//! <https://learn.microsoft.com/en-us/graph/api/overview>.
7
8use core::{error::Error, fmt, marker::PhantomData, time::Duration};
9
10use alloc::{
11    boxed::Box,
12    format,
13    string::{String, ToString},
14    vec::Vec,
15};
16
17use io_http::{
18    coroutine::{HttpCoroutine, HttpCoroutineState},
19    rfc3986::path::{HttpUrlBuildError, http_url_build},
20    rfc6750::bearer::HttpAuthBearer,
21    rfc9110::{
22        request::HttpRequest,
23        response::HttpResponse,
24        send::{HttpSendOutput, HttpSendYield},
25    },
26    rfc9112::send::{Http11Send, Http11SendError},
27};
28use log::{debug, trace};
29use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
30use url::Url;
31
32use crate::coroutine::{MsgraphCoroutine, MsgraphCoroutineState, MsgraphYield};
33
34/// Base URL of the Microsoft Graph API, version 1.0.
35pub const MSGRAPH_API_BASE: &str = "https://graph.microsoft.com/v1.0/";
36
37/// Base path segment addressing a mailbox owner: `me` as-is, any
38/// other value as `users/{id}`.
39///
40/// Graph accepts an explicit user id or principal name under `users/`
41/// but rejects `users/me`; only the bare `me` shortcut addresses the
42/// authenticated user. An id [`path_segment`] refuses is refused here too.
43pub fn user_path(user_id: &str) -> Result<String, MsgraphSendError> {
44    if user_id == "me" {
45        return Ok(String::from("me"));
46    }
47
48    Ok(format!("users/{}", path_segment(user_id)?))
49}
50
51/// Percent-encodes `raw` as one URL path segment, such as a folder or
52/// message id.
53///
54/// The segment is encoded by [`http_url_build`], so a `/`, `?`, `#` or
55/// `%` stays inside it rather than naming another resource. An empty, `.`
56/// or `..` segment is refused, as is one holding a tab or a line break:
57/// URL resolution would drop it, climb a level or strip those bytes.
58pub fn path_segment(raw: &str) -> Result<String, MsgraphSendError> {
59    let url = match http_url_build(MSGRAPH_API_BASE, [raw]) {
60        Ok(url) => url,
61        Err(HttpUrlBuildError::InvalidBaseUrl(err, _)) => return Err(err.into()),
62        Err(HttpUrlBuildError::InvalidSegment(_)) => {
63            let reason = format!("{raw:?} is not a valid path segment");
64            return Err(MsgraphSendError::InvalidRequest(reason));
65        }
66    };
67
68    let (_, segment) = url.path().rsplit_once('/').unwrap_or_default();
69
70    Ok(segment.into())
71}
72
73/// Marker for endpoints that return an empty body (DELETE, sendMail,
74/// send draft); deserialises from anything, including nothing.
75#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
76pub struct MsgraphNoResponse;
77
78impl<'de> Deserialize<'de> for MsgraphNoResponse {
79    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80    where
81        D: Deserializer<'de>,
82    {
83        let _ = serde::de::IgnoredAny::deserialize(deserializer)?;
84        Ok(Self)
85    }
86}
87
88/// Error returned by [`MsgraphSend`] and the raw `$value` coroutines.
89#[derive(Debug)]
90pub enum MsgraphSendError {
91    /// The underlying HTTP/1.1 exchange failed.
92    Send(Http11SendError),
93    /// The JSON request body could not be serialized.
94    SerializeRequest(serde_json::Error),
95    /// The 2xx response body could not be deserialized.
96    ParseResponse(serde_json::Error),
97    /// The request URL could not be built.
98    ParseUrl(url::ParseError),
99    /// The request arguments were rejected before sending.
100    InvalidRequest(String),
101    /// The Graph API answered a non-2xx status.
102    Api(Box<MsgraphApiError>),
103    /// The server answered a 3xx; redirects are never followed.
104    UnexpectedRedirect,
105}
106
107impl fmt::Display for MsgraphSendError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Self::Send(err) => write!(f, "Microsoft Graph HTTP request failed: {err}"),
111            Self::SerializeRequest(err) => {
112                write!(f, "Microsoft Graph request serialization failed: {err}")
113            }
114            Self::ParseResponse(err) => write!(f, "Microsoft Graph response parsing failed: {err}"),
115            Self::ParseUrl(err) => write!(f, "Microsoft Graph URL parsing failed: {err}"),
116            Self::InvalidRequest(reason) => write!(f, "Invalid Microsoft Graph request: {reason}"),
117            Self::Api(err) => err.fmt(f),
118            Self::UnexpectedRedirect => {
119                write!(f, "Microsoft Graph server returned an unexpected redirect")
120            }
121        }
122    }
123}
124
125impl Error for MsgraphSendError {
126    fn source(&self) -> Option<&(dyn Error + 'static)> {
127        match self {
128            Self::Send(err) => Some(err),
129            Self::SerializeRequest(err) | Self::ParseResponse(err) => Some(err),
130            Self::ParseUrl(err) => Some(err),
131            _ => None,
132        }
133    }
134}
135
136impl From<Http11SendError> for MsgraphSendError {
137    fn from(err: Http11SendError) -> Self {
138        match err {
139            Http11SendError::InvalidRequest(err) => Self::InvalidRequest(err.to_string()),
140            err => Self::Send(err),
141        }
142    }
143}
144
145impl From<MsgraphApiError> for MsgraphSendError {
146    fn from(err: MsgraphApiError) -> Self {
147        Self::Api(Box::new(err))
148    }
149}
150
151impl From<url::ParseError> for MsgraphSendError {
152    fn from(err: url::ParseError) -> Self {
153        Self::ParseUrl(err)
154    }
155}
156
157impl MsgraphSendError {
158    /// The API error of a non-2xx answer, `None` for every other
159    /// variant.
160    pub fn api(&self) -> Option<&MsgraphApiError> {
161        match self {
162            Self::Api(err) => Some(err.as_ref()),
163            _ => None,
164        }
165    }
166
167    /// The HTTP status of an [`Api`](Self::Api) error, `None` for
168    /// every other variant.
169    pub fn status(&self) -> Option<u16> {
170        self.api().map(|err| err.status)
171    }
172
173    /// How long the server asked to wait before a retry
174    /// ([`MsgraphApiError::retry_after`]).
175    pub fn retry_after(&self) -> Option<Duration> {
176        self.api().and_then(|err| err.retry_after)
177    }
178
179    /// Whether Graph throttled the request
180    /// ([`MsgraphApiError::is_throttled`]).
181    pub fn is_throttled(&self) -> bool {
182        self.api().is_some_and(MsgraphApiError::is_throttled)
183    }
184
185    /// Whether the request can be sent again as it is
186    /// ([`MsgraphApiError::is_retryable`]).
187    pub fn is_retryable(&self) -> bool {
188        self.api().is_some_and(MsgraphApiError::is_retryable)
189    }
190}
191
192/// A non-2xx answer of the Graph API: its error envelope, and what its
193/// headers tell a caller to do next.
194#[derive(Debug, Clone, Default, Eq, PartialEq)]
195pub struct MsgraphApiError {
196    /// The HTTP status of the response.
197    pub status: u16,
198    /// The error code of the Graph error envelope.
199    pub code: String,
200    /// The human-readable message of the Graph error envelope.
201    pub message: String,
202    /// The method of the refused request, uppercase.
203    pub method: String,
204    /// How long the server asked to wait before a retry: the
205    /// `Retry-After` header in its seconds form, a date reading as none.
206    pub retry_after: Option<Duration>,
207    /// The `WWW-Authenticate` header, which carries the claims challenge
208    /// of a 401 the next token request has to answer.
209    pub www_authenticate: Option<String>,
210    /// The id Graph gave the request, from the `request-id` header, else
211    /// from the envelope.
212    pub request_id: Option<String>,
213    /// Whether the server allows reusing the TCP/TLS connection.
214    pub keep_alive: bool,
215}
216
217impl MsgraphApiError {
218    /// Reads a non-2xx answer: the error envelope of its body, falling
219    /// back as [`parse_api_error`] does, and its headers.
220    ///
221    /// Neither tells the method of the request nor the connection reuse:
222    /// the exchange fills those in.
223    pub fn parse<'a>(
224        status: u16,
225        headers: impl IntoIterator<Item = (&'a str, &'a str)>,
226        body: &[u8],
227    ) -> Self {
228        let envelope = serde_json::from_slice::<ErrorEnvelope>(body).ok();
229        let (status, code, message) = parse_api_error(status, body);
230
231        let mut err = Self {
232            status,
233            code,
234            message,
235            request_id: envelope
236                .and_then(|envelope| envelope.error.inner_error)
237                .and_then(|inner| inner.request_id),
238            ..Default::default()
239        };
240
241        for (name, value) in headers {
242            let value = value.trim();
243
244            if name.eq_ignore_ascii_case("retry-after") {
245                err.retry_after = value.parse().ok().map(Duration::from_secs);
246            } else if name.eq_ignore_ascii_case("www-authenticate") {
247                err.www_authenticate = Some(value.into());
248            } else if name.eq_ignore_ascii_case("request-id") {
249                err.request_id = Some(value.into());
250            }
251        }
252
253        err
254    }
255
256    /// The API error of the non-2xx `response` to a `method` request.
257    pub(crate) fn of(method: &str, response: &HttpResponse, keep_alive: bool) -> Self {
258        let headers = response.headers.iter();
259        let headers = headers.map(|(name, value)| (name.as_str(), value.as_str()));
260
261        let mut err = Self::parse(*response.status, headers, &response.body);
262        err.method = method.into();
263        err.keep_alive = keep_alive;
264
265        err
266    }
267
268    /// Whether Graph throttled the request (429): it was not taken, so
269    /// sending it again after [`retry_after`](Self::retry_after) is safe
270    /// whatever its method.
271    pub fn is_throttled(&self) -> bool {
272        self.status == 429
273    }
274
275    /// Whether the request can be sent again as it is: a throttled one,
276    /// or a transient 5xx on a method a repeat cannot double.
277    ///
278    /// A POST or a PATCH answered by a 5xx may have been applied, so it
279    /// is not retryable here: a mail could be sent twice.
280    pub fn is_retryable(&self) -> bool {
281        let transient = matches!(self.status, 500 | 502 | 503 | 504);
282        let idempotent = matches!(self.method.as_str(), "GET" | "HEAD" | "PUT" | "DELETE");
283
284        self.is_throttled() || (transient && idempotent)
285    }
286}
287
288impl fmt::Display for MsgraphApiError {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        let Self {
291            status,
292            code,
293            message,
294            ..
295        } = self;
296
297        write!(
298            f,
299            "Microsoft Graph API returned HTTP {status} ({code}): {message}"
300        )
301    }
302}
303
304impl Error for MsgraphApiError {}
305
306/// Terminal value of every coroutine: the parsed response, its headers
307/// and the connection reuse hint.
308#[derive(Clone, Debug)]
309pub struct MsgraphSendOutput<T> {
310    /// The parsed response body.
311    pub response: T,
312    /// The response headers, in order, names lowercased.
313    pub headers: Vec<(String, String)>,
314    /// Whether the server allows reusing the TCP/TLS connection.
315    pub keep_alive: bool,
316}
317
318/// I/O-free coroutine sending one authorized Microsoft Graph request
319/// and parsing its JSON response into `T`.
320pub struct MsgraphSend<T> {
321    state: State,
322    method: String,
323    _phantom: PhantomData<T>,
324}
325
326impl<T: DeserializeOwned> MsgraphSend<T> {
327    /// Builds a GET send for the given URL.
328    pub fn get(auth: &HttpAuthBearer, url: Url) -> Self {
329        Self::with_method(auth, "GET", url, None, Vec::new())
330    }
331
332    /// Builds a DELETE send for the given URL.
333    pub fn delete(auth: &HttpAuthBearer, url: Url) -> Self {
334        Self::with_method(auth, "DELETE", url, None, Vec::new())
335    }
336
337    /// Builds a POST send with a JSON body.
338    pub fn post_json<B: Serialize>(
339        auth: &HttpAuthBearer,
340        url: Url,
341        body: &B,
342    ) -> Result<Self, MsgraphSendError> {
343        let body = serde_json::to_vec(body).map_err(MsgraphSendError::SerializeRequest)?;
344        Ok(Self::with_method(
345            auth,
346            "POST",
347            url,
348            Some("application/json"),
349            body,
350        ))
351    }
352
353    /// Builds a PATCH send with a JSON body.
354    pub fn patch_json<B: Serialize>(
355        auth: &HttpAuthBearer,
356        url: Url,
357        body: &B,
358    ) -> Result<Self, MsgraphSendError> {
359        let body = serde_json::to_vec(body).map_err(MsgraphSendError::SerializeRequest)?;
360        Ok(Self::with_method(
361            auth,
362            "PATCH",
363            url,
364            Some("application/json"),
365            body,
366        ))
367    }
368
369    /// Builds a POST send with a text/plain body.
370    pub fn post_text(auth: &HttpAuthBearer, url: Url, body: Vec<u8>) -> Self {
371        Self::with_method(auth, "POST", url, Some("text/plain"), body)
372    }
373
374    /// Builds a send with an arbitrary method, content type and body.
375    pub fn with_method(
376        auth: &HttpAuthBearer,
377        method: &str,
378        url: Url,
379        content_type: Option<&str>,
380        body: Vec<u8>,
381    ) -> Self {
382        let mut request = HttpRequest::get(url.clone())
383            .header("Accept", "application/json")
384            .header("Authorization", auth.to_authorization())
385            .body(body);
386
387        if let Some(content_type) = content_type {
388            request = request.header("Content-Type", content_type);
389        }
390
391        request.method = method.into();
392
393        debug!("prepare request to send");
394        trace!("method: {method}");
395        trace!("url: {url}");
396
397        Self {
398            state: State::Prepare(request),
399            method: method.into(),
400            _phantom: PhantomData,
401        }
402    }
403
404    /// Adds a header to the request.
405    ///
406    /// Only effective before the first
407    /// [`resume`](MsgraphCoroutine::resume), which serializes the
408    /// request: a header added later is ignored.
409    pub fn header(mut self, name: impl ToString, value: impl ToString) -> Self {
410        if let State::Prepare(request) = &mut self.state {
411            request.headers.push((name.to_string(), value.to_string()));
412        }
413        self
414    }
415
416    /// Asks Graph for at most `size` items per page of a paged
417    /// collection (`Prefer: odata.maxpagesize={size}`).
418    ///
419    /// The preference rides on one request only: a caller following
420    /// `@odata.nextLink` asks again on every page. Graph may serve
421    /// fewer items than asked, and caps the size per endpoint.
422    pub fn max_page_size(self, size: u32) -> Self {
423        self.header("Prefer", format!("odata.maxpagesize={size}"))
424    }
425}
426
427impl<T: DeserializeOwned> MsgraphCoroutine for MsgraphSend<T> {
428    type Yield = MsgraphYield;
429    type Return = Result<MsgraphSendOutput<T>, MsgraphSendError>;
430
431    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
432        if let State::Prepare(request) = &mut self.state {
433            let url = request.url.clone();
434            let request = core::mem::replace(request, HttpRequest::get(url));
435            self.state = State::Send(Http11Send::new(request));
436        }
437
438        match &mut self.state {
439            State::Prepare(_) => unreachable!("the request is sent on the first resume"),
440            State::Send(send) => match send.resume(arg) {
441                HttpCoroutineState::Yielded(HttpSendYield::WantsRead) => {
442                    MsgraphCoroutineState::Yielded(MsgraphYield::WantsRead)
443                }
444                HttpCoroutineState::Yielded(HttpSendYield::WantsWrite(bytes)) => {
445                    MsgraphCoroutineState::Yielded(MsgraphYield::WantsWrite(bytes))
446                }
447                HttpCoroutineState::Yielded(HttpSendYield::WantsRedirect { .. }) => {
448                    MsgraphCoroutineState::Complete(Err(MsgraphSendError::UnexpectedRedirect))
449                }
450                HttpCoroutineState::Complete(Err(err)) => {
451                    MsgraphCoroutineState::Complete(Err(err.into()))
452                }
453                HttpCoroutineState::Complete(Ok(HttpSendOutput {
454                    response,
455                    keep_alive,
456                    ..
457                })) => {
458                    if response.status.is_success() {
459                        let body = if response.body.is_empty() {
460                            b"null".as_slice()
461                        } else {
462                            response.body.as_slice()
463                        };
464
465                        match serde_json::from_slice::<T>(body) {
466                            Ok(parsed) => MsgraphCoroutineState::Complete(Ok(MsgraphSendOutput {
467                                response: parsed,
468                                headers: response.headers,
469                                keep_alive,
470                            })),
471                            Err(err) => MsgraphCoroutineState::Complete(Err(
472                                MsgraphSendError::ParseResponse(err),
473                            )),
474                        }
475                    } else {
476                        let err = MsgraphApiError::of(&self.method, &response, keep_alive);
477                        MsgraphCoroutineState::Complete(Err(err.into()))
478                    }
479                }
480            },
481        }
482    }
483}
484
485enum State {
486    /// The request, open to more headers until the first resume.
487    Prepare(HttpRequest),
488    Send(Http11Send),
489}
490
491#[derive(Debug, Deserialize)]
492struct ErrorEnvelope {
493    error: ErrorBody,
494}
495
496#[derive(Debug, Deserialize)]
497struct ErrorBody {
498    code: Option<String>,
499    message: Option<String>,
500    #[serde(rename = "innerError", alias = "innererror")]
501    inner_error: Option<InnerError>,
502}
503
504#[derive(Debug, Deserialize)]
505struct InnerError {
506    #[serde(rename = "request-id")]
507    request_id: Option<String>,
508}
509
510/// Parse a Microsoft Graph error envelope into its
511/// `(http_status, code, message)` triple.
512///
513/// The envelope is `{ "error": { "code", "message" } }`; when the body
514/// is not that JSON shape the raw body text becomes the message, and
515/// empty or missing parts fall back to `unknown` markers.
516pub fn parse_api_error(http_status: u16, body: &[u8]) -> (u16, String, String) {
517    if let Ok(envelope) = serde_json::from_slice::<ErrorEnvelope>(body) {
518        let code = envelope
519            .error
520            .code
521            .filter(|code| !code.trim().is_empty())
522            .unwrap_or_else(|| String::from("unknown"));
523        let message = envelope
524            .error
525            .message
526            .filter(|message| !message.trim().is_empty())
527            .unwrap_or_else(|| String::from("unknown Microsoft Graph API error"));
528        return (http_status, code, message);
529    }
530
531    let message = String::from_utf8_lossy(body).trim().to_string();
532
533    if message.is_empty() {
534        (
535            http_status,
536            String::from("unknown"),
537            String::from("unknown Microsoft Graph API error"),
538        )
539    } else {
540        (http_status, String::from("unknown"), message)
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use crate::v1::send::{MsgraphSendError, path_segment, user_path};
547
548    #[test]
549    fn a_path_segment_keeps_a_graph_id_and_encodes_separators() {
550        let id = "AAMkAGI2T-_x=";
551        assert_eq!(path_segment(id).unwrap(), id);
552        assert_eq!(path_segment("A/B?c#d e%").unwrap(), "A%2FB%3Fc%23d%20e%25");
553        assert_eq!(path_segment("Envoyés").unwrap(), "Envoy%C3%A9s");
554        assert_eq!(
555            user_path("a b@example.org").unwrap(),
556            "users/a%20b@example.org"
557        );
558        assert_eq!(user_path("me").unwrap(), "me");
559    }
560
561    #[test]
562    fn a_path_segment_refuses_what_url_resolution_drops() {
563        for raw in ["", ".", "..", ".\t.", "a\nb"] {
564            let err = path_segment(raw).unwrap_err();
565            assert!(matches!(err, MsgraphSendError::InvalidRequest(_)));
566
567            let err = user_path(raw).unwrap_err();
568            assert!(matches!(err, MsgraphSendError::InvalidRequest(_)));
569        }
570    }
571}