owlauth-types 0.1.1

Public Project Auth and Control API types for OwlAuth
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
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize};
use utoipa::openapi::{
    RefOr,
    schema::{ObjectBuilder, Schema, SchemaType, Type},
    security::{Http, HttpAuthScheme, SecurityScheme},
};
use utoipa::{Modify, OpenApi, ToSchema};

use crate::health::HealthResponse;

fn deserialize_required_nullable<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    Option::<String>::deserialize(deserializer)
}

fn deserialize_active_false<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    let value = bool::deserialize(deserializer)?;
    if value {
        return Err(serde::de::Error::custom("active must be false"));
    }
    Ok(false)
}

fn deserialize_active_true<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    let value = bool::deserialize(deserializer)?;
    if !value {
        return Err(serde::de::Error::custom("active must be true"));
    }
    Ok(true)
}

fn false_schema() -> RefOr<Schema> {
    ObjectBuilder::new()
        .schema_type(SchemaType::Type(Type::Boolean))
        .enum_values(Some([false]))
        .into()
}

fn true_schema() -> RefOr<Schema> {
    ObjectBuilder::new()
        .schema_type(SchemaType::Type(Type::Boolean))
        .enum_values(Some([true]))
        .into()
}

/// Stable Server API error codes. Authentication failures intentionally collapse to one code.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ServerErrorCode {
    InvalidRequest,
    InvalidCredential,
    NotFound,
    Conflict,
    RequestTimeout,
    TemporarilyUnavailable,
    InternalError,
}

/// Complete JSON error envelope for the isolated Server API.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ServerError {
    pub code: ServerErrorCode,
    #[schema(max_length = 256)]
    pub message: String,
    #[schema(max_length = 128)]
    pub request_id: String,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ServerUserStatus {
    Active,
    Disabled,
    Merged,
}

/// Project-owned user read model exposed to one authenticated customer backend.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ServerUser {
    #[schema(max_length = 96)]
    pub user_id: String,
    #[schema(max_length = 96)]
    pub project_id: String,
    pub status: ServerUserStatus,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 128, required = true)]
    pub display_name: Option<String>,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 2048, required = true)]
    pub picture_url: Option<String>,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 320, required = true)]
    pub verified_email: Option<String>,
    #[schema(minimum = 1)]
    pub user_revision: i64,
    #[schema(max_length = 64)]
    pub created_at: String,
    #[schema(max_length = 64)]
    pub updated_at: String,
}

/// One deterministic keyset page ordered by immutable `(created_at, user_id)`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ServerUserList {
    #[schema(max_items = 100)]
    pub items: Vec<ServerUser>,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 64, required = true)]
    pub next_cursor: Option<String>,
}

/// Exact normalized-email lookup body. Email is never carried in a URL.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct LookupServerUserRequest {
    #[schema(min_length = 3, max_length = 320)]
    pub email: String,
}

/// Non-enumerating zero-or-one result inside the already authenticated Project.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct LookupServerUserResponse {
    #[serde(deserialize_with = "deserialize_required_nullable_user")]
    #[schema(required = true)]
    pub user: Option<ServerUser>,
}

fn deserialize_required_nullable_user<'de, D>(
    deserializer: D,
) -> Result<Option<ServerUser>, D::Error>
where
    D: Deserializer<'de>,
{
    Option::<ServerUser>::deserialize(deserializer)
}

/// Existing materialized Application projection; Server never performs an ad hoc reprojection.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ServerApplicationUserProjection {
    #[schema(max_length = 96)]
    pub project_id: String,
    #[schema(max_length = 96)]
    pub application_id: String,
    #[schema(max_length = 96)]
    pub user_id: String,
    #[schema(max_length = 64)]
    pub projection_schema: String,
    #[schema(minimum = 1)]
    pub user_revision: i64,
    #[schema(minimum = 1)]
    pub projection_revision: i64,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 128, required = true)]
    pub display_name: Option<String>,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 2048, required = true)]
    pub picture_url: Option<String>,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 35, required = true)]
    pub locale: Option<String>,
    #[serde(deserialize_with = "deserialize_required_nullable")]
    #[schema(max_length = 320, required = true)]
    pub verified_email: Option<String>,
    #[schema(max_length = 32)]
    pub status: String,
    #[schema(max_length = 64)]
    pub created_at: String,
    #[schema(max_length = 64)]
    pub updated_at: String,
}

