use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct ApiKeys {
inner: Arc<Inner>,
}
impl ApiKeys {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(
&self,
merchant_id: &str,
params: &ApiKeyCreateRequest,
) -> Result<ApiKeyCreateResponse> {
params.validate()?;
let path = format!("/api-keys/{}", encode_segment(merchant_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn retrieve(&self, merchant_id: &str, key_id: &str) -> Result<ApiKeyResponse> {
let path = format!(
"/api-keys/{}/{}",
encode_segment(merchant_id),
encode_segment(key_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update(
&self,
merchant_id: &str,
key_id: &str,
params: &ApiKeyUpdateRequest,
) -> Result<ApiKeyResponse> {
params.validate()?;
let path = format!(
"/api-keys/{}/{}",
encode_segment(merchant_id),
encode_segment(key_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn revoke(&self, merchant_id: &str, key_id: &str) -> Result<ApiKeyRevokeResponse> {
let path = format!(
"/api-keys/{}/{}",
encode_segment(merchant_id),
encode_segment(key_id)
);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<ApiKeyResponse>> {
let path = format!("/api-keys/{}/list", encode_segment(merchant_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn create_by_profile(
&self,
merchant_id: &str,
params: &ApiKeyCreateRequest,
) -> Result<ApiKeyCreateResponse> {
params.validate()?;
let path = format!("/account/{}/profile/api-keys", encode_segment(merchant_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list_by_profile(
&self,
merchant_id: &str,
params: Option<&ApiKeyListParams>,
) -> Result<Vec<ApiKeyResponse>> {
let path = format!("/account/{}/profile/api-keys", encode_segment(merchant_id));
let query = params.map(ApiKeyListParams::to_query).unwrap_or_default();
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn retrieve_by_profile(
&self,
merchant_id: &str,
key_id: &str,
) -> Result<ApiKeyResponse> {
let path = format!(
"/account/{}/profile/api-keys/{}",
encode_segment(merchant_id),
encode_segment(key_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update_by_profile(
&self,
merchant_id: &str,
key_id: &str,
params: &ApiKeyUpdateRequest,
) -> Result<ApiKeyResponse> {
params.validate()?;
let path = format!(
"/account/{}/profile/api-keys/{}",
encode_segment(merchant_id),
encode_segment(key_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn revoke_by_profile(
&self,
merchant_id: &str,
key_id: &str,
) -> Result<ApiKeyRevokeResponse> {
let path = format!(
"/account/{}/profile/api-keys/{}",
encode_segment(merchant_id),
encode_segment(key_id)
);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
}
#[derive(Debug, Clone, Default)]
pub struct ApiKeyListParams {
pub limit: Option<i64>,
pub skip: Option<i64>,
}
impl ApiKeyListParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.skip {
q.push(("skip", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ApiKeyCreateRequest {
pub name: String,
pub expiration: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const API_KEY_CREATE_REQUEST_NAMED: &[&str] = &["name", "expiration", "description"];
impl ValidateRequest for ApiKeyCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if API_KEY_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ApiKeyCreateRequest"
)));
}
}
Ok(())
}
}
impl ApiKeyCreateRequest {
pub fn new(name: impl Into<String>, expiration: impl Into<String>) -> Self {
Self {
name: name.into(),
expiration: expiration.into(),
..Default::default()
}
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ApiKeyUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expiration: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const API_KEY_UPDATE_REQUEST_NAMED: &[&str] = &["name", "description", "expiration"];
impl ValidateRequest for ApiKeyUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if API_KEY_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ApiKeyUpdateRequest"
)));
}
}
Ok(())
}
}
impl ApiKeyUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn expiration(mut self, expiration: impl Into<String>) -> Self {
self.expiration = Some(expiration.into());
self
}
}
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ApiKeyCreateResponse {
pub key_id: String,
pub merchant_id: String,
pub name: String,
pub api_key: String,
pub created: String,
pub expiration: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub profile_id: Option<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
impl std::fmt::Debug for ApiKeyCreateResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let extra_keys: Vec<&str> = self.extra.keys().map(String::as_str).collect();
f.debug_struct("ApiKeyCreateResponse")
.field("key_id", &self.key_id)
.field("merchant_id", &self.merchant_id)
.field("name", &self.name)
.field("api_key", &"[redacted]")
.field("created", &self.created)
.field("expiration", &self.expiration)
.field("description", &self.description)
.field("profile_id", &self.profile_id)
.field("extra_keys", &extra_keys)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ApiKeyResponse {
pub key_id: String,
pub merchant_id: String,
pub name: String,
pub prefix: String,
pub created: String,
pub expiration: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub profile_id: Option<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ApiKeyRevokeResponse {
pub merchant_id: String,
pub key_id: String,
pub revoked: bool,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const CREATE_JSON: &str = r#"{
"key_id": "key_1", "merchant_id": "merch_1", "name": "Production key",
"api_key": "snd_supersecretvalue", "created": "2026-01-01T00:00:00Z",
"expiration": "never"
}"#;
const KEY_JSON: &str = r#"{
"key_id": "key_1", "merchant_id": "merch_1", "name": "Production key",
"prefix": "snd_abcd", "created": "2026-01-01T00:00:00Z",
"expiration": "never"
}"#;
const REVOKE_JSON: &str = r#"{"merchant_id":"merch_1","key_id":"key_1","revoked":true}"#;
#[tokio::test]
async fn create_posts_to_the_merchant_key_path() {
let (client, mock) = client_with(vec![Step::ok(CREATE_JSON)]);
let out = client
.api_keys()
.create(
"merch/1",
&ApiKeyCreateRequest::new("Production key", "never").description("main"),
)
.await
.unwrap();
assert_eq!(out.api_key, "snd_supersecretvalue");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/api-keys/merch%2F1");
let body = seen[0].body_json();
assert_eq!(body["name"], "Production key");
assert_eq!(body["expiration"], "never");
assert_eq!(body["description"], "main");
}
#[tokio::test]
async fn retrieve_update_revoke_share_the_key_path() {
let (client, mock) = client_with(vec![
Step::ok(KEY_JSON),
Step::ok(KEY_JSON),
Step::ok(REVOKE_JSON),
]);
let keys = client.api_keys();
let got = keys.retrieve("merch_1", "key/1").await.unwrap();
assert_eq!(got.prefix, "snd_abcd");
keys.update(
"merch_1",
"key/1",
&ApiKeyUpdateRequest::new()
.name("Renamed")
.expiration("never"),
)
.await
.unwrap();
let revoked = keys.revoke("merch_1", "key/1").await.unwrap();
assert!(revoked.revoked);
let seen = mock.seen.lock().unwrap();
for step in seen.iter() {
assert_eq!(step.url, "https://api.test/api-keys/merch_1/key%2F1");
}
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[1].method, "POST");
assert_eq!(seen[1].body_json()["name"], "Renamed");
assert_eq!(seen[1].body_json()["expiration"], "never");
assert_eq!(seen[2].method, "DELETE");
}
#[tokio::test]
async fn list_gets_the_list_suffix() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{KEY_JSON}]"))]);
let out = client.api_keys().list("merch_1").await.unwrap();
assert_eq!(out[0].key_id, "key_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/api-keys/merch_1/list");
}
#[tokio::test]
async fn create_by_profile_posts_to_the_account_profile_path() {
let (client, mock) = client_with(vec![Step::ok(CREATE_JSON)]);
client
.api_keys()
.create_by_profile("merch/1", &ApiKeyCreateRequest::new("Shop key", "never"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/merch%2F1/profile/api-keys"
);
assert_eq!(seen[0].body_json()["name"], "Shop key");
}
#[tokio::test]
async fn list_by_profile_serializes_pagination() {
let (client, mock) = client_with(vec![Step::ok("[]"), Step::ok("[]")]);
let keys = client.api_keys();
keys.list_by_profile(
"merch_1",
Some(&ApiKeyListParams {
limit: Some(10),
skip: Some(20),
}),
)
.await
.unwrap();
keys.list_by_profile("merch_1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/account/merch_1/profile/api-keys?limit=10&skip=20"
);
assert_eq!(
seen[1].url,
"https://api.test/account/merch_1/profile/api-keys"
);
}
#[tokio::test]
async fn profile_scoped_key_operations_share_their_path() {
let (client, mock) = client_with(vec![
Step::ok(KEY_JSON),
Step::ok(KEY_JSON),
Step::ok(REVOKE_JSON),
]);
let keys = client.api_keys();
keys.retrieve_by_profile("merch_1", "key/1").await.unwrap();
keys.update_by_profile(
"merch_1",
"key/1",
&ApiKeyUpdateRequest::new().description("shop key"),
)
.await
.unwrap();
keys.revoke_by_profile("merch_1", "key/1").await.unwrap();
let seen = mock.seen.lock().unwrap();
for step in seen.iter() {
assert_eq!(
step.url,
"https://api.test/account/merch_1/profile/api-keys/key%2F1"
);
}
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[1].method, "POST");
assert_eq!(seen[1].body_json()["description"], "shop key");
assert_eq!(seen[2].method, "DELETE");
}
#[test]
fn create_response_debug_redacts_the_plaintext_key() {
let created: ApiKeyCreateResponse = serde_json::from_str(CREATE_JSON).unwrap();
let printed = format!("{created:?}");
assert!(
!printed.contains("snd_supersecretvalue"),
"plaintext api_key leaked into Debug output: {printed}"
);
assert!(printed.contains("[redacted]"));
assert!(printed.contains("key_1"));
}
#[test]
fn create_response_debug_hides_extra_values() {
let mut created: ApiKeyCreateResponse = serde_json::from_str(CREATE_JSON).unwrap();
created
.extra
.insert("key_value".to_string(), json!("another_secret"));
let printed = format!("{created:?}");
assert!(
!printed.contains("another_secret"),
"an unmodeled secret leaked through `extra`: {printed}"
);
assert!(printed.contains("key_value"));
}
#[test]
fn api_key_create_request_named_fields_are_complete() {
let req = ApiKeyCreateRequest {
name: "Production key".to_string(),
expiration: "never".to_string(),
description: Some("main".to_string()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
API_KEY_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"API_KEY_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn api_key_update_request_named_fields_are_complete() {
let req = ApiKeyUpdateRequest {
name: Some("Renamed".to_string()),
description: Some("main".to_string()),
expiration: Some("never".to_string()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
API_KEY_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"API_KEY_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_extra_keys_colliding_with_named_fields() {
let mut create = ApiKeyCreateRequest::new("k", "never");
create
.extra
.insert("expiration".to_string(), json!("never"));
match create.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("expiration")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut update = ApiKeyUpdateRequest::new();
update.extra.insert("name".to_string(), json!("collide"));
match update.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}