commit e3ad8474de1540343e66036719215940aac7d4af
parent fcf5d9b3318a625307f57db65d316364c218eb65
Author: Antoine A <>
Date: Wed, 25 Nov 2026 10:14:49 +0100
apns: paginate ids and add length check
Diffstat:
6 files changed, 235 insertions(+), 100 deletions(-)
diff --git a/common/taler-api/src/test.rs b/common/taler-api/src/test.rs
@@ -27,7 +27,7 @@ use serde_json::json;
use sqlx::{PgPool, Row as _, postgres::PgRow};
use taler_common::{
api::{
- ErrorDetail, HashCode, ShortHashCode,
+ HashCode, ShortHashCode,
prepared::PreparedTransferConfig,
revenue::RevenueConfig,
wire::{TransferRequest, TransferResponse, TransferState, WireConfig},
diff --git a/taler-apns-relay/db/apns-relay-drop.sql b/taler-apns-relay/db/apns-relay-drop.sql
@@ -19,7 +19,7 @@ DECLARE
patch text;
BEGIN
IF EXISTS(SELECT FROM information_schema.schemata WHERE schema_name='_v') THEN
- FOR patch IN SELECT patch_name FROM _v.patches WHERE patch_name LIKE 'apns_relay_%' LOOP
+ FOR patch IN SELECT patch_name FROM _v.patches WHERE patch_name LIKE 'apns-relay-%' LOOP
PERFORM _v.unregister_patch(patch);
END LOOP;
END IF;
diff --git a/taler-apns-relay/src/api.rs b/taler-apns-relay/src/api.rs
@@ -31,7 +31,14 @@ use taler_api::{
};
use taler_common::error_code::ErrorCode;
-use crate::db;
+use crate::{constants::MAX_DEVICE_TOKEN_LEN, db};
+
+fn is_valid_device_token(token: &str) -> bool {
+ !token.is_empty()
+ && token.len() <= MAX_DEVICE_TOKEN_LEN
+ && token.len().is_multiple_of(2)
+ && token.bytes().all(|b| b.is_ascii_hexdigit())
+}
pub struct RelayApi {
db: PgPool,
@@ -66,13 +73,13 @@ pub fn router(state: Arc<RelayApi>) -> Router {
"/devices",
post(
async |State(state): State<Arc<RelayApi>>,
- Req(DeviceRegistrationRequest { token}): Req<DeviceRegistrationRequest>| {
- if token.is_empty()
- || !token.len().is_multiple_of(2)
- || !token.bytes().all(|b| b.is_ascii_hexdigit()) {
+ Req(DeviceRegistrationRequest { token }): Req<DeviceRegistrationRequest>| {
+ if !is_valid_device_token(&token) {
return Err(failure(
ErrorCode::GENERIC_PARAMETER_MALFORMED,
- "token must be a nonempty, even-length ASCII hexadecimal string",
+ format!(
+ "token must be a nonempty, even-length ASCII hexadecimal string of at most {MAX_DEVICE_TOKEN_LEN} characters"
+ ),
)
.with_path("token"));
}
@@ -110,11 +117,13 @@ mod test {
use sqlx::PgPool;
use taler_api::api::TalerRouter as _;
+ use taler_common::error_code::ErrorCode;
use taler_macros::db_test;
use taler_test_utils::{json, server::TestServer as _};
use crate::{
api::{ApnsRelayConfig, RelayApi, router},
+ constants::MAX_DEVICE_TOKEN_LEN,
db::all_registrations,
};
@@ -152,10 +161,55 @@ mod test {
.await
.assert_no_content();
- assert_eq!(all_registrations(&pool).await.unwrap(), &["aa01", "aa02"]);
+ // Case is preserved without normalization per APNs guidance
+ server
+ .post("/devices")
+ .json(json!({
+ "token": "AA01"
+ }))
+ .await
+ .assert_no_content();
+
+ // Variable-length tokens up to MAX_DEVICE_TOKEN_LEN are accepted
+ let max_token = "aB".repeat(MAX_DEVICE_TOKEN_LEN / 2);
+ server
+ .post("/devices")
+ .json(json!({
+ "token": max_token
+ }))
+ .await
+ .assert_no_content();
+
+ assert_eq!(
+ all_registrations(&pool).await.unwrap(),
+ &["aa01", "aa02", "AA01", max_token.as_str()]
+ );
+
+ // Reject empty, odd-length, non-hex, and oversized tokens on POST
+ let oversized = "ab".repeat(MAX_DEVICE_TOKEN_LEN / 2 + 1);
+ for bad in ["", "a", "abc", "zz01", "aa 01", oversized.as_str()] {
+ server
+ .post("/devices")
+ .json(json!({
+ "token": bad
+ }))
+ .await
+ .assert_error(ErrorCode::GENERIC_PARAMETER_MALFORMED);
+ }
+ // DELETE is idempotent and returns 204 even for unknown or malformed tokens
+ for bad in ["a", "abc", "zz01", oversized.as_str()] {
+ server
+ .delete(format!("/devices/{bad}"))
+ .await
+ .assert_no_content();
+ }
server.delete("/devices/aa01").await.assert_no_content();
server.delete("/devices/aa03").await.assert_no_content();
- assert_eq!(all_registrations(&pool).await.unwrap(), &["aa02"]);
+ server
+ .delete(format!("/devices/{max_token}"))
+ .await
+ .assert_no_content();
+ assert_eq!(all_registrations(&pool).await.unwrap(), &["aa02", "AA01"]);
}
}
diff --git a/taler-apns-relay/src/constants.rs b/taler-apns-relay/src/constants.rs
@@ -18,3 +18,6 @@ use taler_common::config::parser::ConfigSource;
pub const CONFIG_SOURCE: ConfigSource =
ConfigSource::new("taler-apns-relay", "apns-relay", "taler-apns-relay");
+
+pub const MAX_DEVICE_TOKEN_LEN: usize = 512;
+pub const DEVICE_PAGE_SIZE: u32 = 1000;
diff --git a/taler-apns-relay/src/db.rs b/taler-apns-relay/src/db.rs
@@ -71,16 +71,38 @@ pub async fn unregister(db: &PgPool, token: &str, before: &Timestamp) -> sqlx::R
Ok(())
}
+/// Fetch a page of registered devices
+pub async fn registration_page(
+ db: &PgPool,
+ after_id: i64,
+ limit: u32,
+) -> sqlx::Result<Vec<(i64, String)>> {
+ serialized!(
+ sqlx::query_as(
+ "
+ SELECT device_id, token
+ FROM devices
+ WHERE device_id > $1
+ ORDER BY device_id ASC
+ LIMIT $2
+ ",
+ )
+ .bind(after_id)
+ .bind(i64::from(limit))
+ .fetch_all(db)
+ )
+}
+
/// List all registered devices
pub async fn all_registrations(db: &PgPool) -> sqlx::Result<Vec<String>> {
- sqlx::query_scalar("SELECT token FROM devices")
- .fetch_all(db)
- .await
+ serialized!(
+ sqlx::query_scalar("SELECT token FROM devices ORDER BY device_id ASC").fetch_all(db)
+ )
}
/// Remove all registered devices
pub async fn clear_registration(db: &PgPool) -> sqlx::Result<()> {
- sqlx::query("TRUNCATE TABLE devices").execute(db).await?;
+ serialized!(sqlx::query("TRUNCATE TABLE devices").execute(db))?;
Ok(())
}
@@ -90,16 +112,21 @@ pub mod test {
use sqlx::PgPool;
use taler_macros::db_test;
- use crate::db::{all_registrations, clear_registration, register, unregister};
+ use crate::{
+ constants::MAX_DEVICE_TOKEN_LEN,
+ db::{all_registrations, clear_registration, register, registration_page, unregister},
+ };
#[db_test]
async fn registration(db: PgPool) {
- let token1 = "device_token1";
- let token2 = "device_token2";
+ let token1 = "aa01";
+ let token2 = "AA02";
+ let token3 = "bb03";
let now = Timestamp::now();
// Empty
assert_eq!(all_registrations(&db).await.unwrap(), &[""; 0]);
+ assert!(registration_page(&db, 0, 10).await.unwrap().is_empty());
clear_registration(&db).await.unwrap();
// Register
@@ -110,23 +137,44 @@ pub mod test {
register(&db, token1, &now).await.unwrap();
assert_eq!(all_registrations(&db).await.unwrap(), &[token1]);
- // Many
+ // Many + pagination
register(&db, token2, &(now + SignedDuration::from_mins(1)))
.await
.unwrap();
- assert_eq!(all_registrations(&db).await.unwrap(), &[token1, token2]);
+ register(&db, token3, &(now + SignedDuration::from_mins(2)))
+ .await
+ .unwrap();
+ assert_eq!(
+ all_registrations(&db).await.unwrap(),
+ &[token1, token2, token3]
+ );
+
+ let page1 = registration_page(&db, 0, 2).await.unwrap();
+ assert_eq!(page1.len(), 2);
+ assert_eq!(page1[0].1, token1);
+ assert_eq!(page1[1].1, token2);
+
+ let page2 = registration_page(&db, page1[1].0, 2).await.unwrap();
+ assert_eq!(page2.len(), 1);
+ assert_eq!(page2[0].1, token3);
+ assert!(
+ registration_page(&db, page2[0].0, 2)
+ .await
+ .unwrap()
+ .is_empty()
+ );
// Unregister
unregister(&db, token1, &now).await.unwrap();
- assert_eq!(all_registrations(&db).await.unwrap(), &[token2]);
+ assert_eq!(all_registrations(&db).await.unwrap(), &[token2, token3]);
// Idempotent
unregister(&db, token1, &now).await.unwrap();
- assert_eq!(all_registrations(&db).await.unwrap(), &[token2]);
+ assert_eq!(all_registrations(&db).await.unwrap(), &[token2, token3]);
// Skip reregistered
unregister(&db, token2, &now).await.unwrap();
- assert_eq!(all_registrations(&db).await.unwrap(), &[token2]);
+ assert_eq!(all_registrations(&db).await.unwrap(), &[token2, token3]);
clear_registration(&db).await.unwrap();
assert_eq!(all_registrations(&db).await.unwrap(), &[""; 0]);
diff --git a/taler-apns-relay/src/worker.rs b/taler-apns-relay/src/worker.rs
@@ -24,6 +24,7 @@ use tracing::{error, info, trace, warn};
use crate::{
apns::{ApnsError, Client, Reason},
config::WorkerCfg,
+ constants::DEVICE_PAGE_SIZE,
db,
};
@@ -37,10 +38,60 @@ pub enum WorkerError {
const NB_RETRY: usize = 5;
-async fn wakeup(pool: &PgPool, client: &mut Client) -> Result<(), WorkerError> {
- let tokens = db::all_registrations(pool).await?;
- info!(target: "worker", "send notification to {} devices", tokens.len());
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum FailureAction {
+ Fatal,
+ Config,
+ ExpiredProviderToken,
+ Unregister,
+ Defer,
+ Retry,
+}
+fn classify_reason(reason: Reason) -> FailureAction {
+ match reason {
+ // Request construction bugs independent of the client-supplied token.
+ Reason::BadCollapseId
+ | Reason::BadExpirationDate
+ | Reason::BadMessageId
+ | Reason::BadPriority
+ | Reason::BadTopic
+ | Reason::DuplicateHeaders
+ | Reason::InvalidPushType
+ | Reason::MissingTopic
+ | Reason::PayloadEmpty
+ | Reason::MethodNotAllowed => FailureAction::Fatal,
+ // Provider credentials / topic configuration errors.
+ Reason::TopicDisallowed
+ | Reason::BadCertificate
+ | Reason::BadCertificateEnvironment
+ | Reason::Forbidden
+ | Reason::InvalidProviderToken
+ | Reason::MissingProviderToken
+ | Reason::UnrelatedKeyIdInToken
+ | Reason::BadEnvironmentKeyIdInToken
+ | Reason::PayloadTooLarge => FailureAction::Config,
+ // The client already retried once with a fresh provider token.
+ Reason::ExpiredProviderToken => FailureAction::ExpiredProviderToken,
+ // Invalid, inactive, or path-rejected client token: unregister
+ Reason::BadPath
+ | Reason::MissingDeviceToken
+ | Reason::BadDeviceToken
+ | Reason::DeviceTokenNotForTopic
+ | Reason::ExpiredToken
+ | Reason::Unregistered => FailureAction::Unregister,
+ // Retry this device on the next scheduled pass.
+ Reason::TooManyRequests => FailureAction::Defer,
+ // Wait before retry.
+ Reason::IdleTimeout
+ | Reason::TooManyProviderTokenUpdates
+ | Reason::InternalServerError
+ | Reason::ServiceUnavailable
+ | Reason::Shutdown => FailureAction::Retry,
+ }
+}
+
+async fn wakeup(pool: &PgPool, client: &mut Client) -> Result<(), WorkerError> {
// Wait at least 15 minutes before retrying API calls as per: https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns#Follow-best-practices-while-sending-push-notifications-with-APNs
// After 15 minutes, you can retry JSON payloads that receive response status codes that begin with 5XX.
// While retrying, you may employ a back-off technique. Most notifications with the status code 4XX can
@@ -49,91 +100,70 @@ async fn wakeup(pool: &PgPool, client: &mut Client) -> Result<(), WorkerError> {
// You can retry with a delay, if you get the error code TooManyRequests.
let mut jitter = ExpoBackoffDecorr::new(Duration::from_mins(15), Duration::from_hours(1), 2.5);
- // TODO paginate tokens
// TODO send in batches
+ let mut after_id = 0i64;
+ let mut processed = 0usize;
- 'devices: for token in tokens {
- trace!(target: "worker", "send background notification to {token}");
- let mut attempt = 0;
- while let Err(e) = client.send(&token).await {
- trace!(target: "worker", "notification to {token} failed {e}");
- if let ApnsError::Err { reason, timestamp } = e {
- match reason {
- // Fatal error
- Reason::BadCollapseId
- | Reason::BadExpirationDate
- | Reason::BadMessageId
- | Reason::BadPriority
- | Reason::BadTopic
- | Reason::DuplicateHeaders
- | Reason::InvalidPushType
- | Reason::MissingDeviceToken
- | Reason::MissingTopic
- | Reason::PayloadEmpty
- | Reason::BadPath
- | Reason::MethodNotAllowed => {
- error!(target: "worker", "fatal error the service is broken: {e}");
- std::process::exit(9);
- }
- // Config error
- Reason::TopicDisallowed
- | Reason::BadCertificate
- | Reason::BadCertificateEnvironment
- | Reason::Forbidden
- | Reason::InvalidProviderToken
- | Reason::MissingProviderToken
- | Reason::UnrelatedKeyIdInToken
- | Reason::BadEnvironmentKeyIdInToken
- | Reason::PayloadTooLarge => {
- error!(target: "worker", "config error, check the configuration: {e}");
- std::process::exit(6);
- }
- // The client already retried once with a fresh provider token.
- Reason::ExpiredProviderToken => return Err(e.into()),
- // Unregister
- Reason::BadDeviceToken
- | Reason::DeviceTokenNotForTopic
- | Reason::ExpiredToken
- | Reason::Unregistered => {
- db::unregister(
- pool,
- &token,
- ×tamp
- .and_then(|s| i64::try_from(s).ok())
- .and_then(|s| Timestamp::from_millisecond(s).ok())
- .unwrap_or_else(Timestamp::now),
- )
- .await?;
- continue 'devices;
- }
- // Retry this device on the next scheduled pass.
- Reason::TooManyRequests => {
- warn!(target: "worker", "notification to {token} rate-limited, deferring to the next pass");
- continue 'devices;
+ loop {
+ let page = db::registration_page(pool, after_id, DEVICE_PAGE_SIZE).await?;
+ if page.is_empty() {
+ break;
+ }
+ processed += page.len();
+
+ 'devices: for (device_id, token) in page {
+ after_id = device_id;
+ trace!(target: "worker", "send background notification to {token}");
+ let mut attempt = 0;
+ while let Err(e) = client.send(&token).await {
+ trace!(target: "worker", "notification to {token} failed {e}");
+ if let ApnsError::Err { reason, timestamp } = e {
+ match classify_reason(reason) {
+ FailureAction::Fatal => {
+ error!(target: "worker", "fatal error the service is broken: {e}");
+ std::process::exit(9);
+ }
+ FailureAction::Config => {
+ error!(target: "worker", "config error, check the configuration: {e}");
+ std::process::exit(6);
+ }
+ FailureAction::ExpiredProviderToken => return Err(e.into()),
+ FailureAction::Unregister => {
+ db::unregister(
+ pool,
+ &token,
+ ×tamp
+ .and_then(|s| i64::try_from(s).ok())
+ .and_then(|s| Timestamp::from_millisecond(s).ok())
+ .unwrap_or_else(Timestamp::now),
+ )
+ .await?;
+ continue 'devices;
+ }
+ FailureAction::Defer => {
+ warn!(target: "worker", "notification to {token} rate-limited, deferring to the next pass");
+ continue 'devices;
+ }
+ FailureAction::Retry => {}
}
- // Wait before retry
- Reason::IdleTimeout
- | Reason::TooManyProviderTokenUpdates
- | Reason::InternalServerError
- | Reason::ServiceUnavailable
- | Reason::Shutdown => {}
}
- }
- attempt += 1;
+ attempt += 1;
- if attempt >= NB_RETRY {
- error!(target: "worker", "notification to {token} failed more than {NB_RETRY} times, stopping worker after back-off");
- tokio::time::sleep(jitter.backoff()).await;
- return Err(WorkerError::Apns(e));
- } else {
- warn!(target: "worker", "notification to {token} failed {e}, retrying after back-off");
- tokio::time::sleep(jitter.backoff()).await;
+ if attempt >= NB_RETRY {
+ error!(target: "worker", "notification to {token} failed more than {NB_RETRY} times, stopping worker after back-off");
+ tokio::time::sleep(jitter.backoff()).await;
+ return Err(WorkerError::Apns(e));
+ } else {
+ warn!(target: "worker", "notification to {token} failed {e}, retrying after back-off");
+ tokio::time::sleep(jitter.backoff()).await;
+ }
}
+ info!(target: "trace", "notification to {token} succeeded");
}
- info!(target: "trace", "notification to {token} succeeded");
}
+ info!(target: "worker", "processed notifications for {processed} devices");
Ok(())
}