uptrakit-web-api-types 0.0.4

Shared HTTP request/response types for the Uptrakit web API
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
//! HTTP response types for OAuth AS endpoints plus the Dynamic Client
//! Registration (RFC 7591) request envelope.
//!
//! `TokenResponse` is the JSON body returned by `POST /oauth/token`.
//! `DcrRegistrationRequest`/`Response` are the RFC 7591 register endpoint
//! envelopes; the request is `Validate`d per the project rule.

use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use uuid::Uuid;

use crate::oauth::grant_type::{OAuthGrantType, ResponseType, TokenEndpointAuthMethod};
use crate::validation::{Validate, ValidationError};

/// Successful token endpoint response (RFC 6749 §5.1).
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenResponse {
    pub access_token: String,
    pub token_type: String,
    pub expires_in: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh_expires_in: Option<i64>,
    pub scope: String,
}

impl TokenResponse {
    /// Construct a new token response.
    ///
    /// Required because `#[non_exhaustive]` prevents struct-literal construction
    /// outside the defining crate.
    #[must_use]
    pub fn new(
        access_token: String,
        token_type: String,
        expires_in: i64,
        refresh_token: Option<String>,
        refresh_expires_in: Option<i64>,
        scope: String,
    ) -> Self {
        Self {
            access_token,
            token_type,
            expires_in,
            refresh_token,
            refresh_expires_in,
            scope,
        }
    }
}

/// Dynamic client registration request body (RFC 7591 §2).
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct DcrRegistrationRequest {
    pub client_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_uri: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo_uri: Option<String>,
    pub redirect_uris: Vec<String>,
    pub grant_types: Vec<String>,
    pub response_types: Vec<String>,
    pub token_endpoint_auth_method: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
}

impl DcrRegistrationRequest {
    /// Construct a new registration request.
    #[expect(
        clippy::too_many_arguments,
        reason = "RFC 7591 §2 mandates all these fields; a builder would not reduce the footprint"
    )]
    #[must_use]
    pub fn new(
        client_name: impl Into<String>,
        client_uri: Option<String>,
        logo_uri: Option<String>,
        redirect_uris: Vec<String>,
        grant_types: Vec<String>,
        response_types: Vec<String>,
        token_endpoint_auth_method: impl Into<String>,
        scope: Option<String>,
    ) -> Self {
        Self {
            client_name: client_name.into(),
            client_uri,
            logo_uri,
            redirect_uris,
            grant_types,
            response_types,
            token_endpoint_auth_method: token_endpoint_auth_method.into(),
            scope,
        }
    }
}

const ALLOWED_GRANT_TYPES: &[&str] = &[
    OAuthGrantType::AuthorizationCode.as_str(),
    OAuthGrantType::RefreshToken.as_str(),
];
const ALLOWED_RESPONSE_TYPES: &[&str] = &[ResponseType::Code.as_str()];
const ALLOWED_TOKEN_ENDPOINT_AUTH_METHODS: &[&str] = &[
    TokenEndpointAuthMethod::None.as_str(),
    TokenEndpointAuthMethod::ClientSecretBasic.as_str(),
];

impl Validate for DcrRegistrationRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.redirect_uris.is_empty() {
            return Err(ValidationError {
                field: "redirect_uris",
                message: "at least one redirect_uri is required".to_string(),
            });
        }
        for gt in &self.grant_types {
            if !ALLOWED_GRANT_TYPES.contains(&gt.as_str()) {
                return Err(ValidationError {
                    field: "grant_types",
                    message: format!("unsupported grant_type: {gt}"),
                });
            }
        }
        for rt in &self.response_types {
            if !ALLOWED_RESPONSE_TYPES.contains(&rt.as_str()) {
                return Err(ValidationError {
                    field: "response_types",
                    message: format!("unsupported response_type: {rt}"),
                });
            }
        }
        if !ALLOWED_TOKEN_ENDPOINT_AUTH_METHODS.contains(&self.token_endpoint_auth_method.as_str())
        {
            return Err(ValidationError {
                field: "token_endpoint_auth_method",
                message: format!(
                    "unsupported token_endpoint_auth_method: {}",
                    self.token_endpoint_auth_method
                ),
            });
        }
        Ok(())
    }
}

/// Dynamic client registration response body (RFC 7591 §3.2.1).
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct DcrRegistrationResponse {
    pub client_id: String,
    pub client_id_issued_at: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registration_access_token: Option<String>,
    pub registration_client_uri: String,
    pub client_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_uri: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo_uri: Option<String>,
    pub redirect_uris: Vec<String>,
    pub grant_types: Vec<String>,
    pub response_types: Vec<String>,
    pub token_endpoint_auth_method: String,
    pub scope: String,
}

