From 6306c324a9ecd6735d75378e7ebf198d895fda2a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:28:17 +0000 Subject: [PATCH 1/4] fix(auth): read the Date header and check the date as DynamoDB does ExtendDB read the request date from X-Amz-Date only. With only a Date header, it answered that the request needs X-Amz-Date. It checked the date after the whole Authorization parse. Its text for a date in another form named no value. DynamoDB reads Date when the request has no X-Amz-Date, and an empty value is no date. It checks the date after the missing parameters and before the Bearer answer, the algorithm and the credential. For a value in another form it answers "Date must be in ISO-8601 'basic format'. Got ''. See http://en.wikipedia.org/wiki/ISO_8601". Measured in us-east-1 on 21 Nov 2026. request_date picks the header, and the parse takes the timestamp check as a closure that it runs at that point. parse_authorization keeps its signature for its other callers. Fixes #1289. --- crates/auth/src/lib.rs | 14 ++++-- crates/auth/src/sigv4/parse.rs | 49 +++++++++++++++++++ crates/auth/src/sigv4/verify.rs | 80 ++++++++++++++++++++++++------- tests/test_auth_error_fidelity.py | 37 ++++++++++++-- 4 files changed, 155 insertions(+), 25 deletions(-) diff --git a/crates/auth/src/lib.rs b/crates/auth/src/lib.rs index 3f9dc3472..561daa9ad 100644 --- a/crates/auth/src/lib.rs +++ b/crates/auth/src/lib.rs @@ -140,8 +140,7 @@ impl AuthProvider for BuiltinAuthProvider { .map_or(&b""[..], |value| value.as_bytes()); // Parse Authorization header - let has_date = headers.contains_key("x-amz-date") || headers.contains_key("date"); - let parsed = sigv4::parse::parse_authorization(auth_header, has_date)?; + let has_date = sigv4::verify::request_date(headers).is_some(); // The service checks the request timestamp, then the credential // scope, then looks the key up (measured 2026-10-23: an unknown key @@ -152,12 +151,17 @@ impl AuthProvider for BuiltinAuthProvider { // Neither check reads the stored credential, so running them first // leaves the S-5 timing argument below unchanged. // - // Validate timestamp (within 15 minutes). The X-Amz-Date value it + // The parse runs the timestamp check (within 15 minutes) after the + // missing parameters and before the algorithm and the credential, + // as the service does (measured 2026-11-21). The request date it // returns is what the scope date is compared against. - let timestamp = sigv4::verify::validate_timestamp(headers)?; + let (parsed, timestamp) = + sigv4::parse::parse_authorization_with_date_check(auth_header, has_date, || { + sigv4::verify::validate_timestamp(headers) + })?; // The credential scope must name this server's region, the dynamodb - // service and the date of X-Amz-Date; the service reports every + // service and the request date; the service reports every // complaint in one message when more than one is wrong. sigv4::verify::check_scope(&parsed, self.credentials.region(), ×tamp)?; diff --git a/crates/auth/src/sigv4/parse.rs b/crates/auth/src/sigv4/parse.rs index 565fda306..584731bfb 100755 --- a/crates/auth/src/sigv4/parse.rs +++ b/crates/auth/src/sigv4/parse.rs @@ -46,6 +46,18 @@ pub fn parse_authorization( header: &[u8], has_date: bool, ) -> Result { + parse_authorization_with_date_check(header, has_date, || Ok(())).map(|(parsed, ())| parsed) +} + +/// [`parse_authorization`], running `check_date` where the service checks the +/// request date: after the missing parameters, before the `Bearer` answer, +/// the algorithm and the credential (measured 2026-11-21). Returns the parsed +/// header and the value `check_date` returns. +pub fn parse_authorization_with_date_check( + header: &[u8], + has_date: bool, + check_date: impl FnOnce() -> Result, +) -> Result<(ParsedAuthorization, T), DynamoDbError> { // S-2: Cap Authorization header length to prevent heap abuse from oversized headers. const MAX_AUTH_HEADER_LEN: usize = 8 * 1024; if header.len() > MAX_AUTH_HEADER_LEN { @@ -140,6 +152,8 @@ pub fn parse_authorization( ))); }; + let checked = check_date()?; + // Measured 2026-11-21: DynamoDB answers a `Bearer` value that passes the // checks above with this text. Its text for a request with no // Authorization header is `Request is missing Authentication Token`, which @@ -174,6 +188,7 @@ pub fn parse_authorization( signed_headers: signed_headers.to_owned(), signature: signature.to_owned(), }) + .map(|parsed| (parsed, checked)) } fn incomplete(msg: &str) -> DynamoDbError { @@ -389,6 +404,40 @@ mod tests { assert!(parse_authorization(header.as_bytes(), true).is_err()); } + /// Measured 2026-11-21 with a `Date` value the service refuses: a missing + /// parameter, a part with no '=' and `AWS4-` in another case come first, + /// and the date before the `Bearer` answer, another algorithm and the + /// credential's form. + #[test] + fn the_date_check_runs_after_the_missing_parameters() { + let cred = "Credential=AKID/20260415/us-east-1/dynamodb/aws4_request"; + let rest = format!("{cred}, SignedHeaders=host, Signature=abc"); + let rows = [ + ( + format!("AWS4-HMAC-SHA256 {cred}, SignedHeaders=host"), + false, + ), + ( + "AWS4-HMAC-SHA256 Credential, SignedHeaders=host, Signature=abc".to_owned(), + false, + ), + (format!("aws4-hmac-sha256 {rest}"), false), + (format!("Bearer {rest}"), true), + (format!("AWS4-X {rest}"), true), + ( + "AWS4-HMAC-SHA256 Credential=x, SignedHeaders=host, Signature=abc".to_owned(), + true, + ), + (format!("AWS4-HMAC-SHA256 {rest}"), true), + ]; + let date = || Err::<(), _>(incomplete("date")); + for (header, date_first) in rows { + let got = parse_authorization_with_date_check(header.as_bytes(), true, date); + let is_date = matches!(&got, Err(DynamoDbError::IncompleteSignature(m)) if m == "date"); + assert_eq!(is_date, date_first, "{header}: {got:?}"); + } + } + #[test] fn reject_oversized_header() { // S-2: Headers exceeding 8 KB must be rejected. diff --git a/crates/auth/src/sigv4/verify.rs b/crates/auth/src/sigv4/verify.rs index 7b2b6a891..09496ba41 100755 --- a/crates/auth/src/sigv4/verify.rs +++ b/crates/auth/src/sigv4/verify.rs @@ -18,7 +18,7 @@ use super::signing_key; const MAX_CLOCK_SKEW_SECS: i64 = 15 * 60; /// The scope complaint for a date that is not the `YYYYMMDD` prefix of -/// `X-Amz-Date`, with the trailing period and space the service sends. +/// the request date, with the trailing period and space the service sends. pub(crate) const SCOPE_DATE_COMPLAINT: &str = "Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP. "; @@ -33,7 +33,7 @@ fn scope_date_matches(date: &str, timestamp: &str) -> bool { /// Check the credential scope's region, service and date against this server /// and the request timestamp. /// -/// `timestamp` is the `X-Amz-Date` value, which `validate_timestamp` returns. +/// `timestamp` is the request date, which `validate_timestamp` returns. /// /// The service reports every scope complaint in one message, region first, /// then service, then the date, each sentence ending with a space (measured @@ -106,7 +106,7 @@ pub fn verify_signature( )); } - // CB-5: Validate credential-scope date matches X-Amz-Date[..8]. The + // CB-5: Validate credential-scope date matches the request date[..8]. The // pre-lookup check_scope compares it too; this keeps the refusal for a // caller that verifies a signature on its own. let timestamp = extract_timestamp(headers)?; @@ -158,7 +158,8 @@ pub fn verify_signature( /// Validate the request timestamp is within ±15 minutes of now. /// -/// Returns the `X-Amz-Date` value, which the caller passes to `check_scope`. +/// Returns the request date (see `request_date`), which the caller passes to +/// `check_scope`. /// /// Returns `UnrecognizedClientException` if the timestamp is missing or out of range. /// Returns `InternalServerError` if the system clock is misconfigured. @@ -173,9 +174,10 @@ pub fn validate_timestamp(headers: &HeaderMap) -> Result .ok_or_else(|| DynamoDbError::InternalServerError("server clock error".to_owned()))?; let request_epoch = parse_iso8601_basic(×tamp).ok_or_else(|| { - DynamoDbError::IncompleteSignature( - "Date must be in ISO 8601 basic format (YYYYMMDDTHHMMSSZ)".to_owned(), - ) + // Measured 2026-11-21: the service echoes the value it refuses. + DynamoDbError::IncompleteSignature(format!( + "Date must be in ISO-8601 'basic format'. Got '{timestamp}'. See http://en.wikipedia.org/wiki/ISO_8601" + )) })?; let skew = (now - request_epoch).abs(); @@ -189,16 +191,24 @@ pub fn validate_timestamp(headers: &HeaderMap) -> Result } /// Extract the timestamp from `X-Amz-Date` header. +/// Without that header, the `Date` value counts (see `request_date`). fn extract_timestamp(headers: &HeaderMap) -> Result { + request_date(headers).map(str::to_owned).ok_or_else(|| { + DynamoDbError::IncompleteSignature( + "Authorization header requires existence of 'X-Amz-Date' header".to_owned(), + ) + }) +} + +/// The request's date: the `X-Amz-Date` value when the request has that +/// header, else the `Date` value. Measured 2026-11-21: the service reads +/// `Date` only when `X-Amz-Date` is absent, and an empty value is no date. +pub(crate) fn request_date(headers: &HeaderMap) -> Option<&str> { headers .get("x-amz-date") + .or_else(|| headers.get("date")) .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - .ok_or_else(|| { - DynamoDbError::IncompleteSignature( - "Authorization header requires existence of 'X-Amz-Date' header".to_owned(), - ) - }) + .filter(|v| !v.is_empty()) } /// Parse ISO 8601 basic format `YYYYMMDDTHHMMSSZ` to Unix epoch seconds. @@ -273,11 +283,47 @@ mod tests { assert!(extract_timestamp(&headers).is_err()); } + /// Measured 2026-11-21: `Date` is read only when `X-Amz-Date` is absent, + /// and an empty value is no date. #[test] - fn extract_timestamp_present() { - let mut headers = HeaderMap::new(); - headers.insert("x-amz-date", "20260415T120000Z".parse().unwrap()); - assert_eq!(extract_timestamp(&headers).unwrap(), "20260415T120000Z"); + fn the_request_date_is_x_amz_date_else_date() { + let http = "Sat, 21 Nov 2026 01:36:16 GMT"; + let rows = [ + (vec![], None), + ( + vec![("x-amz-date", "20260415T120000Z")], + Some("20260415T120000Z"), + ), + (vec![("date", http)], Some(http)), + ( + vec![("x-amz-date", http), ("date", "20260415T120000Z")], + Some(http), + ), + (vec![("x-amz-date", ""), ("date", http)], None), + (vec![("date", "")], None), + ]; + for (pairs, want) in rows { + let mut headers = HeaderMap::new(); + for (name, value) in &pairs { + headers.insert(*name, value.parse().unwrap()); + } + assert_eq!(request_date(&headers), want, "{pairs:?}"); + } + } + + /// Measured 2026-11-21: the service echoes a date it cannot read. + #[test] + fn a_date_in_another_form_is_refused_with_its_value() { + let err = validate_timestamp(&make_headers("Sat, 21 Nov 2026 01:36:16 GMT")).unwrap_err(); + assert!( + matches!(err, DynamoDbError::IncompleteSignature(_)), + "{err:?}" + ); + assert_eq!( + err.message(), + "Date must be in ISO-8601 'basic format'. Got 'Sat, 21 Nov 2026 01:36:16 GMT'. \ + See http://en.wikipedia.org/wiki/ISO_8601" + ); } fn make_parsed(service: &str, date: &str, signed_headers: &str) -> ParsedAuthorization { diff --git a/tests/test_auth_error_fidelity.py b/tests/test_auth_error_fidelity.py index 88aa5d2ce..51ba6dafb 100755 --- a/tests/test_auth_error_fidelity.py +++ b/tests/test_auth_error_fidelity.py @@ -277,6 +277,8 @@ def _env_credentials() -> tuple[str, str, str | None]: _KEY = _PAIR.format("missing key") _CASE = "Algorithm must start with 'AWS4-'; got '{header}'" _UNSUPPORTED = "Unsupported AWS 'algorithm': '{}'. " +_HTTP_DATE = "Sat, 21 Nov 2026 01:36:16 GMT" +_DATE = f"Date must be in ISO-8601 'basic format'. Got '{_HTTP_DATE}'. See http://en.wikipedia.org/wiki/ISO_8601" def _missing(*names: str, date: bool = False) -> str: @@ -496,12 +498,13 @@ def test_duplicate_authorization_header_is_refused_on_the_data_plane(self): if self.endpoint_url is not None: assert text == "400 Bad Request", text[:200] - def _describe(self, authorization: str | None, date: str | None) -> tuple[int, dict]: + def _describe(self, authorization: str | None, date: str | list | None) -> tuple[int, dict]: """Send a DescribeTable of a table that does not exist. ``authorization`` goes out one byte per character, and None sends no Authorization header. ``date`` names a date header to send with the - current time: "X-Amz-Date", "Date" or None. + current time: "X-Amz-Date", "Date" or None. A list of (name, value) + pairs sends those headers instead. """ u = urlparse(self.url) headers = [ @@ -513,6 +516,8 @@ def _describe(self, authorization: str | None, date: str | None) -> tuple[int, d headers.append((date, time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()))) elif date == "Date": headers.append((date, email.utils.formatdate(usegmt=True))) + elif date is not None: + headers.extend(date) if authorization is not None: headers.append(("Authorization", authorization)) status, text, _ = self._raw_request( @@ -581,13 +586,31 @@ def _describe(self, authorization: str | None, date: str | None) -> tuple[int, d pytest.param(None, "Bearer a=b", _missing("Credential", "Signature", "SignedHeaders", date=True), id="bearer-unknown-key"), pytest.param(None, f"Bearer {_CRED}, {_SH}, {_SIG}", _missing(date=True), id="bearer-no-date"), + pytest.param([("Date", _HTTP_DATE)], f"{_ALG} {_CRED}, {_SH}, {_SIG}", _DATE, id="http-date-header"), + pytest.param([("X-Amz-Date", _HTTP_DATE)], f"{_ALG} {_CRED}, {_SH}, {_SIG}", _DATE, + id="http-x-amz-date"), + pytest.param([("X-Amz-Date", _HTTP_DATE), ("Date", "20261121T013616Z")], + f"{_ALG} {_CRED}, {_SH}, {_SIG}", _DATE, id="x-amz-date-before-date"), + pytest.param([("Date", _HTTP_DATE)], f"{_ALG} Credential=x, {_SH}, {_SIG}", _DATE, + id="http-date-before-credential"), + pytest.param([("Date", _HTTP_DATE)], f"AWS4-X {_CRED}, {_SH}, {_SIG}", _DATE, + id="http-date-before-algorithm"), + pytest.param([("Date", _HTTP_DATE)], f"Bearer {_CRED}, {_SH}, {_SIG}", _DATE, + id="http-date-before-bearer"), + pytest.param([("Date", "")], f"{_ALG} {_CRED}, {_SH}, {_SIG}", _missing(date=True), + id="empty-date-header"), + pytest.param([("X-Amz-Date", ""), ("Date", _HTTP_DATE)], f"{_ALG} {_CRED}, {_SH}, {_SIG}", + _missing(date=True), id="empty-x-amz-date-and-http-date"), ], ) def test_malformed_authorization_header(self, date, header, want): # Measured against the service on 2026-11-20 and 2026-11-21. AWS4- in # another case is refused first. A part with no '=' or no key is named # before any missing parameter. Every missing parameter and a missing - # date header are named in one message. Another algorithm comes last. + # date header are named in one message. A date the service cannot + # read comes next, before the Bearer answer, another algorithm and + # the credential. The service reads Date only when the request has no + # X-Amz-Date, and an empty value is no date. status, payload = self._describe(header, date) assert status == 400, (status, payload) assert payload["__type"].endswith("#IncompleteSignatureException"), payload @@ -617,6 +640,14 @@ def test_authorization_answered_as_another(self, date, header, reference): # answer to the same pairs split by commas. assert self._describe(header, date) == self._describe(reference, date) + def test_basic_date_header_is_the_request_date(self): + # Measured against the service on 2026-11-21: with no X-Amz-Date, a + # Date value in the basic format is the request date. Both requests + # get the complaint about the scope date of _CRED. + header = f"{_ALG} {_CRED}, {_SH}, {_SIG}" + now = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + assert self._describe(header, [("Date", now)]) == self._describe(header, "X-Amz-Date") + def test_session_token_with_a_long_term_key_is_rejected(self): _, _, env_token = _env_credentials() if env_token: From d82e5a2f94df69df3911859aef93d440f7551621 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:51:05 +0000 Subject: [PATCH 2/4] fix(auth): read a date header with a byte above 0x7F as a date DynamoDB reads each byte of X-Amz-Date and Date as a Latin-1 character. A value with a byte above 0x7F is therefore a date, and the format check refuses it with the value echoed. Before this change, ExtendDB dropped such a value. The request then got the missing date text. Tests hold the 15 minute window of a request dated only by Date, at 16 minutes before and after now. The comments on the request date and the security model manual name both date headers. The manual also gives the place of the date check among the checks of the parse. Measured in us-east-1 on 2 and 3 Dec 2026, each request twice. --- crates/auth/src/sigv4/parse.rs | 8 ++- crates/auth/src/sigv4/verify.rs | 92 ++++++++++++++++++++++++++++--- docs/manuals/10-security-model.md | 6 +- tests/test_auth_error_fidelity.py | 25 ++++++++- 4 files changed, 117 insertions(+), 14 deletions(-) diff --git a/crates/auth/src/sigv4/parse.rs b/crates/auth/src/sigv4/parse.rs index e615a837c..30614abea 100755 --- a/crates/auth/src/sigv4/parse.rs +++ b/crates/auth/src/sigv4/parse.rs @@ -73,7 +73,7 @@ pub fn parse_authorization_with_date_check( // Measured 2026-11-21: DynamoDB reads each byte as a Latin-1 character, // and hashes the value without the spaces and tabs at its ends. - let header: String = header.iter().copied().map(char::from).collect(); + let header = latin1(header); let header = header.trim_matches([' ', '\t']); let hash = || BASE64.encode(Sha256::digest(header)); @@ -221,6 +221,12 @@ fn incomplete(msg: &str) -> DynamoDbError { DynamoDbError::IncompleteSignature(msg.to_owned()) } +/// A header value with each byte read as a Latin-1 character, as DynamoDB +/// reads the `Authorization` and date headers. +pub(crate) fn latin1(value: &[u8]) -> String { + value.iter().copied().map(char::from).collect() +} + /// Split the first part off `value` as DynamoDB splits the header of an item /// operation: a part ends at a comma, a space or a tab, and a comma with the /// spaces and tabs around it ends one part. diff --git a/crates/auth/src/sigv4/verify.rs b/crates/auth/src/sigv4/verify.rs index 41b59b601..6e9915af0 100755 --- a/crates/auth/src/sigv4/verify.rs +++ b/crates/auth/src/sigv4/verify.rs @@ -161,12 +161,14 @@ pub fn verify_signature( /// Returns the request date (see `request_date`), which the caller passes to /// `check_scope`. /// -/// Returns `UnrecognizedClientException` if the timestamp is missing or out of range. +/// Returns `IncompleteSignature` if the request has no date or a date that +/// is not in the basic format, and `UnrecognizedClientException` if the date +/// is more than 15 minutes from now. /// Returns `InternalServerError` if the system clock is misconfigured. pub fn validate_timestamp(headers: &HeaderMap) -> Result { let timestamp = extract_timestamp(headers)?; - // Parse X-Amz-Date: YYYYMMDDTHHMMSSZ + // Parse the request date: YYYYMMDDTHHMMSSZ let now = web_time::SystemTime::now() .duration_since(web_time::UNIX_EPOCH) .ok() @@ -190,10 +192,10 @@ pub fn validate_timestamp(headers: &HeaderMap) -> Result Ok(timestamp) } -/// Extract the timestamp from `X-Amz-Date` header. -/// Without that header, the `Date` value counts (see `request_date`). +/// The request date (see `request_date`), or a refusal when the request has +/// none. fn extract_timestamp(headers: &HeaderMap) -> Result { - request_date(headers).map(str::to_owned).ok_or_else(|| { + request_date(headers).ok_or_else(|| { DynamoDbError::IncompleteSignature( "Authorization header requires existence of 'X-Amz-Date' header".to_owned(), ) @@ -203,11 +205,13 @@ fn extract_timestamp(headers: &HeaderMap) -> Result { /// The request's date: the `X-Amz-Date` value when the request has that /// header, else the `Date` value. Measured 2026-11-21: the service reads /// `Date` only when `X-Amz-Date` is absent, and an empty value is no date. -pub(crate) fn request_date(headers: &HeaderMap) -> Option<&str> { +/// Measured 2026-12-02: it reads each byte as a Latin-1 character, so a +/// value with a byte above 0x7F is a date that the format check refuses. +pub(crate) fn request_date(headers: &HeaderMap) -> Option { headers .get("x-amz-date") .or_else(|| headers.get("date")) - .and_then(|v| v.to_str().ok()) + .map(|v| super::parse::latin1(v.as_bytes())) .filter(|v| !v.is_empty()) } @@ -307,7 +311,77 @@ mod tests { for (name, value) in &pairs { headers.insert(*name, value.parse().unwrap()); } - assert_eq!(request_date(&headers), want, "{pairs:?}"); + assert_eq!(request_date(&headers).as_deref(), want, "{pairs:?}"); + } + } + + /// Measured 2026-12-02: a date value with a byte above 0x7F is read, with + /// `X-Amz-Date` ahead of `Date`, and refused with the value echoed. + #[test] + fn a_date_with_a_byte_above_0x7f_is_refused_with_its_value() { + let value: &[u8] = b"20261202T210318Z\x80"; + let valid: &[u8] = b"20261202T210318Z"; + let rows: [&[(&str, &[u8])]; 3] = [ + &[("x-amz-date", value)], + &[("date", value)], + &[("x-amz-date", value), ("date", valid)], + ]; + for pairs in rows { + let mut headers = HeaderMap::new(); + for (name, bytes) in pairs { + headers.insert(*name, http::HeaderValue::from_bytes(bytes).unwrap()); + } + let err = validate_timestamp(&headers).unwrap_err(); + assert!( + matches!(err, DynamoDbError::IncompleteSignature(_)), + "{err:?}" + ); + assert_eq!( + err.message(), + "Date must be in ISO-8601 'basic format'. Got '20261202T210318Z\u{80}'. \ + See http://en.wikipedia.org/wiki/ISO_8601", + "{pairs:?}" + ); + } + } + + /// A request dated only by `Date` has the window of one dated by + /// `X-Amz-Date`: measured 2026-12-03, the service refuses 16 minutes + /// either side and goes on at 14. The service's type and text for the + /// refusal differ from these (#805). + #[test] + fn a_date_header_has_the_window_of_x_amz_date() { + let basic = |minutes: i64| { + let at = time::OffsetDateTime::now_utc() + time::Duration::minutes(minutes); + format!( + "{:04}{:02}{:02}T{:02}{:02}{:02}Z", + at.year(), + at.month() as u8, + at.day(), + at.hour(), + at.minute(), + at.second(), + ) + }; + for (minutes, refused) in [(-16, true), (16, true), (-14, false), (14, false)] { + let mut headers = HeaderMap::new(); + headers.insert("date", basic(minutes).parse().unwrap()); + let got = validate_timestamp(&headers); + if refused { + let err = got.unwrap_err(); + assert!( + matches!(err, DynamoDbError::UnrecognizedClientException(_)), + "{minutes}: {err:?}" + ); + assert_eq!( + err.message(), + "Signature expired: the signature is too old or the request date is too far \ + in the future.", + "{minutes}" + ); + } else { + assert!(got.is_ok(), "{minutes}: {got:?}"); + } } } @@ -407,7 +481,7 @@ mod tests { } } - /// `validate_timestamp` hands the `X-Amz-Date` value back so the caller + /// `validate_timestamp` hands the request date back so the caller /// compares the scope date against the same string. #[test] fn validate_timestamp_returns_the_header_value() { diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 89d1add82..cb20ae98d 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -54,9 +54,9 @@ extenddb uses SigV4 signature verification with a local credential store and IAM The steps run in this order; every rejection is HTTP 400. 1. Read the `Authorization` header. A request with no header, or with a value that starts with neither `AWS4-` nor `Bearer` and a space, gets `MissingAuthenticationTokenException` -2. Parse the algorithm and the `Credential`, `SignedHeaders` and `Signature` parameters. Commas, spaces and tabs separate the parts. PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchGetItem, TransactGetItems and TransactWriteItems read the parameters by position, as the service does. The other operations read them by name. A malformed value gets `IncompleteSignatureException` with the service's text. The parse checks for a part with no `=` or no name first. On the item operations, a part with no `=` counts only when it is the last of the three and a parameter is missing. Then one message names the missing or empty parameters and a missing date header. After that, a `Bearer` value with the three parameters gets `MissingAuthenticationTokenException`. An algorithm other than `AWS4-HMAC-SHA256`, and then a credential that is not five parts separated by `/`, get `IncompleteSignatureException`. A request with more than one `host` or `authorization` header is refused before this point with a plain 400, as the service's front end does -3. Check `X-Amz-Date` against the server clock: more than 15 minutes of skew is `UnrecognizedClientException` (signature expired) -4. Check the credential scope: the region must be this server's `[server] region` and the service must be `dynamodb`; otherwise `InvalidSignatureException` carrying one sentence per failing part, region first, as the service reports it. The scope date must also be the `YYYYMMDD` prefix of `X-Amz-Date`, and its sentence comes after the region and service sentences +2. Parse the algorithm and the `Credential`, `SignedHeaders` and `Signature` parameters. Commas, spaces and tabs separate the parts. PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchGetItem, TransactGetItems and TransactWriteItems read the parameters by position, as the service does. The other operations read them by name. A malformed value gets `IncompleteSignatureException` with the service's text. The parse checks for a part with no `=` or no name first. On the item operations, a part with no `=` counts only when it is the last of the three and a parameter is missing. Then one message names the missing or empty parameters and a missing date header. The date check of step 3 runs next, as the service orders it. After that, a `Bearer` value with the three parameters gets `MissingAuthenticationTokenException`. An algorithm other than `AWS4-HMAC-SHA256`, and then a credential that is not five parts separated by `/`, get `IncompleteSignatureException`. A request with more than one `host` or `authorization` header is refused before this point with a plain 400, as the service's front end does +3. Check the request date against the server clock. The request date is the `X-Amz-Date` value, or the `Date` value when the request has no `X-Amz-Date` header, with each byte read as a Latin-1 character. An empty value is no date. A date that is not in the basic format `YYYYMMDDTHHMMSSZ` gets `IncompleteSignatureException`, which echoes the value. More than 15 minutes of skew is `UnrecognizedClientException` (signature expired) +4. Check the credential scope: the region must be this server's `[server] region` and the service must be `dynamodb`; otherwise `InvalidSignatureException` carrying one sentence per failing part, region first, as the service reports it. The scope date must also be the `YYYYMMDD` prefix of the request date, and its sentence comes after the region and service sentences 5. Look up the access key in the credential store (through the credential cache, see below); unknown: `UnrecognizedClientException`. The lookup also checks the session expiry of a temporary key, and refuses an expired session at once with `ExpiredTokenException`, before the signature check. It also reads whether the key is active, and step 9 applies that decision 6. Compare the session token: a temporary key must present its stored token, and a long-term key must present none; the decision is applied at step 9 7. Reconstruct the canonical request and the string-to-sign. `host` must be among the signed headers. Repeated headers contribute their values comma-joined. The hashed-payload line is the SHA-256 of the body the server received; a client-supplied `x-amz-content-sha256` header is not used for it, so a request whose body was altered after signing, or signed with a literal such as `UNSIGNED-PAYLOAD`, fails at step 8 diff --git a/tests/test_auth_error_fidelity.py b/tests/test_auth_error_fidelity.py index d9dea054e..bd40664ed 100755 --- a/tests/test_auth_error_fidelity.py +++ b/tests/test_auth_error_fidelity.py @@ -281,6 +281,9 @@ def _env_credentials() -> tuple[str, str, str | None]: _UNSUPPORTED = "Unsupported AWS 'algorithm': '{}'. " _HTTP_DATE = "Sat, 21 Nov 2026 01:36:16 GMT" _DATE = f"Date must be in ISO-8601 'basic format'. Got '{_HTTP_DATE}'. See http://en.wikipedia.org/wiki/ISO_8601" +# A date with a byte above 0x7F, which goes out as one byte. +_BYTE_DATE = "20261202T210318Z\x80" +_BYTE_DATE_TEXT = _DATE.replace(_HTTP_DATE, _BYTE_DATE) def _missing(*names: str, date: bool = False) -> str: @@ -612,6 +615,12 @@ def _describe( id="empty-date-header"), pytest.param([("X-Amz-Date", ""), ("Date", _HTTP_DATE)], f"{_ALG} {_CRED}, {_SH}, {_SIG}", _missing(date=True), id="empty-x-amz-date-and-http-date"), + pytest.param([("X-Amz-Date", _BYTE_DATE)], f"{_ALG} {_CRED}, {_SH}, {_SIG}", _BYTE_DATE_TEXT, + id="byte-above-0x7f-in-x-amz-date"), + pytest.param([("Date", _BYTE_DATE)], f"{_ALG} {_CRED}, {_SH}, {_SIG}", _BYTE_DATE_TEXT, + id="byte-above-0x7f-in-date"), + pytest.param([("X-Amz-Date", _BYTE_DATE), ("Date", "20261121T013616Z")], + f"{_ALG} {_CRED}, {_SH}, {_SIG}", _BYTE_DATE_TEXT, id="byte-above-0x7f-before-date"), ], ) def test_malformed_authorization_header(self, date, header, want): @@ -623,7 +632,8 @@ def test_malformed_authorization_header(self, date, header, want): # date header are named in one message. A date the service cannot read # comes next, before the Bearer answer, another algorithm and the # credential. The service reads Date only when the request has no - # X-Amz-Date, and an empty value is no date. + # X-Amz-Date, and an empty value is no date. It reads each byte of a + # date as a Latin-1 character (measured on 2026-12-02). status, payload = self._describe(header, date) assert status == 400, (status, payload) assert payload["__type"].endswith("#IncompleteSignatureException"), payload @@ -661,6 +671,19 @@ def test_basic_date_header_is_the_request_date(self): now = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) assert self._describe(header, [("Date", now)]) == self._describe(header, "X-Amz-Date") + @pytest.mark.parametrize("minutes", [-16, 16], ids=["16-minutes-before", "16-minutes-after"]) + def test_date_header_outside_the_window_is_refused(self, minutes): + # Measured against the service on 2026-12-03: a request dated only by + # Date, 16 minutes before or after now, gets the expiry answer before + # the key lookup, as a request dated by X-Amz-Date does. The service's + # type and text differ from extenddb's (#805), so the test checks the + # start of the text. + stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(time.time() + minutes * 60)) + header = f"{_ALG} Credential=AKIAIOSFODNN7EXAMPLE/{stamp[:8]}/us-east-1/dynamodb/aws4_request, {_SH}, {_SIG}" + status, payload = self._describe(header, [("Date", stamp)]) + assert status == 400, (status, payload) + assert payload["message"].startswith(("Signature expired", "Signature not yet current")), payload + @pytest.mark.parametrize( "date,pairs,want", [ From 05afa34f6fbceea2a8ea0c7e144bb23bf2f18d94 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:59:04 +0000 Subject: [PATCH 3/4] fix(auth): refuse a request date that is not ASCII before the format parse d82e5a2f94 reads a date header as Latin-1, so a byte above 0x7F becomes a character of two bytes in the date string. The basic-format parse slices each field of that string at a fixed byte offset. It panicked when an offset fell inside such a character. The sigv4_timestamp fuzz target found the 15-byte X-Amz-Date value 20150930T136, the byte 0xCE, then 0Z. The parse now refuses a value that is not ASCII before it slices the fields. The request gets the format refusal with the value echoed, which is DynamoDB's answer to that value (measured 2026-12-03). --- crates/auth/src/sigv4/verify.rs | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/crates/auth/src/sigv4/verify.rs b/crates/auth/src/sigv4/verify.rs index 6e9915af0..223b9efd3 100755 --- a/crates/auth/src/sigv4/verify.rs +++ b/crates/auth/src/sigv4/verify.rs @@ -216,8 +216,12 @@ pub(crate) fn request_date(headers: &HeaderMap) -> Option { } /// Parse ISO 8601 basic format `YYYYMMDDTHHMMSSZ` to Unix epoch seconds. +/// +/// `request_date` reads each byte as a Latin-1 character, and a character +/// above 0x7F takes two bytes in a `str`, so a value that is not ASCII is +/// refused before the fields are cut out by byte offset. fn parse_iso8601_basic(s: &str) -> Option { - if s.len() != 16 || !s.ends_with('Z') || s.as_bytes()[8] != b'T' { + if s.len() != 16 || !s.is_ascii() || !s.ends_with('Z') || s.as_bytes()[8] != b'T' { return None; } let year: i64 = s[0..4].parse().ok()?; @@ -317,16 +321,21 @@ mod tests { /// Measured 2026-12-02: a date value with a byte above 0x7F is read, with /// `X-Amz-Date` ahead of `Date`, and refused with the value echoed. + /// Measured 2026-12-03: also when the byte sits inside the time and the + /// value read is 16 bytes long (a fuzz input that made the parse panic). #[test] fn a_date_with_a_byte_above_0x7f_is_refused_with_its_value() { let value: &[u8] = b"20261202T210318Z\x80"; let valid: &[u8] = b"20261202T210318Z"; - let rows: [&[(&str, &[u8])]; 3] = [ - &[("x-amz-date", value)], - &[("date", value)], - &[("x-amz-date", value), ("date", valid)], + let read = "20261202T210318Z\u{80}"; + let inside: &[u8] = b"20150930T136\xce0Z"; + let rows: [(&[(&str, &[u8])], &str); 4] = [ + (&[("x-amz-date", value)], read), + (&[("date", value)], read), + (&[("x-amz-date", value), ("date", valid)], read), + (&[("x-amz-date", inside)], "20150930T136\u{ce}0Z"), ]; - for pairs in rows { + for (pairs, echoed) in rows { let mut headers = HeaderMap::new(); for (name, bytes) in pairs { headers.insert(*name, http::HeaderValue::from_bytes(bytes).unwrap()); @@ -338,8 +347,10 @@ mod tests { ); assert_eq!( err.message(), - "Date must be in ISO-8601 'basic format'. Got '20261202T210318Z\u{80}'. \ - See http://en.wikipedia.org/wiki/ISO_8601", + format!( + "Date must be in ISO-8601 'basic format'. Got '{echoed}'. \ + See http://en.wikipedia.org/wiki/ISO_8601" + ), "{pairs:?}" ); } From 782ec83d4ed1910941f5897e83c0bbe9eb4876b5 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:12:46 +0000 Subject: [PATCH 4/4] test(auth): allow the type of the rows in the Latin-1 date test 05afa34f6f gave the rows of a_date_with_a_byte_above_0x7f_is_refused_with_its_value a type that the type_complexity lint of clippy refuses under -D warnings. The test now allows that lint on that one statement. --- crates/auth/src/sigv4/verify.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/auth/src/sigv4/verify.rs b/crates/auth/src/sigv4/verify.rs index 223b9efd3..fef625b38 100755 --- a/crates/auth/src/sigv4/verify.rs +++ b/crates/auth/src/sigv4/verify.rs @@ -329,6 +329,7 @@ mod tests { let valid: &[u8] = b"20261202T210318Z"; let read = "20261202T210318Z\u{80}"; let inside: &[u8] = b"20150930T136\xce0Z"; + #[allow(clippy::type_complexity)] let rows: [(&[(&str, &[u8])], &str); 4] = [ (&[("x-amz-date", value)], read), (&[("date", value)], read),