wyrd-client 0.3.0

Shared Wyrd client: transport, authentication, and composed client capabilities.
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
//! The platform control-plane handle.

use std::sync::Arc;

use reqwest::Method;
use secrecy::{ExposeSecret, SecretString};
use serde::Serialize;
use serde::de::DeserializeOwned;
use uuid::Uuid;
use wyrd_spec::DataTenantId;
use wyrd_spec::auth::{
    ConfigurePlatformOidcRequest, CreateTenantRequest, CreateTenantResponse,
    CredentialListResponse, IssuePlatformCredentialRequest, IssuedCredential,
    PlatformOidcConnectionView, PlatformPrincipalListResponse, PrincipalId, ProvisionedTenant,
    ProvisionedTenantAdmin, RecoverTenantAdminRequest, RegisterPlatformAdminRequest,
    RegisterPlatformAdminResponse, SecretBearer, SetPlatformPrincipalStatusRequest,
    SetTenantStatusRequest, TenantListResponse,
};
use wyrd_spec::error::WyrdError;

use crate::auth::{AuthMiddleware, TokenExchange};
use crate::client::WyrdClient;
use crate::config::ClientConfig;
use crate::transport::config::HttpConfig;
use crate::transport::credential::ResolvedCredential;
use crate::transport::http::HttpTransport;
use std::fmt::{Debug, Formatter, Result as FmtResult};

/// A short-lived platform session token.
///
/// Held rather than re-exchanged per call, because the exchange is the one
/// operation that reads credential material and doing it repeatedly would move
/// a secret through the process far more often than the contract requires.
#[derive(Clone)]
pub struct PlatformSession(SecretString);

impl Debug for PlatformSession {
    /// Prints the session without its token.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.debug_tuple("PlatformSession")
            .field(&"[REDACTED]")
            .finish()
    }
}

/// Platform control-plane client.
///
/// Owns one authenticated client bound to one session. Cheap to clone; every
/// clone presents the same session, so they expire together.
#[derive(Clone, Debug)]
pub struct Platform {
    /// Shared client whose credential is the platform session, so every request
    /// travels the same transport, retry policy, and error mapping as any other
    /// Wyrd call.
    client: Arc<WyrdClient>,
}

impl Platform {
    /// Exchange the ambient platform credential for a session and bind a
    /// client to it.
    ///
    /// The server URL and credential resolve as [`WyrdClient::from_global`]
    /// resolves them; the credential must be a platform credential, which is
    /// classified as presented-as-is, so resolution makes no tenant exchange.
    /// Then this is [`Self::connect_with`].
    ///
    /// # Errors
    /// Returns the configuration or credential-resolution error, and
    /// otherwise as [`Self::connect_with`].
    pub async fn connect() -> Result<Self, WyrdError> {
        Self::connect_with(&WyrdClient::from_global().map_err(WyrdError::from)?).await
    }

    /// Exchange `client`'s platform credential for a session and bind a
    /// client to it.
    ///
    /// `client` names the server and carries the platform credential, which
    /// its constructor classifies as a presented-as-is token because it is not
    /// an API key. This is the only call that reads that credential material.
    /// The session it returns becomes the new client's bearer, so every later
    /// request presents it on `X-Wyrd-Access-Token` like any other Wyrd token —
    /// the plane is separated by the session's scope marker and by the
    /// extractor its routes declare, never by which header carried the token.
    ///
    /// # Arguments
    /// * `client` - A client built with the platform credential and the
    ///   server URL; only those two are read.
    ///
    /// # Errors
    /// Returns [`WyrdError::Unauthenticated`] when `client` carries anything
    /// but a presented-as-is credential, and for every credential rejection,
    /// indistinguishably, and a transport error when the server cannot be
    /// reached.
    pub async fn connect_with(client: &WyrdClient) -> Result<Self, WyrdError> {
        let auth = &client.auth;
        let ResolvedCredential::BearerToken(credential) = auth.credential() else {
            return Err(WyrdError::Unauthenticated {
                message: "a platform client needs a platform credential".to_owned(),
                details: serde_json::json!({}),
            });
        };
        let config = ClientConfig {
            http: HttpConfig {
                base_url: client.server_url().trim_end_matches('/').to_owned(),
                ..HttpConfig::default()
            },
            ..ClientConfig::default()
        };
        let exchange = TokenExchange::new(&config.http.base_url, config.http.timeout_ms)
            .map_err(WyrdError::from)?;
        let response = exchange
            .platform_session(&SecretBearer::new(credential.expose_secret().to_owned()))
            .await
            .map_err(crate::auth::AuthError::into_wyrd)?;
        let session = PlatformSession(SecretString::from(
            response.access_token.expose().to_owned(),
        ));
        Self::with_session(config, session)
    }

