openfga 1.0.2

Rust SDK for OpenFGA — the open-source authorization system
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*
 * OpenFGA
 *
 * A high performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar.
 *
 * The version of the OpenAPI document: 1.x
 * Contact: community@openfga.dev
 * Generated by: https://openapi-generator.tech
 */

use std::fmt;

///
/// Exactly one variant should be active per [`Configuration`]. Using
/// [`ConfigurationBuilder`] enforces this at construction time — the last
/// auth setter wins, removing the ambiguity of the old multi-field design.
#[derive(Clone)]
pub enum AuthMethod {
    /// A pre-issued static bearer token.
    Bearer(String),
    /// An OAuth2 access token — sent identically to [`Bearer`](AuthMethod::Bearer) on the wire.
    OAuth(String),
    /// HTTP Basic authentication.
    Basic(BasicAuth),
    /// A raw key sent as the `Authorization` header value, with optional prefix.
    ApiKey {
        /// Optional prefix (e.g. `"Bearer"` or `"Token"`).
        prefix: Option<String>,
        key: String,
    },
}

/// HTTP Basic authentication credentials with named fields.
///
/// Replaces the former `(String, Option<String>)` tuple alias that gave no
/// indication of which position was username vs. password.
#[derive(Clone)]
pub struct BasicAuth {
    pub username: String,
    pub password: Option<String>,
}

impl fmt::Debug for BasicAuth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BasicAuth")
            .field("username", &self.username)
            .field("password", &"[REDACTED]")
            .finish()
    }
}

impl fmt::Debug for AuthMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthMethod::Bearer(_) => f.debug_tuple("Bearer").field(&"[REDACTED]").finish(),
            AuthMethod::OAuth(_) => f.debug_tuple("OAuth").field(&"[REDACTED]").finish(),
            AuthMethod::Basic(_) => f.debug_tuple("Basic").field(&"[REDACTED]").finish(),
            AuthMethod::ApiKey { prefix, .. } => f
                .debug_struct("ApiKey")
                .field("prefix", prefix)
                .field("key", &"[REDACTED]")
                .finish(),
        }
    }
}

/// Runtime configuration for every API call.
///
/// Construct via [`Configuration::builder()`] to get compile-time safety on
/// which auth method is active and to avoid direct field mutation.
///
/// # Example
/// ```no_run
/// use openfga::apis::configuration::Configuration;
///
/// let config = Configuration::builder()
///     .base_path("https://api.fga.example.com")
///     .bearer_token("my-token")
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct Configuration {
    pub(crate) base_path: String,
    pub(crate) user_agent: Option<String>,
    pub(crate) client: reqwest::Client,
    pub(crate) auth: Option<AuthMethod>,
}

impl Default for Configuration {
    fn default() -> Self {
        Configuration {
            base_path: "http://localhost".to_owned(),
            user_agent: Some("OpenFGA-Rust-SDK/1.x".to_owned()),
            client: reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(30))
                .build()
                .expect("failed to build reqwest client"),
            auth: None,
        }
    }
}

impl Configuration {
    /// Create a [`ConfigurationBuilder`] to construct a `Configuration`.
    pub fn builder() -> ConfigurationBuilder {
        ConfigurationBuilder::default()
    }

    /// Apply this configuration's `User-Agent` header and auth credentials to
    /// a request builder. Called internally by every API function, replacing the
    /// former pair of free functions `set_user_agent` + `apply_auth`.
    pub(crate) fn apply_to_request(
        &self,
        req_builder: reqwest::RequestBuilder,
    ) -> reqwest::RequestBuilder {
        let req_builder = if let Some(ua) = &self.user_agent {
            req_builder.header(reqwest::header::USER_AGENT, ua.as_str())
        } else {
            req_builder
        };

        match &self.auth {
            Some(AuthMethod::Bearer(token)) | Some(AuthMethod::OAuth(token)) => {
                req_builder.bearer_auth(token)
            }
            Some(AuthMethod::Basic(creds)) => {
                req_builder.basic_auth(&creds.username, creds.password.as_deref())
            }
            Some(AuthMethod::ApiKey { prefix, key }) => {
                let header_val = match prefix {
                    Some(p) => format!("{} {}", p, key),
                    None => key.clone(),
                };
                req_builder.header(reqwest::header::AUTHORIZATION, header_val)
            }
            None => req_builder,
        }
    }
}

/// Builder for [`Configuration`].
///
/// Auth methods are mutually exclusive setters: calling more than one simply
/// overwrites the previous choice, so the last setter wins. No hidden
/// priority list exists.
#[derive(Debug)]
pub struct ConfigurationBuilder {
    base_path: String,
    user_agent: Option<String>,
    client: Option<reqwest::Client>,
    auth: Option<AuthMethod>,
    timeout: std::time::Duration,
}

