Skip to content
Merged
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
14 changes: 5 additions & 9 deletions crates/engine/src/partiql/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
//! rejection, and `ClientRequestToken` idempotency). It translates each
//! PartiQL statement into the corresponding transact member, cancels the write
//! form with positional reasons when a member cannot be translated against its
//! table, and remaps two error strings the PartiQL surface words differently.
//! table, and remaps the cancellation reason of a duplicate-key `INSERT`, which
//! the PartiQL surface words differently.
//!
//! The members are authorized after the checks of their form (see
//! `authorize_members`). In an all-read transaction, a member on a table
Expand Down Expand Up @@ -497,13 +498,14 @@ fn reshape_write(result: DispatchResult) -> DispatchResult {
}
}

/// Remap the two write errors the PartiQL surface words differently from the
/// Remap the write error the PartiQL surface words differently from the
/// classic `TransactWriteItems` handler.
///
/// A duplicate-key `INSERT` fails the underlying `Put`'s `attribute_not_exists`
/// condition, which the handler reports as `ConditionalCheckFailed`; the PartiQL
/// surface reports `DuplicateItem` for that position. A reused idempotency token
/// with a different body uses the PartiQL message.
/// with a different body passes through: both surfaces answer it with
/// `transact_write_helpers::IDEMPOTENT_MISMATCH_MESSAGE`.
fn remap_write_error(err: DynamoDbError, is_insert: &[bool]) -> DynamoDbError {
match err {
DynamoDbError::TransactionCanceledException {
Expand All @@ -518,12 +520,6 @@ fn remap_write_error(err: DynamoDbError, is_insert: &[bool]) -> DynamoDbError {
}
cancellation(reasons)
}
DynamoDbError::IdempotentParameterMismatchException(_) => {
DynamoDbError::IdempotentParameterMismatchException(
"Specified idempotent token was used with different request parameters within the idempotency window"
.to_owned(),
)
}
other => other,
}
}
Expand Down
184 changes: 170 additions & 14 deletions crates/engine/src/transact_write_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
use extenddb_core::error::DynamoDbError;
use extenddb_core::expression::{ExpressionMaps, PathElement, UpdateAction};
use extenddb_core::types::{
ReturnItemCollectionMetrics, ReturnValuesOnConditionCheckFailure, TableKeyInfo,
attribute_value_size, extract_key, item_size_bytes,
ReturnConsumedCapacity, ReturnItemCollectionMetrics, ReturnValuesOnConditionCheckFailure,
TableKeyInfo, attribute_value_size, extract_key, item_size_bytes,
};
use extenddb_storage::TransactWriteOp;
use hmac::{Hmac, Mac};
Expand Down Expand Up @@ -260,14 +260,51 @@ pub(crate) fn validate_client_request_token(token: &str) -> Result<(), DynamoDbE
Ok(())
}

/// Compute a collision-resistant fingerprint of the transaction operations.
/// The message of the `IdempotentParameterMismatchException` that a request
/// answers when its token was used by a different request inside the
/// idempotency window. `TransactWriteItems` and `ExecuteTransaction` both
/// answer with it.
pub(crate) const IDEMPOTENT_MISMATCH_MESSAGE: &str = "Specified idempotent token was used with \
different request parameters within the idempotency window";

