cosmos_signature/lib.rs
1//! The Azure Cosmos DB master-key `Authorization` header.
2//!
3//! Pure functions and known-answer tests. No HTTP client, no async runtime,
4//! no TLS stack — this crate computes a header value and stops.
5//!
6//! # Why it is worth having separately
7//!
8//! Three details of the signing algorithm each produce an indistinguishable
9//! `401`, and none can be checked against a live account without a
10//! subscription:
11//!
12//! 1. **The case of each line.** The verb and the resource type are
13//! lowercased; the resource link is **not**. Lowercasing the link too is
14//! the classic mistake.
15//! 2. **The date appears identically in two places** — in the string to
16//! sign and in the `x-ms-date` header — and must be lowercase RFC 1123
17//! in GMT in both.
18//! 3. **There is a trailing empty line.** The string to sign ends `\n\n`.
19//!
20//! All three can be checked against the published algorithm, here, offline.
21//! [`MasterKey`] does that; the transport is somebody else's problem.
22//!
23//! # Examples
24//!
25//! ```
26//! use cosmos_signature::{MasterKey, ResourceType, date};
27//! use time::macros::datetime;
28//!
29//! # fn main() -> Result<(), cosmos_signature::KeyError> {
30//! // The account key, as the Azure portal prints it.
31//! let key = MasterKey::new("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")?;
32//!
33//! let when = date(datetime!(2026-08-22 09:15:00 UTC));
34//! let header = key.authorization("GET", ResourceType::Docs, "dbs/MyDb/colls/MyColl/docs/Config", &when);
35//!
36//! // Send `header` as `Authorization` and `when` as `x-ms-date` — the same
37//! // string, in both places.
38//! assert!(header.starts_with("type%3Dmaster"));
39//! assert_eq!(when, "sat, 22 aug 2026 09:15:00 gmt");
40//! # Ok(())
41//! # }
42//! ```
43
44#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
45
46use std::fmt;
47
48use base64::Engine as _;
49use hmac::{Hmac, Mac};
50use sha2::Sha256;
51use time::OffsetDateTime;
52use time::format_description::well_known::Rfc2822;
53
54/// The `x-ms-version` to send alongside a signature computed here.
55///
56/// Pinned rather than left to the caller because a wrong one is a rejection
57/// with no useful message. Override it if you need a newer API surface.
58pub const DEFAULT_API_VERSION: &str = "2018-12-31";
59
60/// Which kind of resource a request addresses.
61///
62/// Lowercased in the string to sign, which is why this is an enum rather
63/// than a `&str` a caller might capitalise.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65pub enum ResourceType {
66 /// A database.
67 Dbs,
68 /// A container (historically a collection).
69 Colls,
70 /// A document.
71 Docs,
72 /// A stored procedure.
73 Sprocs,
74 /// A user-defined function.
75 Udfs,
76 /// A trigger.
77 Triggers,
78 /// A user.
79 Users,
80 /// A permission.
81 Permissions,
82 /// An attachment.
83 Attachments,
84 /// A partition key range.
85 PkRanges,
86 /// An offer (throughput).
87 Offers,
88}
89
90impl ResourceType {
91 /// As it appears in the string to sign — always lowercase.
92 #[must_use]
93 pub const fn as_str(self) -> &'static str {
94 match self {
95 Self::Dbs => "dbs",
96 Self::Colls => "colls",
97 Self::Docs => "docs",
98 Self::Sprocs => "sprocs",
99 Self::Udfs => "udfs",
100 Self::Triggers => "triggers",
101 Self::Users => "users",
102 Self::Permissions => "permissions",
103 Self::Attachments => "attachments",
104 Self::PkRanges => "pkranges",
105 Self::Offers => "offers",
106 }
107 }
108}
109
110impl fmt::Display for ResourceType {
111 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112 formatter.write_str(self.as_str())
113 }
114}
115
116/// Why an account key could not be used for signing.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum KeyError {
119 /// The key is not valid base64.
120 ///
121 /// A Cosmos account key is base64 and is decoded before use. Signing
122 /// with the base64 *text* instead produces a header that looks right
123 /// and is always rejected — so this is caught at construction rather
124 /// than becoming a `401` in production.
125 NotBase64,
126 /// The decoded key cannot be used as an HMAC-SHA256 key.
127 Unusable,
128}
129
130impl fmt::Display for KeyError {
131 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132 // The key itself never appears here: this type is the thing most
133 // likely to be logged.
134 match self {
135 Self::NotBase64 => formatter.write_str(
136 "the Cosmos account key is not valid base64; it is the key as \
137 the Azure portal prints it",
138 ),
139 Self::Unusable => {
140 formatter.write_str("the Cosmos account key is not a usable signing key")
141 }
142 }
143 }
144}
145
146impl std::error::Error for KeyError {}
147
148/// A validated Cosmos DB account key, ready to sign with.
149///
150/// The key is decoded once, at construction, so a malformed one is a
151/// configuration error at startup rather than a `401` at the first request.
152///
153/// # This type does not print its key
154///
155/// [`Debug`] renders `MasterKey(<redacted>)`. It holds the decoded bytes of
156/// an account key, and a struct containing one ends up in a log line
157/// eventually.
158#[derive(Clone)]
159pub struct MasterKey {
160 /// The decoded key bytes.
161 decoded: Vec<u8>,
162}
163
164impl fmt::Debug for MasterKey {
165 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166 formatter.write_str("MasterKey(<redacted>)")
167 }
168}
169
170impl MasterKey {
171 /// Decode and validate an account key.
172 ///
173 /// # Errors
174 ///
175 /// [`KeyError`] when the key is not base64, or is not usable as an
176 /// HMAC-SHA256 key.
177 pub fn new(key: &str) -> Result<Self, KeyError> {
178 let decoded = base64::engine::general_purpose::STANDARD
179 .decode(key.trim())
180 .map_err(|_| KeyError::NotBase64)?;
181
182 // Validate now rather than at the first signature.
183 <Hmac<Sha256>>::new_from_slice(&decoded).map_err(|_| KeyError::Unusable)?;
184
185 Ok(Self { decoded })
186 }
187
188 /// The `Authorization` header value for one request.
189 ///
190 /// `date` must be the same string you send as `x-ms-date`; produce it
191 /// with [`date`] or [`now`].
192 ///
193 /// The result is already percent-encoded and goes into the header
194 /// as-is.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// use cosmos_signature::{MasterKey, ResourceType};
200 ///
201 /// # fn main() -> Result<(), cosmos_signature::KeyError> {
202 /// let key = MasterKey::new("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")?;
203 /// let header = key.authorization(
204 /// "GET",
205 /// ResourceType::Docs,
206 /// "dbs/MyDb/colls/MyColl/docs/Config",
207 /// "sat, 22 aug 2026 09:15:00 gmt",
208 /// );
209 ///
210 /// assert_eq!(
211 /// header,
212 /// "type%3Dmaster%26ver%3D1.0%26sig%3Ds3owIeiRRbneZNM0zO8OWQ5CfQf4NmVge76xBeJG84I%3D"
213 /// );
214 /// # Ok(())
215 /// # }
216 /// ```
217 #[must_use]
218 pub fn authorization(
219 &self,
220 verb: &str,
221 resource_type: ResourceType,
222 resource_link: &str,
223 date: &str,
224 ) -> String {
225 let signature = self.sign(&string_to_sign(verb, resource_type, resource_link, date));
226 percent_encode(&format!("type=master&ver=1.0&sig={signature}"))
227 }
228
229 /// The raw base64 signature of an arbitrary string to sign.
230 ///
231 /// For a caller building a header shape this crate does not cover.
232 #[must_use]
233 pub fn sign(&self, string_to_sign: &str) -> String {
234 // Cannot fail: the key was validated in `new`.
235 let Ok(mut mac) = <Hmac<Sha256>>::new_from_slice(&self.decoded) else {
236 unreachable!("the key was validated at construction")
237 };
238 mac.update(string_to_sign.as_bytes());
239
240 base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())
241 }
242}
243
244/// The date format Cosmos wants: lowercase RFC 1123 in GMT.
245///
246/// `time` spells RFC 2822 rather than 1123, and the two agree for this
247/// purpose except that 2822 writes `+0000` where 1123 writes `GMT` — so
248/// that substitution is made explicitly rather than hoped for.
249///
250/// A non-UTC input is converted before formatting. The header and the
251/// signature must carry the same instant; a local-offset timestamp
252/// formatted as-is is a `401` that looks like a clock problem.
253///
254/// # Examples
255///
256/// ```
257/// use cosmos_signature::date;
258/// use time::macros::datetime;
259///
260/// assert_eq!(date(datetime!(2026-08-22 09:15:00 UTC)), "sat, 22 aug 2026 09:15:00 gmt");
261///
262/// // An offset input gives the same answer as its UTC equivalent.
263/// assert_eq!(
264/// date(datetime!(2026-08-22 11:15:00 +2:00)),
265/// date(datetime!(2026-08-22 09:15:00 UTC))
266/// );
267/// ```
268#[must_use]
269pub fn date(at: OffsetDateTime) -> String {
270 let formatted = at
271 .to_offset(time::UtcOffset::UTC)
272 .format(&Rfc2822)
273 .unwrap_or_default();
274
275 formatted.replace("+0000", "GMT").to_lowercase()
276}
277
278/// [`date`] for the current moment.
279#[must_use]
280pub fn now() -> String {
281 date(OffsetDateTime::now_utc())
282}
283
284/// The five-line string a Cosmos signature covers.
285///
286/// Exposed because it is the thing worth asserting in a test: the case of
287/// each line and the trailing empty line are what a `401` is usually
288/// hiding.
289///
290/// # Examples
291///
292/// ```
293/// use cosmos_signature::{string_to_sign, ResourceType};
294///
295/// let signed = string_to_sign(
296/// "GET",
297/// ResourceType::Docs,
298/// "dbs/MyDb/colls/MyColl",
299/// "sat, 22 aug 2026 09:15:00 gmt",
300/// );
301///
302/// // The verb and the resource type are lowercased; the link keeps its case.
303/// assert!(signed.starts_with("get\ndocs\ndbs/MyDb/colls/MyColl\n"));
304/// // And it ends with an empty fifth line.
305/// assert!(signed.ends_with("\n\n"));
306/// ```
307#[must_use]
308pub fn string_to_sign(
309 verb: &str,
310 resource_type: ResourceType,
311 resource_link: &str,
312 date: &str,
313) -> String {
314 // Verb and type lowercased, the link **not**, the date lowercased, and
315 // a trailing empty line.
316 format!(
317 "{}\n{}\n{}\n{}\n\n",
318 verb.to_lowercase(),
319 resource_type.as_str(),
320 resource_link,
321 date.to_lowercase(),
322 )
323}
324
325/// Percent-encode a header value.
326///
327/// A base64 signature contains `+`, `/` and `=`, all of which change
328/// meaning in a header Cosmos parses as a query string.
329fn percent_encode(value: &str) -> String {
330 let mut out = String::with_capacity(value.len() * 2);
331 for byte in value.bytes() {
332 match byte {
333 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
334 out.push(byte as char);
335 }
336 _ => {
337 use fmt::Write as _;
338 // Cannot fail: writing into a String.
339 let _ = write!(out, "%{byte:02X}");
340 }
341 }
342 }
343 out
344}
345
346/// The resource link for a database: `dbs/{database}`.
347///
348/// Cosmos calls this the "resource link": the path **without** a leading or
349/// trailing slash.
350#[must_use]
351pub fn database_link(database: &str) -> String {
352 format!("dbs/{database}")
353}
354
355/// The resource link for a container: `dbs/{database}/colls/{container}`.
356#[must_use]
357pub fn container_link(database: &str, container: &str) -> String {
358 format!("dbs/{database}/colls/{container}")
359}
360
361/// The resource link for one document.
362///
363/// # Examples
364///
365/// ```
366/// use cosmos_signature::document_link;
367///
368/// assert_eq!(document_link("MyDb", "MyColl", "Config"), "dbs/MyDb/colls/MyColl/docs/Config");
369/// ```
370#[must_use]
371pub fn document_link(database: &str, container: &str, id: &str) -> String {
372 format!("dbs/{database}/colls/{container}/docs/{id}")
373}
374
375/// The URL for one document.
376#[must_use]
377pub fn document_url(endpoint: &str, database: &str, container: &str, id: &str) -> String {
378 format!(
379 "{}/{}",
380 endpoint.trim_end_matches('/'),
381 document_link(database, container, id)
382 )
383}
384
385/// The URL for a container's document collection.
386///
387/// Note the asymmetry that catches people: the URL ends `/docs`, but the
388/// resource link a create signs is the *container's* link, without it.
389///
390/// # Examples
391///
392/// ```
393/// use cosmos_signature::{documents_url, container_link};
394///
395/// assert_eq!(
396/// documents_url("https://acct.documents.azure.com/", "MyDb", "MyColl"),
397/// "https://acct.documents.azure.com/dbs/MyDb/colls/MyColl/docs"
398/// );
399/// assert_eq!(container_link("MyDb", "MyColl"), "dbs/MyDb/colls/MyColl");
400/// ```
401#[must_use]
402pub fn documents_url(endpoint: &str, database: &str, container: &str) -> String {
403 format!(
404 "{}/{}/docs",
405 endpoint.trim_end_matches('/'),
406 container_link(database, container)
407 )
408}
409
410#[cfg(test)]
411mod tests {
412 use time::macros::datetime;
413
414 use super::*;
415
416 /// Not a real key: 32 zero bytes, base64-encoded, so the vectors below
417 /// are reproducible by anyone.
418 const KEY: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
419
420 /// The date the vectors below are signed at.
421 const DATE: &str = "sat, 22 aug 2026 09:15:00 gmt";
422
423 fn key() -> MasterKey {
424 MasterKey::new(KEY).expect("a valid test key")
425 }
426
427 // -- known answers ----------------------------------------------------
428 //
429 // Computed by an independent implementation (Python's `hmac` and
430 // `base64`) rather than by this code, so they check the algorithm
431 // rather than merely pinning current behaviour.
432
433 #[test]
434 fn a_document_read_matches_the_known_answer() {
435 assert_eq!(
436 key().authorization(
437 "GET",
438 ResourceType::Docs,
439 "dbs/MyDb/colls/MyColl/docs/Config",
440 DATE
441 ),
442 "type%3Dmaster%26ver%3D1.0%26sig%3Ds3owIeiRRbneZNM0zO8OWQ5CfQf4NmVge76xBeJG84I%3D"
443 );
444 }
445
446 #[test]
447 fn a_document_create_matches_the_known_answer() {
448 // A create signs the *container's* link, not the `/docs` URL.
449 assert_eq!(
450 key().authorization("POST", ResourceType::Docs, "dbs/MyDb/colls/MyColl", DATE),
451 "type%3Dmaster%26ver%3D1.0%26sig%3Dmy261ykrcdRVqxW85qm9WnHyvIM5DFm%2FgnngDxjTBog%3D"
452 );
453 }
454
455 #[test]
456 fn an_account_level_read_with_an_empty_link_matches_the_known_answer() {
457 // Listing databases: resource type `dbs`, resource link empty.
458 assert_eq!(
459 key().authorization("GET", ResourceType::Dbs, "", DATE),
460 "type%3Dmaster%26ver%3D1.0%26sig%3DlcYK2aeMBIOl9qtHwfupMHpJbmKOzaydCHB%2Bb5seaKw%3D"
461 );
462 }
463
464 // -- the three details a 401 hides ------------------------------------
465
466 #[test]
467 fn the_string_to_sign_lowercases_only_what_it_should() {
468 // Lowercasing the resource link too is the classic mistake, and
469 // Cosmos answers 401 either way.
470 let signed = string_to_sign(
471 "GET",
472 ResourceType::Docs,
473 "dbs/MyDatabase/colls/MyContainer/docs/Config",
474 DATE,
475 );
476
477 assert_eq!(
478 signed,
479 "get\ndocs\ndbs/MyDatabase/colls/MyContainer/docs/Config\n\
480 sat, 22 aug 2026 09:15:00 gmt\n\n"
481 );
482 }
483
484 #[test]
485 fn the_string_to_sign_ends_with_an_empty_line() {
486 // Five newline-terminated fields: verb, type, link, date, and an
487 // empty one. The empty fifth is the detail that is easiest to omit
488 // and impossible to diagnose from the 401 it causes.
489 let signed = string_to_sign("GET", ResourceType::Dbs, "", DATE);
490
491 assert_eq!(signed, format!("get\ndbs\n\n{DATE}\n\n"));
492 assert!(signed.ends_with("\n\n"), "{signed:?}");
493
494 let fields: Vec<&str> = signed.split('\n').collect();
495 assert_eq!(fields, ["get", "dbs", "", DATE, "", ""]);
496 }
497
498 #[test]
499 fn a_date_given_in_mixed_case_is_lowercased_by_the_signer() {
500 // The header value and the signed value must agree; accepting a
501 // mixed-case date and signing it verbatim would not.
502 assert_eq!(
503 key().authorization("GET", ResourceType::Dbs, "", "Sat, 22 Aug 2026 09:15:00 GMT"),
504 key().authorization("GET", ResourceType::Dbs, "", DATE)
505 );
506 }
507
508 #[test]
509 fn the_date_is_lowercase_rfc_1123_in_gmt() {
510 let formatted = date(datetime!(2026-08-22 09:15:00 UTC));
511
512 assert_eq!(formatted, DATE);
513 assert!(!formatted.contains("+0000"), "{formatted}");
514 assert_eq!(formatted, formatted.to_lowercase());
515 }
516
517 #[test]
518 fn a_non_utc_input_is_converted_before_formatting() {
519 assert_eq!(
520 date(datetime!(2026-08-22 11:15:00 +2:00)),
521 date(datetime!(2026-08-22 09:15:00 UTC))
522 );
523 }
524
525 // -- the key ----------------------------------------------------------
526
527 #[test]
528 fn a_key_that_is_not_base64_is_rejected_at_construction() {
529 // Rather than becoming a 401 at the first request.
530 // `MasterKey` deliberately has no `PartialEq`: comparing account
531 // keys is not something this crate should make convenient.
532 assert_eq!(
533 MasterKey::new("not base64!!!").unwrap_err(),
534 KeyError::NotBase64
535 );
536 }
537
538 #[test]
539 fn surrounding_whitespace_in_a_key_is_tolerated() {
540 // Keys arrive from environment variables and get pasted.
541 assert!(MasterKey::new(&format!(" {KEY}\n")).is_ok());
542 }
543
544 #[test]
545 fn a_key_never_prints() {
546 // This type is the thing most likely to end up in a log line.
547 let printed = format!("{:?}", key());
548 assert_eq!(printed, "MasterKey(<redacted>)");
549 assert!(!printed.contains("AAAA"));
550
551 // Nor does the error type.
552 assert!(!KeyError::NotBase64.to_string().contains("AAAA"));
553 }
554
555 // -- encoding ---------------------------------------------------------
556
557 #[test]
558 fn the_header_is_percent_encoded() {
559 // A base64 signature contains `+`, `/` and `=`, all of which change
560 // meaning in a header Cosmos parses as a query string.
561 let header = key().authorization("GET", ResourceType::Docs, "dbs/a/colls/b/docs/c", DATE);
562
563 assert!(!header.contains('='), "{header}");
564 assert!(!header.contains('&'), "{header}");
565 assert!(!header.contains('+'), "{header}");
566 assert!(!header.contains('/'), "{header}");
567 assert!(header.starts_with("type%3Dmaster%26ver%3D1.0%26sig%3D"));
568 }
569
570 #[test]
571 fn every_resource_type_is_lowercase() {
572 for kind in [
573 ResourceType::Dbs,
574 ResourceType::Colls,
575 ResourceType::Docs,
576 ResourceType::Sprocs,
577 ResourceType::Udfs,
578 ResourceType::Triggers,
579 ResourceType::Users,
580 ResourceType::Permissions,
581 ResourceType::Attachments,
582 ResourceType::PkRanges,
583 ResourceType::Offers,
584 ] {
585 assert_eq!(kind.as_str(), kind.as_str().to_lowercase(), "{kind}");
586 }
587 }
588
589 // -- links ------------------------------------------------------------
590
591 #[test]
592 fn links_carry_no_leading_or_trailing_slash() {
593 assert_eq!(database_link("D"), "dbs/D");
594 assert_eq!(container_link("D", "C"), "dbs/D/colls/C");
595 assert_eq!(document_link("D", "C", "i"), "dbs/D/colls/C/docs/i");
596 }
597
598 #[test]
599 fn a_trailing_slash_on_the_endpoint_does_not_double_up() {
600 assert_eq!(
601 document_url("https://a.documents.azure.com/", "D", "C", "i"),
602 document_url("https://a.documents.azure.com", "D", "C", "i")
603 );
604 assert!(!documents_url("https://a/", "D", "C").contains("//dbs"));
605 }
606}