    /// Bind a client to an already minted session.
    ///
    /// # Errors
    /// Returns a transport error when the HTTP client cannot be assembled.
    fn with_session(config: ClientConfig, session: PlatformSession) -> Result<Self, WyrdError> {
        let auth = AuthMiddleware::new(&config, ResolvedCredential::BearerToken(session.0.clone()))
            .map_err(WyrdError::from)?;
        let http = HttpTransport::new(&config.http, Arc::clone(&auth)).map_err(WyrdError::from)?;
        Ok(Self {
            client: Arc::new(WyrdClient {
                auth,
                http,
                grpc_config: config.grpc,
            }),
        })
    }

    /// Provision a tenant and receive its one-time administrative credential.
    ///
    /// The credential is the only way into the new tenant and is returned
    /// exactly once. Store it before dropping the response.
    ///
    /// # Arguments
    /// * `request` - The new tenant's slug and display name.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller lacks tenant creation, the slug is
    /// taken, or provisioning fails.
    pub async fn create_tenant(
        &self,
        request: &CreateTenantRequest,
    ) -> Result<CreateTenantResponse, WyrdError> {
        self.call(Method::POST, "/platform/tenants", Some(request))
            .await
    }

    /// List every tenant in the directory, in every lifecycle state.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller lacks tenant reading or the read
    /// fails.
    pub async fn list_tenants(&self) -> Result<TenantListResponse, WyrdError> {
        self.call::<(), _>(Method::GET, "/platform/tenants", None)
            .await
    }

    /// Read one tenant's directory row.
    ///
    /// # Arguments
    /// * `tenant_id` - The tenant whose directory row is read.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller lacks tenant reading or no such
    /// tenant exists.
    pub async fn tenant(&self, tenant_id: DataTenantId) -> Result<ProvisionedTenant, WyrdError> {
        self.call::<(), _>(Method::GET, &format!("/platform/tenants/{tenant_id}"), None)
            .await
    }

    /// Suspend a tenant or restore it.
    ///
    /// Suspension freezes admission and destroys nothing, so resuming restores
    /// exactly what was there. The transition is refused when the tenant is not
    /// already in the opposite state.
    ///
    /// # Arguments
    /// * `tenant_id` - The tenant to transition.
    /// * `status` - The target status, `active` or `suspended`.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller lacks tenant suspension, the status
    /// is neither `active` nor `suspended`, or the tenant is not in the state
    /// the transition requires.
    pub async fn set_tenant_status(
        &self,
        tenant_id: DataTenantId,
        status: &str,
    ) -> Result<(), WyrdError> {
        let request = SetTenantStatusRequest {
            status: status.to_owned(),
        };
        self.call_no_content(
            Method::PUT,
            &format!("/platform/tenants/{tenant_id}/status"),
            Some(&request),
        )
        .await
    }

    /// Issue a replacement credential for a tenant that has lost every one.
    ///
    /// Restores the existing administrative principal rather than creating a
    /// second, so the tenant's roles and history are untouched.
    ///
    /// # Arguments
    /// * `tenant_id` - The tenant whose administrative principal receives the
    ///   replacement credential.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized or the tenant has
    /// no administrative principal.
    pub async fn recover_tenant_admin(
        &self,
        tenant_id: DataTenantId,
    ) -> Result<ProvisionedTenantAdmin, WyrdError> {
        self.call(
            Method::POST,
            "/platform/tenants/admin/credentials",
            Some(&RecoverTenantAdminRequest { tenant_id }),
        )
        .await
    }

    /// Install or replace the deployment's platform OIDC connection.
    ///
    /// # Arguments
    /// * `request` - The issuer URL, client id, and client authentication to install.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized, the issuer cannot
    /// be screened and discovered, or the write fails.
    pub async fn configure_oidc(
        &self,
        request: &ConfigurePlatformOidcRequest,
    ) -> Result<PlatformOidcConnectionView, WyrdError> {
        self.call(Method::PUT, "/platform/oidc/connection", Some(request))
            .await
    }

    /// Read the configured connection, which never carries the provider secret.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized or no connection is
    /// configured.
    pub async fn oidc_connection(&self) -> Result<PlatformOidcConnectionView, WyrdError> {
        self.call::<(), _>(Method::GET, "/platform/oidc/connection", None)
            .await
    }

