wyrd-spec 0.4.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
//! OAuth 2.0 authorization-server wire contracts.
//!
//! `POST /auth/token` takes `application/x-www-form-urlencoded` parameters
//! (RFC 6749 §6; RFC 8628 §3.4; RFC 8693 §2.1; RFC 7523 §2.1) and
//! answers the RFC 6749 §5.1 [`TokenResponse`] or the §5.2
//! [`OAuthErrorResponse`]. Unrecognized parameters are ignored (RFC 6749
//! §3.2). The client is identified by HTTP Basic authentication or the
//! `client_id` parameter, never by a [`TokenRequest`] field.

use serde::{Deserialize, Serialize};

use crate::auth::{AbsoluteUrl, SecretBearer};
use crate::ids::{CardUid, TenantSlug};

/// Parameters of `POST /auth/token`, discriminated by `grant_type`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "grant_type")]
pub enum TokenRequest {
    /// RFC 6749 §6: renew a human session.
    #[serde(rename = "refresh_token")]
    RefreshToken {
        /// The Wyrd refresh token.
        refresh_token: SecretBearer,
    },
    /// RFC 8628 §3.4: poll with the device code from
    /// `POST /auth/device_authorization`.
    #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
    DeviceCode {
        /// The device code.
        device_code: SecretBearer,
    },
    /// RFC 8693 §2.1 token exchange.
    ///
    /// With an [`ExchangeTokenType::ApiKey`] subject and no actor, the Wyrd
    /// API key is exchanged for an access token of its own principal. With an
    /// [`ExchangeTokenType::AccessToken`] subject and actor, the actor acts on
    /// behalf of the subject: the issued token names the subject as its
    /// principal, the actor as its outermost `act`, and `audience` as its
    /// `aud`, with the intersection of both parties' permissions.
    #[serde(rename = "urn:ietf:params:oauth:grant-type:token-exchange")]
    TokenExchange {
        /// The API key, or the access token of the party acted for.
        subject_token: SecretBearer,
        /// Type of `subject_token`.
        subject_token_type: ExchangeTokenType,
        /// Access token of the party doing the work; delegation only.
        actor_token: Option<SecretBearer>,
        /// Type of `actor_token`.
        actor_token_type: Option<ExchangeTokenType>,
        /// Wyrd resource a delegated token is issued for; delegation only.
        audience: Option<TokenAudience>,
        /// Exact Service root selecting the API key owner's workload
        /// context; API-key subject only. It selects context, never another
        /// principal or tenant.
        workload_uid: Option<CardUid>,
    },
    /// RFC 7523 §2.1: a platform-attested workload assertion.
    #[serde(rename = "urn:ietf:params:oauth:grant-type:jwt-bearer")]
    JwtBearer {
        /// Kubernetes service-account token, SPIFFE JWT-SVID, or cloud token.
        assertion: SecretBearer,
        /// Tenant selector fallback when the request host does not carry tenant.
        tenant: Option<TenantSlug>,
        /// Exact root selecting workload context; overrides the mapping's
        /// configured default and stays within the mapped account's
        /// restriction.
        workload_uid: Option<CardUid>,
    },
}

/// RFC 8693 §3 token type of a subject, actor, or issued token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub enum ExchangeTokenType {
    /// OAuth access token.
    #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
    AccessToken,
    /// A Wyrd API key (`wyrd_sk_…`) or platform credential.
    #[serde(rename = "urn:wyrd:oauth:token-type:api_key")]
    ApiKey,
}

/// Audience (`aud`) of a Wyrd tenant access token.
///
/// Every directly issued token is [`Self::Wyrd`] and is accepted on every
/// tenant surface. A [`Self::Bifrost`] token is accepted only on the Bifrost
/// surfaces, so a token delegated for Bifrost cannot be replayed elsewhere.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum TokenAudience {
    /// Every Wyrd tenant surface.
    Wyrd,
    /// Only the Bifrost ingest and query surfaces.
    Bifrost,
}

impl TokenAudience {
    /// The canonical `aud` claim value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Wyrd => "wyrd",
            Self::Bifrost => "bifrost",
        }
    }
}

/// RFC 6749 §5.1 successful token response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct TokenResponse {
    /// Signed Wyrd access token.
    pub access_token: SecretBearer,
    /// Token type.
    pub token_type: TokenType,
    /// Seconds until the access token expires.
    pub expires_in: u64,
    /// Refresh token. Issued only for a `wyrd-cli` human session: at
    /// device-code redemption and whenever it rotates. No machine grant
    /// issues one: those clients re-present their durable credential instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<SecretBearer>,
    /// RFC 8693 §2.2.1 type of the issued token; present on token-exchange
    /// responses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issued_token_type: Option<ExchangeTokenType>,
}

