nautilus-rs 1.3.0

Official Rust SDK for the Verne Nautilus platform
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
pub mod types;

use std::sync::Arc;

use crate::{error::Error, http::HttpClient};
use types::{
    AccessToken, AuthorizationDecision, AuthorizeParams, CreateIdentityParams, CreateTokenParams,
    Identity, JsonPatchOp, OidcProvider, SecuritySettings, TokenInfo,
};

/// Gate service client — Auth-as-a-Service.
///
/// Provides identity management, short-lived access token issuance, and
/// policy-based authorization checks.
///
/// Obtain a `Gate` instance either as part of the unified [`Verne`] client or
/// standalone:
///
/// ```no_run
/// // Standalone
/// use nautilus_rs::Gate;
/// let gate = Gate::new("vrn_gate_live_sk_…");
///
/// // Via unified client
/// use nautilus_rs::Verne;
/// # fn run() -> Result<(), nautilus_rs::Error> {
/// let verne = Verne::builder().gate("vrn_gate_live_sk_…").build()?;
/// let gate = verne.gate()?;
/// # Ok(())
/// # }
/// ```
///
/// [`Verne`]: crate::Verne
pub struct Gate {
    http: Arc<HttpClient>,
    api_key: String,
}

impl std::fmt::Debug for Gate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Gate").finish_non_exhaustive()
    }
}

impl Gate {
    /// Create a `Gate` client with default settings.
    ///
    /// Panics if the API key is empty or the HTTP client cannot be initialized.
    /// Use [`Gate::builder`] for fallible construction.
    pub fn new(api_key: impl Into<String>) -> Self {
        let key = api_key.into();
        Self::builder()
            .api_key(&key)
            .build()
            .expect("failed to build Gate client")
    }

    /// Return a [`GateBuilder`] for fine-grained configuration.
    pub fn builder() -> GateBuilder {
        GateBuilder::default()
    }

    pub(crate) fn from_http(http: Arc<HttpClient>, api_key: String) -> Self {
        Self { http, api_key }
    }

    /// Return an [`IdentitiesClient`] for CRUD operations on identities.
    pub fn identities(&self) -> IdentitiesClient {
        IdentitiesClient {
            http: Arc::clone(&self.http),
        }
    }

    /// Return a [`TokensClient`] for issuing and introspecting access tokens.
    pub fn tokens(&self) -> TokensClient {
        TokensClient {
            http: Arc::clone(&self.http),
            api_key: self.api_key.clone(),
        }
    }

    /// Return a [`SettingsClient`] for reading and updating tenant settings.
    pub fn settings(&self) -> SettingsClient {
        SettingsClient {
            http: Arc::clone(&self.http),
        }
    }

    /// Check whether a subject is allowed to perform an action on a resource.
    ///
    /// Maps to `POST /v1/gate/authorize`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nautilus_rs::{Gate, AuthorizeParams};
    ///
    /// # async fn run() -> Result<(), nautilus_rs::Error> {
    /// let gate = Gate::new("vrn_gate_live_sk_…");
    /// let decision = gate.authorize(AuthorizeParams {
    ///     subject: "idn_alice".into(),
    ///     action: "read".into(),
    ///     resource: "report:rpt_456".into(),
    ///     context: None,
    /// }).await?;
    /// assert!(decision.allowed);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn authorize(&self, params: AuthorizeParams) -> Result<AuthorizationDecision, Error> {
        self.http.post("/v1/gate/authorize", &params, false).await
    }

    /// List the social login providers currently enabled for a tenant.
    ///
    /// This is a **public, unauthenticated** endpoint — call it from your
    /// login / registration page to decide which social buttons to render.
    /// Maps to `GET /public/gate/providers/{tenant_id}`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nautilus_rs::Gate;
    ///
    /// # async fn run() -> Result<(), nautilus_rs::Error> {
    /// let gate = Gate::new("vrn_gate_live_sk_…");
    /// let providers = gate.get_enabled_providers("ten_001").await?;
    /// // → ["github", "google"]
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_enabled_providers(&self, tenant_id: &str) -> Result<Vec<String>, Error> {
        #[derive(serde::Deserialize)]
        struct Wrapper {
            providers: Vec<String>,
        }

        let wrapped: Wrapper = self
            .http
            .get(&format!("/public/gate/providers/{tenant_id}"))
            .await?;
        Ok(wrapped.providers)
    }

    /// Initialize a Kratos login flow using your Gate API key.
    ///
    /// Call this from your server and pass the returned flow JSON to your
    /// browser-side code to render social login buttons. The flow already
    /// contains only the providers your tenant has enabled. Maps to
    /// `GET /v1/gate/auth/login`.
    ///
    /// The response mirrors the raw Ory Kratos flow JSON, so it is returned as
    /// an untyped [`serde_json::Value`].
    pub async fn create_login_flow(&self) -> Result<serde_json::Value, Error> {
        self.http.get("/v1/gate/auth/login").await
    }
}

