Skip to main content

ably_auth_openapi/apis/
authentication_api.rs

1/*
2 * Ably Platform Auth REST API
3 *
4 * 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. 
5 *
6 * The version of the OpenAPI document: 1.0.0
7 * 
8 * Generated by: https://openapi-generator.tech
9 */
10
11
12use reqwest;
13use serde::{Deserialize, Serialize, de::Error as _};
14use crate::{apis::ResponseContent, models};
15use super::{Error, configuration, ContentType};
16
17
18/// struct for typed errors of method [`request_token`]
19#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(untagged)]
21pub enum RequestTokenError {
22    Status400(models::ErrorResponse),
23    Status401(models::ErrorResponse),
24    UnknownValue(serde_json::Value),
25}
26
27/// struct for typed errors of method [`revoke_tokens`]
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(untagged)]
30pub enum RevokeTokensError {
31    Status400(models::ErrorResponse),
32    Status401(models::ErrorResponse),
33    UnknownValue(serde_json::Value),
34}
35
36
37/// 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. 
38pub 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>> {
39    // add a prefix to parameters to efficiently prevent name collisions
40    let p_path_key_name = key_name;
41    let p_body_request_token_request = request_token_request;
42    let p_header_x_ably_version = x_ably_version;
43
44    let uri_str = format!("{}/keys/{keyName}/requestToken", configuration.base_path, keyName=crate::apis::urlencode(p_path_key_name));
45    let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str);
46
47    if let Some(ref user_agent) = configuration.user_agent {
48        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
49    }
50    if let Some(param_value) = p_header_x_ably_version {
51        req_builder = req_builder.header("X-Ably-Version", param_value.to_string());
52    }
53    if let Some(ref auth_conf) = configuration.basic_auth {
54        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
55    };
56    req_builder = req_builder.json(&p_body_request_token_request);
57
58    let req = req_builder.build()?;
59    let resp = configuration.client.execute(req).await?;
60
61    let status = resp.status();
62    let content_type = resp
63        .headers()
64        .get("content-type")
65        .and_then(|v| v.to_str().ok())
66        .unwrap_or("application/octet-stream");
67    let content_type = super::ContentType::from(content_type);
68
69    if !status.is_client_error() && !status.is_server_error() {
70        let content = resp.text().await?;
71        match content_type {
72            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
73            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TokenDetails`"))),
74            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`")))),
75        }
76    } else {
77        let content = resp.text().await?;
78        let entity: Option<RequestTokenError> = serde_json::from_str(&content).ok();
79        Err(Error::ResponseError(ResponseContent { status, content, entity }))
80    }
81}
82
83/// 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. 
84pub 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>> {
85    // add a prefix to parameters to efficiently prevent name collisions
86    let p_path_key_name = key_name;
87    let p_body_token_revocation_request = token_revocation_request;
88    let p_header_x_ably_version = x_ably_version;
89
90    let uri_str = format!("{}/keys/{keyName}/revokeTokens", configuration.base_path, keyName=crate::apis::urlencode(p_path_key_name));
91    let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str);
92
93    if let Some(ref user_agent) = configuration.user_agent {
94        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
95    }
96    if let Some(param_value) = p_header_x_ably_version {
97        req_builder = req_builder.header("X-Ably-Version", param_value.to_string());
98    }
99    if let Some(ref auth_conf) = configuration.basic_auth {
100        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
101    };
102    req_builder = req_builder.json(&p_body_token_revocation_request);
103
104    let req = req_builder.build()?;
105    let resp = configuration.client.execute(req).await?;
106
107    let status = resp.status();
108    let content_type = resp
109        .headers()
110        .get("content-type")
111        .and_then(|v| v.to_str().ok())
112        .unwrap_or("application/octet-stream");
113    let content_type = super::ContentType::from(content_type);
114
115    if !status.is_client_error() && !status.is_server_error() {
116        let content = resp.text().await?;
117        match content_type {
118            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
119            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TokenRevocationResponse`"))),
120            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`")))),
121        }
122    } else {
123        let content = resp.text().await?;
124        let entity: Option<RevokeTokensError> = serde_json::from_str(&content).ok();
125        Err(Error::ResponseError(ResponseContent { status, content, entity }))
126    }
127}
128