Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions crates/app/src/cmd_backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,8 @@ enum BackupCommand {
long,
value_name = "ARN",
action = clap::ArgAction::Append,
conflicts_with_all = ["adopt_store", "prune_missing"]
conflicts_with_all = ["adopt_store", "prune_missing"],
value_parser = |s: &str| Ok::<_, String>(s.trim().to_owned())
)]
forget_backup: Vec<String>,
},
Expand Down Expand Up @@ -3339,7 +3340,8 @@ mod tests {

/// `backup sync`'s options as clap parses them: the three store options
/// conflict with each other, with `--adopt-store` and with
/// `--prune-missing`; `--forget-backup` repeats, its ARNs in order.
/// `--prune-missing`; `--forget-backup` repeats, its ARNs in order and
/// trimmed.
#[test]
fn the_store_options_conflict_and_forget_backup_repeats() {
use clap::Parser;
Expand Down Expand Up @@ -3372,7 +3374,7 @@ mod tests {
"{refused:?}"
);
}
match parse(&["sync", "--forget-backup", "a", "--forget-backup", "b"]).unwrap() {
match parse(&["sync", "--forget-backup", "a", "--forget-backup", " b\t"]).unwrap() {
super::BackupCommand::Sync {
forget_backup,
move_store: None,
Expand Down
95 changes: 56 additions & 39 deletions crates/core/src/backup_format/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ pub fn backup_creation_date_time(id_or_arn: &str) -> Option<f64> {
/// The parts of a well-formed backup ARN, borrowed from the input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackupArnParts<'a> {
/// The ARN with surrounding ASCII whitespace removed, as the other fields
/// were read from it.
/// The ARN with one trailing line terminator removed
/// ([`trim_backup_arn`]), as the other fields were read from it.
pub arn: &'a str,
pub partition: &'a str,
pub region: &'a str,
Expand Down Expand Up @@ -240,18 +240,18 @@ pub fn check_store_prefix_table_name(table_name: &str) -> Result<(), FormatError
Ok(())
}

/// Strip surrounding ASCII whitespace from a `BackupArn`. Measured on
/// `DynamoDB`: an ARN with a trailing newline or CRLF resolves, and one with a
/// leading space or tab is refused with `Invalid Backup ARN`. This parser
/// trims both ends and every ASCII whitespace character, as main's parser
/// did; the leading-whitespace case is kept for compatibility with callers
/// of that parser, not because the service accepts it. Every layer that
/// reads a backup ARN from a request, the engine through
/// [`check_backup_arn`] and authorization before it derives the resource,
/// trims with this one function so they act on the same string.
/// Strip one trailing line terminator (`\r\n`, `\n`, `\r`, U+0085, U+2028 or
/// U+2029) from a `BackupArn`. The service ignores it and refuses every other
/// whitespace around the ARN (measured on 2026-11-21, the whitespace rows of
/// `tests/test_backup_restore_fidelity.py`). Other whitespace stays for
/// [`check_backup_arn`] to refuse. Authorization and the engine strip with
/// this function before they read the backup, so they act on the same
/// string.
#[must_use]
pub fn trim_backup_arn(arn: &str) -> &str {
arn.trim_matches(|c: char| c.is_ascii_whitespace())
arn.strip_suffix("\r\n")
.or_else(|| arn.strip_suffix(['\n', '\r', '\u{85}', '\u{2028}', '\u{2029}']))
.unwrap_or(arn)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A backup id that is only whitespace now answers differently. main turned .../backup/ into .../backup/ with an empty id, which the pre-authorization check refused as Invalid Backup ARN. trim_backup_arn strips only a line terminator, so the id stays " " or "\t" and reaches the printable-ASCII test in check_backup_arn. Measured on DynamoDB twice, identical, and on SQLite builds:

DescribeBackup {"BackupArn": "arn:aws:dynamodb:us-east-1:123456789012:table/<table>/backup/ "}

  • DynamoDB and main: Invalid Backup ARN
  • This PR: Invalid Request: BackupArn is not valid

Same for DeleteBackup, and for the ids \t, FF, \n\n and \t\n (22 cells per operation). A one-line check that treats a whitespace-only id as Invalid Backup ARN would restore this.

One smaller case in the same place: a bad backup id followed by U+0085, U+2028 or U+2029 now reaches is_backup_id after the strip and answers Invalid Backup ARN. DynamoDB and main answer Invalid Request: BackupArn is not valid. The older mapping of a non-hex id to Invalid Backup ARN is the real difference: DynamoDB answers not valid for every bad id (for example the ARN followed by a), and the PR makes three more terminators reach that mapping. Fixing the mapping fixes both.

}

/// Format a backup ARN from its parts. The one place the string is built;
Expand All @@ -273,18 +273,16 @@ pub fn parse_backup_arn(arn: &str) -> Option<BackupArnParts<'_>> {
check_backup_arn(arn).ok()
}

/// Parse a backup ARN after trimming surrounding ASCII whitespace with
/// [`trim_backup_arn`] (wider than the service, which resolves a trailing
/// newline or CRLF and refuses leading whitespace; see there), with the
/// length limit below applied to what remains, refusing one that is not exactly six
/// colon-separated fields, not `arn:<partition>:dynamodb:...`, has an empty
/// or malformed region, account, or table name, a resource other than
/// `table/<name>/backup/<id>`, a control or non-ASCII character, more than
/// [`MAX_BACKUP_ARN_LEN`] bytes, or an id that is not a backup id
/// ([`is_backup_id`]). The region and partition are checked for shape only:
/// an ARN in another region of the caller's account resolves on the service,
/// so the engine substitutes its own region rather than refuse it, and the
/// engine decides which partitions it serves.
/// Parse a backup ARN after stripping one trailing line terminator with
/// [`trim_backup_arn`], with the length limit below applied to what remains,
/// refusing one that is not exactly six colon-separated fields, not
/// `arn:<partition>:dynamodb:...`, has an empty or malformed region, account,
/// or table name, a resource other than `table/<name>/backup/<id>`, a control
/// or non-ASCII character, more than [`MAX_BACKUP_ARN_LEN`] bytes, or an id
/// that is not a backup id ([`is_backup_id`]). The region and partition are
/// checked for shape only: an ARN in another region of the caller's account
/// resolves on the service, so the engine substitutes its own region rather
/// than refuse it, and the engine decides which partitions it serves.
///
/// The field split is [`crate::arn::fields`], shared with authorization.
///
Expand Down Expand Up @@ -378,7 +376,8 @@ impl BackupArn {
))
})?;
// A separator inside a component would have parsed back as different
// fields; a leading or trailing space would have been trimmed away.
// fields, and a trailing line terminator on the backup id would have
// been stripped away.
if (
parts.partition,
parts.region,
Expand Down Expand Up @@ -796,10 +795,9 @@ mod tests {
))
.is_err()
);
// Surrounding whitespace is trimmed at both ends (the service trims
// only a trailing newline; `trim_backup_arn`); the parsed ARN is the
// trimmed one.
let padded = format!(" {ARN}\n");
// One trailing line terminator is stripped (`trim_backup_arn`); the
// parsed ARN is the stripped one.
let padded = format!("{ARN}\n");
assert_eq!(BackupArn::parse(&padded).unwrap().to_arn_string(), ARN);
}

