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 = 32;
const CURSOR_VERSION: u8 = 1;
pub use cursor::{decode_cursor, decode_typed_cursor, encode_cursor, encode_typed_cursor};
pub use error::{CursorError, PaginationError};
pub use page::{CursorPage, OffsetPage, OffsetPageRequest, PageLimits, PageRequest, SortDirection};
pub use signed::SignedCursorCodec;
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use serde_json::json;
use super::{
CursorError, CursorPage, MAX_CURSOR_LENGTH, OffsetPage, OffsetPageRequest, PageLimits,
PageRequest, 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";
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Cursor {
username: String,
id: String,
}
#[test]
fn validates_page_size_upper_bound() {
let result = PageRequest::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 = PageRequest::new_with_limits(None, None, false, limits)
.expect("page request should be valid");
assert_eq!(page.page_size(), 25);
assert!(matches!(
PageRequest::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).validate(),
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);
let result = PageRequest::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 = PageRequest::new(None, Some(String::new()), false);
assert!(matches!(result, Err(PaginationError::CursorEmpty)));
}
#[test]
fn rejects_query_cursor_with_unsupported_characters() {
let result = PageRequest::new(None, Some("cursor value".to_owned()), false);
assert!(matches!(
result,
Err(PaginationError::CursorInvalidCharacters)
));
}
#[test]
fn page_request_deserialization_uses_same_validation() {
assert!(
serde_json::from_value::<PageRequest>(json!({
"page_size": 0,
"cursor": null,
"include_total": false
}))
.is_err()
);
assert!(
serde_json::from_value::<PageRequest>(json!({
"page_size": 20,
"cursor": "bad cursor",
"include_total": false
}))
.is_err()
);
let request: PageRequest = 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 = PageRequest::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_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_secret(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 = PageRequest::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 { .. })));
}
}