mod cursor;
mod error;
mod page;
mod signed;
pub const DEFAULT_PAGE_SIZE: u32 = 20;
pub const MAX_PAGE_SIZE: u32 = 100;
pub const DEFAULT_PAGE: u32 = 1;
pub const MAX_CURSOR_LENGTH: usize = 4096;
pub const MAX_CURSOR_KIND_LENGTH: usize = 128;
pub const MIN_CURSOR_SECRET_BYTES: usize = crate::signing::MIN_SIGNING_KEY_BYTES;
const CURSOR_VERSION: u8 = 1;
pub use cursor::{decode_cursor, decode_typed_cursor, encode_cursor, encode_typed_cursor};
pub use error::{CursorError, CursorPageBuildError, PaginationError};
pub use page::{
CursorPage, CursorPageRequest, OffsetPage, OffsetPageRequest, PageLimits, SortDirection,
};
pub use signed::SignedCursorCodec;
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use serde_json::json;
use super::{
CursorError, CursorPage, CursorPageRequest, MAX_CURSOR_LENGTH, OffsetPage,
OffsetPageRequest, PageLimits, PaginationError, SignedCursorCodec, decode_cursor,
decode_typed_cursor, encode_cursor, encode_typed_cursor,
};
use crate::result::{ClassifyError, ErrorKind};
const CURSOR_SECRET: &[u8] = b"0123456789abcdef0123456789abcdef";
const CURRENT_CURSOR_SECRET: &[u8] = b"current-secret-0123456789abcdef0";
const PREVIOUS_CURSOR_SECRET: &[u8] = b"previous-secret-0123456789abcdef";
#[test]
fn cursor_pages_round_trip_json_and_binary_with_optional_metadata() {
for total in [None, Some(2)] {
for next_cursor in [None, Some("next".to_owned())] {
let page = CursorPage::new(
vec![1_u32],
1,
next_cursor.clone(),
next_cursor.is_some(),
total,
)
.unwrap();
let json = serde_json::to_vec(&page).unwrap();
assert_eq!(
serde_json::from_slice::<CursorPage<u32>>(&json).unwrap(),
page
);
assert!(
serde_json::from_slice::<serde_json::Value>(&json)
.unwrap()
.get("total")
.is_some()
);
let binary = postcard::to_allocvec(&page).unwrap();
assert_eq!(
postcard::from_bytes::<CursorPage<u32>>(&binary).unwrap(),
page
);
}
}
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Cursor {
username: String,
id: String,
}
#[test]
fn limit_plus_one_rejects_invalid_metadata_and_preserves_encoder_errors() {
use super::CursorPageBuildError;
use std::convert::Infallible;
for cursor in [String::new(), "bad cursor".to_owned()] {
assert!(matches!(
CursorPage::from_limit_plus_one(vec![1, 2], 1, None, |_| Ok::<_, Infallible>(
cursor
)),
Err(CursorPageBuildError::Pagination(_))
));
}
assert!(matches!(
CursorPage::from_limit_plus_one(vec![1], 0, None, |_| Ok::<_, Infallible>(
"next".into()
)),
Err(CursorPageBuildError::Pagination(
PaginationError::PageSizeZero
))
));
assert!(matches!(
CursorPage::from_limit_plus_one(vec![1], 1, Some(0), |_| Ok::<_, Infallible>(
"next".into()
)),
Err(CursorPageBuildError::Pagination(
PaginationError::TotalLessThanItems { .. }
))
));
assert!(matches!(
CursorPage::from_limit_plus_one(vec![1, 2], 1, None, |_| Err("encoder failed")),
Err(CursorPageBuildError::Cursor("encoder failed"))
));
for items in [vec![], vec![1], vec![1, 2, 3]] {
let page = CursorPage::from_limit_plus_one(items, 2, None, |item| {
Ok::<_, Infallible>(format!("next_{item}"))
})
.unwrap();
let json = serde_json::to_value(&page).unwrap();
assert_eq!(
serde_json::from_value::<CursorPage<i32>>(json).unwrap(),
page
);
}
}
#[test]
fn custom_offset_limits_reject_overflow_at_construction() {
let limits = PageLimits::new(1, u32::MAX).unwrap();
assert!(matches!(
OffsetPageRequest::new_with_limits(Some(u32::MAX), Some(u32::MAX), limits),
Err(PaginationError::OffsetOverflow)
));
let last_safe = (i64::MAX / i64::from(u32::MAX)) as u32 + 1;
let request =
OffsetPageRequest::new_with_limits(Some(last_safe), Some(u32::MAX), limits).unwrap();
assert!(request.offset() > 0);
assert!(matches!(
OffsetPageRequest::new_with_limits(Some(last_safe + 1), Some(u32::MAX), limits),
Err(PaginationError::OffsetOverflow)
));
}
#[test]
fn validates_page_size_upper_bound() {
let result = CursorPageRequest::new(Some(101), None, false);
assert!(result.is_err());
}
#[test]
fn applies_custom_page_limits() {
let limits = PageLimits::new(25, 50).expect("limits should be valid");
let page = CursorPageRequest::new_with_limits(None, None, false, limits)
.expect("page request should be valid");
assert_eq!(page.page_size(), 25);
assert!(matches!(
CursorPageRequest::new_with_limits(Some(51), None, false, limits),
Err(PaginationError::PageSizeTooLarge { max: 50 })
));
}
#[test]
fn rejects_invalid_page_limits() {
assert!(matches!(
PageLimits::new(101, 100),
Err(PaginationError::DefaultPageSizeTooLarge {
default: 101,
max: 100
})
));
assert!(matches!(
PageLimits::default().with_max_cursor_length(0),
Err(PaginationError::MaxCursorLengthZero)
));
}
#[test]
fn page_limits_deserialization_uses_same_validation() {
assert!(
serde_json::from_value::<PageLimits>(json!({
"default_page_size": 101,
"max_page_size": 100,
"max_cursor_length": 4096
}))
.is_err()
);
let limits: PageLimits = serde_json::from_value(json!({
"default_page_size": 25,
"max_page_size": 50,
"max_cursor_length": 1024
}))
.expect("limits should deserialize");
assert_eq!(limits.default_page_size(), 25);
assert_eq!(limits.max_page_size(), 50);
assert_eq!(limits.max_cursor_length(), 1024);
}
#[test]
fn rejects_oversized_query_cursor() {
let limits = PageLimits::default().with_max_cursor_length(4).unwrap();
let result =
CursorPageRequest::new_with_limits(None, Some("12345".to_owned()), false, limits);
assert!(matches!(
result,
Err(PaginationError::CursorTooLarge { max: 4 })
));
}
#[test]
fn rejects_empty_query_cursor() {
let result = CursorPageRequest::new(None, Some(String::new()), false);
assert!(matches!(result, Err(PaginationError::CursorEmpty)));
}
#[test]
fn rejects_query_cursor_with_unsupported_characters() {
let result = CursorPageRequest::new(None, Some("cursor value".to_owned()), false);
assert!(matches!(
result,
Err(PaginationError::CursorInvalidCharacters)
));
}
#[test]
fn requests_round_trip_custom_limits_without_reapplying_default_policy() {
let limits = PageLimits::new(200, 500)
.unwrap()
.with_max_cursor_length(8192)
.unwrap();
let cursor =
CursorPageRequest::new_with_limits(Some(200), Some("a".repeat(5000)), false, limits)
.unwrap();
let offset = OffsetPageRequest::new_with_limits(Some(3), Some(200), limits).unwrap();
assert_eq!(
serde_json::from_value::<CursorPageRequest>(serde_json::to_value(&cursor).unwrap())
.unwrap(),
cursor
);
assert_eq!(
serde_json::from_value::<OffsetPageRequest>(serde_json::to_value(offset).unwrap())
.unwrap(),
offset
);
assert!(CursorPageRequest::new(Some(200), None, false).is_err());
assert!(
serde_json::from_value::<OffsetPageRequest>(
json!({"page": u32::MAX, "page_size": u32::MAX})
)
.is_err()
);
let page = CursorPage::new(vec![1], 200, cursor.into_cursor(), true, None).unwrap();
assert_eq!(
serde_json::from_value::<CursorPage<i32>>(serde_json::to_value(&page).unwrap())
.unwrap(),
page
);
}
#[test]
fn page_request_deserialization_validates_structure() {
assert!(
serde_json::from_value::<CursorPageRequest>(json!({
"page_size": 0,
"cursor": null,
"include_total": false
}))
.is_err()
);
assert!(
serde_json::from_value::<CursorPageRequest>(json!({
"page_size": 20,
"cursor": "bad cursor",
"include_total": false
}))
.is_err()
);
let request: CursorPageRequest = serde_json::from_value(json!({
"page_size": 20,
"cursor": "cursor_01",
"include_total": true
}))
.expect("request should deserialize");
assert_eq!(request.page_size(), 20);
assert_eq!(request.cursor(), Some("cursor_01"));
assert!(request.include_total());
}
#[test]
fn cursor_page_from_limit_plus_one_requires_cursor_for_more_results() {
let page = CursorPage::from_limit_plus_one(vec![1, 2, 3], 2, Some(3), |item| {
Ok::<_, std::convert::Infallible>(format!("cursor_{item}"))
})
.expect("page should build");
assert_eq!(page.items(), &[1, 2]);
assert!(page.has_more());
assert_eq!(page.next_cursor(), Some("cursor_2"));
assert_eq!(page.total(), Some(3));
}
#[test]
fn cursor_page_can_map_items_without_rebuilding_metadata_by_hand() {
let page = CursorPage::new(vec![1, 2], 2, Some("next".to_owned()), true, Some(3))
.expect("page should build")
.try_map_items(|item| Ok::<_, std::convert::Infallible>(item.to_string()))
.expect("mapping should succeed");
assert_eq!(page.items(), &["1".to_owned(), "2".to_owned()]);
assert_eq!(page.next_cursor(), Some("next"));
assert!(page.has_more());
assert_eq!(page.total(), Some(3));
}
#[test]
fn cursor_page_rejects_inconsistent_response_metadata() {
assert!(matches!(
CursorPage::new(vec![1, 2, 3], 2, None, false, None),
Err(PaginationError::PageItemsExceedPageSize { .. })
));
assert!(matches!(
CursorPage::<i32>::new(Vec::new(), 20, None, true, None),
Err(PaginationError::CursorRequiredForMoreResults)
));
assert!(matches!(
CursorPage::<i32>::new(Vec::new(), 20, Some("next".to_owned()), false, None),
Err(PaginationError::CursorUnexpectedWithoutMoreResults)
));
assert!(matches!(
CursorPage::new(vec![1, 2], 20, None, false, Some(1)),
Err(PaginationError::TotalLessThanItems { .. })
));
}
#[test]
fn pagination_errors_are_classified() {
let error = CursorPageRequest::new(Some(0), None, false).unwrap_err();
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "pagination_page_size_zero");
}
#[test]
fn rejects_zero_offset_page() {
let result = OffsetPageRequest::new(Some(0), Some(20));
assert!(result.is_err());
}
#[test]
fn offset_page_request_deserialization_uses_same_validation() {
assert!(
serde_json::from_value::<OffsetPageRequest>(json!({
"page": 0,
"page_size": 20
}))
.is_err()
);
let request: OffsetPageRequest = serde_json::from_value(json!({
"page": 2,
"page_size": 20
}))
.expect("request should deserialize");
assert_eq!(request.page(), 2);
assert_eq!(request.page_size(), 20);
}
#[test]
fn offset_page_rejects_inconsistent_response_metadata() {
assert!(matches!(
OffsetPage::new(vec![1], 0, 20, 1),
Err(PaginationError::PageZero)
));
assert!(matches!(
OffsetPage::new(vec![1, 2, 3], 1, 2, 3),
Err(PaginationError::PageItemsExceedPageSize { .. })
));
assert!(matches!(
OffsetPage::new(vec![1, 2], 1, 20, 1),
Err(PaginationError::TotalLessThanItems { .. })
));
}
#[test]
fn page_response_deserialization_uses_same_validation() {
assert!(
serde_json::from_value::<CursorPage<i32>>(json!({
"items": [1, 2, 3],
"page_size": 2,
"next_cursor": null,
"has_more": false
}))
.is_err()
);
assert!(
serde_json::from_value::<OffsetPage<i32>>(json!({
"items": [1],
"page": 0,
"page_size": 20,
"total": 1
}))
.is_err()
);
let cursor_page: CursorPage<i32> = serde_json::from_value(json!({
"items": [1, 2],
"page_size": 2,
"next_cursor": "next",
"has_more": true,
"total": 3
}))
.expect("cursor page should deserialize");
assert_eq!(cursor_page.items(), &[1, 2]);
assert_eq!(cursor_page.next_cursor(), Some("next"));
let offset_page: OffsetPage<i32> = serde_json::from_value(json!({
"items": [1, 2],
"page": 1,
"page_size": 20,
"total": 2
}))
.expect("offset page should deserialize");
assert_eq!(offset_page.items(), &[1, 2]);
}
#[test]
fn round_trips_cursor_payload() {
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let encoded = encode_cursor(&cursor).expect("cursor should encode");
let decoded: Cursor = decode_cursor(&encoded).expect("cursor should decode");
assert_eq!(decoded, cursor);
}
#[test]
fn round_trips_typed_cursor_payload() {
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let encoded = encode_typed_cursor("users", &cursor).expect("cursor should encode");
let decoded: Cursor = decode_typed_cursor("users", &encoded).expect("cursor should decode");
assert_eq!(decoded, cursor);
}
#[test]
fn rejects_cursor_kind_mismatch() {
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let encoded = encode_typed_cursor("users", &cursor).expect("cursor should encode");
let result = decode_typed_cursor::<Cursor>("clients", &encoded);
assert!(matches!(result, Err(CursorError::KindMismatch { .. })));
}
#[test]
fn rejects_invalid_cursor_encoding() {
let result = decode_cursor::<Cursor>("$not-base64url$");
assert!(matches!(result, Err(CursorError::InvalidEncoding)));
}
#[test]
fn rejects_empty_cursor() {
let result = decode_cursor::<Cursor>("");
assert!(matches!(result, Err(CursorError::Empty)));
}
#[test]
fn rejects_invalid_cursor_kind() {
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let result = encode_typed_cursor("users/read", &cursor);
assert!(matches!(result, Err(CursorError::InvalidKind)));
}
#[test]
fn cursor_errors_are_classified() {
let error = decode_cursor::<Cursor>("").unwrap_err();
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "cursor_empty");
}
#[test]
fn signed_cursor_rejects_invalid_kind() {
let codec = SignedCursorCodec::new(CURSOR_SECRET).expect("secret should be valid");
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let result = codec.encode_typed("users/read", &cursor);
assert!(matches!(result, Err(CursorError::InvalidKind)));
}
#[test]
fn rejects_oversized_cursor() {
let oversized = "a".repeat(MAX_CURSOR_LENGTH + 1);
let result = decode_cursor::<Cursor>(&oversized);
assert!(matches!(result, Err(CursorError::TooLarge { .. })));
}
#[test]
fn signed_cursor_rejects_tampering() {
let codec = SignedCursorCodec::new(CURSOR_SECRET).expect("secret should be valid");
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let encoded = codec
.encode_typed("users", &cursor)
.expect("cursor should encode");
let tampered = encoded.replace('.', "x.");
let result = codec.decode_typed::<Cursor>("users", &tampered);
assert!(matches!(result, Err(CursorError::InvalidSignature)));
}
#[test]
fn signed_cursor_preserves_typed_wire_format() {
let codec = SignedCursorCodec::new(b"01234567890123456789012345678901").unwrap();
let expected = "eyJ2ZXJzaW9uIjoxLCJraW5kIjoidXNlcnMiLCJwYXlsb2FkIjp7InN1YiI6InVzcl8wMSJ9fQ.OySVa1uwjFlsD887Z7Txq1QxUld28U1CCbopRFjYUAA";
let payload = serde_json::json!({"sub": "usr_01"});
assert_eq!(codec.encode_typed("users", &payload).unwrap(), expected);
assert_eq!(
codec
.decode_typed::<serde_json::Value>("users", expected)
.unwrap(),
payload
);
assert!(
codec
.decode_typed::<serde_json::Value>("accounts", expected)
.is_err()
);
assert!(codec.with_previous_keys([b"short"]).is_err());
}
#[test]
fn signed_cursor_round_trips_payload() {
let codec = SignedCursorCodec::new(CURSOR_SECRET).expect("secret should be valid");
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let encoded = codec.encode(&cursor).expect("cursor should encode");
let decoded: Cursor = codec.decode(&encoded).expect("cursor should decode");
assert_eq!(decoded, cursor);
}
#[test]
fn signed_cursor_supports_previous_secrets() {
let previous_codec =
SignedCursorCodec::new(PREVIOUS_CURSOR_SECRET).expect("secret should be valid");
let current_codec = SignedCursorCodec::new(CURRENT_CURSOR_SECRET)
.expect("secret should be valid")
.with_previous_key(PREVIOUS_CURSOR_SECRET)
.expect("previous secret should be valid");
let cursor = Cursor {
username: "admin".to_owned(),
id: "usr_01".to_owned(),
};
let encoded = previous_codec
.encode(&cursor)
.expect("cursor should encode");
let decoded: Cursor = current_codec
.decode(&encoded)
.expect("cursor should decode");
assert_eq!(decoded, cursor);
}
#[test]
fn signed_cursor_debug_output_redacts_secrets() {
let codec = SignedCursorCodec::new(CURSOR_SECRET).expect("secret should be valid");
let output = format!("{codec:?}");
assert!(output.contains("SignedCursorCodec"));
assert!(output.contains("<redacted:32 bytes>"));
assert!(!output.contains("0123456789abcdef"));
}
#[test]
fn pagination_debug_output_redacts_cursor_payloads() {
let cursor = "private-pagination-cursor";
let request = CursorPageRequest::new(Some(20), Some(cursor.to_owned()), false)
.expect("request should be valid");
let page = CursorPage::new(
vec!["visible-item"],
20,
Some(cursor.to_owned()),
true,
None,
)
.expect("page should be valid");
let output = format!("{request:?} {page:?}");
assert!(output.contains("[REDACTED]"));
assert!(output.contains("visible-item"));
assert!(!output.contains(cursor));
assert_eq!(request.cursor(), Some(cursor));
assert_eq!(page.next_cursor(), Some(cursor));
}
#[test]
fn signed_cursor_rejects_weak_secret() {
let result = SignedCursorCodec::new("short");
assert!(matches!(result, Err(CursorError::InvalidSecret { .. })));
}
}