impl Default for ConfigurationBuilder {
    fn default() -> Self {
        ConfigurationBuilder {
            base_path: "http://localhost".to_owned(),
            user_agent: Some("OpenFGA-Rust-SDK/1.x".to_owned()),
            client: None,
            auth: None,
            timeout: std::time::Duration::from_secs(30),
        }
    }
}

impl ConfigurationBuilder {
    /// Set the OpenFGA server base URL (e.g. `"https://api.fga.example.com"`).
    pub fn base_path(mut self, base_path: impl Into<String>) -> Self {
        self.base_path = base_path.into();
        self
    }

    /// Override the `User-Agent` header sent with every request.
    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    /// Provide a pre-built [`reqwest::Client`] (e.g. with custom TLS settings
    /// or connection pool tuning). A default client is used if not set.
    pub fn client(mut self, client: reqwest::Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Override the default 30-second request timeout applied to every request.
    ///
    /// Has no effect when a pre-built client is supplied via [`.client()`].
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Authenticate with a static bearer token.
    pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
        self.auth = Some(AuthMethod::Bearer(token.into()));
        self
    }

    /// Authenticate with an OAuth2 access token.
    pub fn oauth_token(mut self, token: impl Into<String>) -> Self {
        self.auth = Some(AuthMethod::OAuth(token.into()));
        self
    }

    /// Authenticate with HTTP Basic credentials.
    pub fn basic_auth(
        mut self,
        username: impl Into<String>,
        password: Option<impl Into<String>>,
    ) -> Self {
        self.auth = Some(AuthMethod::Basic(BasicAuth {
            username: username.into(),
            password: password.map(Into::into),
        }));
        self
    }

    /// Authenticate with a raw API key sent as the `Authorization` header.
    ///
    /// The header value will be `"<prefix> <key>"` if a prefix is provided,
    /// or just `"<key>"` otherwise.
    pub fn api_key(mut self, key: impl Into<String>, prefix: Option<impl Into<String>>) -> Self {
        self.auth = Some(AuthMethod::ApiKey {
            key: key.into(),
            prefix: prefix.map(Into::into),
        });
        self
    }

