wyrd-spec 0.1.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
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
//! Wire contract for a tenant's human OIDC login connection.
//!
//! A tenant has at most one `Active` connection that human login trusts and at
//! most one `Candidate` staged to replace it. The lifecycle is headless:
//! `PUT /v1/identity/oidc/candidate` stages or rotates, `POST .../test` starts
//! a real test sign-in that proves the exact candidate revision against the
//! provider, and `POST .../activate` swaps it in. The bearer credential, never a request field, selects the
//! tenant.
//!
//! Secrets travel inbound only. [`HumanConnectionView`] carries no secret or
//! sealing metadata, and [`HumanClientAuth`] deliberately has no
//! `PrivateKeyJwt` arm: an unimplemented method is refused with
//! `WYRD_AUTH_400_UNSUPPORTED_CLIENT_AUTH` by [`ConnectionInput::from_slice`]
//! and never appears in a generated schema.

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;

use crate::DataTenantId;
use crate::auth::{AbsoluteUrl, ClaimMappingPayload, IssuerTokenPolicy, IssuerUrl, SecretBearer};
use crate::error::WyrdError;

/// Wire spelling of the client-authentication method Wyrd does not implement.
const PRIVATE_KEY_JWT: &str = "PrivateKeyJwt";

/// Lifecycle state of one tenant human connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub enum HumanConnectionState {
    /// Staged configuration; never trusted by login.
    Candidate,
    /// The one configuration human login trusts.
    Active,
    /// Retired, deactivated, or removed; never trusted by login.
    Inactive,
}

impl HumanConnectionState {
    /// Stable storage and wire spelling.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Candidate => "Candidate",
            Self::Active => "Active",
            Self::Inactive => "Inactive",
        }
    }

    /// Parse the stored spelling.
    ///
    /// # Errors
    /// Returns [`WyrdError::Internal`] for an unknown stored value.
    pub fn parse(value: &str) -> Result<Self, WyrdError> {
        match value {
            "Candidate" => Ok(Self::Candidate),
            "Active" => Ok(Self::Active),
            "Inactive" => Ok(Self::Inactive),
            other => Err(WyrdError::Internal {
                message: "stored human connection state is unknown".to_owned(),
                details: serde_json::json!({ "state": other }),
            }),
        }
    }
}

/// How Wyrd authenticates to the provider token endpoint for human login.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub enum HumanClientAuth {
    /// HTTP Basic with the client secret; requires `client_secret`.
    SecretBasic,
    /// Client secret in the form body; requires `client_secret`.
    SecretPost,
    /// Public PKCE client; `client_secret` must be absent.
    Public,
}

impl HumanClientAuth {
    /// Stable storage and wire spelling.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SecretBasic => "SecretBasic",
            Self::SecretPost => "SecretPost",
            Self::Public => "Public",
        }
    }

    /// Parse the stored spelling.
    ///
    /// # Errors
    /// Returns [`WyrdError::Internal`] for an unknown stored value.
    pub fn parse(value: &str) -> Result<Self, WyrdError> {
        match value {
            "SecretBasic" => Ok(Self::SecretBasic),
            "SecretPost" => Ok(Self::SecretPost),
            "Public" => Ok(Self::Public),
            other => Err(WyrdError::Internal {
                message: "stored human connection client auth is unknown".to_owned(),
                details: serde_json::json!({ "client_auth": other }),
            }),
        }
    }

    /// Whether this method sends a client secret.
    #[must_use]
    pub fn requires_secret(self) -> bool {
        !matches!(self, Self::Public)
    }
}

