gize-openapi 0.9.8

OpenAPI spec generation for Gize (Beta phase; see ADR-010).
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
//! OpenAPI spec generation for Gize (ADR-010).
//!
//! The spec is generated from the **manifest** (`gize.toml`) — the same source of truth the
//! CRUD, auth and admin generators use — so it matches the generated routes *by construction*
//! rather than by hand-kept annotations. Output is an OpenAPI 3.0.3 document as
//! `serde_json::Value`; the CLI writes it to `openapi.json` and the app serves it.

use anyhow::Result;
use gize_core::naming::table_name;
use gize_core::{Api, FieldType, Manifest, ModelSpec};
use serde_json::{Value, json};

/// The set of `(method, path)` operations Gize generates for a module. Used both to build the
/// spec and by the parity test that checks the spec against the router.
pub fn operations(manifest: &Manifest) -> Result<Vec<(String, String)>> {
    // A versioned project (ADR-016) serves every route under `/api/v1`, so the spec's paths
    // carry the same prefix and stay aligned with the router by construction.
    let prefix = api_prefix(manifest);
    let mut ops = Vec::new();
    for module in &manifest.modules {
        let table = &module.name;
        ops.push(("get".into(), format!("{prefix}/{table}")));
        ops.push(("post".into(), format!("{prefix}/{table}")));
        ops.push(("get".into(), format!("{prefix}/{table}/{{id}}")));
        ops.push(("put".into(), format!("{prefix}/{table}/{{id}}")));
        ops.push(("delete".into(), format!("{prefix}/{table}/{{id}}")));
        if table == "users" {
            ops.push(("post".into(), format!("{prefix}/users/register")));
            ops.push(("post".into(), format!("{prefix}/users/login")));
            ops.push(("get".into(), format!("{prefix}/users/me")));
        }
    }
    Ok(ops)
}

/// The API route prefix a versioned project mounts under (e.g. `/api/v1`), or empty when the
/// project is unversioned (ADR-016).
fn api_prefix(manifest: &Manifest) -> String {
    manifest
        .api
        .as_ref()
        .map(Api::mount_path)
        .unwrap_or_default()
}

/// Render the full OpenAPI document for a project from its manifest.
pub fn spec_json(manifest: &Manifest) -> Result<Value> {
    let prefix = api_prefix(manifest);
    let mut paths = serde_json::Map::new();
    let mut schemas = serde_json::Map::new();

    for module in &manifest.modules {
        let model = module.model_spec()?;
        let table = table_name(&model.name);
        let name = &model.name;

        // Component schemas: the response model plus the Create/Update request bodies.
        // `users` hides `password` in responses (it holds a hash; see the generated model).
        let hidden: &[&str] = if table == "users" { &["password"] } else { &[] };
        schemas.insert(name.clone(), model_response_schema(&model, hidden));
        schemas.insert(format!("{name}Page"), page_schema(name));
        schemas.insert(format!("Create{name}"), dto_schema(&model));
        schemas.insert(format!("Update{name}"), dto_schema(&model));

        // The `users` resource is admin-gated end to end, including reads (ADR-021).
        let guard_reads = table == "users";
        paths.insert(
            format!("{prefix}/{table}"),
            collection_path(&table, name, guard_reads),
        );
        paths.insert(
            format!("{prefix}/{table}/{{id}}"),
            item_path(&table, name, guard_reads),
        );

        if table == "users" {
            schemas.insert("LoginRequest".into(), login_request_schema());
            schemas.insert("TokenResponse".into(), token_response_schema());
            paths.insert(format!("{prefix}/users/register"), register_path());
            paths.insert(format!("{prefix}/users/login"), login_path());
            paths.insert(format!("{prefix}/users/me"), me_path());
        }
    }

    Ok(json!({
        "openapi": "3.0.3",
        "info": {
            "title": format!("{} API", manifest.project.name),
            "version": "0.1.0",
            "description": "Generated by Gize (see ADR-010)."
        },
        "components": {
            "securitySchemes": {
                "bearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" }
            },
            "schemas": Value::Object(schemas)
        },
        "paths": Value::Object(paths)
    }))
}

