diff --git a/crates/auth/src/lib.rs b/crates/auth/src/lib.rs index be8abeca1..f03b58606 100644 --- a/crates/auth/src/lib.rs +++ b/crates/auth/src/lib.rs @@ -168,8 +168,7 @@ impl AuthProvider for BuiltinAuthProvider { | "TransactWriteItems" ) }); - let has_date = headers.contains_key("x-amz-date") || headers.contains_key("date"); - let parsed = sigv4::parse::parse_authorization(auth_header, has_date, by_position)?; + 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 @@ -180,12 +179,19 @@ 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, + by_position, + || 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 5d67515c9..0e5a9792b 100755 --- a/crates/auth/src/sigv4/parse.rs +++ b/crates/auth/src/sigv4/parse.rs @@ -50,6 +50,20 @@ pub fn parse_authorization( has_date: bool, by_position: bool, ) -> Result { + parse_authorization_with_date_check(header, has_date, by_position, || 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, + by_position: 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 { @@ -60,7 +74,7 @@ pub fn parse_authorization( // 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)); @@ -167,6 +181,8 @@ pub fn parse_authorization( ))); }; + let checked = check_date()?; + // Measured 2026-11-21 and 2026-12-02: DynamoDB answers a `Bearer` value // that passes the checks above with this text, and not with the text for // a request with no Authorization header. @@ -199,12 +215,19 @@ pub fn parse_authorization( signed_headers: signed_headers.to_owned(), signature: signature.to_owned(), }) + .map(|parsed| (parsed, checked)) } 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. @@ -606,6 +629,40 @@ mod tests { assert!(parse_authorization(header.as_bytes(), true, false).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, false, 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 be3334a23..fef625b38 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,14 +158,17 @@ 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 `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() @@ -173,9 +176,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(); @@ -188,22 +192,36 @@ pub fn validate_timestamp(headers: &HeaderMap) -> Result Ok(timestamp) } -/// Extract the timestamp from `X-Amz-Date` header. +/// The request date (see `request_date`), or a refusal when the request has +/// none. fn extract_timestamp(headers: &HeaderMap) -> Result { + request_date(headers).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. +/// 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") - .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(), - ) - }) + .or_else(|| headers.get("date")) + .map(|v| super::parse::latin1(v.as_bytes())) + .filter(|v| !v.is_empty()) } /// 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()?; @@ -273,11 +291,125 @@ 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).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. + /// 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 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), + (&[("x-amz-date", value), ("date", valid)], read), + (&[("x-amz-date", inside)], "20150930T136\u{ce}0Z"), + ]; + for (pairs, echoed) 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(), + format!( + "Date must be in ISO-8601 'basic format'. Got '{echoed}'. \ + 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:?}"); + } + } + } + + /// 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 { @@ -361,7 +493,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 d3abd5cfd..85c302d6f 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 service does so only for a valid request body (see [Differences from DynamoDB](../differences-from-dynamodb.md)). 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 service does so only for a valid request body (see [Differences from DynamoDB](../differences-from-dynamodb.md)). 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 5024bd626..7c9fd2da5 100755 --- a/tests/test_auth_error_fidelity.py +++ b/tests/test_auth_error_fidelity.py @@ -279,6 +279,11 @@ 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" +# 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: @@ -499,13 +504,14 @@ def test_duplicate_authorization_header_is_refused_on_the_data_plane(self): assert text == "400 Bad Request", text[:200] def _describe( - self, authorization: str | None, date: str | None, operation: str = "DescribeTable" + self, authorization: str | None, date: str | list | None, operation: str = "DescribeTable" ) -> tuple[int, dict]: """Send a DescribeTable, or a PutItem, 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 = [ @@ -517,6 +523,8 @@ def _describe( 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)) body = {"TableName": "no-such-table"} @@ -592,6 +600,27 @@ def _describe( 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"), + 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): @@ -600,7 +629,11 @@ def test_malformed_authorization_header(self, date, header, want): # the credential. AWS4- in another case is refused first. A part with # no '=' or no key is named before any missing parameter. Every missing # parameter, an empty Credential or Signature included, 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. 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 @@ -630,6 +663,27 @@ 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") + + @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", [