Skip to main content

rs_identity_model/token/
exchange.rs

1//! Request parameters for the OAuth 2.0 Token Exchange grant (RFC 8693).
2//!
3//! [`TokenExchangeRequest`] carries the per-call parameters of an exchange:
4//! the REQUIRED `subject_token` / `subject_token_type`, the optional
5//! `actor_token` (with its REQUIRED-when-present `actor_token_type`), and the
6//! optional `requested_token_type`, `scope`, `resource`, and `audience`
7//! targeting hints (RFC 8693 §2.1).
8//!
9//! They live in a per-call request rather than on [`TokenClientBuilder`]
10//! because they describe one exchange, not the client: the same
11//! [`TokenClient`] trades many different subject tokens over its lifetime.
12//!
13//! Behavioural contract: `spec/vectors/token-exchange.json`
14//! (`EXCH-001`..`EXCH-006`).
15//!
16//! [`TokenClient`]: super::TokenClient
17//! [`TokenClientBuilder`]: super::TokenClientBuilder
18
19use std::fmt;
20
21use crate::{IdentityError, Result};
22
23/// Placeholder printed in place of token material in `Debug` output (#24).
24const REDACTED: &str = "<redacted>";
25
26/// An OAuth 2.0 access token (RFC 8693 §3).
27pub const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token";
28/// An OAuth 2.0 refresh token (RFC 8693 §3).
29pub const TOKEN_TYPE_REFRESH_TOKEN: &str = "urn:ietf:params:oauth:token-type:refresh_token";
30/// An OpenID Connect ID Token (RFC 8693 §3).
31pub const TOKEN_TYPE_ID_TOKEN: &str = "urn:ietf:params:oauth:token-type:id_token";
32/// A SAML 1.1 assertion (RFC 8693 §3).
33pub const TOKEN_TYPE_SAML1: &str = "urn:ietf:params:oauth:token-type:saml1";
34/// A SAML 2.0 assertion (RFC 8693 §3).
35pub const TOKEN_TYPE_SAML2: &str = "urn:ietf:params:oauth:token-type:saml2";
36/// A JWT that is not one of the more specific types (RFC 8693 §3).
37pub const TOKEN_TYPE_JWT: &str = "urn:ietf:params:oauth:token-type:jwt";
38
39/// The six token type identifier URIs defined in RFC 8693 §3, in the order the
40/// section lists them.
41///
42/// They are used verbatim as `subject_token_type`, `actor_token_type`, and
43/// `requested_token_type` request parameters and as the `issued_token_type`
44/// response field; an implementation MUST NOT abbreviate or normalise them
45/// (EXCH-003).
46pub const TOKEN_TYPE_URIS: [&str; 6] = [
47    TOKEN_TYPE_ACCESS_TOKEN,
48    TOKEN_TYPE_REFRESH_TOKEN,
49    TOKEN_TYPE_ID_TOKEN,
50    TOKEN_TYPE_SAML1,
51    TOKEN_TYPE_SAML2,
52    TOKEN_TYPE_JWT,
53];
54
55/// The parameters of one RFC 8693 token exchange request (RFC 8693 §2.1).
56///
57/// Build one with [`TokenExchangeRequest::new`], which takes the two REQUIRED
58/// parameters, then chain the optional ones. Supplying only the subject token
59/// requests an **impersonation** token; adding
60/// [`actor_token`](TokenExchangeRequest::actor_token) makes it a **delegation**
61/// exchange (RFC 8693 §1.1).
62///
63/// `Debug` redacts the subject and actor tokens so they cannot leak into logs
64/// (#24); their presence is still visible.
65///
66/// ```
67/// use rs_identity_model::{TokenExchangeRequest, TOKEN_TYPE_ACCESS_TOKEN, TOKEN_TYPE_JWT};
68///
69/// // Delegation: an actor acting on behalf of the subject, scoped to one API.
70/// let request = TokenExchangeRequest::new("subject.tok", TOKEN_TYPE_ACCESS_TOKEN)
71///     .actor_token("actor.tok", TOKEN_TYPE_JWT)
72///     .audience("https://api.example.com")
73///     .scope("https://api.example.com/read");
74/// ```
75#[derive(Clone)]
76pub struct TokenExchangeRequest {
77    /// The security token being exchanged (REQUIRED).
78    pub(crate) subject_token: String,
79    /// The type URI of `subject_token` (REQUIRED).
80    pub(crate) subject_token_type: String,
81    /// The token representing the acting party, for a delegation exchange.
82    pub(crate) actor_token: Option<String>,
83    /// The type URI of `actor_token`; REQUIRED whenever `actor_token` is set.
84    pub(crate) actor_token_type: Option<String>,
85    /// The desired type of the issued token; the server MAY issue another.
86    pub(crate) requested_token_type: Option<String>,
87    /// The requested scope, sent as a single space-delimited parameter.
88    pub(crate) scope: Option<String>,
89    /// Target resource URIs; each is sent as its own repeated parameter.
90    pub(crate) resources: Vec<String>,
91    /// Target audiences; each is sent as its own repeated parameter.
92    pub(crate) audiences: Vec<String>,
93}
94
95impl fmt::Debug for TokenExchangeRequest {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.debug_struct("TokenExchangeRequest")
98            .field("subject_token", &REDACTED)
99            .field("subject_token_type", &self.subject_token_type)
100            .field("actor_token", &self.actor_token.as_ref().map(|_| REDACTED))
101            .field("actor_token_type", &self.actor_token_type)
102            .field("requested_token_type", &self.requested_token_type)
103            .field("scope", &self.scope)
104            .field("resources", &self.resources)
105            .field("audiences", &self.audiences)
106            .finish()
107    }
108}
109
110impl TokenExchangeRequest {
111    /// Starts an impersonation exchange of `subject_token`, whose type is named
112    /// by `subject_token_type` — one of the [`TOKEN_TYPE_URIS`] (RFC 8693 §3).
113    /// Both are REQUIRED (RFC 8693 §2.1).
114    pub fn new(subject_token: impl Into<String>, subject_token_type: impl Into<String>) -> Self {
115        Self {
116            subject_token: subject_token.into(),
117            subject_token_type: subject_token_type.into(),
118            actor_token: None,
119            actor_token_type: None,
120            requested_token_type: None,
121            scope: None,
122            resources: Vec::new(),
123            audiences: Vec::new(),
124        }
125    }
126
127    /// Attaches the acting party's token, turning the request into a delegation
128    /// exchange (RFC 8693 §1.1, §2.1). `token_type` is one of the
129    /// [`TOKEN_TYPE_URIS`] and is REQUIRED whenever an actor token is present.
130    ///
131    /// Both arguments must be non-empty: an empty one is rejected when the
132    /// exchange is validated, so an accidental empty actor token cannot quietly
133    /// turn a delegation into an impersonation. Simply do not call this method
134    /// to request impersonation.
135    pub fn actor_token(mut self, token: impl Into<String>, token_type: impl Into<String>) -> Self {
136        self.actor_token = Some(token.into());
137        self.actor_token_type = Some(token_type.into());
138        self
139    }
140
141    /// Names the desired type of the issued token (RFC 8693 §2.1). The server
142    /// MAY issue a different type, which it reports in `issued_token_type`.
143    pub fn requested_token_type(mut self, uri: impl Into<String>) -> Self {
144        self.requested_token_type = Some(uri.into());
145        self
146    }
147
148    /// Requests `scope`, sent as a single space-delimited `scope` parameter
149    /// (RFC 6749 §3.3). When unset, no `scope` parameter is sent.
150    pub fn scope(mut self, scope: impl Into<String>) -> Self {
151        self.scope = Some(scope.into());
152        self
153    }
154
155    /// Adds a target resource URI (RFC 8693 §2.1). `resource` MAY appear more
156    /// than once, so repeated calls accumulate rather than replace.
157    pub fn resource(mut self, resource: impl Into<String>) -> Self {
158        self.resources.push(resource.into());
159        self
160    }
161
162    /// Adds a target audience (RFC 8693 §2.1). `audience` MAY appear more than
163    /// once, so repeated calls accumulate rather than replace.
164    pub fn audience(mut self, audience: impl Into<String>) -> Self {
165        self.audiences.push(audience.into());
166        self
167    }
168
169    /// Checks the RFC 8693 §2.1 parameter requirements before a request is
170    /// built, so a malformed exchange never reaches the wire.
171    ///
172    /// # Errors
173    ///
174    /// [`IdentityError::Validation`] when `subject_token` or
175    /// `subject_token_type` is empty, when a present `actor_token` is the empty
176    /// string, or when an `actor_token` is present without a non-empty
177    /// `actor_token_type`.
178    pub(crate) fn validate(&self) -> Result<()> {
179        if self.subject_token.is_empty() {
180            return Err(IdentityError::Validation(
181                "token exchange: subject_token is required".to_string(),
182            ));
183        }
184        if self.subject_token_type.is_empty() {
185            return Err(IdentityError::Validation(
186                "token exchange: subject_token_type is required".to_string(),
187            ));
188        }
189        // An actor token that is present but empty is rejected rather than
190        // dropped: silently sending a subject-only request would downgrade the
191        // delegation the caller asked for into an impersonation
192        // (RFC 8693 §1.1). A caller who wants impersonation omits
193        // `actor_token` entirely.
194        if self.actor_token.as_deref().is_some_and(str::is_empty) {
195            return Err(IdentityError::Validation(
196                "token exchange: actor_token must not be empty when provided".to_string(),
197            ));
198        }
199        // actor_token_type is REQUIRED whenever actor_token is present
200        // (RFC 8693 §2.1), and a type that is present but empty is as unusable
201        // as an absent one. The absent and empty cases are folded into one
202        // check on purpose: `actor_token()` is the only way to set either half
203        // and it always sets both, so a separate "type is None" arm would be
204        // unreachable through the public API and could never be tested.
205        if self.actor_token.is_some()
206            && !self
207                .actor_token_type
208                .as_deref()
209                .is_some_and(|t| !t.is_empty())
210        {
211            return Err(IdentityError::Validation(
212                "token exchange: actor_token_type is required and must not be empty \
213                 when actor_token is set"
214                    .to_string(),
215            ));
216        }
217        Ok(())
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    // EXCH-003: the exported constants are the six RFC 8693 §3 URIs, verbatim
226    // and in section order. The cross-language fixture
227    // spec/test-fixtures/token-exchange/token-type-uris.json holds the same set;
228    // tests/it/local/token_exchange.rs asserts the two agree.
229    #[test]
230    fn token_type_uris_are_the_six_rfc_8693_uris() {
231        assert_eq!(
232            TOKEN_TYPE_URIS,
233            [
234                "urn:ietf:params:oauth:token-type:access_token",
235                "urn:ietf:params:oauth:token-type:refresh_token",
236                "urn:ietf:params:oauth:token-type:id_token",
237                "urn:ietf:params:oauth:token-type:saml1",
238                "urn:ietf:params:oauth:token-type:saml2",
239                "urn:ietf:params:oauth:token-type:jwt",
240            ]
241        );
242    }
243
244    // A minimal impersonation request carries no actor or targeting parameters.
245    #[test]
246    fn new_builds_a_bare_impersonation_request() {
247        let request = TokenExchangeRequest::new("subject.tok", TOKEN_TYPE_ACCESS_TOKEN);
248        assert_eq!(request.subject_token, "subject.tok");
249        assert_eq!(request.subject_token_type, TOKEN_TYPE_ACCESS_TOKEN);
250        assert!(request.actor_token.is_none());
251        assert!(request.actor_token_type.is_none());
252        assert!(request.requested_token_type.is_none());
253        assert!(request.scope.is_none());
254        assert!(request.resources.is_empty());
255        assert!(request.audiences.is_empty());
256        request.validate().expect("a bare impersonation is valid");
257    }
258
259    // RFC 8693 §2.1: resource and audience MAY each appear more than once, so
260    // the builder accumulates instead of replacing.
261    #[test]
262    fn resource_and_audience_accumulate() {
263        let request = TokenExchangeRequest::new("s", TOKEN_TYPE_ACCESS_TOKEN)
264            .resource("https://rs1.example.com")
265            .resource("https://rs2.example.com")
266            .audience("aud-a")
267            .audience("aud-b");
268        assert_eq!(
269            request.resources,
270            ["https://rs1.example.com", "https://rs2.example.com"]
271        );
272        assert_eq!(request.audiences, ["aud-a", "aud-b"]);
273    }
274
275    // RFC 8693 §2.1 REQUIRED: an empty subject_token is rejected locally.
276    #[test]
277    fn validate_rejects_empty_subject_token() {
278        let err = TokenExchangeRequest::new("", TOKEN_TYPE_ACCESS_TOKEN)
279            .validate()
280            .expect_err("empty subject_token must be rejected");
281        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
282    }
283
284    // RFC 8693 §2.1 REQUIRED: an empty subject_token_type is rejected locally.
285    #[test]
286    fn validate_rejects_empty_subject_token_type() {
287        let err = TokenExchangeRequest::new("subject.tok", "")
288            .validate()
289            .expect_err("empty subject_token_type must be rejected");
290        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
291    }
292
293    // RFC 8693 §2.1: actor_token_type is REQUIRED whenever actor_token is
294    // present, and an empty type is as unusable as a missing one.
295    #[test]
296    fn validate_rejects_actor_token_without_type() {
297        let err = TokenExchangeRequest::new("subject.tok", TOKEN_TYPE_ACCESS_TOKEN)
298            .actor_token("actor.tok", "")
299            .validate()
300            .expect_err("actor_token without a type must be rejected");
301        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
302    }
303
304    // RFC 8693 §1.1: a present-but-empty actor token is rejected, not dropped.
305    // Dropping it would send a subject-only request, silently turning the
306    // delegation the caller asked for into an impersonation.
307    #[test]
308    fn validate_rejects_empty_actor_token() {
309        for (token, token_type) in [("", ""), ("", TOKEN_TYPE_JWT)] {
310            let err = TokenExchangeRequest::new("subject.tok", TOKEN_TYPE_ACCESS_TOKEN)
311                .actor_token(token, token_type)
312                .validate()
313                .expect_err("an empty actor token must be rejected");
314            match err {
315                IdentityError::Validation(message) => {
316                    assert!(message.contains("actor_token"), "{message}");
317                }
318                other => panic!("expected Validation, got {other:?}"),
319            }
320        }
321    }
322
323    // #24: Debug never prints the subject or actor token, but still reveals
324    // whether a delegation actor is present.
325    #[test]
326    fn debug_redacts_subject_and_actor_tokens() {
327        let request = TokenExchangeRequest::new("SUBJECT-SECRET", TOKEN_TYPE_ACCESS_TOKEN)
328            .actor_token("ACTOR-SECRET", TOKEN_TYPE_JWT);
329        let dbg = format!("{request:?}");
330        assert!(!dbg.contains("SUBJECT-SECRET"), "subject leaked: {dbg}");
331        assert!(!dbg.contains("ACTOR-SECRET"), "actor leaked: {dbg}");
332        assert!(dbg.contains(REDACTED), "no redaction marker: {dbg}");
333        assert!(dbg.contains("actor_token: Some"), "{dbg}");
334        // The type URIs are not secret and stay legible for diagnostics.
335        assert!(dbg.contains(TOKEN_TYPE_ACCESS_TOKEN), "{dbg}");
336    }
337
338    // An impersonation request shows the absent actor as None, not a redaction
339    // marker.
340    #[test]
341    fn debug_shows_absent_actor_as_none() {
342        let request = TokenExchangeRequest::new("s", TOKEN_TYPE_ACCESS_TOKEN);
343        assert!(format!("{request:?}").contains("actor_token: None"));
344    }
345}