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 rotate(&self, merchant_id: &str, key_id: &str) -> Result<ApiKeyCreateResponse> {
let path = format!(
"/api-keys/{}/{}/rotate",
encode_segment(merchant_id),
encode_segment(key_id)
);
self.inner
.request_body_keyed(HttpMethod::Post, &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 rotate_by_profile(
&self,
merchant_id: &str,
key_id: &str,
) -> Result<ApiKeyCreateResponse> {
let path = format!(
"/account/{}/profile/api-keys/{}/rotate",
encode_segment(merchant_id),
encode_segment(key_id)
);
self.inner
.request_body_keyed(HttpMethod::Post, &path, None, None)
.await
}
}
#[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(skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub permission_groups: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_origins: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rate_limit_per_minute: Option<i32>,
#[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",
"scope",
"permission_groups",
"profile_ids",
"allowed_origins",
"rate_limit_per_minute",
];
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
}
#[must_use]
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
#[must_use]
pub fn permission_groups(mut self, groups: Vec<String>) -> Self {
self.permission_groups = Some(groups);
self
}
#[must_use]
pub fn profile_ids(mut self, profile_ids: Vec<String>) -> Self {
self.profile_ids = Some(profile_ids);
self
}
#[must_use]
pub fn allowed_origins(mut self, origins: Vec<String>) -> Self {
self.allowed_origins = Some(origins);
self
}
#[must_use]
pub fn rate_limit_per_minute(mut self, limit: i32) -> Self {
self.rate_limit_per_minute = Some(limit);
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(skip_serializing_if = "Option::is_none")]
pub permission_groups: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_origins: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rate_limit_per_minute: Option<i32>,
#[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",
"permission_groups",
"profile_ids",
"allowed_origins",
"rate_limit_per_minute",
];
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(default)]
pub scope: Option<String>,
#[serde(default)]
pub allowed_origins: Option<Vec<String>>,
#[serde(default)]
pub rate_limit_per_minute: Option<i32>,
#[serde(default)]
pub permission_groups: Option<Vec<String>>,
#[serde(default)]
pub profile_ids: Option<Vec<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("scope", &self.scope)
.field("allowed_origins", &self.allowed_origins)
.field("rate_limit_per_minute", &self.rate_limit_per_minute)
.field("permission_groups", &self.permission_groups)
.field("profile_ids", &self.profile_ids)
.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(default)]
pub scope: Option<String>,
#[serde(default)]
pub allowed_origins: Option<Vec<String>>,
#[serde(default)]
pub rate_limit_per_minute: Option<i32>,
#[serde(default)]
pub permission_groups: Option<Vec<String>>,
#[serde(default)]
pub profile_ids: Option<Vec<String>>,
#[serde(default)]
pub last_used: 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, client_with_retries};
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", "scope": "restricted",
"permission_groups": ["OperationsView"], "profile_ids": ["pro_1"],
"allowed_origins": ["https://shop.test"], "rate_limit_per_minute": 60,
"last_used": "2026-02-01T00:00:00Z"
}"#;
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");
assert_eq!(got.scope.as_deref(), Some("restricted"));
assert_eq!(got.rate_limit_per_minute, Some(60));
assert_eq!(got.last_used.as_deref(), Some("2026-02-01T00:00:00Z"));
assert_eq!(got.profile_ids.as_deref(), Some(&["pro_1".to_string()][..]));
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 rotate_posts_to_the_rotate_suffix_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"key_id": "key_1", "merchant_id": "merch_1", "name": "Production key",
"api_key": "snd_rotatedvalue", "created": "2026-01-01T00:00:00Z",
"expiration": "never", "rotated_from": "snd_abcd"
}"#,
)]);
let out = client.api_keys().rotate("merch/1", "key/1").await.unwrap();
assert_eq!(out.api_key, "snd_rotatedvalue");
assert_eq!(out.extra["rotated_from"], "snd_abcd");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/api-keys/merch%2F1/key%2F1/rotate"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn rotate_by_profile_posts_to_the_account_profile_rotate_suffix() {
let (client, mock) = client_with(vec![Step::ok(CREATE_JSON)]);
let out = client
.api_keys()
.rotate_by_profile("merch/1", "key/1")
.await
.unwrap();
assert_eq!(out.key_id, "key_1");
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/key%2F1/rotate"
);
assert!(seen[0].body.is_none());
}
#[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::new("Production key", "never")
.description("main")
.scope("restricted")
.permission_groups(vec!["OperationsView".to_string()])
.profile_ids(vec!["pro_1".to_string()])
.allowed_origins(vec!["https://shop.test".to_string()])
.rate_limit_per_minute(60);
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()),
permission_groups: Some(vec!["OperationsView".to_string()]),
profile_ids: Some(vec!["pro_1".to_string()]),
allowed_origins: Some(vec!["https://shop.test".to_string()]),
rate_limit_per_minute: Some(60),
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:?}"),
}
}
#[tokio::test]
async fn rotations_ignore_the_client_wide_idempotency_key() {
for by_profile in [false, true] {
let (client, mock) =
client_with_retries(vec![Step::status(503, "{}"), Step::ok(CREATE_JSON)], 2);
let keys = client.with_idempotency_key("client-key").api_keys();
let out = if by_profile {
keys.rotate_by_profile("merch_1", "key_1").await
} else {
keys.rotate("merch_1", "key_1").await
};
assert!(out.is_err());
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
}
}