Skip to content
16 changes: 11 additions & 5 deletions crates/auth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(), &timestamp)?;

Expand Down
59 changes: 58 additions & 1 deletion crates/auth/src/sigv4/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,20 @@ pub fn parse_authorization(
has_date: bool,
by_position: bool,
) -> Result<ParsedAuthorization, DynamoDbError> {
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<T>(
header: &[u8],
has_date: bool,
by_position: bool,
check_date: impl FnOnce() -> Result<T, DynamoDbError>,
) -> 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 {
Expand All @@ -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));

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
178 changes: 155 additions & 23 deletions crates/auth/src/sigv4/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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. ";

Expand All @@ -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
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -158,24 +158,28 @@ 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<String, DynamoDbError> {
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()
.and_then(|d| i64::try_from(d.as_secs()).ok())
.ok_or_else(|| DynamoDbError::InternalServerError("server clock error".to_owned()))?;

let request_epoch = parse_iso8601_basic(&timestamp).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();
Expand All @@ -188,22 +192,36 @@ pub fn validate_timestamp(headers: &HeaderMap) -> Result<String, DynamoDbError>
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<String, DynamoDbError> {
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<String> {
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<i64> {
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()?;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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() {
Expand Down
Loading
Loading