    /// Pre-register a human platform administrator.
    ///
    /// # Arguments
    /// * `request` - The administrator's name and the identity-provider claim it
    ///   matches.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized, no connection is
    /// configured, or the name or claim is already registered.
    pub async fn register_admin(
        &self,
        request: &RegisterPlatformAdminRequest,
    ) -> Result<RegisterPlatformAdminResponse, WyrdError> {
        self.call(Method::POST, "/platform/admins", Some(request))
            .await
    }

    /// List every platform principal, including suspended ones.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized or the read fails.
    pub async fn list_admins(&self) -> Result<PlatformPrincipalListResponse, WyrdError> {
        self.call::<(), _>(Method::GET, "/platform/admins", None)
            .await
    }

    /// Suspend or restore a platform principal.
    ///
    /// # Arguments
    /// * `principal_id` - The platform principal to transition.
    /// * `status` - The target status, such as `active` or `suspended`.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized, the principal is
    /// unknown, or the change would leave the deployment with no active
    /// principal.
    pub async fn set_admin_status(
        &self,
        principal_id: &PrincipalId,
        status: &str,
    ) -> Result<(), WyrdError> {
        let request = SetPlatformPrincipalStatusRequest {
            status: status.to_owned(),
        };
        self.call_no_content(
            Method::PUT,
            &format!("/platform/admins/{principal_id}/status"),
            Some(&request),
        )
        .await
    }

    /// Mint a credential for an existing platform principal.
    ///
    /// The plaintext is in the response and nowhere else. Store it before
    /// dropping the response: no later call can recover it.
    ///
    /// # Arguments
    /// * `principal_id` - The platform principal the credential is minted for.
    /// * `expires_in_days` - The credential lifetime in days, or `None` for an
    ///   unbounded credential.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller lacks platform credential
    /// administration, the principal is unknown, or the write fails.
    pub async fn issue_credential(
        &self,
        principal_id: &PrincipalId,
        expires_in_days: Option<u32>,
    ) -> Result<IssuedCredential, WyrdError> {
        self.call(
            Method::POST,
            &format!("/platform/admins/{principal_id}/credentials"),
            Some(&IssuePlatformCredentialRequest { expires_in_days }),
        )
        .await
    }

    /// List a platform principal's credential metadata, newest first.
    ///
    /// Never returns credential material; the listing exists so an operator can
    /// see what is live, expired, or already retired before rotating.
    ///
    /// # Arguments
    /// * `principal_id` - The platform principal whose credentials are listed.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized or the read fails.
    pub async fn list_credentials(
        &self,
        principal_id: &PrincipalId,
    ) -> Result<CredentialListResponse, WyrdError> {
        self.call::<(), _>(
            Method::GET,
            &format!("/platform/admins/{principal_id}/credentials"),
            None,
        )
        .await
    }

    /// Retire one of a platform principal's credentials.
    ///
    /// Takes effect on the next request: a platform session names the
    /// credential that minted it, so the retired credential's live sessions
    /// stop working immediately.
    ///
    /// # Arguments
    /// * `principal_id` - The platform principal that owns the credential.
    /// * `credential_id` - The credential to retire.
    ///
    /// # Errors
    /// Returns a Wyrd error when the caller is unauthorized, or the credential
    /// is not this principal's or is already retired.
    pub async fn revoke_credential(
        &self,
        principal_id: &PrincipalId,
        credential_id: Uuid,
    ) -> Result<(), WyrdError> {
        self.call_no_content::<()>(
            Method::DELETE,
            &format!("/platform/admins/{principal_id}/credentials/{credential_id}"),
            None,
        )
        .await
    }

    /// Send one authenticated platform request expecting a JSON body.
    ///
    /// # Errors
    /// Returns the server's stable Wyrd error, or a transport error.
    async fn call<S, D>(&self, method: Method, path: &str, body: Option<&S>) -> Result<D, WyrdError>
    where
        S: Serialize,
        D: DeserializeOwned,
    {
        self.client.http.request_json(method, path, body).await
    }

    /// Send one authenticated platform request expecting no body.
    ///
    /// The shared transport decodes an empty `2xx` body as JSON `null`, so the
    /// no-content routes need no second code path — only a unit target.
    ///
    /// # Errors
    /// Returns the server's stable Wyrd error, or a transport error.
    async fn call_no_content<S>(
        &self,
        method: Method,
        path: &str,
        body: Option<&S>,
    ) -> Result<(), WyrdError>
    where
        S: Serialize,
    {
        self.client
            .http
            .request_json::<S, ()>(method, path, body)
            .await
    }
}