usso 0.4.1

The usso provides a universal single sign-on (SSO) integration for microservices, making it easy to add secure, scalable authentication across different frameworks. This client simplifies the process of connecting any microservice to the USSO service.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Synchronous (blocking) API client.

use std::collections::HashMap;

use reqwest::blocking::Client;
use serde_json::Value;
use thiserror::Error;

use crate::core::Usso;
use crate::exceptions::USSOError;
use crate::schemas::UserResponse;

/// Errors returned by the sync and async API clients.
#[derive(Error, Debug)]
pub enum ClientError {
    #[error("HTTP error: {0}")]
    HttpError(reqwest::Error),
    #[error("USSO error: {0}")]
    USSOError(USSOError),
    #[error("Value error: {0}")]
    ValueError(String),
}

/// A synchronous (blocking) API client for the USSO backend.
///
/// Supports API key, agent JWT, and refresh-token-based authentication.
/// Automatically manages access tokens and provides user management APIs.
///
/// # Example
///
/// ```rust,no_run
/// use usso::client::sync::UssoClient;
///
/// let mut client = UssoClient::new(
///     "https://sso.usso.io",
///     Some("api-key-123".into()),
///     None, None, None,
/// );
/// let users = client.get_users().unwrap();
/// ```
pub struct UssoClient {
    pub client: Client,
    pub usso: Usso,
    pub base_url: String,
    pub api_key: Option<String>,
    pub agent_id: Option<String>,
    pub agent_private_key: Option<String>,
    pub refresh_token: Option<String>,
    pub access_token: Option<String>,
    pub headers: HashMap<String, String>,
    pub usso_refresh_url: String,
}

impl UssoClient {
    /// Create a new `UssoClient`.
    ///
    /// - `base_url` — the USSO server base URL (e.g. `https://sso.usso.io`)
    /// - `api_key` — optional API key for API-key auth
    /// - `agent_id` — optional agent ID for agent JWT auth
    /// - `agent_private_key` — optional Ed25519 private key (PEM or raw 32-byte seed)
    /// - `refresh_token` — optional refresh token for token-refresh auth
    pub fn new(
        base_url: &str,
        api_key: Option<String>,
        agent_id: Option<String>,
        agent_private_key: Option<String>,
        refresh_token: Option<String>,
    ) -> Self {
        let base_url = base_url.trim_end_matches('/').to_string();
        let usso_refresh_url = format!("{}/api/sso/v1/auth/refresh", base_url);
        let mut headers = HashMap::new();
        if let Some(ref key) = api_key {
            headers.insert("x-api-key".to_string(), key.clone());
        }

        UssoClient {
            client: Client::new(),
            usso: Usso::new(None, None, None),
            base_url,
            api_key,
            agent_id,
            agent_private_key,
            refresh_token,
            access_token: None,
            headers,
            usso_refresh_url,
        }
    }

    /// Check whether the cached access token is not expired.
    pub fn is_temporally_valid(&self) -> bool {
        match &self.access_token {
            Some(token) => crate::core::is_expired(token).map(|expired| !expired).unwrap_or(false),
            None => false,
        }
    }

    /// Ensure a valid session exists.
    ///
    /// If an API key is set, this is a no-op. Otherwise refreshes the access
    /// token if it is missing or expired.
    pub fn get_session(&mut self) -> Result<(), ClientError> {
        if self.api_key.is_some() {
            return Ok(());
        }
        if !self.is_temporally_valid() {
            self.refresh()?;
        }
        Ok(())
    }

    /// Refresh the access token using the configured refresh token.
    ///
    /// Sends a POST to `{base}/api/sso/v1/auth/refresh`.
    pub fn refresh(&mut self) -> Result<(), ClientError> {
        let token = self
            .refresh_token
            .as_ref()
            .ok_or_else(|| ClientError::ValueError("refresh_token is required".to_string()))?;

        let response = self
            .client
            .post(&self.usso_refresh_url)
            .json(&serde_json::json!({"refresh_token": token}))
            .send()
            .map_err(ClientError::HttpError)?;

        if !response.status().is_success() {
            return Err(ClientError::ValueError("Failed to refresh token".to_string()));
        }

        let data: Value = response.json().map_err(ClientError::HttpError)?;
        let access_token = data
            .get("access_token")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ClientError::ValueError("No access_token in response".to_string()))?;