/// The OpenAPI schema fragment for a scalar field type.
fn field_schema(ty: FieldType) -> Value {
    match ty {
        FieldType::String => json!({ "type": "string" }),
        FieldType::Bool => json!({ "type": "boolean" }),
        FieldType::I32 => json!({ "type": "integer", "format": "int32" }),
        FieldType::I64 => json!({ "type": "integer", "format": "int64" }),
        FieldType::F64 => json!({ "type": "number", "format": "double" }),
        FieldType::Uuid => json!({ "type": "string", "format": "uuid" }),
        FieldType::DateTime => json!({ "type": "string", "format": "date-time" }),
    }
}

/// The response schema for a model: `id`, its (visible) fields, and timestamps.
fn model_response_schema(model: &ModelSpec, hidden: &[&str]) -> Value {
    let mut props = serde_json::Map::new();
    props.insert("id".into(), field_schema(FieldType::Uuid));
    for f in &model.fields {
        if hidden.contains(&f.name.as_str()) {
            continue;
        }
        props.insert(f.name.clone(), field_schema(f.ty));
    }
    props.insert("created_at".into(), field_schema(FieldType::DateTime));
    props.insert("updated_at".into(), field_schema(FieldType::DateTime));
    json!({ "type": "object", "properties": Value::Object(props) })
}

/// The request-body schema for a Create/Update DTO: every declared field, all required.
fn dto_schema(model: &ModelSpec) -> Value {
    let mut props = serde_json::Map::new();
    let mut required = Vec::new();
    for f in &model.fields {
        props.insert(f.name.clone(), field_schema(f.ty));
        required.push(Value::String(f.name.clone()));
    }
    json!({ "type": "object", "properties": Value::Object(props), "required": required })
}

fn login_request_schema() -> Value {
    json!({
        "type": "object",
        "properties": { "email": { "type": "string", "format": "email" }, "password": { "type": "string" } },
        "required": ["email", "password"]
    })
}

fn token_response_schema() -> Value {
    json!({ "type": "object", "properties": { "token": { "type": "string" } }, "required": ["token"] })
}

/// The page envelope a list route returns (ADR-022).
fn page_schema(name: &str) -> Value {
    json!({
        "type": "object",
        "required": ["items", "page", "per_page", "total"],
        "properties": {
            "items": { "type": "array", "items": schema_ref(name) },
            "page": { "type": "integer", "format": "int32", "minimum": 1 },
            "per_page": { "type": "integer", "format": "int32", "minimum": 1, "maximum": 100 },
            "total": { "type": "integer", "format": "int64", "minimum": 0 }
        }
    })
}

/// The `page` / `per_page` query parameters of a list route (ADR-022).
fn page_params() -> Value {
    json!([
        {
            "name": "page", "in": "query", "required": false,
            "description": "1-based page number.",
            "schema": { "type": "integer", "format": "int32", "minimum": 1, "default": 1 }
        },
        {
            "name": "per_page", "in": "query", "required": false,
            "description": "Items per page.",
            "schema": {
                "type": "integer", "format": "int32", "minimum": 1, "maximum": 100, "default": 25
            }
        }
    ])
}

fn schema_ref(name: &str) -> Value {
    json!({ "$ref": format!("#/components/schemas/{name}") })
}

fn json_content(schema: Value) -> Value {
    json!({ "content": { "application/json": { "schema": schema } } })
}

/// Add a response to an operation's `responses` map (no-op if the shape is unexpected).
fn add_response(op: &mut Value, code: &str, description: &str) {
    if let Some(responses) = op.get_mut("responses").and_then(|r| r.as_object_mut()) {
        responses.insert(code.to_string(), json!({ "description": description }));
    }
}

/// Mark an otherwise-public read operation as admin-gated: require a bearer token and document
/// the 401/403 responses. Used for the `users` resource (ADR-021).
fn guard_read(op: &mut Value) {
    op["security"] = json!([{ "bearerAuth": [] }]);
    add_response(op, "401", "unauthorized");
    add_response(op, "403", "forbidden");
}

