From dc858f5b99d0c4c4af31f871ca1ff72cd6b63a30 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:11:44 +0000 Subject: [PATCH 1/2] fix(backup): strip only one trailing line terminator from a backup ARN DescribeBackup, DeleteBackup, RestoreTableFromBackup and the ExclusiveStartBackupArn of ListBackups trimmed all ASCII whitespace from both ends of the ARN. An ARN with a space or a tab around it resolved. DynamoDB ignores one trailing line terminator and refuses all other whitespace (measured in us-east-1 on 2026-11-21): - One trailing \n, \r\n, \r, U+0085, U+2028 or U+2029 resolves on DescribeBackup and in an ExclusiveStartBackupArn. - An ARN that starts with whitespace is ValidationException "Invalid Backup ARN", also when one line terminator follows it. - Other whitespace after the ARN, two line terminators included, is ValidationException "Invalid Request: BackupArn is not valid". - For a backup that does not exist, BackupNotFoundException names the ARN as the request wrote it, its line terminator included. trim_backup_arn now strips only the one line terminator. The engine refuses leading whitespace with "Invalid Backup ARN" before it parses the ARN. Before, VT, NBSP and other non-ASCII whitespace before the ARN got "not valid" on RestoreTableFromBackup and in a cursor. The three operations build their not-found text from the request's BackupArn. The server's ARN gate now calls trim_backup_arn in place of its own trim, so the gate, authorization and the engine read the same string. One case changes with the gate: a RestoreTableFromBackup ARN with ASCII whitespace other than VT before it and a table name outside the pattern. Main's gate refused it with "Invalid Backup ARN" before authorization. Now authorization evaluates the ARN as sent. A caller without an Allow on it gets AccessDeniedException, and the engine refuses it for any other caller. DynamoDB's answer to that input was not measured. backup sync --forget-backup trims its arguments when it parses them, as backup migrate-legacy does. An argument that 1.0.0 accepted is read as before. VT and non-ASCII whitespace around an argument, which 1.0.0 refused, is now trimmed too. In an ExclusiveStartBackupArn, DynamoDB answers trailing whitespace other than one line terminator with "Invalid Request: The supplied ExclusiveStartBackupArn is not a valid backup arn". ExtendDB answers the BackupArn text, as it does for the other malformed cursors that #1315 and #907 list. The new test rows for that case are strict xfail on ExtendDB. The differences document, the limits document and the upgrade manual describe the new rule. Closes #617 Refs #1315 --- crates/app/src/cmd_backup.rs | 8 +- crates/core/src/backup_format/layout.rs | 94 +++++++++++-------- crates/core/src/backup_format/manifest.rs | 4 +- crates/engine/src/backup.rs | 50 ++++++++-- crates/engine/src/backup/tests.rs | 17 ++-- crates/server/src/arn_gate.rs | 12 ++- crates/server/src/authz_resource.rs | 25 ++--- .../src/authz_resource/cross_account/tests.rs | 4 +- crates/storage/src/util/backup_id.rs | 4 +- docs/differences-from-dynamodb.md | 4 +- docs/dynamodb-limits.md | 2 +- docs/manuals/07-upgrade-manual.md | 6 ++ tests/test_backup_restore_fidelity.py | 93 +++++++++++++++++- 13 files changed, 242 insertions(+), 81 deletions(-) diff --git a/crates/app/src/cmd_backup.rs b/crates/app/src/cmd_backup.rs index e99e605e1..a32404048 100644 --- a/crates/app/src/cmd_backup.rs +++ b/crates/app/src/cmd_backup.rs @@ -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, }, @@ -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; @@ -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, diff --git a/crates/core/src/backup_format/layout.rs b/crates/core/src/backup_format/layout.rs index 204f00688..94f8b0f79 100644 --- a/crates/core/src/backup_format/layout.rs +++ b/crates/core/src/backup_format/layout.rs @@ -154,8 +154,8 @@ pub fn backup_creation_date_time(id_or_arn: &str) -> Option { /// 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, @@ -240,18 +240,17 @@ 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. Every layer that reads a backup ARN from a +/// request strips with this function, 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) } /// Format a backup ARN from its parts. The one place the string is built; @@ -273,18 +272,16 @@ pub fn parse_backup_arn(arn: &str) -> Option> { 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::dynamodb:...`, has an empty -/// or malformed region, account, or table name, a resource other than -/// `table//backup/`, 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::dynamodb:...`, has an empty or malformed region, account, +/// or table name, a resource other than `table//backup/`, 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. /// @@ -378,7 +375,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, @@ -796,10 +794,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); } @@ -904,13 +901,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] @@ -954,9 +970,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()); diff --git a/crates/core/src/backup_format/manifest.rs b/crates/core/src/backup_format/manifest.rs index fc7ab815f..a7661de74 100644 --- a/crates/core/src/backup_format/manifest.rs +++ b/crates/core/src/backup_format/manifest.rs @@ -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}"); diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 80e9254e9..9bf3fda22 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -64,12 +64,13 @@ const LIST_BACKUPS_MAX_LIMIT: i64 = 100; /// 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. /// @@ -176,6 +177,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 @@ -251,15 +263,24 @@ 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 fn check_backup_arn( backup_arn: &str, ) -> Result, 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 { @@ -274,6 +295,10 @@ fn check_backup_arn( /// shape (measured on DynamoDB). 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"; + fn required_str<'a>(body: &'a Value, member: &str, path: &str) -> Result<&'a str, DynamoDbError> { body.get(member).and_then(|v| v.as_str()).ok_or_else(|| { DynamoDbError::ValidationException(format!( @@ -685,7 +710,9 @@ pub(crate) async fn handle_describe_backup( ctx: &OperationContext, ) -> Result { 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 })) } @@ -1015,7 +1042,7 @@ async fn list_backups( /// 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, @@ -1221,7 +1248,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 })) } @@ -1648,6 +1676,7 @@ pub(crate) async fn handle_restore_table_from_backup( ctx: &OperationContext, ) -> Result { 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), @@ -1674,6 +1703,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 diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index 204be8e56..c31acee28 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -4461,6 +4461,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 { @@ -4487,15 +4493,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" @@ -4544,7 +4549,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"))); diff --git a/crates/server/src/arn_gate.rs b/crates/server/src/arn_gate.rs index af84224cb..17caf1006 100644 --- a/crates/server/src/arn_gate.rs +++ b/crates/server/src/arn_gate.rs @@ -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(extenddb_core::backup_format::trim_backup_arn(arn)) { Some(res) if matches!(res.sub, Some(SubResource::Backup(_))) && !in_pattern(&res.table) => { Err(validation("Invalid Backup ARN".to_owned())) } @@ -539,6 +539,16 @@ 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 reads the ARN as the engine does: one trailing line + // terminator stripped, and whitespace before it left for the engine. + assert_eq!( + message(check_backup_arn(&format!("{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}") diff --git a/crates/server/src/authz_resource.rs b/crates/server/src/authz_resource.rs index 4261d9efb..da23bae68 100644 --- a/crates/server/src/authz_resource.rs +++ b/crates/server/src/authz_resource.rs @@ -256,12 +256,12 @@ fn canonical_resource(arn: &str, region: &str, account_id: &str) -> String { } } -/// A `BackupArn` with the surrounding ASCII whitespace the engine trims -/// before it resolves the backup (`check_backup_arn`) trimmed here too, so -/// authorization evaluates the backup the engine acts on. Without this, a Deny -/// on a backup ARN would be bypassed by sending the ARN with a trailing -/// newline: authorization would evaluate `.../backup/\n` and the engine -/// act on `.../backup/`. +/// A `BackupArn` with the one trailing line terminator that the engine +/// strips before it resolves the backup (`trim_backup_arn`) stripped here +/// too, so authorization evaluates the backup the engine acts on. Without +/// this, a Deny on a backup ARN would be bypassed by sending the ARN with a +/// trailing newline: authorization would evaluate `.../backup/\n` and the +/// engine act on `.../backup/`. fn backup_arn_field(input: &Value) -> String { str_field(input, "BackupArn") .map(|arn| extenddb_core::backup_format::trim_backup_arn(&arn).to_owned()) @@ -865,16 +865,16 @@ mod tests { t[0].resource.clone() } - /// The engine trims surrounding ASCII whitespace from a `BackupArn` - /// before it resolves the backup, so authorization evaluates the trimmed + /// The engine strips one trailing line terminator from a `BackupArn` + /// before it resolves the backup, so authorization evaluates the stripped /// backup and a Deny on it cannot be bypassed with a trailing newline. #[test] - fn backup_arn_with_surrounding_whitespace_authorizes_the_trimmed_backup() { + fn backup_arn_with_a_trailing_line_terminator_authorizes_the_stripped_backup() { let arn = format!("arn:aws:dynamodb:{R}:{A}:table/T/backup/01791976431438-73d8d5bc"); for spelled in [ format!("{arn}\n"), - format!(" {arn}"), - format!("\t{arn}\r\n"), + format!("{arn}\r\n"), + format!("{arn}\u{2028}"), ] { for op in ["DescribeBackup", "DeleteBackup"] { assert!(validate_operation_arns(op, &json!({ "BackupArn": spelled }), R).is_ok()); @@ -892,7 +892,8 @@ mod tests { ); assert_eq!( (restore[0].action.as_str(), restore[0].resource.as_str()), - ("RestoreTableFromBackup", arn.as_str()) + ("RestoreTableFromBackup", arn.as_str()), + "{spelled:?}" ); } } diff --git a/crates/server/src/authz_resource/cross_account/tests.rs b/crates/server/src/authz_resource/cross_account/tests.rs index 1a66cd484..5a19ecf49 100644 --- a/crates/server/src/authz_resource/cross_account/tests.rs +++ b/crates/server/src/authz_resource/cross_account/tests.rs @@ -49,11 +49,11 @@ fn every_resource_arn_field_is_read() { ); } for op in ["DescribeBackup", "DeleteBackup", "RestoreTableFromBackup"] { - let input = json!({ "BackupArn": format!(" {BACKUP}\n"), "TargetTableName": "r" }); + let input = json!({ "BackupArn": format!("{BACKUP}\n"), "TargetTableName": "r" }); assert_eq!( find(op, &input, A), other(op, BACKUP), - "{op}: the trimmed ARN" + "{op}: the stripped ARN" ); } let input = json!({ "TableArn": FOREIGN, "S3Bucket": "b" }); diff --git a/crates/storage/src/util/backup_id.rs b/crates/storage/src/util/backup_id.rs index 3fb4c7c6a..b37273e89 100644 --- a/crates/storage/src/util/backup_id.rs +++ b/crates/storage/src/util/backup_id.rs @@ -127,9 +127,9 @@ mod tests { assert_eq!(parse_backup_arn(&arn).unwrap().backup_id, id, "{id}"); assert!(is_backup_id(id), "{id}"); } - // Surrounding ASCII whitespace is trimmed (the service resolves an + // One trailing line terminator is stripped (the service resolves an // ARN with a trailing newline). - let padded = format!(" \t{arn}\n"); + let padded = format!("{arn}\n"); let p = check_backup_arn(&padded).unwrap(); assert_eq!(p.arn, arn); assert_eq!(p.backup_id, "01489602797149-73d8d5bc"); diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index c44479284..9bd453b90 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -122,10 +122,10 @@ Behaviour stated as measured, and every number below, was observed with release | Members of the `RestoreTableFromBackup` response | The `CREATING` description omits `DeletionProtectionEnabled`, the table's `ProvisionedThroughput.NumberOfDecreasesToday`, and each GSI's `IndexStatus` | The same on all four backends; `DescribeTable` reports the first two. Each GSI's `ProvisionedThroughput` keeps `NumberOfDecreasesToday`; what the service sends there was not measured | | Restoring into a name that exists | `TableAlreadyExistsException`; into a name that is itself a `CREATING` restore target, `TableInUseException`: "Table: is already being restored from backup: " for the same backup, and "Attempt to change a resource which is still in use: Table: is being used." for a different one (both measured) | `TableAlreadyExistsException` on all four backends for an existing table; `TableInUseException` for a name that is a `CREATING` restore target, whichever backup is restored, always with the same-backup text naming the backup the existing target is being restored from (the service's text for a different backup is not reproduced). The engine checks the name after the backup is read and before the overrides are checked against it, the order the service uses: a restore of a missing backup into an existing table, into a table `CreateTable` is still creating or into a `CREATING` restore target is `BackupNotFoundException` "Backup not found: " (measured on DynamoDB, twice each, and the same on `main`); an earlier build of this release checked the name first and answered `TableAlreadyExistsException` or `TableInUseException` for those three. The name is still checked before the job permit is taken, so the answer does not depend on whether a permit is free; each backend checks the name again under its registration (a missing backup reaches the backend only when it is deleted after the engine has read it), whose target insert is the fence that tells an existing table from a `CREATING` target, so two simultaneous requests cannot both pass. The existing table or target is unchanged | | `UpdateTable` on a `CREATING` restore target | `ResourceNotFoundException` (measured on DynamoDB) | `ResourceInUseException` on all four backends, the engine's mapping of a table that is not `ACTIVE`. A plain `CreateTable` into the target's name is `ResourceInUseException` "Table already exists: ", the service's text for a taken name (measured on DynamoDB), without the backup ARN. The target is unchanged | -| `BackupArn` that is malformed or belongs to another account | Not an ARN of the right shape, too long (over 1024), a control character, a slash or `..` in the region: `ValidationException` "Invalid Request: BackupArn is not valid". The right shape with an id that is not a backup id (not hex, a wildcard): `ValidationException` "Invalid Backup ARN" (both measured; which input gets which text was captured for one input only: a bare 13-digit id is "Invalid Request: BackupArn is not valid"). Surrounding whitespace, a trailing newline for one, is trimmed, and an ARN naming another region of the caller's account resolves (measured). One in another partition is `ValidationException` (measured; text not captured) | The same two texts on all four backends, split by ExtendDB's parser: a string that is not `arn:aws:dynamodb:::table//backup/` with a region in `[a-z0-9-]`, a digit-only account, a name in `[a-zA-Z0-9_.-]`, only printable ASCII, and at most 1024 bytes after trimming is "Invalid Request: BackupArn is not valid" (so is one in a partition other than `aws`, the only one ExtendDB issues); one of that shape whose id is neither `[0-9]{14}-[0-9a-f]{8}` nor a shape an earlier build issued (13 digits, `-`, 8 hex digits, which every backend issued before the shared id; 13 bare digits, which PostgreSQL v0.1.0 to v0.1.2 issued) is "Invalid Backup ARN"; no build has put a UUID in a backup ARN, so none resolves. Surrounding ASCII whitespace is trimmed (only a trailing newline was measured on the service; trimming all surrounding whitespace is ExtendDB's generalisation), and the region is checked for shape only: the backup is looked up under the ARN rebuilt in this deployment's `server.region` first and, when that is not found and the caller wrote a different ARN, under the ARN as written, so another region's resolves and a backup created under an earlier `server.region` stays reachable by the ARN `ListBackups` reports for it, though not by that ARN rewritten with the new region (see the upgrade manual on `server.region`). A bare 13-digit id (the shape PostgreSQL v0.1.0 to v0.1.2 issued) passes the id check, so such an ARN that names no backup is `BackupNotFoundException`, where the service answers `ValidationException` "Invalid Request: BackupArn is not valid" (measured on DynamoDB). Under a `server.region` outside `[a-z0-9-]` no backup ARN can be formed, so `CreateBackup` is refused with a `ValidationException` naming `server.region`, and the backups taken before the upgrade under such a region keep an ARN the three operations refuse as "not valid"; the server starts and logs a warning saying so. A well-formed ARN naming another account, of any number of digits, is refused on `DescribeBackup`, `DeleteBackup`, and `RestoreTableFromBackup` before any policy is evaluated, in dev mode too, with the service's answers (see "A resource ARN in another account"). The same checks apply to `ListBackups`'s `ExclusiveStartBackupArn`, where another account's or region's cursor is instead a `ValidationException` (see `ListBackups` paging). In every build, dev mode included, `DescribeBackup` and `DeleteBackup` first refuse a `BackupArn` that does not parse as a backup ARN at all (a table ARN, an `xrn:` prefix, an empty field) with "Invalid Backup ARN" before any policy is evaluated, as the service does (measured on DynamoDB), so those shapes get that text instead of the engine's. Every other `BackupArn` is authorized as the backup it names in this deployment (the table and id, in the server's region and the caller's account, surrounding whitespace trimmed as the engine trims it) and then checked by the engine as above. Same on all four backends | +| `BackupArn` that is malformed or belongs to another account | Not an ARN of the right shape, too long (over 1024), a control character, a slash or `..` in the region: `ValidationException` "Invalid Request: BackupArn is not valid". The right shape with an id that is not a backup id (not hex, a wildcard): `ValidationException` "Invalid Backup ARN" (both measured; which input gets which text was captured for one input only: a bare 13-digit id is "Invalid Request: BackupArn is not valid"). One trailing line terminator (`\n`, `\r\n`, `\r`, U+0085, U+2028 or U+2029) is ignored, measured on `DescribeBackup` and `ExclusiveStartBackupArn`. An ARN that starts with whitespace is "Invalid Backup ARN". Other whitespace after it, two line terminators included, is "Invalid Request: BackupArn is not valid". In an `ExclusiveStartBackupArn` it is "Invalid Request: The supplied ExclusiveStartBackupArn is not a valid backup arn". For a backup that does not exist, `BackupNotFoundException` names the ARN as the request wrote it, its line terminator included (all measured on 2026-11-21). An ARN naming another region of the caller's account resolves (measured). One in another partition is `ValidationException` (measured; text not captured) | The same two texts on all four backends, split by ExtendDB's parser: a string that is not `arn:aws:dynamodb:::table//backup/` with a region in `[a-z0-9-]`, a digit-only account, a name in `[a-zA-Z0-9_.-]`, only printable ASCII, and at most 1024 bytes once one trailing line terminator is stripped is "Invalid Request: BackupArn is not valid" (so is one in a partition other than `aws`, the only one ExtendDB issues); one of that shape whose id is neither `[0-9]{14}-[0-9a-f]{8}` nor a shape an earlier build issued (13 digits, `-`, 8 hex digits, which every backend issued before the shared id; 13 bare digits, which PostgreSQL v0.1.0 to v0.1.2 issued) is "Invalid Backup ARN"; no build has put a UUID in a backup ARN, so none resolves. As on the service, one trailing line terminator is stripped, and an ARN that starts with whitespace is "Invalid Backup ARN". Other whitespace after it makes the ARN "not valid", and the not-found text names the ARN as written. An `ExclusiveStartBackupArn` gets the same two texts, where the service answers whitespace after a cursor with its own cursor text. The region is checked for shape only: the backup is looked up under the ARN rebuilt in this deployment's `server.region` first and, when that is not found and the caller wrote a different ARN, under the ARN as written, so another region's resolves and a backup created under an earlier `server.region` stays reachable by the ARN `ListBackups` reports for it, though not by that ARN rewritten with the new region (see the upgrade manual on `server.region`). A bare 13-digit id (the shape PostgreSQL v0.1.0 to v0.1.2 issued) passes the id check, so such an ARN that names no backup is `BackupNotFoundException`, where the service answers `ValidationException` "Invalid Request: BackupArn is not valid" (measured on DynamoDB). Under a `server.region` outside `[a-z0-9-]` no backup ARN can be formed, so `CreateBackup` is refused with a `ValidationException` naming `server.region`, and the backups taken before the upgrade under such a region keep an ARN the three operations refuse as "not valid"; the server starts and logs a warning saying so. A well-formed ARN naming another account, of any number of digits, is refused on `DescribeBackup`, `DeleteBackup`, and `RestoreTableFromBackup` before any policy is evaluated, in dev mode too, with the service's answers (see "A resource ARN in another account"). The same checks apply to `ListBackups`'s `ExclusiveStartBackupArn`, where another account's or region's cursor is instead a `ValidationException` (see `ListBackups` paging). In every build, dev mode included, `DescribeBackup` and `DeleteBackup` first refuse a `BackupArn` that does not parse as a backup ARN at all (a table ARN, an `xrn:` prefix, an empty field) with "Invalid Backup ARN" before any policy is evaluated, as the service does (measured on DynamoDB), so those shapes get that text instead of the engine's. Every other `BackupArn` is authorized as the backup it names in this deployment (the table and id, in the server's region and the caller's account, with one trailing line terminator stripped as the engine strips it) and then checked by the engine as above. Same on all four backends | | Tag conditions on backups | The backup resource has no `aws:ResourceTag` condition key: a backup has no tags to match | `DescribeBackup`, `DeleteBackup`, and `RestoreTableFromBackup` are authorized on the backup ARN as a resource with no tags. An `aws:ResourceTag/` condition finds the key absent for a backup (and `dynamodb:ResourceTag/` is absent for every resource), so, for example, an Allow conditioned on `StringEquals` never grants on a backup and a Deny conditioned on `StringEquals` never denies one. This holds whatever an earlier build stored under the backup ARN (it accepted `TagResource` on one; see Tagging), and a backup does not take its table's tags. For `RestoreTableFromBackup`, the seven item actions evaluated on `table/` (see the authorization rows below) read that ARN's resource tags. A target that does not exist has no tags, so an `aws:ResourceTag/` condition on those actions finds none and does not grant the restore; a target that exists is evaluated with its tags, and a request that is otherwise valid then passes authorization and fails `TableAlreadyExistsException` (or `TableInUseException` for a `CREATING` restore target) when the condition is met, and fails `AccessDeniedException` naming the first item action when it is not (measured on SQLite). Whether the service reads a target's tags in these evaluations was not measured. Scope backup permissions by ARN (`table//backup/*`). Measured on PostgreSQL and SQLite for the Allow case, including tags written under a backup ARN by the earlier build and then served by this one; the Deny case and role sessions rest on unit tests of the authorization path, which is the same for every backend | | Authorization of `ListBackups` | `dynamodb:ListBackups` is evaluated on `arn:aws:dynamodb:::table/*/backup/*`, or on `table//backup/*` when `TableName` filters the list (measured on DynamoDB) | The same on all four backends (the check runs in the server before the backend is reached). A statement on `*` or `table/*` covers every list; one on `table//backup/*` (or `table//*`) covers only the list filtered to that table; one on the table's own ARN, `table/`, covers none. The unfiltered list is one resource, so a Deny on `table//backup/*` denies the list filtered to that table and not the unfiltered list that would include its backups, which follows from the resources the service evaluates. A `TableName` that is not a string is evaluated as no filter; the engine then refuses the request. These resources have been evaluated since v0.1.14; the admin guide's compatibility notes describe what earlier builds evaluated | -| Authorization of `RestoreTableFromBackup` | `dynamodb:RestoreTableFromBackup` on the backup ARN, and `dynamodb:Scan`, `dynamodb:Query`, `dynamodb:GetItem`, `dynamodb:PutItem`, `dynamodb:UpdateItem`, `dynamodb:DeleteItem`, and `dynamodb:BatchWriteItem` on `table/`, each of which must be allowed; `dynamodb:RestoreTableFromBackup` is not evaluated on the target (measured on DynamoDB) | The same eight evaluations on all four backends, in that order: the backup first, then the target under each item action in the order listed, stopping at the first denial, which the `AccessDeniedException` names (`User: ... is not authorized to perform: dynamodb:Scan on resource: arn:aws:dynamodb:::table/`); the service's order was not measured. A missing `TargetTableName` is evaluated as `table/` (an empty name, which no statement but `*`-style wildcards covers); the engine then refuses the request. The seven item-action evaluations read the target ARN's resource tags: a target that does not exist has none, one that exists is evaluated with its tags and the restore then fails `TableAlreadyExistsException` (see Tag conditions on backups). Every DynamoDB condition key (`dynamodb:LeadingKeys`, `dynamodb:Attributes`, `dynamodb:Select`, `dynamodb:ReturnValues`, `dynamodb:ReturnConsumedCapacity`, `dynamodb:FullTableScan`, `dynamodb:EnclosingOperation`) is absent in these seven evaluations, so `ForAllValues:*` and `Null: true` conditions pass and bare `StringEquals` and `Bool` conditions fail: an Allow of the item actions conditioned on `ForAllValues:StringEquals dynamodb:LeadingKeys` grants the restore of every item in the backup, an Allow of `dynamodb:Scan` conditioned on `Bool dynamodb:FullTableScan: false` blocks every restore, and a Deny of `dynamodb:Scan` conditioned on `Bool dynamodb:FullTableScan: true` blocks none; the keys the service sets in these evaluations were not measured. The backup ARN is evaluated as the backup it names in this deployment: the table and backup id from the request, in the server's region and the caller's account, whatever partition, region or account the caller wrote, with surrounding whitespace trimmed as the engine trims it. The engine resolves the same table and id (under the server's region first, then as written for a backup created under an earlier `server.region`), so it never acts on a backup other than the one evaluated. `DescribeBackup` and `DeleteBackup` are evaluated the same way. These resources have been evaluated since v0.1.14 (see the admin guide's compatibility notes). A Deny of `dynamodb:RestoreTableFromBackup` on a table does not block restores into it; deny one of the seven item actions on it instead | +| Authorization of `RestoreTableFromBackup` | `dynamodb:RestoreTableFromBackup` on the backup ARN, and `dynamodb:Scan`, `dynamodb:Query`, `dynamodb:GetItem`, `dynamodb:PutItem`, `dynamodb:UpdateItem`, `dynamodb:DeleteItem`, and `dynamodb:BatchWriteItem` on `table/`, each of which must be allowed; `dynamodb:RestoreTableFromBackup` is not evaluated on the target (measured on DynamoDB) | The same eight evaluations on all four backends, in that order: the backup first, then the target under each item action in the order listed, stopping at the first denial, which the `AccessDeniedException` names (`User: ... is not authorized to perform: dynamodb:Scan on resource: arn:aws:dynamodb:::table/`); the service's order was not measured. A missing `TargetTableName` is evaluated as `table/` (an empty name, which no statement but `*`-style wildcards covers); the engine then refuses the request. The seven item-action evaluations read the target ARN's resource tags: a target that does not exist has none, one that exists is evaluated with its tags and the restore then fails `TableAlreadyExistsException` (see Tag conditions on backups). Every DynamoDB condition key (`dynamodb:LeadingKeys`, `dynamodb:Attributes`, `dynamodb:Select`, `dynamodb:ReturnValues`, `dynamodb:ReturnConsumedCapacity`, `dynamodb:FullTableScan`, `dynamodb:EnclosingOperation`) is absent in these seven evaluations, so `ForAllValues:*` and `Null: true` conditions pass and bare `StringEquals` and `Bool` conditions fail: an Allow of the item actions conditioned on `ForAllValues:StringEquals dynamodb:LeadingKeys` grants the restore of every item in the backup, an Allow of `dynamodb:Scan` conditioned on `Bool dynamodb:FullTableScan: false` blocks every restore, and a Deny of `dynamodb:Scan` conditioned on `Bool dynamodb:FullTableScan: true` blocks none; the keys the service sets in these evaluations were not measured. The backup ARN is evaluated as the backup it names in this deployment: the table and backup id from the request, in the server's region and the caller's account, whatever partition, region or account the caller wrote, with one trailing line terminator stripped as the engine strips it. The engine resolves the same table and id (under the server's region first, then as written for a backup created under an earlier `server.region`), so it never acts on a backup other than the one evaluated. `DescribeBackup` and `DeleteBackup` are evaluated the same way. These resources have been evaluated since v0.1.14 (see the admin guide's compatibility notes). A Deny of `dynamodb:RestoreTableFromBackup` on a table does not block restores into it; deny one of the seven item actions on it instead | | Multi-part base table keys (preview) | Not supported | A store-backed backup of a table created under `limits.allow_multipart_table_keys` is written `unordered`, and its restore preserves the item set: the restored table holds what the source's `Scan` held, with the source's key schema and attribute definitions, the target laid out as a natively created table (`bulk_load` keys rows with the backend's own key functions) *(measured on PostgreSQL and SQLite with the preview enabled, `tests/test_backup_job.py`; the engine test `a_multi_part_key_manifest_is_registered`)*. The preview's item paths address such a table by its first HASH attribute on every backend, restored or not: on PostgreSQL a `GetItem` by the whole key finds nothing on the source or on the restored table (a `Query` naming both key attributes does find the item), on SQLite the source itself keeps one item per first HASH key value and a `GetItem` returns that item whatever second key it was given, and a `Query` on the first HASH key alone is refused on both ("Query condition missed key schema element") *(measured on PostgreSQL and SQLite with the preview enabled)*. An in-catalog backup of such a table (no store, or Cassandra) is refused at restore with `ValidationException` *(from the code and storage-level tests)* | | `DeleteBackup` and `DeleteTable` during a restore | `DeleteTable` on the `CREATING` target is `ResourceInUseException`. `DeleteBackup` during a restore was not measured | While the target is `CREATING`, `DeleteTable` on it is `ResourceInUseException` on all four backends, as on the service. `DeleteBackup` on its source backup is `BackupInUseException` on all four: that refusal is ExtendDB's contract, not measured against the service. Both succeed once the target is `ACTIVE`. How the restore and `DeleteBackup` are ordered differs *(from the code)*. PostgreSQL and SQLite register the restore in the transaction that creates the target, holding the backup row, so a concurrent `DeleteBackup` is ordered strictly before (the restore then finds no backup) or after (it finds the restore). MongoDB runs the restore's registration and `DeleteBackup`'s claim each as one session transaction that first increments a lock field on the backup's catalog document while it is `AVAILABLE`, so the two conflict and one orders wholly before the other: a `DeleteBackup` that wins leaves the registration no `AVAILABLE` backup (`BackupNotFoundException`), a registration that wins makes the `DeleteBackup` `BackupInUseException`. Cassandra uses two lightweight transactions on different partitions: the target's row is inserted first (`IF NOT EXISTS`, which reserves the name), then the restore is registered on the backup's row (`IF backup_status = 'AVAILABLE'`), which `DeleteBackup` claims on the same partition; a concurrent `DescribeTable` can therefore see a `CREATING` target for a restore that then fails with `BackupNotFoundException`, after which the target is removed. On MongoDB `DeleteBackup` writes the backup `DELETING` before it drops the data and `DELETED` after; a `DeleteBackup` whose request fails or is cancelled after the drop started leaves the backup `DELETING`, which `DescribeBackup`, `ListBackups` and a restore treat as gone (`BackupNotFoundException`), and a retry of `DeleteBackup` finishes the drop and answers `DELETED` *(from the code and storage-level tests)*. MongoDB reads the catalog from the primary with read concern `local` regardless of the connection string, which the lock and the job records rely on; the connection string must use `readPreference=primary` (any other read preference is refused at startup). The write concern follows the connection string and must be `majority` (the server default): a connection string with `w=1` is refused at startup, because a `DELETING` write or a job record acknowledged under `w=1` just before a primary failover can be rolled back | | Concurrent restores of one backup | A second `RestoreTableFromBackup` of a backup while a restore from it is still `CREATING` is `BackupInUseException` (measured) | The same on all four backends: the second restore is refused with `BackupInUseException` and creates nothing; the check runs inside the transaction that registers the restore (PostgreSQL, with the backup row locked `FOR UPDATE`; SQLite), inside the claim on the backup document followed by a check for a `CREATING` target of the backup (MongoDB), or inside the lightweight transaction on the backup row (Cassandra), so two simultaneous requests cannot both pass. For a store-backed restore the registration takes the same lock on the `backup_index` row instead of the legacy `backups` row (PostgreSQL `SELECT ... FOR UPDATE`, SQLite the `BEGIN IMMEDIATE` write transaction, MongoDB a `$inc lock_seq` on the `backup_index` document, Cassandra the `active_restores` lightweight transaction on the backup's partition), the same ordering guarantee, so a legacy restore and a store-backed restore of two different backups never contend and a `DeleteBackup` of a store-backed backup meets only store-backed registrations. Two concurrent registrations of one backup leave one restore target on Cassandra as on MongoDB: the registration's lightweight transaction (`IF backup_status = 'AVAILABLE' AND active_restores = null`) is linearized on the backup's partition, so the second finds `active_restores` non-null and is `BackupInUseException`; the in-use pre-read is advisory *(storage-level tests on both)*. Once the first target is `ACTIVE` the backup restores again; on MongoDB the check reads majority-committed data (at the default transaction read concern) while `DescribeTable` reads at `local`, so a `RestoreTableFromBackup` or `DeleteBackup` issued within the majority-commit lag after `DescribeTable` first shows the target `ACTIVE` can still be `BackupInUseException` and succeeds when retried (the lag is the journal flush plus any concurrent batch write still holding an earlier oplog slot; measured at 7 to 12 ms, once in about 2,000 observations, with a 3,000-item insert running beside the write). A restore of a backup whose `DeleteBackup` is in progress answers `BackupNotFoundException` on every backend (the service's answer was not measured), by two mechanisms: on MongoDB and Cassandra the delete marks the backup `DELETING` before it drops the data, and the restore finds no `AVAILABLE` backup; on PostgreSQL and SQLite the restore waits for the delete's transaction and then finds no backup. Earlier builds accepted concurrent restores of one backup on PostgreSQL, SQLite, and Cassandra, and on MongoDB after a 2 s retry | diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 92bfc362c..a1981898e 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -130,7 +130,7 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb |-------|---------------|--------|-------| | Concurrent restores | 50 | Partial | Every backend: one server process runs at most `[backup] max_concurrent_jobs` (default 4, at most 1024) backup and restore jobs at once, `CreateBackup` and `RestoreTableFromBackup` together and not per account; a request that finds every slot held waits up to 30 s for one (holding nothing while it waits: the permit is the last of its checks) and is then refused with `LimitExceededException` ("Too many backup and restore jobs are running on this server (at most N at once, the [backup] max_concurrent_jobs bound); retry later") and creates nothing (storage-level and engine tests; measured on PostgreSQL with `max_concurrent_jobs = 1` on an earlier build that did not wait: a running restore made a CreateBackup and a second restore refuse in under 60 ms). On PostgreSQL `pool_size` and `catalog_pool_size` are raised to at least `2 * max_concurrent_jobs + 10` so every admitted job has a connection. SQLite also bounds the snapshot slots `CreateBackup` and table snapshots (#395) share, a count derived from `[storage.sqlite] pool_size` (the formula is stated once, on that setting's documentation in `SqliteConfig`; 4 for the default pool) so half the pool stays free for ordinary requests; a server raises a smaller `pool_size` to `2 * (max_concurrent_jobs + 1)`, at most 34 (the slots are capped at 16), with a warning naming both numbers, so the slot bound refuses no job the `max_concurrent_jobs` permit admitted (no change at the defaults: a pool of 10 has 4 slots for 4 jobs); above 16 jobs a 17th concurrent job is refused by the slot. A `CreateBackup` that finds no slot free is refused at once with the same `LimitExceededException`, its parenthesis naming that bound and its count in place of `max_concurrent_jobs` ("at most N at once, the [storage.sqlite] pool_size snapshot-slot bound"); PostgreSQL bounds open table snapshots at half its (raised) pool the same way, naming `[storage.postgres] pool_size snapshot-slot`; a PostgreSQL job whose dedicated claim connection the database server refuses is refused with the same exception naming the server's connection slots ("the database server has no connection slot left for the job"), with no count; the same error while `extenddb backup purge` holds the catalog's maintenance claim names a backup maintenance command and the claim, not a bound. A restore request on any backend that is not registered within 60 seconds (`RESTORE_REGISTRATION_TIMEOUT`) answers an internal error while the restore continues in the background. A restore from an S3 store holds the compressed backup size at `spool_path` while it runs; a restore's write batch on SQLite and Cassandra is bounded at 32 MiB of item text, measured on the serialized item (not on the service's `item_size_bytes`), and on Cassandra the item is serialized once more to measure it, a CPU cost per item the bound buys; a restore ends by counting the target against the manifest's item total, which on Cassandra is a full `COUNT(*)` of the restored table (one scan of a CREATING table, run once per restore and once more on a resume without recorded progress; no run has measured its cost past 12,000 rows, the largest Cassandra restore measured; a transient failure of this count is retried a few times, and a count that keeps failing leaves the record RUNNING for the reconciler to resume rather than failing the restore and removing its loaded target) | | `BackupName` and `TableName` on `CreateBackup`, `TableName` on `ListBackups` | Length 3 to 255, `[a-zA-Z0-9_.-]+` | Enforced | The service model's constraints, with its texts ("1 validation error detected: Value '' at 'backupName' failed to satisfy constraint: ...", "2 validation errors detected: ...; ..." when length and pattern both fail). Length is counted in characters. `BackupName` takes the model's 3 to 255; a `TableName` member takes the deployment's `[limits]` `min_table_name_length` and `max_table_name_length` (defaults 3 and 255), as `CreateTable` does, so a table the deployment can create can be listed and backed up whatever its name, as on the service: a name over 255 bytes (with `max_table_name_length` raised) or made only of dots fits no store prefix, so the store-backed create refuses it before it opens a snapshot or writes a row, and the in-catalog create (no store, Cassandra) carries it (see the differences document's backup creation row). Both members may also be the table's ARN; an ARN whose region is not the server's is `ValidationException` "1 validation error detected: Invalid AWS region in ''", the service's text. The value is echoed in the message as sent | -| `BackupArn` | 37 to 1024 characters | Maximum enforced; minimum implied | Surrounding ASCII whitespace is trimmed first, then over 1024 bytes, not of the backup ARN shape, a control or non-ASCII character, or a region outside `[a-z0-9-]`, an account that is not digits, or a table name outside `[a-zA-Z0-9_.-]` is `ValidationException` "Invalid Request: BackupArn is not valid"; the right shape with an id that is not a backup id is "Invalid Backup ARN"; a digit-only account that is not the caller's is `AccessDeniedException`. No minimum is checked: the shortest string of the right shape is longer than 37 characters. Another region of the caller's account resolves (the server's region is tried first, then the ARN as written). `ListBackups`'s `ExclusiveStartBackupArn` must also match the account, the region, and `TableName` when given | +| `BackupArn` | 37 to 1024 characters | Maximum enforced; minimum implied | One trailing line terminator (`\n`, `\r\n`, `\r`, U+0085, U+2028 or U+2029) is stripped first. An ARN that starts with whitespace is `ValidationException` "Invalid Backup ARN". Then any other whitespace, over 1024 bytes, not of the backup ARN shape, a control or non-ASCII character, or a region outside `[a-z0-9-]`, an account that is not digits, or a table name outside `[a-zA-Z0-9_.-]` is `ValidationException` "Invalid Request: BackupArn is not valid"; the right shape with an id that is not a backup id is "Invalid Backup ARN"; a digit-only account that is not the caller's is `AccessDeniedException`. No minimum is checked: the shortest string of the right shape is longer than 37 characters. Another region of the caller's account resolves (the server's region is tried first, then the ARN as written). `ListBackups`'s `ExclusiveStartBackupArn` must also match the account, the region, and `TableName` when given | | `ListBackups` page size | 100 | Enforced | `Limit` 1 to 100, default 100; more rows come back through `LastEvaluatedBackupArn` and `ExclusiveStartBackupArn`. Each request reads every backup of the account (or of the table, with `TableName`) and pages in memory, so walking N backups reads about N²/100 rows. `TimeRangeLowerBound`, `TimeRangeUpperBound`, and `BackupType` filter the list before paging; a bound before the epoch, or a lower bound above the upper bound ("Time range lower bound must be less than or equal to upper bound"), is `ValidationException` | | Backup store | A backup lives in the service's own storage | N/A | `[backup.store]` selects where CreateBackup writes its backups on PostgreSQL, SQLite and MongoDB (Cassandra, any backend without a store, and SQLite on a platform where the serve lock is not taken (not Unix), write the in-catalog format) and where restores and deletes of store-backed backups read: a filesystem root (`backups/` beside a SQLite database file when the section is absent), an S3 bucket and prefix, or `disabled`. The knobs are `[backup]`: `data_file_target_bytes` 64 MiB (minimum 32 MiB), `heartbeat_interval_secs` 15, `stale_job_after_secs` 300 (at least three heartbeats), `failed_row_retention_secs` 7 days, `reconcile_interval_secs` 60, `max_concurrent_jobs` 4 per instance, `spool_path` (required with an S3 store except beside a SQLite database file). A filesystem store holds every backup's compressed size under its root, beside the database on the SQLite default, and `extenddb destroy` leaves it; a restore from an S3 store holds the compressed backup size at `spool_path` while it runs. Instances that share a catalog must share one store root; an unhealthy store refuses CreateBackup where it writes to the store and the restore and delete of store-backed backups with `ValidationException` naming the store's kind, and the server keeps serving (`/health` reports `degraded`). See the admin guide's `[backup.store]` | | Backup data file | Not specified | N/A | A data file holds one item per line as DynamoDB JSON, gzip-compressed, in key order on a table whose key schema is orderable (`item_order` in the manifest); a line is at most 32 MiB (`MAX_LINE_BYTES`, which holds the largest line a 400 KB item can expand to, 27.7 MB); a file closes at the first item that takes its uncompressed bytes to or past `[backup] data_file_target_bytes` (default 64 MiB, minimum 32 MiB, the line cap), so it exceeds the knob by less than one line. The snapshot streams on PostgreSQL and SQLite page the table by key and cut each page at 64 MiB of item text (`SNAPSHOT_FETCH_BYTES`, a constant), so a page holds at most that plus one row; MongoDB's batches are bounded by the server's 16 MiB reply | diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index ab3b307fe..e1a86e76d 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,6 +388,12 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### v1.1.0: a backup ARN with whitespace around it is refused, except one trailing line terminator + +**What changed.** `DescribeBackup`, `DeleteBackup`, `RestoreTableFromBackup` and the `ExclusiveStartBackupArn` of `ListBackups` strip one trailing line terminator (`\n`, `\r\n`, `\r`, U+0085, U+2028 or U+2029) from the backup ARN. They refuse any other whitespace around it, as DynamoDB does (measured on 2026-11-21). An ARN that starts with whitespace is `ValidationException` "Invalid Backup ARN". Other whitespace after the ARN, two line terminators included, is `ValidationException` "Invalid Request: BackupArn is not valid". 1.0.0 trimmed all ASCII whitespace from both ends and resolved such an ARN (#617). An ARN followed by one U+0085, U+2028 or U+2029 now resolves, and 1.0.0 refused it. For a backup that does not exist, the `BackupNotFoundException` text now names the ARN as the request wrote it, its line terminator included, as on DynamoDB. + +**Who is affected.** A client that sends a backup ARN with whitespace before it, or with any whitespace after it other than one line terminator. An ARN sent as `CreateBackup` or `ListBackups` returned it is not affected. No catalog migration is required, and a rollback to 1.0.0 brings back the trim. + ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` **What changed.** The Cassandra backend runs its reads and writes at `LOCAL_QUORUM`. 0.1.15 ran many of them at `ONE`, the driver's default, in each area: items (the reads of GetItem, Query and Scan among them), transactions, TTL, streams, the catalog, IAM and `init`. A read with `ConsistentRead` `false` also runs at `LOCAL_QUORUM`. A lightweight transaction runs Paxos at `LOCAL_SERIAL` and commits at `LOCAL_QUORUM`. 0.1.15 ran many of its lightweight transactions at those levels already, and others, among them the admin user creation and most IAM writes, at the driver's defaults, `SERIAL` and `ONE`. Batches ran at `LOCAL_QUORUM` before and still do. No setting changes these levels (#945). diff --git a/tests/test_backup_restore_fidelity.py b/tests/test_backup_restore_fidelity.py index 12da741c7..b5453a595 100644 --- a/tests/test_backup_restore_fidelity.py +++ b/tests/test_backup_restore_fidelity.py @@ -2328,8 +2328,7 @@ def test_backup_arn_shapes_the_service_refuses_and_trims(dynamodb_client): assert desc["BackupDetails"]["BackupArn"] == backup_arn, resolving assert desc["BackupDetails"]["BackupStatus"] == "AVAILABLE" - not_valid = "Invalid Request: BackupArn is not valid" - invalid_id = "Invalid Backup ARN" + not_valid, invalid_id = _ARN_NOT_VALID, _INVALID_BACKUP_ARN bad = [ (f"{prefix}/{backup_id}\x00", not_valid), (f"{prefix}/{backup_id}\x07", not_valid), @@ -2368,6 +2367,96 @@ def test_backup_arn_shapes_the_service_refuses_and_trims(dynamodb_client): _cleanup(client, backup_arn, source) +# Whitespace around a BackupArn, measured on DynamoDB on 2026-11-21. Each +# row below was sent at least twice, with the same answer each time. One +# trailing line terminator (\n, \r\n, \r, U+0085, U+2028 or U+2029) +# resolves on DescribeBackup and as an ExclusiveStartBackupArn; it is not sent +# to DeleteBackup or RestoreTableFromBackup, which would act on the backup. +# Other whitespace after the ARN, and any whitespace before it, is refused. +# For a backup that does not exist, BackupNotFoundException names the ARN as +# the request wrote it, its line terminator included. +_ARN_NOT_VALID = "Invalid Request: BackupArn is not valid" +_INVALID_BACKUP_ARN = "Invalid Backup ARN" +_CURSOR_NOT_VALID = ( + "Invalid Request: The supplied ExclusiveStartBackupArn is not a valid backup arn" +) +_NOT_FOUND = "Backup not found: " +_RESOLVING_SUFFIXES = ["\n", "\r\n", "\r", "\u0085", "\u2028", "\u2029"] +_REFUSED_SUFFIXES = [ + "\n\n", "\r\n\r\n", "\n\r", "\r\r", " \n", "\n ", " ", "\t", "\x0c", "\x0b", "\u00a0", +] +_REFUSED_AROUND = [ + (" ", ""), ("\t", ""), ("\n", ""), ("\r\n", ""), ("\x0c", ""), ("\x0b", ""), + ("\u00a0", ""), ("\n", "\n"), +] + + +def _whitespace_cases(): + for suffix in _RESOLVING_SUFFIXES: + for op in ("DescribeBackup", "ListBackups"): + yield pytest.param(op, "", suffix, None, id=f"{op}-{suffix!r}") + for suffix in _REFUSED_SUFFIXES: + for op in ("DescribeBackup", "DeleteBackup", "RestoreTableFromBackup"): + yield pytest.param(op, "", suffix, _ARN_NOT_VALID, id=f"{op}-{suffix!r}") + yield pytest.param( + "ListBackups", "", suffix, _CURSOR_NOT_VALID, id=f"ListBackups-{suffix!r}", + marks=pytest.mark.xfail( + not _is_real_dynamodb(), strict=True, + reason="ExtendDB answers the BackupArn text for a malformed cursor (#1315)", + ), + ) + for prefix, suffix in _REFUSED_AROUND: + for op in ("DescribeBackup", "DeleteBackup", "RestoreTableFromBackup", "ListBackups"): + yield pytest.param( + op, prefix, suffix, _INVALID_BACKUP_ARN, id=f"{op}-{prefix!r}-{suffix!r}" + ) + for suffix in ["", *_RESOLVING_SUFFIXES]: + for op in ("DescribeBackup", "DeleteBackup", "RestoreTableFromBackup"): + yield pytest.param(op, "", suffix, _NOT_FOUND, id=f"{op}-missing-{suffix!r}") + + +@pytest.fixture(scope="module") +def whitespace_backup(dynamodb_client): + """A table and one AVAILABLE backup of it, shared by the whitespace cases: + a refused spelling changes nothing, and no resolving spelling is sent to + DeleteBackup or RestoreTableFromBackup.""" + source = f"restore-arnspace-{uuid.uuid4().hex[:10]}" + backup_arn = None + try: + _simple_source(dynamodb_client, source) + backup_arn = _create_backup(dynamodb_client, source) + yield source, backup_arn + finally: + _cleanup(dynamodb_client, backup_arn, f"{source}-x", source) + + +@pytest.mark.parametrize(("operation", "prefix", "suffix", "expected"), list(_whitespace_cases())) +def test_backup_arn_whitespace_as_the_service_reads_it( + whitespace_backup, operation, prefix, suffix, expected +): + source, backup_arn = whitespace_backup + if expected == _NOT_FOUND: + # The same ARN with another hex suffix in its backup id names no backup. + other = "1" * 8 if backup_arn.endswith("0" * 8) else "0" * 8 + backup_arn = backup_arn[:-8] + other + spelled = prefix + backup_arn + suffix + if operation == "ListBackups": + body = {"TableName": source, "ExclusiveStartBackupArn": spelled} + else: + body = {"BackupArn": spelled} + if operation == "RestoreTableFromBackup": + body["TargetTableName"] = f"{source}-x" + resp = _signed(operation, body) + if expected is None: + assert resp.status_code == 200, (spelled, resp.text) + elif expected == _NOT_FOUND: + assert resp.status_code == 400, (spelled, resp.text) + assert _error(resp) == ("BackupNotFoundException", _NOT_FOUND + spelled), spelled + else: + assert resp.status_code == 400, (spelled, resp.text) + assert _error(resp) == ("ValidationException", expected), spelled + + def test_list_backups_cursor_and_time_range_are_checked(dynamodb_client): """ExclusiveStartBackupArn of another account is ValidationException "Invalid Request: The supplied ExclusiveStartBackupArn does not match the From 49bd69e3b4db6ff1d34c0617e3d024f3002886e6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:06:08 +0000 Subject: [PATCH 2/2] fix(server): parse a backup ARN as sent in the ARN gate The server's ARN gate refuses a backup ARN whose table name is outside the pattern with "Invalid Backup ARN". It stripped one trailing line terminator with trim_backup_arn before it parsed the ARN. The strip changed the gate's answer for one kind of input: a backup id that is one line terminator, as in ".../table//backup/\n". The strip left an empty backup id, the ARN did not parse, and the gate passed it on. RestoreTableFromBackup then got "Invalid Request: BackupArn is not valid" from the engine. Without the strip, the gate answers "Invalid Backup ARN" on DescribeBackup, DeleteBackup and RestoreTableFromBackup. DynamoDB answers "Invalid Backup ARN" to that ARN on DescribeBackup and RestoreTableFromBackup (measured in us-east-1 on 2026-11-25, twice each). The strip touches only the end of the ARN, and the gate reads only the table name and the resource kind. So for every other ARN the gate gives the same answer with and without the strip. The gate now parses the ARN as sent. A new row of the gate's unit test sends ".../table//backup/\n" and fails with the strip in place. The doc comment of trim_backup_arn now names authorization and the engine as the layers that strip. --- crates/core/src/backup_format/layout.rs | 5 +++-- crates/server/src/arn_gate.rs | 11 ++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/core/src/backup_format/layout.rs b/crates/core/src/backup_format/layout.rs index 94f8b0f79..964cb9dd1 100644 --- a/crates/core/src/backup_format/layout.rs +++ b/crates/core/src/backup_format/layout.rs @@ -244,8 +244,9 @@ pub fn check_store_prefix_table_name(table_name: &str) -> Result<(), FormatError /// 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. Every layer that reads a backup ARN from a -/// request strips with this function, so they act on the same string. +/// [`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.strip_suffix("\r\n") diff --git a/crates/server/src/arn_gate.rs b/crates/server/src/arn_gate.rs index 17caf1006..c07a98417 100644 --- a/crates/server/src/arn_gate.rs +++ b/crates/server/src/arn_gate.rs @@ -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(extenddb_core::backup_format::trim_backup_arn(arn)) { + match parse(arn) { Some(res) if matches!(res.sub, Some(SubResource::Backup(_))) && !in_pattern(&res.table) => { Err(validation("Invalid Backup ARN".to_owned())) } @@ -539,12 +539,17 @@ 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 reads the ARN as the engine does: one trailing line - // terminator stripped, and whitespace before it left for 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"