/// Bounded online introspection input. The token is write-only and always redacted in `Debug`.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct IntrospectProjectTokenRequest {
    #[schema(min_length = 1, max_length = 16384, write_only)]
    pub token: String,
    #[schema(max_length = 96)]
    pub expected_application_id: Option<String>,
}

impl fmt::Debug for IntrospectProjectTokenRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IntrospectProjectTokenRequest")
            .field("token", &"[REDACTED]")
            .field("expected_application_id", &self.expected_application_id)
            .finish()
    }
}

impl Drop for IntrospectProjectTokenRequest {
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.token);
    }
}

/// Exact inactive introspection response. No denial reason or resource identity is disclosed.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct InactiveProjectToken {
    #[serde(deserialize_with = "deserialize_active_false")]
    #[schema(schema_with = false_schema)]
    pub active: bool,
}

/// Current online authority for one active Project access token.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct ActiveProjectToken {
    #[serde(deserialize_with = "deserialize_active_true")]
    #[schema(schema_with = true_schema)]
    pub active: bool,
    #[schema(max_length = 96)]
    pub project_id: String,
    #[schema(max_length = 96)]
    pub application_id: String,
    #[schema(max_length = 96)]
    pub user_id: String,
    #[schema(max_length = 64)]
    pub session_id: String,
    #[schema(max_length = 32)]
    pub token_type: String,
    #[schema(max_length = 64)]
    pub issued_at: String,
    #[schema(max_length = 64)]
    pub expires_at: String,
    #[schema(minimum = 1)]
    pub user_revision: i64,
    #[schema(minimum = 1)]
    pub session_revision: i64,
    #[schema(minimum = 1)]
    pub application_revision: i64,
    pub projection: ServerApplicationUserProjection,
}

/// Non-enumerating introspection union. Invalid or inactive authority is always the inactive arm.
#[allow(
    clippy::large_enum_variant,
    reason = "the public untagged HTTP union keeps its reviewed schema and avoids boxed wire models"
)]
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
#[serde(untagged)]
pub enum ProjectTokenIntrospectionResponse {
    Active(ActiveProjectToken),
    Inactive(InactiveProjectToken),
}

#[utoipa::path(
    get,
    path = "/v1/projects/{project_id}/users",
    params(
        ("project_id" = String, Path, max_length = 96),
        ("cursor" = Option<String>, Query, max_length = 64),
        ("limit" = Option<usize>, Query, minimum = 1, maximum = 100)
    ),
    responses(
        (status = 200, body = ServerUserList),
        (status = 400, body = ServerError),
        (status = 401, description = "Missing or invalid Project server key", body = ServerError, headers(("WWW-Authenticate" = String, description = "Required Bearer authentication challenge"))),
                (status = 503, body = ServerError)
    ),
    security(("project_server_key" = []))
)]
#[doc(hidden)]
pub fn list_project_users() {}

#[utoipa::path(
    post,
    path = "/v1/projects/{project_id}/users/lookup",
    params(("project_id" = String, Path, max_length = 96)),
    request_body = LookupServerUserRequest,
    responses(
        (status = 200, body = LookupServerUserResponse),
        (status = 400, body = ServerError),
        (status = 401, description = "Missing or invalid Project server key", body = ServerError, headers(("WWW-Authenticate" = String, description = "Required Bearer authentication challenge"))),
                (status = 503, body = ServerError)
    ),
    security(("project_server_key" = []))
)]
#[doc(hidden)]
pub fn lookup_project_user() {}

#[utoipa::path(
    get,
    path = "/v1/projects/{project_id}/users/{user_id}",
    params(
        ("project_id" = String, Path, max_length = 96),
        ("user_id" = String, Path, max_length = 96)
    ),
    responses(
        (status = 200, body = ServerUser),
        (status = 400, body = ServerError),
        (status = 401, description = "Missing or invalid Project server key", body = ServerError, headers(("WWW-Authenticate" = String, description = "Required Bearer authentication challenge"))),
        (status = 404, body = ServerError),
                (status = 503, body = ServerError)
    ),
    security(("project_server_key" = []))
)]
#[doc(hidden)]
pub fn get_project_user() {}