/// Builder for a standalone [`Gate`] client.
///
/// # Example
///
/// ```no_run
/// use nautilus_rs::Gate;
///
/// let gate = Gate::builder()
///     .api_key("vrn_gate_live_sk_…")
///     .timeout_secs(15)
///     .build()
///     .expect("invalid configuration");
/// ```
#[derive(Default)]
pub struct GateBuilder {
    api_key: Option<String>,
    base_url: Option<String>,
    timeout_secs: Option<u64>,
}

impl GateBuilder {
    /// Set the Gate API key (**required**).
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Override the API base URL (default: `https://api.vernesoft.com`).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set the HTTP request timeout in seconds (default: `30`).
    pub fn timeout_secs(mut self, secs: u64) -> Self {
        self.timeout_secs = Some(secs);
        self
    }

    /// Consume the builder and return a configured [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if the API key was not set.
    pub fn build(self) -> Result<Gate, Error> {
        let key = self
            .api_key
            .ok_or_else(|| Error::Config("gate API key is required".into()))?;
        let http = HttpClient::new(&key, self.base_url, self.timeout_secs)?;
        Ok(Gate {
            http: Arc::new(http),
            api_key: key,
        })
    }
}

/// Access to the `/v1/gate/identities` endpoints.
///
/// Obtain via [`Gate::identities`].
pub struct IdentitiesClient {
    http: Arc<HttpClient>,
}

impl IdentitiesClient {
    /// Create a new identity.
    ///
    /// Maps to `POST /v1/gate/identities`.
    pub async fn create(&self, params: CreateIdentityParams) -> Result<Identity, Error> {
        self.http.post("/v1/gate/identities", &params, false).await
    }

    /// Fetch a single identity by ID.
    ///
    /// Maps to `GET /v1/gate/identities/{id}`.
    pub async fn get(&self, identity_id: &str) -> Result<Identity, Error> {
        self.http
            .get(&format!("/v1/gate/identities/{identity_id}"))
            .await
    }

    /// Partially update an identity using [RFC 6902](https://datatracker.ietf.org/doc/html/rfc6902)
    /// JSON Patch operations.
    ///
    /// Maps to `PATCH /v1/gate/identities/{id}`.
    pub async fn patch(&self, identity_id: &str, ops: Vec<JsonPatchOp>) -> Result<Identity, Error> {
        self.http
            .patch(&format!("/v1/gate/identities/{identity_id}"), &ops)
            .await
    }

    /// Permanently delete an identity.
    ///
    /// Maps to `DELETE /v1/gate/identities/{id}`.
    pub async fn delete(&self, identity_id: &str) -> Result<(), Error> {
        self.http
            .delete(&format!("/v1/gate/identities/{identity_id}"))
            .await
    }

    /// Activate or deactivate an identity.
    ///
    /// An `"inactive"` identity cannot log in — Kratos rejects its credentials
    /// automatically — until it is reactivated. The identity is not deleted.
    /// Fires the `identity.state_changed` webhook event.
    ///
    /// Maps to `PATCH /v1/gate/identities/{id}/state`. `state` must be
    /// `"active"` or `"inactive"`.
    pub async fn set_state(&self, identity_id: &str, state: &str) -> Result<Identity, Error> {
        #[derive(serde::Serialize)]
        struct StateBody<'a> {
            state: &'a str,
        }

        self.http
            .patch(
                &format!("/v1/gate/identities/{identity_id}/state"),
                &StateBody { state },
            )
            .await
    }

    /// Activate an identity — convenience wrapper for [`set_state`](Self::set_state)
    /// with `"active"`.
    pub async fn activate(&self, identity_id: &str) -> Result<Identity, Error> {
        self.set_state(identity_id, "active").await
    }

    /// Deactivate an identity — convenience wrapper for [`set_state`](Self::set_state)
    /// with `"inactive"`.
    pub async fn deactivate(&self, identity_id: &str) -> Result<Identity, Error> {
        self.set_state(identity_id, "inactive").await
    }

    /// Trigger a new email verification flow for an identity.
    ///
    /// Useful when the original verification email expired or was never
    /// received; the user receives a fresh verification email.
    ///
    /// Maps to `POST /v1/gate/identities/{id}/resend-verification`.
    pub async fn resend_verification(&self, identity_id: &str) -> Result<(), Error> {
        self.http
            .post_discard(&format!("/v1/gate/identities/{identity_id}/resend-verification"))
            .await
    }
}

/// Access to the `/v1/gate/tokens` endpoints.
///
/// Obtain via [`Gate::tokens`].
pub struct TokensClient {
    http: Arc<HttpClient>,
    api_key: String,
}