/// Bearer token marker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "PascalCase")]
pub enum TokenType {
    /// Bearer token.
    Bearer,
}

/// The registered OAuth clients of a Wyrd deployment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub enum OAuthClientId {
    /// The CLI and SDK saved logins: a public client.
    #[serde(rename = "wyrd-cli")]
    WyrdCli,
}

impl OAuthClientId {
    /// The `client_id` value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::WyrdCli => "wyrd-cli",
        }
    }

    /// The client a `client_id` value names, if any.
    #[must_use]
    pub fn parse(client_id: &str) -> Option<Self> {
        match client_id {
            "wyrd-cli" => Some(Self::WyrdCli),
            _ => None,
        }
    }
}

/// An OAuth error code: RFC 6749 §4.1.2.1 and §5.2, RFC 8628 §3.5, and
/// RFC 8693 §2.2.2.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OAuthErrorCode {
    /// A required parameter is missing, invalid, or repeated.
    InvalidRequest,
    /// Client authentication failed.
    InvalidClient,
    /// The grant or refresh token is invalid, expired, revoked, or was
    /// issued to another client or redirect URI.
    InvalidGrant,
    /// The client may not use this grant or endpoint.
    UnauthorizedClient,
    /// The grant type is not supported.
    UnsupportedGrantType,
    /// The response type is not supported.
    UnsupportedResponseType,
    /// RFC 8693 §2.2.2: the server cannot issue a token for the requested
    /// `audience`.
    InvalidTarget,
    /// The resource owner or the server denied the request.
    AccessDenied,
    /// The device authorization is still pending.
    AuthorizationPending,
    /// The device code was polled too often.
    SlowDown,
    /// The device code expired.
    ExpiredToken,
    /// The server failed.
    ServerError,
    /// The server is temporarily unavailable.
    TemporarilyUnavailable,
}

/// RFC 6749 §5.2 error response body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct OAuthErrorResponse {
    /// The error code.
    pub error: OAuthErrorCode,
    /// Human-readable detail.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_description: Option<String>,
    /// Stable Wyrd error code of a catalog refusal, an extension member
    /// (RFC 6749 §8.2) so clients project the same typed error the problem
    /// surface reports. Absent for a refusal of the OAuth wire itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
}