    /// Consume the builder and produce a [`Configuration`].
    pub fn build(self) -> Configuration {
        Configuration {
            base_path: self.base_path,
            user_agent: self.user_agent,
            client: self.client.unwrap_or_else(|| {
                reqwest::Client::builder()
                    .timeout(self.timeout)
                    .build()
                    .expect("failed to build reqwest client")
            }),
            auth: self.auth,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::apis::{Error, ResponseContent, urlencode};

    // ── GROUP A: ConfigurationBuilder ──────────────────────────────────────────

    #[test]
    fn builder_default_base_path_is_localhost() {
        let config = Configuration::builder().build();
        assert_eq!(config.base_path, "http://localhost");
    }

    #[test]
    fn builder_bearer_token_sets_bearer_auth() {
        let config = Configuration::builder().bearer_token("my-token").build();
        assert!(
            matches!(&config.auth, Some(AuthMethod::Bearer(t)) if t == "my-token"),
            "expected Bearer(\"my-token\"), got {:?}",
            config.auth
        );
    }

    #[test]
    fn builder_oauth_token_sets_oauth_auth() {
        let config = Configuration::builder().oauth_token("oauth-tok").build();
        assert!(
            matches!(&config.auth, Some(AuthMethod::OAuth(t)) if t == "oauth-tok"),
            "expected OAuth(\"oauth-tok\"), got {:?}",
            config.auth
        );
    }

    #[test]
    fn builder_basic_auth_has_named_fields() {
        let config = Configuration::builder()
            .basic_auth("user", Some("pass"))
            .build();
        match &config.auth {
            Some(AuthMethod::Basic(creds)) => {
                // Access by field name, not tuple index — proves AP-2 fix
                assert_eq!(creds.username, "user");
                assert_eq!(creds.password.as_deref(), Some("pass"));
            }
            other => panic!("expected Basic auth, got {:?}", other),
        }
    }

    #[test]
    fn builder_api_key_with_prefix() {
        let config = Configuration::builder()
            .api_key("my-key", Some("Token"))
            .build();
        match &config.auth {
            Some(AuthMethod::ApiKey { prefix, key }) => {
                assert_eq!(key, "my-key");
                assert_eq!(prefix.as_deref(), Some("Token"));
            }
            other => panic!("expected ApiKey auth, got {:?}", other),
        }
    }

    #[test]
    fn builder_last_auth_setter_wins() {
        let config = Configuration::builder()
            .bearer_token("first")
            .oauth_token("second")
            .build();
        // Last setter (oauth_token) must win — no hidden priority list
        assert!(
            matches!(&config.auth, Some(AuthMethod::OAuth(t)) if t == "second"),
            "expected OAuth(\"second\") to win, got {:?}",
            config.auth
        );
    }

    #[test]
    fn builder_custom_base_path_is_preserved() {
        let config = Configuration::builder()
            .base_path("https://prod.example.com")
            .build();
        assert_eq!(config.base_path, "https://prod.example.com");
    }

    // ── GROUP B: Error Display ─────────────────────────────────────────────────

    #[test]
    fn error_display_response_error_with_entity_includes_entity_details() {
        let rc: ResponseContent<String> = ResponseContent {
            status: reqwest::StatusCode::BAD_REQUEST,
            content: String::from("raw body"),
            entity: Some(String::from("detail string")),
        };
        let err: Error<String> = Error::ResponseError(rc);
        let display = format!("{err}");
        assert!(
            display.contains("status code"),
            "display should contain 'status code', got: {display}"
        );
        // entity debug repr should appear
        assert!(
            display.contains("detail string"),
            "display should contain entity details, got: {display}"
        );
    }

    #[test]
    fn error_display_response_error_without_entity_shows_status_only() {
        let rc: ResponseContent<String> = ResponseContent {
            status: reqwest::StatusCode::BAD_REQUEST,
            content: String::from("raw body"),
            entity: None,
        };
        let err: Error<String> = Error::ResponseError(rc);
        let display = format!("{err}");
        assert!(
            display.contains("status code 400"),
            "display should contain 'status code 400', got: {display}"
        );
    }

    #[test]
    fn error_display_serde_error_shows_serde_module() {
        let serde_err = serde_json::from_str::<i32>("not-a-number").unwrap_err();
        let err: Error<String> = Error::Serde(serde_err);
        let display = format!("{err}");
        assert!(
            display.starts_with("error in serde:"),
            "display should start with 'error in serde:', got: {display}"
        );
    }

    // ── GROUP C: urlencode ─────────────────────────────────────────────────────

    #[test]
    fn urlencode_encodes_slashes_and_spaces() {
        let encoded = urlencode("store/id with space");
        // url::form_urlencoded encodes '/' as %2F and space as '+'
        assert!(
            encoded.contains("%2F"),
            "slash should be percent-encoded, got: {encoded}"
        );
        // space is encoded as '+' by form_urlencoded
        assert!(
            encoded.contains('+') || encoded.contains("%20"),
            "space should be encoded, got: {encoded}"
        );
    }

    #[test]
    fn urlencode_empty_string_returns_empty() {
        let encoded = urlencode("");
        assert_eq!(encoded, "", "empty string should encode to empty string");
    }

    // ── GROUP D: Debug redaction (F-3) ────────────────────────────────────────

    #[test]
    fn basic_auth_debug_redacts_password() {
        let creds = BasicAuth {
            username: "alice".to_string(),
            password: Some("super-secret".to_string()),
        };
        let debug = format!("{creds:?}");
        assert!(!debug.contains("super-secret"), "password must not appear in debug output");
        assert!(debug.contains("[REDACTED]"));
        assert!(debug.contains("alice"), "username should be visible");
    }

    #[test]
    fn auth_method_bearer_debug_redacts_token() {
        let auth = AuthMethod::Bearer("my-secret-token".to_string());
        let debug = format!("{auth:?}");
        assert!(!debug.contains("my-secret-token"));
        assert!(debug.contains("[REDACTED]"));
    }

    #[test]
    fn auth_method_oauth_debug_redacts_token() {
        let auth = AuthMethod::OAuth("oauth-secret".to_string());
        let debug = format!("{auth:?}");
        assert!(!debug.contains("oauth-secret"));
        assert!(debug.contains("[REDACTED]"));
    }

    #[test]
    fn auth_method_basic_debug_redacts_credentials() {
        let auth = AuthMethod::Basic(BasicAuth {
            username: "bob".to_string(),
            password: Some("hunter2".to_string()),
        });
        let debug = format!("{auth:?}");
        assert!(!debug.contains("hunter2"));
        assert!(debug.contains("[REDACTED]"));
    }

    #[test]
    fn auth_method_apikey_debug_redacts_key_keeps_prefix() {
        let auth = AuthMethod::ApiKey {
            prefix: Some("Token".to_string()),
            key: "api-secret-key".to_string(),
        };
        let debug = format!("{auth:?}");
        assert!(!debug.contains("api-secret-key"));
        assert!(debug.contains("[REDACTED]"));
        assert!(debug.contains("Token"), "prefix should remain visible");
    }

    // ── GROUP E: Configuration::default + apply_to_request branches ───────────

    #[test]
    fn configuration_default_has_localhost_base_path() {
        let config = Configuration::default();
        assert_eq!(config.base_path, "http://localhost");
        assert!(config.auth.is_none());
    }

    #[test]
    fn apply_to_request_skips_ua_header_when_user_agent_is_none() {
        let mut config = Configuration::default();
        config.user_agent = None;
        let req = reqwest::Client::new().get("http://localhost");
        // must not panic — covers the `else { req_builder }` branch (line 119)
        let _req = config.apply_to_request(req);
    }

    #[test]
    fn apply_to_request_with_basic_auth_does_not_panic() {
        let config = Configuration::builder()
            .basic_auth("user", Some("pass"))
            .build();
        let req = reqwest::Client::new().get("http://localhost");
        let _req = config.apply_to_request(req);
    }

    #[test]
    fn apply_to_request_with_api_key_no_prefix_does_not_panic() {
        let config = Configuration::builder()
            .api_key("raw-key", None::<String>)
            .build();
        let req = reqwest::Client::new().get("http://localhost");
        let _req = config.apply_to_request(req);
    }

    #[test]
    fn apply_to_request_with_api_key_with_prefix_does_not_panic() {
        let config = Configuration::builder()
            .api_key("raw-key", Some("Token"))
            .build();
        let req = reqwest::Client::new().get("http://localhost");
        let _req = config.apply_to_request(req);
    }

    #[test]
    fn apply_to_request_with_no_auth_does_not_panic() {
        let config = Configuration::default(); // auth = None
        let req = reqwest::Client::new().get("http://localhost");
        let _req = config.apply_to_request(req);
    }

    // ── GROUP F: Builder — remaining setters ──────────────────────────────────

    #[test]
    fn builder_user_agent_override_is_preserved() {
        let config = Configuration::builder()
            .user_agent("my-app/1.0")
            .build();
        assert_eq!(config.user_agent.as_deref(), Some("my-app/1.0"));
    }

    #[test]
    fn builder_custom_client_is_stored() {
        let custom = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(5))
            .build()
            .unwrap();
        let config = Configuration::builder()
            .bearer_token("t")
            .client(custom)
            .build();
        assert!(matches!(&config.auth, Some(AuthMethod::Bearer(_))));
    }

    #[test]
    fn builder_timeout_setter_does_not_panic() {
        let _config = Configuration::builder()
            .bearer_token("t")
            .timeout(std::time::Duration::from_secs(5))
            .build();
    }

    // ── GROUP G: Error::Io + From impls + source() ────────────────────────────

    #[test]
    fn error_display_io_error_shows_io_module() {
        let io_err = std::io::Error::new(std::io::ErrorKind::Other, "disk full");
        let err: Error<String> = Error::from(io_err);
        let display = format!("{err}");
        assert!(
            display.starts_with("error in IO:"),
            "display should start with 'error in IO:', got: {display}"
        );
        assert!(display.contains("disk full"));
    }

    #[test]
    fn error_from_io_error_creates_io_variant() {
        let io_err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe");
        let err: Error<String> = Error::from(io_err);
        assert!(matches!(err, Error::Io(_)));
    }

    #[test]
    fn error_source_returns_some_for_io() {
        use std::error::Error as StdError;
        let io_err = std::io::Error::new(std::io::ErrorKind::Other, "source-test");
        let err: Error<String> = Error::from(io_err);
        assert!(err.source().is_some());
    }

    #[test]
    fn error_source_returns_some_for_serde() {
        use std::error::Error as StdError;
        let serde_err = serde_json::from_str::<i32>("not-a-number").unwrap_err();
        let err: Error<String> = Error::Serde(serde_err);
        assert!(err.source().is_some());
    }

    #[test]
    fn error_source_returns_none_for_response_error() {
        use std::error::Error as StdError;
        let rc: ResponseContent<String> = ResponseContent {
            status: reqwest::StatusCode::BAD_REQUEST,
            content: String::new(),
            entity: None,
        };
        let err: Error<String> = Error::ResponseError(rc);
        assert!(err.source().is_none());
    }

    #[test]
    fn error_source_returns_some_for_reqwest() {
        use std::error::Error as StdError;
        let build_result = reqwest::Client::new().get("").build();
        let reqwest_err = build_result.unwrap_err();
        let err: Error<String> = Error::from(reqwest_err);
        assert!(err.source().is_some());
    }

    #[test]
    fn error_from_reqwest_error_creates_reqwest_variant() {
        // Force a reqwest::Error via an empty URL — url crate rejects it before network
        let build_result = reqwest::Client::new().get("").build();
        let reqwest_err = build_result.unwrap_err();
        let err: Error<String> = Error::from(reqwest_err);
        assert!(matches!(err, Error::Reqwest(_)));
        let display = format!("{err}");
        assert!(
            display.starts_with("error in reqwest:"),
            "display should start with 'error in reqwest:', got: {display}"
        );
    }
}