        self.access_token = Some(access_token.to_string());
        self.headers
            .insert("Authorization".to_string(), format!("Bearer {}", access_token));
        Ok(())
    }

    /// Fetch users from `GET {base}/api/sso/v1/users`.
    pub fn get_users(&self) -> Result<Vec<UserResponse>, ClientError> {
        let url = format!("{}/api/sso/v1/users", self.base_url);
        let mut req = self.client.get(&url);
        for (k, v) in &self.headers {
            req = req.header(k.as_str(), v.as_str());
        }
        let response = req.send().map_err(ClientError::HttpError)?;
        let data: Value = response.json().map_err(ClientError::HttpError)?;
        let items = data
            .get("items")
            .and_then(|v| v.as_array())
            .ok_or_else(|| ClientError::ValueError("No items in response".to_string()))?;
        items
            .iter()
            .map(|item| {
                serde_json::from_value::<UserResponse>(item.clone())
                    .map_err(|e| ClientError::ValueError(e.to_string()))
            })
            .collect()
    }

    /// Create a user via `POST {base}/api/sso/v1/users`.
    pub fn create_users(&self, data: Option<Value>) -> Result<UserResponse, ClientError> {
        let url = format!("{}/api/sso/v1/users", self.base_url);
        let mut req = self.client.post(&url);
        for (k, v) in &self.headers {
            req = req.header(k.as_str(), v.as_str());
        }
        if let Some(json_data) = data {
            req = req.json(&json_data);
        }
        let response = req.send().map_err(ClientError::HttpError)?;
        response
            .json::<UserResponse>()
            .map_err(ClientError::HttpError)
    }

    /// Get a user's profile via `GET {base}/api/sso/v1/profiles/{user_id}`.
    pub fn get_profile(&self, user_id: &str) -> Result<Value, ClientError> {
        let url = format!("{}/api/sso/v1/profiles/{}", self.base_url, user_id);
        let mut req = self.client.get(&url);
        for (k, v) in &self.headers {
            req = req.header(k.as_str(), v.as_str());
        }
        let response = req.send().map_err(ClientError::HttpError)?;
        response.json::<Value>().map_err(ClientError::HttpError)
    }

    /// Add an identifier (email, phone, etc.) to a user.
    ///
    /// Sends `POST {base}/api/sso/v1/users/{user_id}/identifiers`.
    pub fn add_identifier(
        &self,
        user_id: &str,
        identifier_type: &str,
        identifier: &str,
    ) -> Result<Value, ClientError> {
        let url = format!("{}/api/sso/v1/users/{}/identifiers", self.base_url, user_id);
        let mut req = self.client.post(&url);
        for (k, v) in &self.headers {
            req = req.header(k.as_str(), v.as_str());
        }
        let response = req
            .json(&serde_json::json!({"type": identifier_type, "identifier": identifier}))
            .send()
            .map_err(ClientError::HttpError)?;
        response.json::<Value>().map_err(ClientError::HttpError)
    }

    /// Generate an Ed25519-signed agent JWT and exchange it for a USSO access token.
    ///
    /// The agent must have `agent_id` and `agent_private_key` configured.
    /// The private key can be a PEM-encoded PKCS#8 key or a raw 32-byte seed.
    pub fn use_agent_token(
        &mut self,
        scopes: &[String],
        aud: &str,
        tenant_id: Option<&str>,
    ) -> Result<String, ClientError> {
        let agent_id = self
            .agent_id
            .as_ref()
            .ok_or_else(|| ClientError::ValueError("agent_id is required".to_string()))?;
        let agent_private_key = self
            .agent_private_key
            .as_ref()
            .ok_or_else(|| ClientError::ValueError("agent_private_key is required".to_string()))?;

        let tenant_id = match tenant_id {
            Some(tid) => Some(tid.to_string()),
            None => {
                let agent_response = self.get_agent_scopes()?;
                agent_response
                    .get("tenant_id")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
            }
        };

        let jwt = crate::utils::agent::generate_agent_jwt(
            scopes,
            aud,
            tenant_id.as_deref(),
            Some(agent_id),
            Some(agent_private_key),
        );

        let token = crate::utils::agent::get_agent_token(&jwt, &self.base_url)?;
        self.access_token = Some(token.clone());
        self.headers
            .insert("Authorization".to_string(), format!("Bearer {}", token));
        Ok(token)
    }

    fn get_agent_scopes(&self) -> Result<Value, ClientError> {
        let agent_id = self
            .agent_id
            .as_ref()
            .ok_or_else(|| ClientError::ValueError("agent_id is required".to_string()))?;
        let agent_private_key = self
            .agent_private_key
            .as_ref()
            .ok_or_else(|| ClientError::ValueError("agent_private_key is required".to_string()))?;

        let jwt = crate::utils::agent::generate_agent_jwt(
            &[],
            "sso",
            None,
            Some(agent_id),
            Some(agent_private_key),
        );

        let url = format!("{}/api/sso/v1/agents/scopes", self.base_url);
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt))
            .send()
            .map_err(ClientError::HttpError)?;
        response.json::<Value>().map_err(ClientError::HttpError)
    }

    fn get_api_key_scopes(&self) -> Result<Value, ClientError> {
        let api_key = self
            .api_key
            .as_ref()
            .ok_or_else(|| ClientError::ValueError("api_key is required".to_string()))?;

        let url = format!("{}/api/sso/v1/apikeys/verify", self.base_url);
        let response = self
            .client
            .post(&url)
            .json(&serde_json::json!({"api_key": api_key}))
            .send()
            .map_err(ClientError::HttpError)?;
        response.json::<Value>().map_err(ClientError::HttpError)
    }

    /// Resolve the effective scopes for the current session.
    ///
    /// Tries the following sources in order:
    /// 1. Decoded access token payload
    /// 2. API key scopes (via `POST /api/sso/v1/apikeys/verify`)
    /// 3. Agent scopes (via `POST /api/sso/v1/agents/scopes`)
    /// 4. Refresh token (if a token refresh yields scopes)
    pub fn get_scopes(&mut self) -> Result<Vec<String>, ClientError> {
        if let Some(ref token) = self.access_token {
            let parts: Vec<&str> = token.split('.').collect();
            if parts.len() == 3 {
                use base64::Engine;
                let payload_bytes =
                    base64::engine::general_purpose::URL_SAFE_NO_PAD
                        .decode(parts[1])
                        .map_err(|e| ClientError::ValueError(e.to_string()))?;
                if let Ok(payload) =
                    serde_json::from_slice::<serde_json::Value>(&payload_bytes)
                {
                    if let Some(scopes) = payload.get("scopes").and_then(|v| v.as_array()) {
                        return Ok(scopes
                            .iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect());
                    }
                }
            }
        }

        if self.api_key.is_some() {
            let response = self.get_api_key_scopes()?;
            return Ok(response
                .get("scopes")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default());
        }

        if self.agent_id.is_some() && self.agent_private_key.is_some() {
            let response = self.get_agent_scopes()?;
            return Ok(response
                .get("scopes")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default());
        }

        if self.refresh_token.is_some() {
            self.refresh()?;
            if let Some(ref token) = self.access_token {
                let parts: Vec<&str> = token.split('.').collect();
                if parts.len() == 3 {
                    use base64::Engine;
                    let payload_bytes =
                        base64::engine::general_purpose::URL_SAFE_NO_PAD
                            .decode(parts[1])
                            .map_err(|e| ClientError::ValueError(e.to_string()))?;
                    if let Ok(payload) =
                        serde_json::from_slice::<serde_json::Value>(&payload_bytes)
                    {
                        if let Some(scopes) = payload.get("scopes").and_then(|v| v.as_array()) {
                            return Ok(scopes
                                .iter()
                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                                .collect());
                        }
                    }
                }
            }
        }

        Ok(vec![])
    }

    /// Request a token with specific scopes.
    ///
    /// First verifies that the current session's scopes contain the requested
    /// scopes (via [`has_subset_scope`](crate::authorization::has_subset_scope)).
    /// Then exchanges an agent JWT for an access token with those scopes.
    pub fn get_token(
        &mut self,
        scopes: &[String],
        aud: &str,
    ) -> Result<Option<String>, ClientError> {
        let user_scopes = self.get_scopes()?;
        for scope in scopes {
            if !crate::authorization::has_subset_scope(scope, &user_scopes) {
                return Err(ClientError::USSOError(USSOError::PermissionDenied));
            }
        }

        if self.agent_id.is_none() || self.agent_private_key.is_none() {
            return Ok(None);
        }

        self.use_agent_token(scopes, aud, None).map(Some)
    }
}