/// RFC 8414 §2 authorization server metadata, served at
/// `/.well-known/oauth-authorization-server`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct AuthorizationServerMetadata {
    /// The deployment's public origin.
    pub issuer: AbsoluteUrl,
    /// `POST /auth/token`.
    pub token_endpoint: AbsoluteUrl,
    /// RFC 8628 §4: `POST /auth/device_authorization`.
    pub device_authorization_endpoint: AbsoluteUrl,
    /// RFC 7009: `POST /auth/revoke`.
    pub revocation_endpoint: AbsoluteUrl,
    /// Empty: no grant uses an authorization endpoint, so none is published
    /// (RFC 8414 §2).
    pub response_types_supported: Vec<String>,
    /// Every grant `POST /auth/token` accepts.
    pub grant_types_supported: Vec<String>,
    /// `["none"]`: `wyrd-cli` is a public client.
    pub token_endpoint_auth_methods_supported: Vec<String>,
    /// The same methods at the revocation endpoint.
    pub revocation_endpoint_auth_methods_supported: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::{
        ExchangeTokenType, OAuthClientId, OAuthErrorCode, OAuthErrorResponse, TokenAudience,
        TokenRequest, TokenResponse, TokenType,
    };
    use crate::auth::SecretBearer;
    use crate::ids::CardUid;

    /// Decode form-shaped parameters, as the token endpoint does.
    ///
    /// # Errors
    /// Returns the decode error when the parameters name no supported grant
    /// or omit one of its required parameters.
    fn parse(pairs: &[(&str, &str)]) -> Result<TokenRequest, serde_json::Error> {
        let map = pairs
            .iter()
            .map(|(key, value)| ((*key).to_owned(), serde_json::json!(value)))
            .collect::<serde_json::Map<_, _>>();
        serde_json::from_value(serde_json::Value::Object(map))
    }

    /// Every grant decodes from its RFC parameters and ignores parameters it
    /// does not define (RFC 6749 §3.2); an unknown grant type does not decode.
    ///
    /// # Panics
    /// Panics when a grant decodes differently.
    #[test]
    fn grants_decode_from_rfc_parameters() {
        assert_eq!(
            parse(&[
                (
                    "grant_type",
                    "urn:ietf:params:oauth:grant-type:token-exchange"
                ),
                ("subject_token", "wyrd_sk_key"),
                ("subject_token_type", "urn:wyrd:oauth:token-type:api_key"),
            ])
            .expect("api-key exchange decodes"),
            TokenRequest::TokenExchange {
                subject_token: SecretBearer::new("wyrd_sk_key".to_owned()),
                subject_token_type: ExchangeTokenType::ApiKey,
                actor_token: None,
                actor_token_type: None,
                audience: None,
                workload_uid: None,
            }
        );
        let root = "019a7c00-0000-7000-8000-000000000001";
        assert_eq!(
            parse(&[
                (
                    "grant_type",
                    "urn:ietf:params:oauth:grant-type:token-exchange"
                ),
                ("subject_token", "wyrd_sk_key"),
                ("subject_token_type", "urn:wyrd:oauth:token-type:api_key"),
                ("workload_uid", root),
            ])
            .expect("api-key exchange with a root decodes"),
            TokenRequest::TokenExchange {
                subject_token: SecretBearer::new("wyrd_sk_key".to_owned()),
                subject_token_type: ExchangeTokenType::ApiKey,
                actor_token: None,
                actor_token_type: None,
                audience: None,
                workload_uid: Some(CardUid::new(root).expect("static v7 uid")),
            }
        );
        assert!(
            parse(&[
                ("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
                ("assertion", "a"),
                ("workload_uid", "not-a-uid"),
            ])
            .is_err(),
            "a malformed root is refused, not ignored"
        );
        assert_eq!(
            parse(&[
                ("grant_type", "refresh_token"),
                ("refresh_token", "r"),
                ("scope", "ignored"),
            ])
            .expect("refresh decodes"),
            TokenRequest::RefreshToken {
                refresh_token: SecretBearer::new("r".to_owned()),
            }
        );
        assert!(parse(&[("grant_type", "password"), ("username", "u")]).is_err());
        assert!(
            parse(&[
                ("grant_type", "authorization_code"),
                ("code", "c"),
                ("redirect_uri", "https://wyrd.example.com/login/callback"),
                ("code_verifier", "v"),
            ])
            .is_err(),
            "the retired browser code grant does not decode"
        );
        assert!(parse(&[("grant_type", "wyrd_api_key"), ("api_key", "k")]).is_err());
    }

    /// The success body carries `expires_in` and omits absent optional
    /// members; the error body carries the snake-case RFC code.
    ///
    /// # Panics
    /// Panics when a body serializes differently.
    #[test]
    fn response_bodies_follow_rfc_6749_section_5() {
        let response = TokenResponse {
            access_token: SecretBearer::new("access".to_owned()),
            token_type: TokenType::Bearer,
            expires_in: 300,
            refresh_token: None,
            issued_token_type: Some(ExchangeTokenType::AccessToken),
        };
        assert_eq!(
            serde_json::to_value(&response).expect("serializes"),
            serde_json::json!({
                "access_token": "access",
                "token_type": "Bearer",
                "expires_in": 300,
                "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
            })
        );
        let error = OAuthErrorResponse {
            error: OAuthErrorCode::AuthorizationPending,
            error_description: None,
            code: None,
        };
        assert_eq!(
            serde_json::to_value(&error).expect("serializes"),
            serde_json::json!({ "error": "authorization_pending" })
        );
        assert_eq!(
            serde_json::to_value(OAuthErrorCode::InvalidTarget).expect("serializes"),
            "invalid_target"
        );
        assert_eq!(
            OAuthClientId::parse("wyrd-cli"),
            Some(OAuthClientId::WyrdCli)
        );
        assert_eq!(OAuthClientId::WyrdCli.as_str(), "wyrd-cli");
        assert_eq!(OAuthClientId::parse("wyrd-ui"), None);
        assert_eq!(OAuthClientId::parse("other"), None);
    }

    /// Secret-bearing parameters never reach `Debug`.
    ///
    /// # Panics
    /// Panics when the assertion is printed.
    #[test]
    fn secret_grants_redact_debug() {
        let request = TokenRequest::JwtBearer {
            assertion: SecretBearer::new("top-secret-assertion".to_owned()),
            tenant: None,
            workload_uid: None,
        };

        let debug = format!("{request:?}");

        assert!(debug.contains("REDACTED"));
        assert!(!debug.contains("top-secret-assertion"));
    }

    /// The audience wire values are the `aud` claim values.
    ///
    /// # Panics
    /// Panics when they differ.
    #[test]
    fn audience_wire_values_are_claim_values() {
        for audience in [TokenAudience::Wyrd, TokenAudience::Bifrost] {
            assert_eq!(
                serde_json::to_value(audience).expect("serializes"),
                audience.as_str()
            );
        }
    }
}