/*
* Ably Platform Auth REST API
*
* The subset of the Ably **platform** REST API used for authentication and token lifecycle: requesting Ably Tokens, revoking them, and reading server time. This is a *separate* API from the Ably Chat REST API (`openapi/ably-chat-rest.yaml`, path prefix `/chat/v4`) — token issuance and revocation live on the platform host under `/keys/...`, not under `/chat/_*`. ## Scope & provenance Ably publishes an authoritative platform spec, [`ably/open-specs`](https://github.com/ably/open-specs) `platform-v1.yaml`, which covers the full generic pub/sub REST API (`/channels`, `/push`, `/keys`, `/stats`, `/time`). **This document is deliberately narrow**: it models only the endpoints this project's authentication story ([ADR-0012](../docs/adr/0012-token-issuance-permissions.md), [SPEC §13](../docs/SPEC.md)) touches — `POST /keys/{keyName}/requestToken`, `POST /keys/{keyName}/revokeTokens`, and `GET /time`. Field-level details are cross-checked against `platform-v1.yaml`, the Ably auth docs, and the `ably-js` auth implementation (see [`../docs/research/2026-07-24-ably-chat-auth-permissions.md`](../docs/research/2026-07-24-ably-chat-auth-permissions.md)). ## Relationship to the Chat client `ably-chat-rs` is a Chat REST client; it does not itself sign TokenRequests or call `/keys/...` (ADR-0012 Tier 4). This spec documents the platform endpoints a *token server* (or the official `ably` crate) uses to mint the Bearer credentials that are then handed to the Chat client. Capability documents carried by these tokens are described in SPEC §13, not here.
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration, ContentType};
/// struct for typed errors of method [`request_token`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestTokenError {
Status400(models::ErrorResponse),
Status401(models::ErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method [`revoke_tokens`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RevokeTokensError {
Status400(models::ErrorResponse),
Status401(models::ErrorResponse),
UnknownValue(serde_json::Value),
}
/// Exchange a token request for an Ably Token (`TokenDetails`). Two request forms are accepted: - A **signed** `TokenRequest` (carries a `mac` computed with the API key secret). No `Authorization` header is required — the `mac` is the credential. This is how an untrusted client redeems a request its server signed. - An **unsigned** `TokenParams` body. Requires HTTP Basic authentication with the API key; Ably signs the token server-side. The effective capability of the returned token is the intersection of the requested capability and the issuing key's own capability; an empty intersection fails the request.
pub async fn request_token(configuration: &configuration::Configuration, key_name: &str, request_token_request: models::RequestTokenRequest, x_ably_version: Option<&str>) -> Result<models::TokenDetails, Error<RequestTokenError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_key_name = key_name;
let p_body_request_token_request = request_token_request;
let p_header_x_ably_version = x_ably_version;
let uri_str = format!("{}/keys/{keyName}/requestToken", configuration.base_path, keyName=crate::apis::urlencode(p_path_key_name));
let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(param_value) = p_header_x_ably_version {
req_builder = req_builder.header("X-Ably-Version", param_value.to_string());
}
if let Some(ref auth_conf) = configuration.basic_auth {
req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
};
req_builder = req_builder.json(&p_body_request_token_request);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TokenDetails`"))),
ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::TokenDetails`")))),
}
} else {
let content = resp.text().await?;
let entity: Option<RequestTokenError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent { status, content, entity }))
}
}
/// Revoke tokens previously issued from this API key. The key MUST have had **revocable tokens** enabled before the tokens were issued. Requires HTTP Basic authentication with the API key — a client authenticated with a token (rather than the key) is rejected with Ably error `40162`. Targets are specified as `type:value` strings — `clientId:<id>`, `revocationKey:<value>` (matches the `x-ably-revocation-key` JWT claim), or `channel:<name>`. `issuedBefore` scopes revocation to tokens issued before a timestamp; `allowReauthMargin` postpones enforcement ~30s and hints live connections to re-authenticate first.
pub async fn revoke_tokens(configuration: &configuration::Configuration, key_name: &str, token_revocation_request: models::TokenRevocationRequest, x_ably_version: Option<&str>) -> Result<models::TokenRevocationResponse, Error<RevokeTokensError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_key_name = key_name;
let p_body_token_revocation_request = token_revocation_request;
let p_header_x_ably_version = x_ably_version;
let uri_str = format!("{}/keys/{keyName}/revokeTokens", configuration.base_path, keyName=crate::apis::urlencode(p_path_key_name));
let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(param_value) = p_header_x_ably_version {
req_builder = req_builder.header("X-Ably-Version", param_value.to_string());
}
if let Some(ref auth_conf) = configuration.basic_auth {
req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
};
req_builder = req_builder.json(&p_body_token_revocation_request);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TokenRevocationResponse`"))),
ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::TokenRevocationResponse`")))),
}
} else {
let content = resp.text().await?;
let entity: Option<RevokeTokensError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent { status, content, entity }))
}
}