/// Redacted projection of one tenant human connection.
///
/// Never carries a client secret, its ciphertext, or sealing-key identifiers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct HumanConnectionView {
    /// Stable connection id; kept as a tombstone after removal.
    pub id: Uuid,
    /// Owning tenant.
    pub tenant_id: DataTenantId,
    /// Tenant-monotonic configuration revision.
    pub revision: u64,
    /// Lifecycle state.
    pub state: HumanConnectionState,
    /// Provider issuer URL, pinned as the ID-token `iss`.
    pub issuer: String,
    /// Wyrd's client id at the provider, also the ID-token audience.
    pub client_id: String,
    /// Client-authentication method; the secret itself is never returned.
    pub client_auth: HumanClientAuth,
    /// Verified claim mapping (`subject`, optional `email` and `groups`).
    pub claim_mapping: ClaimMappingPayload,
    /// Provider group to tenant role names.
    pub group_role_map: HashMap<String, Vec<String>>,
    /// JWKS key-cache lifetime in seconds.
    pub jwks_ttl_secs: u64,
    /// Revision the last successful test proved, when one is current.
    pub tested_revision: Option<u64>,
    /// Instant after which activation requires a fresh test.
    pub tested_until: Option<DateTime<Utc>>,
    /// Creation instant.
    pub created_at: DateTime<Utc>,
    /// Last mutation instant.
    pub updated_at: DateTime<Utc>,
    /// Exact redirect URI to register at the provider, derived from the
    /// deployment's configured public origin. `None` only when the deployment
    /// has no public origin configured, in which case staging and testing are
    /// refused.
    pub callback_url: Option<String>,
}

/// `GET /v1/identity/oidc/connections` response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct HumanConnectionsResponse {
    /// The connection human login trusts, if any.
    pub active: Option<HumanConnectionView>,
    /// The staged replacement, if any.
    pub candidate: Option<HumanConnectionView>,
    /// Redirect URI to register at the provider, available before any
    /// connection exists. `None` when no public origin is configured.
    pub callback_url: Option<String>,
}

/// `PUT /v1/identity/oidc/candidate` body: stage or rotate the candidate.
///
/// Also the rotation path for a secret or group-role map on an unchanged
/// issuer: stage the same issuer with the new values, test, and activate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct ConnectionInput {
    /// Provider issuer URL; endpoints and JWKS come from its discovery document.
    pub issuer: IssuerUrl,
    /// Wyrd's client id at the provider; the ID-token audience is derived
    /// from it.
    pub client_id: String,
    /// Client-authentication method.
    pub client_auth: HumanClientAuth,
    /// Client secret for `SecretBasic`/`SecretPost`; must be absent for
    /// `Public`. Sealed before storage and never returned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<SecretBearer>,
    /// Claim mapping. `subject` must be exactly `sub`: a human is identified
    /// by the provider's immutable OIDC subject, never a mutable claim such as
    /// email. `email` and `groups` stay configurable.
    pub claim_mapping: ClaimMappingPayload,
    /// Provider group to tenant role names.
    #[serde(default)]
    pub group_role_map: HashMap<String, Vec<String>>,
    /// Revision of the candidate being replaced. Required when a candidate
    /// exists; must be omitted when none does.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_revision: Option<u64>,
}

/// The only subject claim a tenant human connection may map: the provider's
/// immutable OIDC `sub`. Durable User identity is `(issuer, sub)`.
pub const HUMAN_SUBJECT_CLAIM: &str = "sub";

impl ConnectionInput {
    /// Decode a raw request body, refusing unsupported client authentication
    /// with its own stable code before generic validation.
    ///
    /// The bytes are parsed as JSON once; a `client_auth` of `PrivateKeyJwt`
    /// is refused before the contract shape is checked, so that method keeps
    /// its stable code even though the schema does not offer it. The body is
    /// then decoded into the contract and its cross-field rules are checked.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the bytes are not JSON or do not
    /// match the contract, [`WyrdError::UnsupportedClientAuth`] when
    /// `client_auth` names `PrivateKeyJwt`, and the result of
    /// [`Self::validate`] otherwise.
    pub fn from_slice(body: &[u8]) -> Result<Self, WyrdError> {
        let body: Value = serde_json::from_slice(body).map_err(invalid_input)?;
        if body.get("client_auth").and_then(Value::as_str) == Some(PRIVATE_KEY_JWT) {
            return Err(unsupported_client_auth());
        }
        let input: Self = serde_json::from_value(body).map_err(invalid_input)?;
        input.validate()?;
        Ok(input)
    }