/// `/<table>` — list and create. Reads are public unless `guard_reads` (the `users` resource,
/// ADR-021), where the list is admin-gated and every write also documents 403.
fn collection_path(table: &str, name: &str, guard_reads: bool) -> Value {
    let mut get_op = json!({
        "tags": [table],
        "summary": format!("List {table}"),
        "parameters": page_params(),
        "responses": {
            "200": json_content(schema_ref(&format!("{name}Page"))),
            "422": { "description": "invalid page or per_page" }
        }
    });
    let mut post_op = json!({
        "tags": [table],
        "summary": format!("Create a {name}"),
        "security": [{ "bearerAuth": [] }],
        "requestBody": json_content(schema_ref(&format!("Create{name}"))),
        "responses": {
            "201": json_content(schema_ref(name)),
            "401": { "description": "unauthorized" },
            "409": { "description": "conflict" },
            "422": { "description": "validation failed" }
        }
    });
    if guard_reads {
        guard_read(&mut get_op);
        add_response(&mut post_op, "403", "forbidden");
    }
    json!({ "get": get_op, "post": post_op })
}

/// `/<table>/{id}` — show, update and delete. Reads are public unless `guard_reads` (the
/// `users` resource, ADR-021), where show is admin-gated and every write also documents 403.
fn item_path(table: &str, name: &str, guard_reads: bool) -> Value {
    let id_param = json!([{
        "name": "id", "in": "path", "required": true,
        "schema": { "type": "string", "format": "uuid" }
    }]);
    let mut get_op = json!({
        "tags": [table],
        "summary": format!("Get a {name}"),
        "parameters": id_param,
        "responses": {
            "200": json_content(schema_ref(name)),
            "404": { "description": "not found" }
        }
    });
    let mut put_op = json!({
        "tags": [table],
        "summary": format!("Update a {name}"),
        "security": [{ "bearerAuth": [] }],
        "parameters": id_param,
        "requestBody": json_content(schema_ref(&format!("Update{name}"))),
        "responses": {
            "200": json_content(schema_ref(name)),
            "401": { "description": "unauthorized" },
            "404": { "description": "not found" },
            "409": { "description": "conflict" },
            "422": { "description": "validation failed" }
        }
    });
    let mut delete_op = json!({
        "tags": [table],
        "summary": format!("Delete a {name}"),
        "security": [{ "bearerAuth": [] }],
        "parameters": id_param,
        "responses": {
            "204": { "description": "deleted" },
            "401": { "description": "unauthorized" },
            "404": { "description": "not found" }
        }
    });
    if guard_reads {
        guard_read(&mut get_op);
        add_response(&mut put_op, "403", "forbidden");
        add_response(&mut delete_op, "403", "forbidden");
    }
    json!({ "get": get_op, "put": put_op, "delete": delete_op })
}

fn register_path() -> Value {
    json!({
        "post": {
            "tags": ["users"],
            "summary": "Register a new user and receive a token",
            "requestBody": json_content(schema_ref("CreateUser")),
            "responses": {
                "201": json_content(schema_ref("TokenResponse")),
                "409": { "description": "conflict" },
                "422": { "description": "validation failed" }
            }
        }
    })
}

fn login_path() -> Value {
    json!({
        "post": {
            "tags": ["users"],
            "summary": "Exchange credentials for a token",
            "requestBody": json_content(schema_ref("LoginRequest")),
            "responses": {
                "200": json_content(schema_ref("TokenResponse")),
                "401": { "description": "invalid credentials" },
                "422": { "description": "validation failed" }
            }
        }
    })
}