/// Compute a collision-resistant fingerprint of the transaction request.
///
/// Uses HMAC-SHA256 keyed by the client request token over the JSON-serialized
/// `TransactItems` array. The keyed hash prevents an attacker from crafting a
/// `TransactItems` array, followed by the request's `ReturnConsumedCapacity`
/// and `ReturnItemCollectionMetrics` values. The service compares those two
/// fields on a token replay and treats an absent field as `NONE`, so each
/// field contributes to the hash only when it is not `NONE`. An
/// `ExecuteTransaction` write calls `handle_transact_write_items` with its
/// `ReturnConsumedCapacity`, so this fingerprint decides its replays too.
///
/// Versions before this change hashed the items alone. A retry replays only
/// when its fingerprint equals the stored one. A token stored before an
/// upgrade or a downgrade therefore answers as follows while the backend
/// keeps it:
/// - A token stored for a request with neither field, or with both set to
/// `NONE`, has the same fingerprint in both versions. An identical retry
/// replays in both directions.
/// - A token that an earlier version stored for a request with `TOTAL`,
/// `INDEXES` or `SIZE` answers `IdempotentParameterMismatchException` to an
/// identical retry on this version. A retry without the field replays.
/// - A token that this version stored for a request with `TOTAL`, `INDEXES`
/// or `SIZE` answers `IdempotentParameterMismatchException` to every retry
/// on an earlier version. This includes an identical retry and a retry
/// without the field.
///
/// PostgreSQL, SQLite and MongoDB keep a token for 10 minutes. Cassandra
/// keeps it with no expiry.
///
/// The keyed hash prevents an attacker from crafting a
/// different request body that produces the same fingerprint for a given token.
/// The result is truncated to 16 hex chars (64 bits) for storage efficiency
/// while remaining collision-resistant for the idempotency use case.
pub(crate) fn compute_fingerprint(body: &Value, token: &str) -> String {
pub(crate) fn compute_fingerprint(
body: &Value,
token: &str,
return_consumed_capacity: ReturnConsumedCapacity,
return_item_collection_metrics: ReturnItemCollectionMetrics,
) -> String {
let items = body.get("TransactItems").unwrap_or(&Value::Null);
// serde_json::to_string on a Value is infallible — all Value variants
// are representable as JSON. Using unwrap_or_default as a defensive fallback.
Expand All @@ -278,6 +315,17 @@ pub(crate) fn compute_fingerprint(body: &Value, token: &str) -> String {
let mut mac =
Hmac::<Sha256>::new_from_slice(token.as_bytes()).expect("HMAC accepts any key length");
mac.update(json.as_bytes());
// The items JSON is a complete JSON value, so a suffix that is not JSON
// cannot coincide with the serialization of another items array.
match return_consumed_capacity {
ReturnConsumedCapacity::None => {}
ReturnConsumedCapacity::Total => mac.update(b"\nReturnConsumedCapacity=TOTAL"),
ReturnConsumedCapacity::Indexes => mac.update(b"\nReturnConsumedCapacity=INDEXES"),
}
match return_item_collection_metrics {
ReturnItemCollectionMetrics::None => {}
ReturnItemCollectionMetrics::Size => mac.update(b"\nReturnItemCollectionMetrics=SIZE"),
}
let result = mac.finalize().into_bytes();
hex::encode(&result[..8])
}
Expand Down Expand Up @@ -343,30 +391,138 @@ mod tests {
assert!(validate_client_request_token("abc!").is_err());
}

const NO_RCC: ReturnConsumedCapacity = ReturnConsumedCapacity::None;
const NO_RICM: ReturnItemCollectionMetrics = ReturnItemCollectionMetrics::None;

fn fp(body: &Value, token: &str) -> String {
compute_fingerprint(body, token, NO_RCC, NO_RICM)
}

#[test]
fn fingerprint_deterministic() {
let body: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t"}}]});
let a = compute_fingerprint(&body, "tok-1");
let b = compute_fingerprint(&body, "tok-1");
let a = fp(&body, "tok-1");
let b = fp(&body, "tok-1");
assert_eq!(a, b);
}

#[test]
fn fingerprint_differs_for_different_ops() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This case uses NONE only. A mutation that hashes the items only when ReturnConsumedCapacity is NONE passes all 7 unit tests and all 21 wire tests. In that build, a retry with TOTAL and different items is served as a replay that writes nothing. Measured: the service answers that retry with IdempotentParameterMismatchException and stores nothing, for TOTAL and for SIZE, two sends each. Please add the same check with ReturnConsumedCapacity::Total.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in bd07f9e. fingerprint_differs_for_different_ops_with_total and fingerprint_differs_for_different_ops_with_size run the different items check with TOTAL and with SIZE.

let a: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t1"}}]});
let b: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t2"}}]});
assert_ne!(
compute_fingerprint(&a, "tok-1"),
compute_fingerprint(&b, "tok-1")
);
assert_ne!(fp(&a, "tok-1"), fp(&b, "tok-1"));
}

/// A Return field is added to the hashed items, so a retry that sets the
/// field and changes the items is a mismatch, not a replay.
#[test]
fn fingerprint_differs_for_different_ops_with_total() {
let a: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t1"}}]});
let b: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t2"}}]});
let total =
|body| compute_fingerprint(body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM);
assert_ne!(total(&a), total(&b));
}

#[test]
fn fingerprint_differs_for_different_ops_with_size() {
let a: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t1"}}]});
let b: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t2"}}]});
let size =
|body| compute_fingerprint(body, "tok-1", NO_RCC, ReturnItemCollectionMetrics::Size);
assert_ne!(size(&a), size(&b));
}

#[test]
fn fingerprint_differs_for_different_tokens() {
let body: Value = serde_json::json!({"TransactItems": [{"Put": {"TableName": "t"}}]});
assert_ne!(
compute_fingerprint(&body, "tok-1"),
compute_fingerprint(&body, "tok-2")
assert_ne!(fp(&body, "tok-1"), fp(&body, "tok-2"));
}

/// The value stored for this body and token by 744ea291, whose fingerprint
/// hashed `TransactItems` alone. A request with neither Return field, or
/// with both set to NONE, must keep producing it so tokens stored before
/// the upgrade still replay.
const PINNED_ITEMS_ONLY: &str = "ef18f4e7c37d6b12";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Tokens stored with TOTAL, INDEXES or SIZE have the same upgrade exposure as the items-only value pinned here. Swapping the order of the two suffixes passes every test. Pinning the suffixed values for pinned_body() and tok-1 would catch that: TOTAL 8fa51ffc1314a046, INDEXES ee2c3412f0fdbdf1, SIZE 70eb830c93e9079f, TOTAL with SIZE e9957d3c7431e1d4 (HMAC-SHA256 recomputed outside the crate; the items-only value matches ef18f4e7c37d6b12).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in bd07f9e. A new test pins your four values for pinned_body() and tok-1, and with the two suffixes swapped the TOTAL with SIZE pin fails.


/// The values this version stores for this body and token when a Return
/// field is set. A later version must keep producing them so these tokens
/// replay after an upgrade, which fixes the suffix bytes and their order.
const PINNED_TOTAL: &str = "8fa51ffc1314a046";
const PINNED_INDEXES: &str = "ee2c3412f0fdbdf1";
const PINNED_SIZE: &str = "70eb830c93e9079f";
const PINNED_TOTAL_SIZE: &str = "e9957d3c7431e1d4";

/// Keys are written in sorted order at every level so the serialized
/// JSON is the same whether serde_json sorts map keys or preserves
/// insertion order (the MongoDB build enables `preserve_order` through
/// bson).
fn pinned_body() -> Value {
serde_json::json!({"TransactItems": [{"Put": {"Item": {"pk": {"S": "a"}}, "TableName": "t"}}]})
}

#[test]
fn fingerprint_items_only_keeps_stored_value() {
assert_eq!(fp(&pinned_body(), "tok-1"), PINNED_ITEMS_ONLY);
}

#[test]
fn fingerprint_with_return_fields_keeps_stored_values() {
let body = pinned_body();
let f = |rcc, ricm| compute_fingerprint(&body, "tok-1", rcc, ricm);
let total = ReturnConsumedCapacity::Total;
let indexes = ReturnConsumedCapacity::Indexes;
let size = ReturnItemCollectionMetrics::Size;
assert_eq!(f(total, NO_RICM), PINNED_TOTAL, "TOTAL");
assert_eq!(f(indexes, NO_RICM), PINNED_INDEXES, "INDEXES");
assert_eq!(f(NO_RCC, size), PINNED_SIZE, "SIZE");
assert_eq!(f(total, size), PINNED_TOTAL_SIZE, "TOTAL with SIZE");
}

#[test]
fn fingerprint_none_equals_absent() {
let mut body = pinned_body();
body["ReturnConsumedCapacity"] = Value::String("NONE".to_owned());
body["ReturnItemCollectionMetrics"] = Value::String("NONE".to_owned());
assert_eq!(
compute_fingerprint(
&body,
"tok-1",
ReturnConsumedCapacity::None,
ReturnItemCollectionMetrics::None
),
PINNED_ITEMS_ONLY
);
}

#[test]
fn fingerprint_differs_for_return_consumed_capacity() {
let body = pinned_body();
let total = compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM);
let indexes = compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Indexes, NO_RICM);
assert_ne!(total, PINNED_ITEMS_ONLY);
assert_ne!(indexes, PINNED_ITEMS_ONLY);
assert_ne!(total, indexes);
assert_eq!(
total,
compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM)
);
}