    /// Check the cross-field rules the type cannot express.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when `client_id` is empty, the
    /// subject claim path is not exactly [`HUMAN_SUBJECT_CLAIM`], a secret
    /// method omits its secret or supplies an empty one, or `Public` supplies
    /// any secret value, including an empty one.
    fn validate(&self) -> Result<(), WyrdError> {
        if self.client_id.trim().is_empty() {
            return Err(validation("client_id must not be empty", "client_id"));
        }
        if self.claim_mapping.subject != HUMAN_SUBJECT_CLAIM {
            return Err(validation(
                "claim_mapping.subject must be \"sub\": a human connection identifies people by \
                 the provider's OIDC subject",
                "claim_mapping",
            ));
        }
        // Presence and content are separate facts: a Public client refuses
        // any supplied value, even an empty one, and a secret method needs a
        // supplied, nonempty one.
        match (self.client_auth.requires_secret(), &self.client_secret) {
            (true, Some(secret)) if !secret.expose().is_empty() => Ok(()),
            (true, _) => Err(validation(
                "client_secret is required and must not be empty for SecretBasic and SecretPost",
                "client_secret",
            )),
            (false, Some(_)) => Err(validation(
                "client_secret must be omitted for a Public client",
                "client_secret",
            )),
            (false, None) => Ok(()),
        }
    }
}

/// `POST /v1/identity/oidc/candidate/test` body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct ConnectionTestRequest {
    /// Candidate revision to test; a newer revision is a conflict.
    pub expected_revision: u64,
}

/// `POST /v1/identity/oidc/candidate/test` response: the test sign-in to
/// complete.
///
/// The candidate is marked tested only when a person completes this real
/// authorization-code sign-in and the common callback verifies its ID token
/// exactly as a login; the test issues no session, credential, or user.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct ConnectionTestResponse {
    /// Provider authorization URL that starts the test sign-in. It carries
    /// one-use state bound to the candidate revision and the caller, and
    /// expires with that state.
    pub authorization_url: AbsoluteUrl,
}

/// `POST /v1/identity/oidc/candidate/activate` body.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct ConnectionActivate {
    /// Candidate revision to activate; must match the tested revision.
    pub expected_revision: u64,
    /// API key of an existing headless principal of this tenant holding
    /// `identity_connections:write`, proving a non-SSO way back in exists
    /// before the old provider is retired. Verified, never stored or echoed.
    pub recovery_api_key: SecretBearer,
}

/// Refuse a Human issuer on the workload trusted-issuer surfaces.
///
/// # Errors
/// Returns [`WyrdError::HumanConnectionRequired`] when `principal_kind` is
/// `Human`.
pub fn refuse_human_trusted_issuer(principal_kind: IssuerTokenPolicy) -> Result<(), WyrdError> {
    if principal_kind == IssuerTokenPolicy::Human {
        return Err(WyrdError::HumanConnectionRequired {
            message: "trusted issuers are workload-only; configure human login through the \
                      tenant OIDC connection API (/v1/identity/oidc)"
                .to_owned(),
            details: serde_json::json!({ "principal_kind": "human" }),
        });
    }
    Ok(())
}

/// The `UNSUPPORTED_CLIENT_AUTH` refusal.
fn unsupported_client_auth() -> WyrdError {
    WyrdError::UnsupportedClientAuth {
        message: "PrivateKeyJwt client authentication is not supported for tenant connections"
            .to_owned(),
        details: serde_json::json!({ "field": "client_auth" }),
    }
}

/// The refusal for a body that is not JSON or does not match the contract.
fn invalid_input(error: serde_json::Error) -> WyrdError {
    WyrdError::Validation {
        message: format!("connection input is invalid: {error}"),
        details: serde_json::json!({}),
    }
}

/// A field-scoped validation refusal.
fn validation(message: &str, field: &str) -> WyrdError {
    WyrdError::Validation {
        message: message.to_owned(),
        details: serde_json::json!({ "field": field }),
    }
}

#[cfg(test)]
mod tests {
    use super::{ConnectionInput, HumanClientAuth, refuse_human_trusted_issuer};
    use crate::auth::IssuerTokenPolicy;
    use crate::error::WyrdError;

    /// A minimal valid public-client body.
    fn body() -> serde_json::Value {
        serde_json::json!({
            "issuer": "https://idp.example.com",
            "client_id": "wyrd",
            "client_auth": "Public",
            "claim_mapping": { "subject": "sub" },
        })
    }

    /// Encode `body` as the raw request bytes the decoder receives.
    fn bytes(body: &serde_json::Value) -> Vec<u8> {
        serde_json::to_vec(body).expect("test body encodes")
    }