#[utoipa::path(
    get,
    path = "/v1/projects/{project_id}/applications/{application_id}/users/{user_id}",
    params(
        ("project_id" = String, Path, max_length = 96),
        ("application_id" = String, Path, max_length = 96),
        ("user_id" = String, Path, max_length = 96)
    ),
    responses(
        (status = 200, body = ServerApplicationUserProjection),
        (status = 400, body = ServerError),
        (status = 401, description = "Missing or invalid Project server key", body = ServerError, headers(("WWW-Authenticate" = String, description = "Required Bearer authentication challenge"))),
        (status = 404, body = ServerError),
        (status = 409, body = ServerError),
                (status = 503, body = ServerError)
    ),
    security(("project_server_key" = []))
)]
#[doc(hidden)]
pub fn get_application_user_projection() {}

#[utoipa::path(
    post,
    path = "/v1/projects/{project_id}/tokens/introspect",
    params(("project_id" = String, Path, max_length = 96)),
    request_body = IntrospectProjectTokenRequest,
    responses(
        (status = 200, body = ProjectTokenIntrospectionResponse),
        (status = 400, body = ServerError),
        (status = 401, description = "Missing or invalid Project server key", body = ServerError, headers(("WWW-Authenticate" = String, description = "Required Bearer authentication challenge"))),
                (status = 503, body = ServerError)
    ),
    security(("project_server_key" = []))
)]
#[doc(hidden)]
pub fn introspect_project_token() {}

#[derive(OpenApi)]
#[openapi(
    info(
        title = "OwlAuth Server API",
        description = "Project-scoped customer backend Server API"
    ),
    paths(
        crate::health::get_liveness,
        crate::health::get_readiness,
        list_project_users,
        lookup_project_user,
        get_project_user,
        get_application_user_projection,
        introspect_project_token
    ),
    components(schemas(
        HealthResponse,
        ServerErrorCode,
        ServerError,
        ServerUserStatus,
        ServerUser,
        ServerUserList,
        LookupServerUserRequest,
        LookupServerUserResponse,
        ServerApplicationUserProjection,
        IntrospectProjectTokenRequest,
        InactiveProjectToken,
        ActiveProjectToken,
        ProjectTokenIntrospectionResponse
    )),
    modifiers(&ServerSecurity)
)]
struct ServerApiDoc;

struct ServerSecurity;

impl Modify for ServerSecurity {
    fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
        openapi
            .components
            .get_or_insert_default()
            .add_security_scheme(
                "project_server_key",
                SecurityScheme::Http(Http::new(HttpAuthScheme::Bearer)),
            );
    }
}

/// Generates the complete Server-plane `OpenAPI` document.
#[must_use]
pub fn openapi() -> utoipa::openapi::OpenApi {
    let mut document = ServerApiDoc::openapi();
    crate::add_response_to_operations(&mut document, "408", |_| {
        crate::json_error_response(
            "The request exceeded the Server listener time budget",
            "ServerError",
            "application/json",
        )
    });
    document
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn secret_bearing_request_debug_is_redacted() {
        let request = IntrospectProjectTokenRequest {
            token: "secret-access-token".to_owned(),
            expected_application_id: Some("app_1".to_owned()),
        };
        let debug = format!("{request:?}");
        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains("secret-access-token"));
    }

    #[test]
    fn request_and_response_models_reject_unknown_fields() {
        assert!(
            serde_json::from_value::<LookupServerUserRequest>(serde_json::json!({
                "email": "person@example.com",
                "prefix": true
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<InactiveProjectToken>(serde_json::json!({
                "active": false,
                "reason": "revoked"
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<InactiveProjectToken>(serde_json::json!({"active": true}))
                .is_err()
        );
        let mut active = serde_json::json!({
            "active": false,
            "project_id": "project",
            "application_id": "application",
            "user_id": "user",
            "session_id": "00000000-0000-0000-0000-000000000001",
            "token_type": "Bearer",
            "issued_at": "2026-01-01T00:00:00Z",
            "expires_at": "2026-01-01T01:00:00Z",
            "user_revision": 1,
            "session_revision": 1,
            "application_revision": 1,
            "projection": {
                "project_id": "project",
                "application_id": "application",
                "user_id": "user",
                "projection_schema": "owlauth.user.v1",
                "user_revision": 1,
                "projection_revision": 1,
                "display_name": null,
                "picture_url": null,
                "locale": null,
                "verified_email": null,
                "status": "active",
                "created_at": "2026-01-01T00:00:00Z",
                "updated_at": "2026-01-01T00:00:00Z"
            }
        });
        assert!(serde_json::from_value::<ActiveProjectToken>(active.clone()).is_err());
        active["active"] = serde_json::json!(true);
        assert!(serde_json::from_value::<ActiveProjectToken>(active).is_ok());
    }
}