impl TokensClient {
    /// Issue a short-lived access token for a subject.
    ///
    /// Maps to `POST /v1/gate/tokens`. The API key is sent in the request body
    /// rather than the `Authorization` header.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nautilus_rs::{Gate, CreateTokenParams};
    ///
    /// # async fn run() -> Result<(), nautilus_rs::Error> {
    /// let gate = Gate::new("vrn_gate_live_sk_…");
    /// let token = gate.tokens().create(CreateTokenParams {
    ///     subject: "idn_alice".into(),
    ///     scopes: Some(vec!["read:profile".into()]),
    ///     ttl_seconds: Some(900),
    /// }).await?;
    /// println!("expires at {}", token.expires_at);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create(&self, params: CreateTokenParams) -> Result<AccessToken, Error> {
        #[derive(serde::Serialize)]
        struct CreateTokenBody {
            api_key: String,
            subject: String,
            #[serde(skip_serializing_if = "Option::is_none")]
            scopes: Option<Vec<String>>,
            #[serde(skip_serializing_if = "Option::is_none")]
            ttl_seconds: Option<u64>,
        }

        let body = CreateTokenBody {
            api_key: self.api_key.clone(),
            subject: params.subject,
            scopes: params.scopes,
            ttl_seconds: params.ttl_seconds,
        };

        self.http.post("/v1/gate/tokens", &body, true).await
    }

    /// Validate an access token and retrieve its claims.
    ///
    /// Maps to `POST /v1/gate/tokens/introspect`. Check
    /// [`TokenInfo::active`] to determine whether the token is still valid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nautilus_rs::Gate;
    ///
    /// # async fn run() -> Result<(), nautilus_rs::Error> {
    /// let gate = Gate::new("vrn_gate_live_sk_…");
    /// let info = gate.tokens().introspect("eyJ…").await?;
    /// if info.active {
    ///     println!("valid token for {}", info.subject);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn introspect(&self, access_token: &str) -> Result<TokenInfo, Error> {
        #[derive(serde::Serialize)]
        struct IntrospectBody<'a> {
            access_token: &'a str,
        }

        self.http
            .post(
                "/v1/gate/tokens/introspect",
                &IntrospectBody { access_token },
                false,
            )
            .await
    }
}

/// Access to the `/v1/gate/settings` endpoints.
///
/// Obtain via [`Gate::settings`].
pub struct SettingsClient {
    http: Arc<HttpClient>,
}

impl SettingsClient {
    /// Fetch the tenant's security settings (passwordless / MFA).
    ///
    /// Maps to `GET /v1/gate/settings/security`.
    pub async fn get_security(&self) -> Result<SecuritySettings, Error> {
        self.http.get("/v1/gate/settings/security").await
    }

    /// Replace the tenant's security settings.
    ///
    /// Both fields are always sent — the update is a full replacement, not a
    /// merge. Maps to `PUT /v1/gate/settings/security`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nautilus_rs::{Gate, SecuritySettings};
    ///
    /// # async fn run() -> Result<(), nautilus_rs::Error> {
    /// let gate = Gate::new("vrn_gate_live_sk_…");
    /// gate.settings().update_security(SecuritySettings {
    ///     passwordless_enabled: true,
    ///     mfa_enabled: false,
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn update_security(&self, settings: SecuritySettings) -> Result<(), Error> {
        self.http
            .put_discard("/v1/gate/settings/security", &settings)
            .await
    }

    /// List the tenant's social login (OIDC) providers and whether each is
    /// enabled — covering every provider Gate supports, regardless of state.
    ///
    /// Maps to `GET /v1/gate/settings/oidc-providers`.
    pub async fn get_oidc_providers(&self) -> Result<Vec<OidcProvider>, Error> {
        #[derive(serde::Deserialize)]
        struct Wrapper {
            providers: Vec<OidcProvider>,
        }

        let wrapped: Wrapper = self.http.get("/v1/gate/settings/oidc-providers").await?;
        Ok(wrapped.providers)
    }

    /// Set the `enabled` flag for one or more social login providers.
    ///
    /// Any provider omitted from `providers` is left unchanged. Returns the
    /// full, updated provider list. Maps to
    /// `PUT /v1/gate/settings/oidc-providers`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nautilus_rs::{Gate, OidcProvider};
    ///
    /// # async fn run() -> Result<(), nautilus_rs::Error> {
    /// let gate = Gate::new("vrn_gate_live_sk_…");
    /// let providers = gate.settings().update_oidc_providers(vec![
    ///     OidcProvider { provider: "github".into(), enabled: true },
    ///     OidcProvider { provider: "google".into(), enabled: true },
    /// ]).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn update_oidc_providers(
        &self,
        providers: Vec<OidcProvider>,
    ) -> Result<Vec<OidcProvider>, Error> {
        #[derive(serde::Serialize)]
        struct Body {
            providers: Vec<OidcProvider>,
        }

        #[derive(serde::Deserialize)]
        struct Wrapper {
            providers: Vec<OidcProvider>,
        }

        let wrapped: Wrapper = self
            .http
            .put("/v1/gate/settings/oidc-providers", &Body { providers })
            .await?;
        Ok(wrapped.providers)
    }
}