impl DcrRegistrationResponse {
    /// Construct a new registration response.
    #[expect(
        clippy::too_many_arguments,
        reason = "RFC 7591 §3.2.1 mandates all these fields; a builder would not reduce the footprint"
    )]
    #[must_use]
    pub fn new(
        client_id: String,
        client_id_issued_at: i64,
        registration_access_token: Option<String>,
        registration_client_uri: String,
        client_name: String,
        client_uri: Option<String>,
        logo_uri: Option<String>,
        redirect_uris: Vec<String>,
        grant_types: Vec<String>,
        response_types: Vec<String>,
        token_endpoint_auth_method: String,
        scope: String,
    ) -> Self {
        Self {
            client_id,
            client_id_issued_at,
            registration_access_token,
            registration_client_uri,
            client_name,
            client_uri,
            logo_uri,
            redirect_uris,
            grant_types,
            response_types,
            token_endpoint_auth_method,
            scope,
        }
    }
}

/// Operator-facing OAuth client row (`GET /api/oauth/clients` items).
///
/// `last_used_at` is intentionally absent: `oauth_clients.last_used_at` is
/// never written by any production path; the field re-enters this contract
/// once a token-issuance write site exists.
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OAuthClientResponse {
    pub id: String,
    pub client_name: String,
    pub client_uri: Option<String>,
    pub redirect_uris: Vec<String>,
    pub created_via: String,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, format = DateTime)
    )]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = Option<String>, format = DateTime)
    )]
    pub revoked_at: Option<OffsetDateTime>,
    #[serde(with = "time::serde::rfc3339::option")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = Option<String>, format = DateTime)
    )]
    pub trusted_at: Option<OffsetDateTime>,
}

impl OAuthClientResponse {
    /// Construct a new client response row.
    ///
    /// Required because `#[non_exhaustive]` prevents struct-literal
    /// construction outside the defining crate.
    #[expect(
        clippy::too_many_arguments,
        reason = "flat response row; a builder would not reduce the footprint"
    )]
    #[must_use]
    pub fn new(
        id: String,
        client_name: String,
        client_uri: Option<String>,
        redirect_uris: Vec<String>,
        created_via: String,
        created_at: OffsetDateTime,
        revoked_at: Option<OffsetDateTime>,
        trusted_at: Option<OffsetDateTime>,
    ) -> Self {
        Self {
            id,
            client_name,
            client_uri,
            redirect_uris,
            created_via,
            created_at,
            revoked_at,
            trusted_at,
        }
    }
}

/// End-user consent row (`GET /api/oauth/consents` items).
///
/// `client_name` is non-optional: `fk_oauth_consents_client` is
/// `ON DELETE RESTRICT` and client revocation is a soft delete, so a
/// consent's client row always exists.
#[non_exhaustive]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct OAuthConsentResponse {
    pub id: Uuid,
    pub client_id: String,
    pub client_name: String,
    pub scopes: String,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, format = DateTime)
    )]
    pub granted_at: OffsetDateTime,
}

impl OAuthConsentResponse {
    /// Construct a new consent response row.
    ///
    /// Required because `#[non_exhaustive]` prevents struct-literal
    /// construction outside the defining crate.
    #[must_use]
    pub fn new(
        id: Uuid,
        client_id: String,
        client_name: String,
        scopes: String,
        granted_at: OffsetDateTime,
    ) -> Self {
        Self {
            id,
            client_id,
            client_name,
            scopes,
            granted_at,
        }
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::assertions_on_result_states,
        reason = "test assertions — is_ok/is_err provides readable failure messages"
    )]
    use super::*;

    #[test]
    fn dcr_request_rejects_empty_redirect_uris() {
        let req = DcrRegistrationRequest {
            client_name: "test".into(),
            client_uri: None,
            logo_uri: None,
            redirect_uris: vec![],
            grant_types: vec!["authorization_code".into()],
            response_types: vec!["code".into()],
            token_endpoint_auth_method: "none".into(),
            scope: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn dcr_request_rejects_unknown_grant_type() {
        let req = DcrRegistrationRequest {
            client_name: "test".into(),
            client_uri: None,
            logo_uri: None,
            redirect_uris: vec!["https://x/cb".into()],
            grant_types: vec!["password".into()],
            response_types: vec!["code".into()],
            token_endpoint_auth_method: "none".into(),
            scope: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn dcr_request_rejects_unknown_response_type() {
        let req = DcrRegistrationRequest {
            client_name: "test".into(),
            client_uri: None,
            logo_uri: None,
            redirect_uris: vec!["https://x/cb".into()],
            grant_types: vec!["authorization_code".into()],
            response_types: vec!["token".into()],
            token_endpoint_auth_method: "none".into(),
            scope: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn dcr_request_rejects_unknown_token_endpoint_auth_method() {
        let req = DcrRegistrationRequest {
            client_name: "test".into(),
            client_uri: None,
            logo_uri: None,
            redirect_uris: vec!["https://x/cb".into()],
            grant_types: vec!["authorization_code".into()],
            response_types: vec!["code".into()],
            token_endpoint_auth_method: "private_key_jwt".into(),
            scope: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn dcr_valid_request_passes() {
        let req = DcrRegistrationRequest {
            client_name: "test".into(),
            client_uri: None,
            logo_uri: None,
            redirect_uris: vec!["https://x/cb".into()],
            grant_types: vec!["authorization_code".into(), "refresh_token".into()],
            response_types: vec!["code".into()],
            token_endpoint_auth_method: "none".into(),
            scope: None,
        };
        assert!(req.validate().is_ok());
    }
}