Skip to main content

acs_signature/
lib.rs

1//! Signing Azure Communication Services requests with an access key.
2//!
3//! Every ACS data-plane API — email, SMS, chat, identity — accepts the same
4//! HMAC-SHA256 access-key scheme, and this crate computes it. Connection
5//! string in, three headers out. No HTTP client, no async runtime, no TLS
6//! stack.
7//!
8//! # The scheme, in one line
9//!
10//! Sign `"{METHOD}\n{path and query}\n{date};{host};{base64 sha256 of the body}"`
11//! with the base64-decoded access key, then send the signature alongside
12//! the date and the body hash — because the two headers are part of what
13//! was signed, and the service recomputes both.
14//!
15//! # Examples
16//!
17//! ```
18//! use acs_signature::{ConnectionString, Signer};
19//!
20//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
21//! let parsed = ConnectionString::parse(
22//!     "endpoint=https://contoso.communication.azure.com/;accesskey=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
23//! )?;
24//! let signer = Signer::new(parsed.access_key())?;
25//!
26//! let body = r#"{"senderAddress":"a@b.c"}"#;
27//! let signed = signer.sign(
28//!     "POST",
29//!     "/emails:send?api-version=2023-03-31",
30//!     "contoso.communication.azure.com",
31//!     &acs_signature::now(),
32//!     body.as_bytes(),
33//! );
34//!
35//! // Send all three, exactly as given.
36//! for (name, value) in signed.headers() {
37//!     let _ = (name, value);
38//! }
39//! # Ok(())
40//! # }
41//! ```
42
43#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
44
45use std::fmt;
46
47use base64::Engine as _;
48use hmac::{Hmac, Mac};
49use sha2::{Digest as _, Sha256};
50use time::OffsetDateTime;
51use time::format_description::well_known::Rfc2822;
52
53/// The header carrying the request date.
54pub const DATE_HEADER: &str = "x-ms-date";
55
56/// The header carrying the base64 SHA-256 of the body.
57pub const CONTENT_HASH_HEADER: &str = "x-ms-content-sha256";
58
59/// The header carrying the signature.
60pub const AUTHORIZATION_HEADER: &str = "Authorization";
61
62/// The headers named in the `SignedHeaders` list, in the order they are
63/// signed in.
64pub const SIGNED_HEADERS: &str = "x-ms-date;host;x-ms-content-sha256";
65
66/// Why a connection string could not be used.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum ParseError {
69    /// No `endpoint=` part.
70    NoEndpoint,
71    /// No `accesskey=` part.
72    NoAccessKey,
73}
74
75impl fmt::Display for ParseError {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        // The connection string is never echoed back: it contains the key,
78        // and this type is the thing most likely to be logged.
79        match self {
80            Self::NoEndpoint => {
81                formatter.write_str("the ACS connection string has no endpoint= part")
82            }
83            Self::NoAccessKey => {
84                formatter.write_str("the ACS connection string has no accesskey= part")
85            }
86        }
87    }
88}
89
90impl std::error::Error for ParseError {}
91
92/// Why an access key could not be used for signing.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum KeyError {
95    /// The key is not valid base64.
96    ///
97    /// An ACS access key is base64 and is decoded before use. Signing with
98    /// the base64 *text* instead produces a header that looks right and is
99    /// always rejected.
100    NotBase64,
101    /// The decoded key cannot be used as an HMAC-SHA256 key.
102    Unusable,
103}
104
105impl fmt::Display for KeyError {
106    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107        match self {
108            Self::NotBase64 => formatter.write_str("the ACS access key is not valid base64"),
109            Self::Unusable => formatter.write_str("the ACS access key is not a usable signing key"),
110        }
111    }
112}
113
114impl std::error::Error for KeyError {}
115
116/// The two parts of an ACS connection string.
117///
118/// The string is
119/// `endpoint=https://x.communication.azure.com/;accesskey=…`.
120///
121/// # This type does not print its key
122///
123/// [`Debug`] shows the endpoint and `<redacted>`.
124#[derive(Clone)]
125pub struct ConnectionString {
126    /// The endpoint, with any trailing slash removed.
127    endpoint: String,
128    /// The access key, still base64.
129    access_key: String,
130}
131
132impl fmt::Debug for ConnectionString {
133    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
134        formatter
135            .debug_struct("ConnectionString")
136            .field("endpoint", &self.endpoint)
137            .field("access_key", &"<redacted>")
138            .finish()
139    }
140}
141
142impl ConnectionString {
143    /// Parse a connection string.
144    ///
145    /// Part names are matched case-insensitively, and a trailing slash is
146    /// removed from the endpoint so that joining a path cannot double up.
147    ///
148    /// # Errors
149    ///
150    /// [`ParseError`] naming what is missing — never the string itself.
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// use acs_signature::ConnectionString;
156    ///
157    /// # fn main() -> Result<(), acs_signature::ParseError> {
158    /// let parsed = ConnectionString::parse(
159    ///     "endpoint=https://x.communication.azure.com/;accesskey=c2VjcmV0",
160    /// )?;
161    ///
162    /// assert_eq!(parsed.endpoint(), "https://x.communication.azure.com");
163    /// assert_eq!(parsed.host(), "x.communication.azure.com");
164    /// # Ok(())
165    /// # }
166    /// ```
167    pub fn parse(connection_string: &str) -> Result<Self, ParseError> {
168        let mut endpoint = None;
169        let mut access_key = None;
170
171        for part in connection_string.split(';') {
172            // `split_once` stops at the FIRST `=`, which is what lets a
173            // base64 key keep its `=` padding. Splitting on every `=` would
174            // truncate the key, and the signature would then be wrong in a
175            // way that looks like a permissions problem.
176            let Some((name, value)) = part.split_once('=') else {
177                continue;
178            };
179            match name.trim().to_ascii_lowercase().as_str() {
180                "endpoint" => endpoint = Some(value.trim().trim_end_matches('/').to_string()),
181                "accesskey" => access_key = Some(value.trim().to_string()),
182                _ => {}
183            }
184        }
185
186        Ok(Self {
187            endpoint: endpoint.ok_or(ParseError::NoEndpoint)?,
188            access_key: access_key.ok_or(ParseError::NoAccessKey)?,
189        })
190    }
191
192    /// The endpoint, without a trailing slash.
193    #[must_use]
194    pub fn endpoint(&self) -> &str {
195        &self.endpoint
196    }
197
198    /// The access key, still base64.
199    ///
200    /// Hand it to [`Signer::new`], which decodes and validates it.
201    #[must_use]
202    pub fn access_key(&self) -> &str {
203        &self.access_key
204    }
205
206    /// The host, as the signature needs it: no scheme, no path, no slash.
207    ///
208    /// Getting this wrong is a signature mismatch rather than a connection
209    /// failure, because the host is *signed* as well as connected to.
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// use acs_signature::ConnectionString;
215    ///
216    /// # fn main() -> Result<(), acs_signature::ParseError> {
217    /// let parsed = ConnectionString::parse("endpoint=https://x.communication.azure.com/;accesskey=c2VjcmV0")?;
218    /// assert_eq!(parsed.host(), "x.communication.azure.com");
219    /// # Ok(())
220    /// # }
221    /// ```
222    #[must_use]
223    pub fn host(&self) -> &str {
224        self.endpoint
225            .split_once("://")
226            .map_or(self.endpoint.as_str(), |(_, rest)| rest)
227            .split('/')
228            .next()
229            .unwrap_or(&self.endpoint)
230    }
231}
232
233/// The three headers a signed request carries.
234///
235/// All three must be sent, exactly as given: the date and the content hash
236/// are part of what was signed, and the service recomputes the signature
237/// from the headers it receives.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct Signed {
240    /// The `x-ms-date` value.
241    pub date: String,
242    /// The `x-ms-content-sha256` value.
243    pub content_hash: String,
244    /// The `Authorization` value.
245    pub authorization: String,
246}
247
248impl Signed {
249    /// The three headers as name/value pairs, ready to add to a request.
250    ///
251    /// # Examples
252    ///
253    /// ```
254    /// use acs_signature::Signer;
255    ///
256    /// # fn main() -> Result<(), acs_signature::KeyError> {
257    /// let signer = Signer::new("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")?;
258    /// let signed = signer.sign("GET", "/x", "h.communication.azure.com", "sat, 22 aug 2026 09:15:00 gmt", b"");
259    ///
260    /// let names: Vec<&str> = signed.headers().iter().map(|(name, _)| *name).collect();
261    /// assert_eq!(names, ["x-ms-date", "x-ms-content-sha256", "Authorization"]);
262    /// # Ok(())
263    /// # }
264    /// ```
265    #[must_use]
266    pub fn headers(&self) -> [(&'static str, &str); 3] {
267        [
268            (DATE_HEADER, self.date.as_str()),
269            (CONTENT_HASH_HEADER, self.content_hash.as_str()),
270            (AUTHORIZATION_HEADER, self.authorization.as_str()),
271        ]
272    }
273}
274
275/// A validated access key, ready to sign with.
276///
277/// The key is decoded once, at construction, so a malformed one is a
278/// configuration error at startup rather than a `401` at the first request.
279///
280/// # This type does not print its key
281#[derive(Clone)]
282pub struct Signer {
283    /// The decoded key bytes.
284    decoded: Vec<u8>,
285}
286
287impl fmt::Debug for Signer {
288    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
289        formatter.write_str("Signer(<redacted>)")
290    }
291}
292
293impl Signer {
294    /// Decode and validate a base64 access key.
295    ///
296    /// # Errors
297    ///
298    /// [`KeyError`] when the key is not base64, or not usable for
299    /// HMAC-SHA256.
300    pub fn new(access_key: &str) -> Result<Self, KeyError> {
301        let decoded = base64::engine::general_purpose::STANDARD
302            .decode(access_key.trim())
303            .map_err(|_| KeyError::NotBase64)?;
304
305        <Hmac<Sha256>>::new_from_slice(&decoded).map_err(|_| KeyError::Unusable)?;
306
307        Ok(Self { decoded })
308    }
309
310    /// Sign one request.
311    ///
312    /// `path_and_query` is everything after the host, starting with `/` and
313    /// including the query string — `?api-version=…` is signed, and
314    /// omitting it is a signature mismatch.
315    ///
316    /// `date` should come from [`now`] or [`date`]. `body` is the exact
317    /// bytes that will be sent; an empty slice for a GET.
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// use acs_signature::Signer;
323    ///
324    /// # fn main() -> Result<(), acs_signature::KeyError> {
325    /// let signer = Signer::new("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")?;
326    /// let signed = signer.sign(
327    ///     "POST",
328    ///     "/emails:send?api-version=2023-03-31",
329    ///     "x.communication.azure.com",
330    ///     "sat, 22 aug 2026 09:15:00 gmt",
331    ///     br#"{"senderAddress":"a@b.c"}"#,
332    /// );
333    ///
334    /// assert_eq!(signed.content_hash, "JppGVhXOsxjTDFEjYrQyeJE/eLwcSbSYvYuKFodVIO0=");
335    /// assert!(signed.authorization.starts_with("HMAC-SHA256 SignedHeaders="));
336    /// # Ok(())
337    /// # }
338    /// ```
339    #[must_use]
340    pub fn sign(
341        &self,
342        method: &str,
343        path_and_query: &str,
344        host: &str,
345        date: &str,
346        body: &[u8],
347    ) -> Signed {
348        let content_hash = content_hash(body);
349        let to_sign = string_to_sign(method, path_and_query, host, date, &content_hash);
350        let signature = self.raw_signature(&to_sign);
351
352        Signed {
353            date: date.to_string(),
354            content_hash,
355            authorization: format!(
356                "HMAC-SHA256 SignedHeaders={SIGNED_HEADERS}&Signature={signature}"
357            ),
358        }
359    }
360
361    /// The base64 HMAC-SHA256 of an arbitrary string to sign.
362    ///
363    /// For a caller building a header shape this crate does not cover.
364    #[must_use]
365    pub fn raw_signature(&self, string_to_sign: &str) -> String {
366        // Cannot fail: the key was validated in `new`.
367        let Ok(mut mac) = <Hmac<Sha256>>::new_from_slice(&self.decoded) else {
368            unreachable!("the key was validated at construction")
369        };
370        mac.update(string_to_sign.as_bytes());
371
372        base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())
373    }
374}
375
376/// The three-line string an ACS signature covers.
377///
378/// Exposed because it is the thing worth asserting in a test.
379///
380/// # Examples
381///
382/// ```
383/// use acs_signature::{content_hash, string_to_sign};
384///
385/// let hash = content_hash(b"");
386/// let signed = string_to_sign("GET", "/x?a=1", "h.communication.azure.com", "sat, 22 aug 2026 09:15:00 gmt", &hash);
387///
388/// assert_eq!(
389///     signed,
390///     format!("GET\n/x?a=1\nsat, 22 aug 2026 09:15:00 gmt;h.communication.azure.com;{hash}")
391/// );
392/// ```
393#[must_use]
394pub fn string_to_sign(
395    method: &str,
396    path_and_query: &str,
397    host: &str,
398    date: &str,
399    content_hash: &str,
400) -> String {
401    // The method is uppercased; nothing else changes case. Note the
402    // separator changes: newlines between the first three fields, then
403    // semicolons within the third.
404    format!(
405        "{}\n{}\n{};{};{}",
406        method.to_uppercase(),
407        path_and_query,
408        date,
409        host,
410        content_hash
411    )
412}
413
414/// The base64 SHA-256 of a request body.
415///
416/// Part of what is signed, so a body modified in flight is rejected rather
417/// than sent.
418///
419/// # Examples
420///
421/// ```
422/// use acs_signature::content_hash;
423///
424/// // The well-known SHA-256 of the empty input.
425/// assert_eq!(content_hash(b""), "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=");
426/// ```
427#[must_use]
428pub fn content_hash(body: &[u8]) -> String {
429    base64::engine::general_purpose::STANDARD.encode(Sha256::digest(body))
430}
431
432/// The date format ACS wants: lowercase RFC 1123 in GMT.
433///
434/// `time` spells RFC 2822 rather than 1123, and the two agree for this
435/// purpose except that 2822 writes `+0000` where 1123 writes `GMT` — so
436/// that substitution is made explicitly rather than hoped for.
437///
438/// A non-UTC input is converted before formatting: the header and the
439/// signature must carry the same instant.
440///
441/// # Examples
442///
443/// ```
444/// use acs_signature::date;
445/// use time::macros::datetime;
446///
447/// assert_eq!(date(datetime!(2026-08-22 09:15:00 UTC)), "sat, 22 aug 2026 09:15:00 gmt");
448/// assert_eq!(
449///     date(datetime!(2026-08-22 11:15:00 +2:00)),
450///     date(datetime!(2026-08-22 09:15:00 UTC))
451/// );
452/// ```
453#[must_use]
454pub fn date(at: OffsetDateTime) -> String {
455    let formatted = at
456        .to_offset(time::UtcOffset::UTC)
457        .format(&Rfc2822)
458        .unwrap_or_default();
459
460    formatted.replace("+0000", "GMT").to_lowercase()
461}
462
463/// [`date`] for the current moment.
464#[must_use]
465pub fn now() -> String {
466    date(OffsetDateTime::now_utc())
467}
468
469#[cfg(test)]
470mod tests {
471    use time::macros::datetime;
472
473    use super::*;
474
475    /// Not a real key: 32 zero bytes, base64-encoded, so the vectors below
476    /// are reproducible by anyone.
477    const KEY: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
478    const HOST: &str = "x.communication.azure.com";
479    const DATE: &str = "sat, 22 aug 2026 09:15:00 gmt";
480
481    fn signer() -> Signer {
482        Signer::new(KEY).expect("a valid test key")
483    }
484
485    // -- known answers ----------------------------------------------------
486    //
487    // Computed by an independent implementation (Python's `hmac`, `hashlib`
488    // and `base64`) rather than by this code.
489
490    #[test]
491    fn a_post_matches_the_known_answer() {
492        let signed = signer().sign(
493            "POST",
494            "/emails:send?api-version=2023-03-31",
495            HOST,
496            DATE,
497            br#"{"senderAddress":"a@b.c"}"#,
498        );
499
500        assert_eq!(
501            signed.content_hash,
502            "JppGVhXOsxjTDFEjYrQyeJE/eLwcSbSYvYuKFodVIO0="
503        );
504        assert_eq!(
505            signed.authorization,
506            "HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256\
507             &Signature=Mztr7ETllMC1E+swVgksDR4wY+kb3Yy39QgyQ7Zn57s="
508        );
509    }
510
511    #[test]
512    fn a_get_with_no_body_matches_the_known_answer() {
513        let signed = signer().sign("GET", "/identities?api-version=2023-10-01", HOST, DATE, b"");
514
515        assert_eq!(
516            signed.content_hash,
517            "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
518            "the well-known SHA-256 of the empty input"
519        );
520        assert_eq!(
521            signed.authorization,
522            "HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256\
523             &Signature=AVAmeAnhXob2LgKZ6VrF4D/t77DHKr6RgOEOep19Ffw="
524        );
525    }
526
527    // -- the string to sign -----------------------------------------------
528
529    #[test]
530    fn the_string_to_sign_has_two_newlines_then_semicolons() {
531        // The separator changes partway through, which is the detail that
532        // is easiest to get wrong by analogy with other Azure schemes.
533        let hash = content_hash(b"");
534        let signed = string_to_sign("GET", "/x?a=1", HOST, DATE, &hash);
535
536        assert_eq!(signed, format!("GET\n/x?a=1\n{DATE};{HOST};{hash}"));
537        assert_eq!(signed.matches('\n').count(), 2);
538        assert_eq!(signed.matches(';').count(), 2);
539    }
540
541    #[test]
542    fn the_method_is_uppercased_and_nothing_else_changes_case() {
543        let hash = content_hash(b"");
544        let lower = string_to_sign("post", "/Emails:Send", HOST, DATE, &hash);
545        let upper = string_to_sign("POST", "/Emails:Send", HOST, DATE, &hash);
546
547        assert_eq!(lower, upper);
548        assert!(lower.contains("/Emails:Send"), "the path keeps its case");
549    }
550
551    #[test]
552    fn the_query_string_is_part_of_what_is_signed() {
553        // Omitting `?api-version=…` is a signature mismatch, not a 400.
554        let with = signer().sign("GET", "/x?api-version=1", HOST, DATE, b"");
555        let without = signer().sign("GET", "/x", HOST, DATE, b"");
556
557        assert_ne!(with.authorization, without.authorization);
558    }
559
560    #[test]
561    fn the_host_is_signed_as_well_as_connected_to() {
562        let one = signer().sign("GET", "/x", HOST, DATE, b"");
563        let two = signer().sign("GET", "/x", "other.communication.azure.com", DATE, b"");
564
565        assert_ne!(one.authorization, two.authorization);
566    }
567
568    #[test]
569    fn a_changed_body_changes_the_signature() {
570        // The point of hashing the body into the signed string.
571        let one = signer().sign("POST", "/x", HOST, DATE, b"{}");
572        let two = signer().sign("POST", "/x", HOST, DATE, b"{ }");
573
574        assert_ne!(one.content_hash, two.content_hash);
575        assert_ne!(one.authorization, two.authorization);
576    }
577
578    // -- the connection string --------------------------------------------
579
580    #[test]
581    fn a_connection_string_is_split_into_its_parts() {
582        let parsed =
583            ConnectionString::parse("endpoint=https://x.communication.azure.com/;accesskey=c2VjcmV0")
584                .unwrap();
585
586        assert_eq!(parsed.endpoint(), "https://x.communication.azure.com");
587        assert_eq!(parsed.access_key(), "c2VjcmV0");
588        assert_eq!(parsed.host(), "x.communication.azure.com");
589    }
590
591    #[test]
592    fn a_base64_key_keeps_its_padding() {
593        // THE subtle one. An access key is base64 and routinely ends in
594        // `=`; splitting on every `=` rather than the first would truncate
595        // it, and the signature would then be wrong in a way that looks
596        // like a permissions problem.
597        let parsed = ConnectionString::parse(&format!(
598            "endpoint=https://x.communication.azure.com/;accesskey={KEY}"
599        ))
600        .unwrap();
601
602        assert_eq!(parsed.access_key(), KEY);
603        assert!(parsed.access_key().ends_with('='));
604    }
605
606    #[test]
607    fn part_names_are_matched_case_insensitively() {
608        let parsed =
609            ConnectionString::parse("Endpoint=https://x.communication.azure.com;AccessKey=c2VjcmV0")
610                .unwrap();
611
612        assert_eq!(parsed.host(), "x.communication.azure.com");
613        assert_eq!(parsed.access_key(), "c2VjcmV0");
614    }
615
616    #[test]
617    fn a_missing_part_is_named_without_echoing_the_string() {
618        assert_eq!(
619            ConnectionString::parse("accesskey=c2VjcmV0").unwrap_err(),
620            ParseError::NoEndpoint
621        );
622        assert_eq!(
623            ConnectionString::parse("endpoint=https://x/").unwrap_err(),
624            ParseError::NoAccessKey
625        );
626        assert!(!ParseError::NoEndpoint.to_string().contains("accesskey"));
627    }
628
629    #[test]
630    fn a_trailing_slash_is_removed_so_a_join_cannot_double_up() {
631        let with = ConnectionString::parse("endpoint=https://x.y/;accesskey=c2VjcmV0").unwrap();
632        let without = ConnectionString::parse("endpoint=https://x.y;accesskey=c2VjcmV0").unwrap();
633
634        assert_eq!(with.endpoint(), without.endpoint());
635    }
636
637    // -- keys and secrecy --------------------------------------------------
638
639    #[test]
640    fn a_key_that_is_not_base64_is_rejected_at_construction() {
641        assert_eq!(Signer::new("not base64!!!").unwrap_err(), KeyError::NotBase64);
642    }
643
644    #[test]
645    fn nothing_prints_a_key() {
646        // These types are the ones most likely to reach a log line.
647        assert_eq!(format!("{:?}", signer()), "Signer(<redacted>)");
648
649        let parsed = ConnectionString::parse(&format!(
650            "endpoint=https://x.communication.azure.com;accesskey={KEY}"
651        ))
652        .unwrap();
653        let printed = format!("{parsed:?}");
654
655        assert!(printed.contains("x.communication.azure.com"));
656        assert!(printed.contains("<redacted>"));
657        assert!(!printed.contains("AAAA"), "{printed}");
658    }
659
660    // -- headers and date --------------------------------------------------
661
662    #[test]
663    fn all_three_headers_are_returned_in_a_fixed_order() {
664        let signed = signer().sign("GET", "/x", HOST, DATE, b"");
665        let names: Vec<&str> = signed.headers().iter().map(|(name, _)| *name).collect();
666
667        assert_eq!(
668            names,
669            ["x-ms-date", "x-ms-content-sha256", "Authorization"]
670        );
671        assert_eq!(signed.headers()[0].1, DATE, "the signed date, verbatim");
672    }
673
674    #[test]
675    fn the_date_is_lowercase_rfc_1123_in_gmt() {
676        let formatted = date(datetime!(2026-08-22 09:15:00 UTC));
677
678        assert_eq!(formatted, DATE);
679        assert!(!formatted.contains("+0000"));
680    }
681
682    #[test]
683    fn a_non_utc_input_is_converted_before_formatting() {
684        assert_eq!(
685            date(datetime!(2026-08-22 11:15:00 +2:00)),
686            date(datetime!(2026-08-22 09:15:00 UTC))
687        );
688    }
689}