Expand Down Expand Up @@ -904,13 +902,32 @@ mod tests {
);
assert_eq!(arn, ARN);
assert_eq!(BackupArn::parse(ARN).unwrap().to_arn_string(), arn);
assert_eq!(trim_backup_arn(" \t\n"), "");
assert_eq!(trim_backup_arn(&format!("\t{ARN}\n")), ARN);
assert_eq!(
trim_backup_arn("\u{a0}x"),
"\u{a0}x",
"non-ASCII whitespace is not trimmed"
);
}

#[test]
fn only_one_trailing_line_terminator_is_stripped() {
let rows: &[(&str, &str, bool)] = &[
("", "", true),
("", "\n", true),
("", "\r\n", true),
("", "\r", true),
("", "\u{85}", true),
("", "\u{2028}", true),
("", "\u{2029}", true),
("", "\n\n", false),
("", "\r\n\r\n", false),
("", "\n\r", false),
("", " ", false),
("", "\u{a0}", false),
(" ", "", false),
("\n", "", false),
];
for (before, after, resolves) in rows {
let spelled = format!("{before}{ARN}{after}");
assert_eq!(trim_backup_arn(&spelled) == ARN, *resolves, "{spelled:?}");
let expected = (!*resolves).then_some(BackupArnError::Invalid);
assert_eq!(check_backup_arn(&spelled).err(), expected, "{spelled:?}");
}
}

