api.rs (6504B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::sync::Arc; 18 19 use axum::{ 20 Json, Router, 21 extract::State, 22 response::{IntoResponse as _, NoContent}, 23 routing::{delete, get, post}, 24 }; 25 use jiff::Timestamp; 26 use serde::{Deserialize, Serialize}; 27 use sqlx::PgPool; 28 use taler_api::{ 29 error::{ApiResult, failure}, 30 extract::{Path, Req}, 31 }; 32 use taler_common::error_code::ErrorCode; 33 34 use crate::{constants::MAX_DEVICE_TOKEN_LEN, db}; 35 36 fn is_valid_device_token(token: &str) -> bool { 37 !token.is_empty() 38 && token.len() <= MAX_DEVICE_TOKEN_LEN 39 && token.len().is_multiple_of(2) 40 && token.bytes().all(|b| b.is_ascii_hexdigit()) 41 } 42 43 pub struct RelayApi { 44 db: PgPool, 45 } 46 47 impl RelayApi { 48 pub fn new(db: PgPool) -> Self { 49 Self { db } 50 } 51 } 52 53 #[derive(Debug, Deserialize, Serialize)] 54 pub struct DeviceRegistrationRequest { 55 pub token: String, 56 } 57 58 #[derive(Debug, Deserialize, Serialize)] 59 pub struct DeviceUnregistrationRequest { 60 pub token: String, 61 } 62 63 #[derive(Debug, Deserialize, Serialize)] 64 pub struct ApnsRelayConfig<'a> { 65 pub name: &'a str, 66 pub version: &'a str, 67 pub implementation: Option<&'a str>, 68 } 69 70 pub fn router(state: Arc<RelayApi>) -> Router { 71 Router::new() 72 .route( 73 "/devices", 74 post( 75 async |State(state): State<Arc<RelayApi>>, 76 Req(DeviceRegistrationRequest { token }): Req<DeviceRegistrationRequest>| { 77 if !is_valid_device_token(&token) { 78 return Err(failure( 79 ErrorCode::GENERIC_PARAMETER_MALFORMED, 80 format!( 81 "token must be a nonempty, even-length ASCII hexadecimal string of at most {MAX_DEVICE_TOKEN_LEN} characters" 82 ), 83 ) 84 .with_path("token")); 85 } 86 db::register(&state.db, &token, &Timestamp::now()).await?; 87 ApiResult::Ok(NoContent) 88 }, 89 ), 90 ) 91 .route( 92 "/devices/{token}", 93 delete( 94 async |State(state): State<Arc<RelayApi>>, Path(token): Path<String>| { 95 db::unregister(&state.db, &token, &Timestamp::now()).await?; 96 ApiResult::Ok(NoContent) 97 }, 98 ), 99 ) 100 .route( 101 "/config", 102 get(async || { 103 Json(ApnsRelayConfig { 104 name: "taler-apns-relay", 105 version: "0:0:0", 106 implementation: Some("urn:net:taler:specs:taler-apns-relay:taler-rust"), 107 }) 108 .into_response() 109 }), 110 ) 111 .with_state(state) 112 } 113 114 #[cfg(test)] 115 mod test { 116 use std::sync::Arc; 117 118 use sqlx::PgPool; 119 use taler_api::api::TalerRouter as _; 120 use taler_common::error_code::ErrorCode; 121 use taler_macros::db_test; 122 use taler_test_utils::{json, server::TestServer as _}; 123 124 use crate::{ 125 api::{ApnsRelayConfig, RelayApi, router}, 126 constants::MAX_DEVICE_TOKEN_LEN, 127 db::all_registrations, 128 }; 129 130 #[db_test] 131 async fn api(pool: PgPool) { 132 let api = Arc::new(RelayApi::new(pool.clone())); 133 let server = router(api).finalize(); 134 135 server 136 .get("/config") 137 .await 138 .assert_ok_json::<ApnsRelayConfig>(); 139 140 assert_eq!(all_registrations(&pool).await.unwrap(), &[""; 0]); 141 142 server 143 .post("/devices") 144 .json(json!({ 145 "token": "aa01" 146 })) 147 .await 148 .assert_no_content(); 149 server 150 .post("/devices") 151 .json(json!({ 152 "token": "aa01" 153 })) 154 .await 155 .assert_no_content(); 156 server 157 .post("/devices") 158 .json(json!({ 159 "token": "aa02" 160 })) 161 .await 162 .assert_no_content(); 163 164 // Case is preserved without normalization per APNs guidance 165 server 166 .post("/devices") 167 .json(json!({ 168 "token": "AA01" 169 })) 170 .await 171 .assert_no_content(); 172 173 // Variable-length tokens up to MAX_DEVICE_TOKEN_LEN are accepted 174 let max_token = "aB".repeat(MAX_DEVICE_TOKEN_LEN / 2); 175 server 176 .post("/devices") 177 .json(json!({ 178 "token": max_token 179 })) 180 .await 181 .assert_no_content(); 182 183 assert_eq!( 184 all_registrations(&pool).await.unwrap(), 185 &["aa01", "aa02", "AA01", max_token.as_str()] 186 ); 187 188 // Reject empty, odd-length, non-hex, and oversized tokens on POST 189 let oversized = "ab".repeat(MAX_DEVICE_TOKEN_LEN / 2 + 1); 190 for bad in ["", "a", "abc", "zz01", "aa 01", oversized.as_str()] { 191 server 192 .post("/devices") 193 .json(json!({ 194 "token": bad 195 })) 196 .await 197 .assert_error(ErrorCode::GENERIC_PARAMETER_MALFORMED); 198 } 199 // DELETE is idempotent and returns 204 even for unknown or malformed tokens 200 for bad in ["a", "abc", "zz01", oversized.as_str()] { 201 server 202 .delete(format!("/devices/{bad}")) 203 .await 204 .assert_no_content(); 205 } 206 207 server.delete("/devices/aa01").await.assert_no_content(); 208 server.delete("/devices/aa03").await.assert_no_content(); 209 server 210 .delete(format!("/devices/{max_token}")) 211 .await 212 .assert_no_content(); 213 assert_eq!(all_registrations(&pool).await.unwrap(), &["aa02", "AA01"]); 214 } 215 }