    /// `PrivateKeyJwt` is refused with its own code even when the rest of the
    /// body would fail ordinary validation, and bytes that are not JSON are a
    /// validation refusal.
    #[test]
    fn private_key_jwt_precedes_validation_and_malformed_bytes_are_invalid() {
        let raw = serde_json::json!({ "client_auth": "PrivateKeyJwt", "unknown": true });
        assert!(matches!(
            ConnectionInput::from_slice(&bytes(&raw)),
            Err(WyrdError::UnsupportedClientAuth { .. })
        ));
        for malformed in [&b"{not json"[..], b"", b"[]"] {
            assert!(
                matches!(
                    ConnectionInput::from_slice(malformed),
                    Err(WyrdError::Validation { .. })
                ),
                "{malformed:?} is a validation refusal"
            );
        }
    }

    /// `PrivateKeyJwt` gets its own stable code, not a generic decode error.
    #[test]
    fn private_key_jwt_is_refused_with_its_own_code() {
        let mut raw = body();
        raw["client_auth"] = serde_json::json!("PrivateKeyJwt");
        assert!(matches!(
            ConnectionInput::from_slice(&bytes(&raw)),
            Err(WyrdError::UnsupportedClientAuth { .. })
        ));
    }

    /// Secret presence must agree with the client-auth method.
    #[test]
    fn secret_presence_follows_the_method() {
        let input = ConnectionInput::from_slice(&bytes(&body())).expect("public client decodes");
        assert_eq!(input.client_auth, HumanClientAuth::Public);

        let mut missing = body();
        missing["client_auth"] = serde_json::json!("SecretPost");
        assert!(matches!(
            ConnectionInput::from_slice(&bytes(&missing)),
            Err(WyrdError::Validation { .. })
        ));

        for secret in ["s3cret", ""] {
            let mut extra = body();
            extra["client_secret"] = serde_json::json!(secret);
            assert!(
                matches!(
                    ConnectionInput::from_slice(&bytes(&extra)),
                    Err(WyrdError::Validation { .. })
                ),
                "Public refuses a supplied secret {secret:?}"
            );
        }

        for method in ["SecretBasic", "SecretPost"] {
            let mut empty = body();
            empty["client_auth"] = serde_json::json!(method);
            empty["client_secret"] = serde_json::json!("");
            assert!(
                matches!(
                    ConnectionInput::from_slice(&bytes(&empty)),
                    Err(WyrdError::Validation { .. })
                ),
                "{method} refuses an empty secret"
            );
            let mut valid = body();
            valid["client_auth"] = serde_json::json!(method);
            valid["client_secret"] = serde_json::json!("s3cret");
            let input =
                ConnectionInput::from_slice(&bytes(&valid)).expect("a nonempty secret decodes");
            assert!(input.client_auth.requires_secret());
        }
    }

    /// A human connection maps exactly `sub` as its subject; any other path,
    /// including email or an empty one, is refused, while email and groups
    /// remain configurable.
    #[test]
    fn human_subject_must_be_exactly_sub() {
        let mut valid = body();
        valid["claim_mapping"] =
            serde_json::json!({ "subject": "sub", "email": "email", "groups": "roles" });
        ConnectionInput::from_slice(&bytes(&valid)).expect("sub with email and groups decodes");

        for subject in ["email", "preferred_username", "sub.id", " sub", ""] {
            let mut other = body();
            other["claim_mapping"] = serde_json::json!({ "subject": subject });
            assert!(
                matches!(
                    ConnectionInput::from_slice(&bytes(&other)),
                    Err(WyrdError::Validation { .. })
                ),
                "subject {subject:?} is refused"
            );
        }
    }

    /// The generated schema never offers `PrivateKeyJwt` and never leaks
    /// secret-bearing field shapes into the view.
    #[test]
    fn schema_does_not_offer_private_key_jwt() {
        let schema = schemars::schema_for!(ConnectionInput);
        let text = serde_json::to_string(&schema).expect("schema serializes");
        assert!(!text.contains("PrivateKeyJwt"));
    }

    /// Workload trusted issuers pass; Human ones are redirected to this API.
    #[test]
    fn human_trusted_issuer_is_refused() {
        assert!(refuse_human_trusted_issuer(IssuerTokenPolicy::Workload).is_ok());
        assert!(matches!(
            refuse_human_trusted_issuer(IssuerTokenPolicy::Human),
            Err(WyrdError::HumanConnectionRequired { .. })
        ));
    }
}