#[test]
Expand Down Expand Up @@ -954,9 +971,9 @@ mod tests {
assert!(err.to_string().contains("Mu sic"), "{err}");
assert!(BackupArn::new("aws", "us:east", "1234", "Music", ID).is_err());
assert!(BackupArn::new("", "us-east-1", "1234", "Music", ID).is_err());
// A component with surrounding whitespace would parse back trimmed.
// Inner components are refused by the character rules; the round-trip
// comparison is what catches whitespace at the two ends of the string.
// The character rules refuse whitespace in a component. The one
// exception is a trailing line terminator on the backup id, which the
// parse strips; the round-trip comparison catches that one.
assert!(BackupArn::new("aws", "us-east-1", "1234", "Music ", ID).is_err());
assert!(BackupArn::new("aws", "us-east-1", " 1234", "Music", ID).is_err());
assert!(BackupArn::new(" aws", "us-east-1", "1234", "Music", ID).is_err());
Expand Down
4 changes: 3 additions & 1 deletion crates/core/src/backup_format/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2384,8 +2384,10 @@ mod tests {
let good = sample_manifest();
good.validate_identity().unwrap();

// A trailing newline parses (`trim_backup_arn`), and the spelling is
// still not the canonical one.
let mut padded = good.clone();
padded.backup_arn = format!(" {}\n", good.backup_arn);
padded.backup_arn = format!("{}\n", good.backup_arn);
let err = padded.validate_identity().unwrap_err();
assert!(err.to_string().contains("canonical"), "{err}");

Expand Down
33 changes: 25 additions & 8 deletions crates/engine/src/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,13 @@ use crate::{OperationContext, serialize_output};
/// therefore tell "my backup does not exist" (`BackupNotFoundException`, from
/// the backend) from "that ARN belongs to another account".
///
/// The service trims a trailing newline and resolves an ARN naming another
/// region of the caller's account (measured on DynamoDB). The backends look
/// up the exact string they stored, which carries the `server.region` in
/// force when the backup was created, so the engine tries the ARN rebuilt in
/// this deployment's region first and, when that is not found and the caller
/// wrote a different ARN, the ARN as written (trimmed); see
/// The service ignores one trailing line terminator and resolves an ARN
/// naming another region of the caller's account (measured on DynamoDB). The
/// backends look up the exact string they stored, which carries the
/// `server.region` in force when the backup was created, so the engine tries
/// the ARN rebuilt in this deployment's region first and, when that is not
/// found and the caller wrote a different ARN, the ARN as written (the
/// terminator stripped); see
/// [`resolve_backup`]. A backup created under an earlier `server.region`
/// therefore stays reachable by the ARN `ListBackups` reports for it.
///
Expand Down Expand Up @@ -178,6 +179,17 @@ fn backup_not_found(arn: &str) -> DynamoDbError {
))
}

/// A `BackupNotFoundException` of `DescribeBackup`, `DeleteBackup` or
/// `RestoreTableFromBackup` names the `BackupArn` as the request wrote it,
/// its trailing line terminator included, where the lookup used the stripped
/// spelling (measured on DynamoDB on 2026-11-21).
fn named_as_requested(e: DynamoDbError, requested: Option<&str>) -> DynamoDbError {
match (e, requested) {
(DynamoDbError::BackupNotFoundException(_), Some(arn)) => backup_not_found(arn),
(e, _) => e,
}
}

/// The error for a CREATING row, or one whose backup a CREATING restore
/// target still reads: `BackupInUseException`, as the service answers. The
/// in-use text names the backup, not the target (the service's text); the
Expand Down Expand Up @@ -520,7 +532,9 @@ pub(crate) async fn handle_describe_backup(
ctx: &OperationContext,
) -> Result<Value, DynamoDbError> {
let backup_arn = backup_arn_field(&body, &ctx.account_id, &ctx.region)?;
let desc = describe_backup(&*ctx.storage, &ctx.account_id, &ctx.region, &backup_arn).await?;
let desc = describe_backup(&*ctx.storage, &ctx.account_id, &ctx.region, &backup_arn)
.await
.map_err(|e| named_as_requested(e, body["BackupArn"].as_str()))?;
serialize_output(&json!({ "BackupDescription": desc }))
}