#[test]
fn fingerprint_differs_for_return_item_collection_metrics() {
let body = pinned_body();
let size = compute_fingerprint(&body, "tok-1", NO_RCC, ReturnItemCollectionMetrics::Size);
let both = compute_fingerprint(
&body,
"tok-1",
ReturnConsumedCapacity::Total,
ReturnItemCollectionMetrics::Size,
);
let total = compute_fingerprint(&body, "tok-1", ReturnConsumedCapacity::Total, NO_RICM);
assert_ne!(size, PINNED_ITEMS_ONLY);
assert_ne!(size, total);
assert_ne!(both, total);
assert_ne!(both, size);
}
}
20 changes: 14 additions & 6 deletions crates/engine/src/transact_write_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use crate::request_limits;
use crate::serialize_output;
use crate::stream_capture;
use crate::transact_write_helpers::{
PreparedOp, compute_fingerprint, validate_client_request_token, validate_no_key_updates,
IDEMPOTENT_MISMATCH_MESSAGE, PreparedOp, compute_fingerprint, validate_client_request_token,
validate_no_key_updates,
};
use crate::{DispatchMetrics, DispatchResult};
use extenddb_core::error::DynamoDbError;
Expand Down Expand Up @@ -48,11 +49,20 @@ pub async fn handle_transact_write_items(
serde_json::from_value(body.clone()).map_err(crate::deserialize_error)?;

// Compute fingerprint keyed by the client request token for collision
// resistance. Must happen after parsing so the token is available.
// resistance. Must happen after parsing so the token is available. The
// two Return fields are part of the fingerprint: the service refuses a
// replay that changes either of them.
let fingerprint = input
.client_request_token
.as_deref()
.map(|t| compute_fingerprint(&body, t))
.map(|t| {
compute_fingerprint(
&body,
t,
input.return_consumed_capacity,
input.return_item_collection_metrics,
)
})
.unwrap_or_default();

// At least one and at most 100 items. The server runs the same check
Expand Down Expand Up @@ -228,9 +238,7 @@ pub async fn handle_transact_write_items(
}
Err(extenddb_storage::error::StorageError::IdempotentMismatch) => {
return Err(DynamoDbError::IdempotentParameterMismatchException(
"The request uses the same client token as a previous, \
but different, request."
.to_owned(),
IDEMPOTENT_MISMATCH_MESSAGE.to_owned(),
));
}
Err(e) => return Err(storage_err_to_dynamo(e)),
Expand Down
18 changes: 17 additions & 1 deletion docs/design/04-component-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ Storage backends write stream records atomically with data writes when `stream`
- `ConditionFailed { old_item: Option<Item> }` — condition expression evaluated to false
- `TransactionCanceled(Vec<CancellationReason>)` — transaction failed with per-item reasons
- `IdempotentReplay` — idempotency token matched previous request
- `IdempotentMismatch` — idempotency token exists with different operations
- `IdempotentMismatch`: idempotency token exists with a different fingerprint (the items or a Return field)
- `IndexNotFound` — secondary index does not exist
- `Internal(String)` — backend-specific error

Expand Down Expand Up @@ -832,6 +832,22 @@ account in DynamoDB, so the same token value from two accounts never collides.
If a request arrives with the same `(account_id, token)` but a different
fingerprint, return `IdempotentParameterMismatchException`.

The fingerprint (`compute_fingerprint` in
`crates/engine/src/transact_write_helpers.rs`) is an HMAC-SHA256 keyed by the
token. It hashes the request's `TransactItems` JSON, then its
`ReturnConsumedCapacity` and `ReturnItemCollectionMetrics`. Each of the two
fields adds to the hashed input only when it is not `NONE`. The service treats
an absent field as `NONE` and refuses a replay that changes either field. The
stored value is the first 64 bits of the HMAC, as 16 hex characters. For a
`TransactWriteItems` request, the fingerprint hashes the items as the request
writes them. Some retries that the service replays therefore answer the
mismatch in ExtendDB (see "Transactions" in
`docs/differences-from-dynamodb.md`). ExtendDB translates an
`ExecuteTransaction` write into a `TransactWriteItems` request before it
computes the fingerprint. It builds the `TransactItems` from the parsed
statements and copies the request's token and `ReturnConsumedCapacity`. The
same fingerprint then decides the replays of the write.

## 10. Backend Plugin Architecture

ExtendDB uses a factory pattern with compile-time registration to enable
Expand Down
Loading
Loading