/// `/users/me` — self-service read of the caller's own record. Needs any valid bearer token
/// (not admin); the user is identified by the token's `sub` claim.
fn me_path() -> Value {
    json!({
        "get": {
            "tags": ["users"],
            "summary": "Get the authenticated user's own record",
            "security": [{ "bearerAuth": [] }],
            "responses": {
                "200": json_content(schema_ref("User")),
                "401": { "description": "unauthorized" },
                "404": { "description": "not found" }
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use gize_core::{Module, Relation};

    fn blog_manifest() -> Manifest {
        let mut m = Manifest::new("blog");
        m.upsert_module(Module {
            name: "users".to_string(),
            model: None,
            fields: vec![
                "name:String".to_string(),
                "email:String".to_string(),
                "password:String".to_string(),
                "is_admin:bool".to_string(),
            ],
            belongs_to: vec![],
        });
        m.upsert_module(Module {
            name: "posts".to_string(),
            model: None,
            fields: vec!["title:String".to_string()],
            belongs_to: vec![Relation {
                field: "author".to_string(),
                target: "users".to_string(),
            }],
        });
        m
    }

    #[test]
    fn emits_crud_and_auth_paths() {
        let spec = spec_json(&blog_manifest()).unwrap();
        let paths = spec["paths"].as_object().unwrap();
        for p in [
            "/users",
            "/users/{id}",
            "/users/register",
            "/users/login",
            "/posts",
            "/posts/{id}",
        ] {
            assert!(paths.contains_key(p), "missing path {p}");
        }
        // Generic resource: write ops are guarded, reads are public.
        assert!(paths["/posts"]["post"].get("security").is_some());
        assert!(paths["/posts"]["get"].get("security").is_none());
        // `users` is admin-gated end to end, including reads (ADR-021), and reads document 403.
        assert!(paths["/users"]["get"].get("security").is_some());
        assert!(paths["/users/{id}"]["get"].get("security").is_some());
        assert!(paths["/users"]["get"]["responses"].get("403").is_some());
        assert!(paths["/users"]["post"]["responses"].get("403").is_some());
        assert!(
            paths["/users/{id}"]["delete"]["responses"]
                .get("403")
                .is_some()
        );
        // register/login stay public.
        assert!(paths["/users/register"]["post"].get("security").is_none());
        assert!(paths["/users/login"]["post"].get("security").is_none());
        // `/users/me` is self-service: it requires a bearer token but is not admin-gated.
        assert!(paths.contains_key("/users/me"), "missing path /users/me");
        assert!(paths["/users/me"]["get"].get("security").is_some());
        assert_eq!(
            paths["/users/me"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
                ["$ref"],
            "#/components/schemas/User"
        );
    }

    #[test]
    fn list_routes_document_the_page_envelope() {
        let spec = spec_json(&blog_manifest()).unwrap();
        let list = &spec["paths"]["/posts"]["get"];
        let names: Vec<_> = list["parameters"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, ["page", "per_page"]);
        assert_eq!(list["parameters"][1]["schema"]["maximum"], 100);
        assert_eq!(
            list["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/PostPage"
        );
        assert!(list["responses"].get("422").is_some());
        let page = &spec["components"]["schemas"]["PostPage"];
        assert_eq!(
            page["properties"]["items"]["items"]["$ref"],
            "#/components/schemas/Post"
        );
        assert!(spec["components"]["schemas"].get("UserPage").is_some());
    }

    #[test]
    fn user_response_hides_password_but_dto_keeps_it() {
        let spec = spec_json(&blog_manifest()).unwrap();
        let schemas = &spec["components"]["schemas"];
        assert!(schemas["User"]["properties"].get("password").is_none());
        assert!(schemas["User"]["properties"].get("is_admin").is_some());
        assert!(
            schemas["CreateUser"]["properties"]
                .get("password")
                .is_some()
        );
    }

    #[test]
    fn relationship_fk_is_in_the_schema() {
        let spec = spec_json(&blog_manifest()).unwrap();
        let post = &spec["components"]["schemas"]["Post"]["properties"];
        assert!(
            post.get("author_id").is_some(),
            "FK column should appear in the schema"
        );
        assert_eq!(post["author_id"]["format"], "uuid");
    }

    #[test]
    fn operations_match_paths() {
        let m = blog_manifest();
        let ops = operations(&m).unwrap();
        let spec = spec_json(&m).unwrap();
        let paths = spec["paths"].as_object().unwrap();
        for (method, path) in ops {
            assert!(
                paths.get(&path).and_then(|p| p.get(&method)).is_some(),
                "spec missing {method} {path}"
            );
        }
    }
}