Expand Down Expand Up @@ -713,7 +727,8 @@ pub(crate) async fn handle_delete_backup(
&ctx.region,
&backup_arn,
)
.await?;
.await
.map_err(|e| named_as_requested(e, body["BackupArn"].as_str()))?;
serialize_output(&json!({ "BackupDescription": desc }))
}

Expand Down Expand Up @@ -1140,6 +1155,7 @@ pub(crate) async fn handle_restore_table_from_backup(
ctx: &OperationContext,
) -> Result<Value, DynamoDbError> {
let auth_cache = ctx.auth_cache.clone();
let requested = body["BackupArn"].as_str().map(str::to_owned);
restore_table_from_backup_detached(
Arc::clone(&ctx.storage),
Arc::clone(&ctx.backup),
Expand All @@ -1166,6 +1182,7 @@ pub(crate) async fn handle_restore_table_from_backup(
},
)
.await
.map_err(|e| named_as_requested(e, requested.as_deref()))
}

/// Run one restore, and then `after` with the target name, in a task of its
Expand Down
17 changes: 11 additions & 6 deletions crates/engine/src/backup/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4462,6 +4462,12 @@ async fn malformed_arn_is_a_validation_exception_with_the_services_text() {
),
INVALID_ID,
),
// Whitespace before the ARN, and whitespace after it other than one
// line terminator (measured on 2026-11-21, the whitespace rows of
// tests/test_backup_restore_fidelity.py).
(format!(" {}", arn(ACCOUNT)), INVALID_ID),
(format!("\u{a0}{}", arn(ACCOUNT)), INVALID_ID),
(format!("{} ", arn(ACCOUNT)), NOT_VALID),
];
let fake = Fake::with_source(source(Some(definition("PROVISIONED"))));
for (candidate, expected) in &cases {
Expand All @@ -4488,15 +4494,14 @@ async fn malformed_arn_is_a_validation_exception_with_the_services_text() {
assert!(fake.restores().is_empty());
}

/// Measured on DynamoDB: the service trims a trailing newline and resolves an ARN
/// naming another region of the caller's account. The engine hands the
/// backend the ARN it issued: trimmed, in its own region.
/// Measured on DynamoDB: the service strips one trailing line terminator and
/// resolves an ARN naming another region of the caller's account. The engine
/// hands the backend the ARN it issued: stripped, in its own region.
#[tokio::test]
async fn whitespace_is_trimmed_and_another_region_resolves() {
async fn a_trailing_line_terminator_is_stripped_and_another_region_resolves() {
let ours = arn(ACCOUNT);
for candidate in [
format!("{ours}\n"),
format!(" {ours}\t\r\n"),
format!("arn:aws:dynamodb:eu-west-1:{ACCOUNT}:table/Music/backup/01791976431438-73d8d5bc"),
format!(
"arn:aws:dynamodb:eu-west-1:{ACCOUNT}:table/Music/backup/01791976431438-73d8d5bc\n"
Expand Down Expand Up @@ -4545,7 +4550,7 @@ async fn a_backup_stored_under_another_region_resolves_as_written() {
assert_eq!(spellings.as_written.as_deref(), Some(stored.as_str()));
// The server's own spelling has no second spelling to try.
assert_eq!(own(&ours).as_written, None);
assert_eq!(own(&format!(" {ours}\n")).as_written, None, "trimmed first");
assert_eq!(own(&format!("{ours}\n")).as_written, None, "stripped first");

let stored_source = || {
let mut src = source(Some(definition("PROVISIONED")));
Expand Down
17 changes: 15 additions & 2 deletions crates/engine/src/backup_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,24 @@ pub(crate) fn canonical_backup_arn(
/// measured on DynamoDB; its text was not captured, so the "not valid" one
/// is used), before the account is looked at.
///
/// An ARN that starts with whitespace is `Invalid Backup ARN`, also when one
/// line terminator follows it (the rows measured in
/// `tests/test_backup_restore_fidelity.py`).
///
/// [`ARN_PARTITION`]: extenddb_storage::util::ARN_PARTITION
pub(crate) fn check_backup_arn(
backup_arn: &str,
) -> Result<extenddb_storage::util::BackupArnParts<'_>, DynamoDbError> {
use extenddb_storage::util::BackupArnError;
if backup_arn.starts_with(char::is_whitespace) {
return Err(DynamoDbError::ValidationException(
INVALID_BACKUP_ARN.to_owned(),
));
}
let parts = extenddb_storage::util::check_backup_arn(backup_arn).map_err(|e| {
DynamoDbError::ValidationException(match e {
BackupArnError::Invalid => BACKUP_ARN_NOT_VALID.to_owned(),
BackupArnError::Id => "Invalid Backup ARN".to_owned(),
BackupArnError::Id => INVALID_BACKUP_ARN.to_owned(),
})
})?;
if parts.partition != extenddb_storage::util::ARN_PARTITION {
Expand All @@ -73,6 +82,10 @@ pub(crate) fn check_backup_arn(
/// shape (measured on DynamoDB).
pub(crate) const BACKUP_ARN_NOT_VALID: &str = "Invalid Request: BackupArn is not valid";

/// The service's text for a `BackupArn` whose backup id is not one, or that
/// starts with whitespace (measured on DynamoDB).
const INVALID_BACKUP_ARN: &str = "Invalid Backup ARN";

pub(crate) fn required_str<'a>(
body: &'a Value,
member: &str,
Expand Down Expand Up @@ -354,7 +367,7 @@ pub(crate) async fn list_backups<S: BackupCatalog + LegacyBackupReader + ?Sized>
/// the region and table-name texts were captured as fragments ("does not
/// match the region", "does not match the table name predicate") and are
/// completed on the account text's pattern. Returns the cursor as this
/// deployment issued it (whitespace trimmed).
/// deployment issued it (one trailing line terminator stripped).
fn list_backups_cursor(
arn: &str,
account_id: &str,
Expand Down
17 changes: 16 additions & 1 deletion crates/server/src/arn_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ pub(crate) fn check_stream_arn(arn: &str) -> Result<(), DynamoDbError> {
/// `RestoreTableFromBackup`). U+0000 in the backup id keeps the engine's
/// `Invalid Request: BackupArn is not valid`, as measured.
pub(crate) fn check_backup_arn(arn: &str) -> Result<(), DynamoDbError> {
match parse(arn.trim_matches(|c: char| c.is_ascii_whitespace())) {
match parse(arn) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the trim here, a leading space, tab, LF, CR, CRLF or FF makes parse return None, because it needs the arn: prefix. The gate passes the ARN and the later member checks answer first. main trimmed here, so the gate refused the ARN first. Measured in us-east-1 on 2026-11-30, twice, identical, and on SQLite builds of main and this head:

RestoreTableFromBackup {"BackupArn": " arn:aws:dynamodb:us-east-1:123456789012:table/bad table!/backup/01796075814728-deadbeef", "TargetTableName": "bad name!"}

  • DynamoDB and main: Invalid Backup ARN
  • This PR: 1 validation error detected: Value 'bad name!' at 'targetTableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+

The same holds with BillingModeOverride: "BAD" as the second fault, and for the leading space, tab, LF, CR, CRLF and FF, in the caller's account and in another account (24 cells). Have the gate refuse an ARN with leading whitespace as Invalid Backup ARN, or run the engine's leading check before the member checks.

Some(res) if matches!(res.sub, Some(SubResource::Backup(_))) && !in_pattern(&res.table) => {
Err(validation("Invalid Backup ARN".to_owned()))
}
Expand Down Expand Up @@ -539,6 +539,21 @@ mod tests {
);
let backup_id = format!("{}/backup/0170\u{0}", table("ok"));
assert!(check_backup_arn(&backup_id).is_ok(), "left to the engine");
// The gate parses the ARN as sent: whitespace before it is left to
// the later checks, and a trailing line terminator stays in the
// backup id, also when it is the whole id (measured on 2026-11-25).
assert_eq!(
message(check_backup_arn(&format!("{backup}\n"))).unwrap(),
"Invalid Backup ARN"
);
assert_eq!(
message(check_backup_arn(&format!("{bad}/backup/\n"))).unwrap(),
"Invalid Backup ARN"
);
assert!(
check_backup_arn(&format!(" {backup}")).is_ok(),
"left to the engine"
);
assert_eq!(
message(check_tag_resource_arn(&bad)).unwrap(),
format!("Invalid TableArn: Invalid ResourceArn provided as input {bad}")
Expand Down
Loading
Loading