Skip to main content

arks_server/web/api/
openapi.rs

1//! Single-source `API_ROUTES` table and OpenAPI 3.1.0 document generator
2//! (governed by `rest-api-standards.sot.md` RA-OAS-1..7).
3//!
4//! Runtime `GET /api/v1/openapi.json`, CLI `arks serve openapi`, and the
5//! published `docs/assets/data/openapi.json` artifact are all generated from
6//! [`API_ROUTES`] and enforced byte-for-byte by unit tests.
7
8use serde_json::{Map, Value, json};
9
10/// Server listener surface owning an API route (`x-arks-surface`).
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ApiSurface {
13    /// `arks serve` HTTP listener (`:8080` demo default).
14    Serve,
15    /// `arks hub` forge listener (`:3920` demo default).
16    Forge,
17    /// `arks serve` operational probes & metrics on the `serve` listener.
18    Ops,
19}
20
21impl ApiSurface {
22    pub const fn as_str(self) -> &'static str {
23        match self {
24            Self::Serve => "serve",
25            Self::Forge => "forge",
26            Self::Ops => "ops",
27        }
28    }
29}
30
31/// Release line availability of a route (`v1.0` stays Kinetic-free).
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ReleaseLine {
34    Both,
35    V2Only,
36}
37
38/// Declarative API route definition driving OpenAPI 3.1.0 generation and route audits.
39#[derive(Debug, Clone, Copy)]
40pub struct ApiRouteDef {
41    pub method: &'static str,
42    pub pattern: &'static str,
43    pub op_id: &'static str,
44    pub tag: &'static str,
45    pub summary: &'static str,
46    pub scopes: &'static [&'static str],
47    pub surface: ApiSurface,
48    pub line: ReleaseLine,
49}
50
51/// Single source of truth for `arks serve` and `arks hub` documented REST operations.
52pub const API_ROUTES: &[ApiRouteDef] = &[
53    // Discovery & OpenAPI (`serve`)
54    ApiRouteDef {
55        method: "GET",
56        pattern: "/api/v1",
57        op_id: "getApiIndex",
58        tag: "Discovery",
59        summary: "API v1 discovery index",
60        scopes: &[],
61        surface: ApiSurface::Serve,
62        line: ReleaseLine::Both,
63    },
64    ApiRouteDef {
65        method: "GET",
66        pattern: "/api/v1/openapi.json",
67        op_id: "getOpenApiSpec",
68        tag: "Discovery",
69        summary: "OpenAPI 3.1.0 specification generated from API_ROUTES",
70        scopes: &[],
71        surface: ApiSurface::Serve,
72        line: ReleaseLine::Both,
73    },
74    // Native `serve` `/api/v1/*`
75    ApiRouteDef {
76        method: "GET",
77        pattern: "/api/v1/repo",
78        op_id: "getRepoSummary",
79        tag: "Native Ops & LFS",
80        summary: "Repository summary (default branch, counts, archived state)",
81        scopes: &["repo:read"],
82        surface: ApiSurface::Serve,
83        line: ReleaseLine::Both,
84    },
85    ApiRouteDef {
86        method: "GET",
87        pattern: "/api/v1/leases",
88        op_id: "listLeases",
89        tag: "Native Ops & LFS",
90        summary: "List active multi-session revision leases",
91        scopes: &["repo:read"],
92        surface: ApiSurface::Serve,
93        line: ReleaseLine::Both,
94    },
95    ApiRouteDef {
96        method: "DELETE",
97        pattern: "/api/v1/leases/{name}",
98        op_id: "releaseLease",
99        tag: "Native Ops & LFS",
100        summary: "Release or force-unlock a named lease",
101        scopes: &["repo:write"],
102        surface: ApiSurface::Serve,
103        line: ReleaseLine::Both,
104    },
105    ApiRouteDef {
106        method: "GET",
107        pattern: "/api/v1/issues",
108        op_id: "listNativeIssues",
109        tag: "Native Ops & LFS",
110        summary: "List repository issues (native JSON)",
111        scopes: &["repo:read"],
112        surface: ApiSurface::Serve,
113        line: ReleaseLine::Both,
114    },
115    ApiRouteDef {
116        method: "POST",
117        pattern: "/api/v1/issues",
118        op_id: "createNativeIssue",
119        tag: "Native Ops & LFS",
120        summary: "Create a repository issue (native JSON)",
121        scopes: &["repo:write"],
122        surface: ApiSurface::Serve,
123        line: ReleaseLine::Both,
124    },
125    ApiRouteDef {
126        method: "GET",
127        pattern: "/api/v1/pulls",
128        op_id: "listNativePulls",
129        tag: "Native Ops & LFS",
130        summary: "List pull requests (native JSON)",
131        scopes: &["repo:read"],
132        surface: ApiSurface::Serve,
133        line: ReleaseLine::Both,
134    },
135    ApiRouteDef {
136        method: "GET",
137        pattern: "/api/v1/releases",
138        op_id: "listNativeReleases",
139        tag: "Native Ops & LFS",
140        summary: "List releases (native JSON)",
141        scopes: &["repo:read"],
142        surface: ApiSurface::Serve,
143        line: ReleaseLine::Both,
144    },
145    // GitHub-compatible `/repos/{owner}/{repo}/*` on `serve :8080`
146    ApiRouteDef {
147        method: "GET",
148        pattern: "/repos/{owner}/{repo}/issues",
149        op_id: "listRepoIssues",
150        tag: "GitHub-Compatible",
151        summary: "List repository issues",
152        scopes: &["repo:read"],
153        surface: ApiSurface::Serve,
154        line: ReleaseLine::Both,
155    },
156    ApiRouteDef {
157        method: "POST",
158        pattern: "/repos/{owner}/{repo}/issues",
159        op_id: "createRepoIssue",
160        tag: "GitHub-Compatible",
161        summary: "Create a repository issue",
162        scopes: &["repo:write"],
163        surface: ApiSurface::Serve,
164        line: ReleaseLine::Both,
165    },
166    ApiRouteDef {
167        method: "GET",
168        pattern: "/repos/{owner}/{repo}/issues/{number}",
169        op_id: "getRepoIssue",
170        tag: "GitHub-Compatible",
171        summary: "Get a single issue by number",
172        scopes: &["repo:read"],
173        surface: ApiSurface::Serve,
174        line: ReleaseLine::Both,
175    },
176    ApiRouteDef {
177        method: "PATCH",
178        pattern: "/repos/{owner}/{repo}/issues/{number}",
179        op_id: "updateRepoIssue",
180        tag: "GitHub-Compatible",
181        summary: "Update issue title, body, state, labels, or assignee",
182        scopes: &["repo:write"],
183        surface: ApiSurface::Serve,
184        line: ReleaseLine::Both,
185    },
186    ApiRouteDef {
187        method: "POST",
188        pattern: "/repos/{owner}/{repo}/issues/{number}/comments",
189        op_id: "createIssueComment",
190        tag: "GitHub-Compatible",
191        summary: "Add a comment to an issue or pull request",
192        scopes: &["repo:write"],
193        surface: ApiSurface::Serve,
194        line: ReleaseLine::Both,
195    },
196    ApiRouteDef {
197        method: "GET",
198        pattern: "/repos/{owner}/{repo}/pulls",
199        op_id: "listRepoPulls",
200        tag: "GitHub-Compatible",
201        summary: "List pull requests",
202        scopes: &["repo:read"],
203        surface: ApiSurface::Serve,
204        line: ReleaseLine::Both,
205    },
206    ApiRouteDef {
207        method: "POST",
208        pattern: "/repos/{owner}/{repo}/pulls",
209        op_id: "createRepoPull",
210        tag: "GitHub-Compatible",
211        summary: "Open a pull request",
212        scopes: &["repo:write"],
213        surface: ApiSurface::Serve,
214        line: ReleaseLine::Both,
215    },
216    ApiRouteDef {
217        method: "GET",
218        pattern: "/repos/{owner}/{repo}/releases",
219        op_id: "listRepoReleases",
220        tag: "GitHub-Compatible",
221        summary: "List releases",
222        scopes: &["repo:read"],
223        surface: ApiSurface::Serve,
224        line: ReleaseLine::Both,
225    },
226    ApiRouteDef {
227        method: "POST",
228        pattern: "/repos/{owner}/{repo}/releases",
229        op_id: "createRepoRelease",
230        tag: "GitHub-Compatible",
231        summary: "Create a release",
232        scopes: &["repo:write"],
233        surface: ApiSurface::Serve,
234        line: ReleaseLine::Both,
235    },
236    ApiRouteDef {
237        method: "GET",
238        pattern: "/repos/{owner}/{repo}/actions/runs",
239        op_id: "listActionRuns",
240        tag: "GitHub-Compatible",
241        summary: "List workflow runs",
242        scopes: &["repo:read"],
243        surface: ApiSurface::Serve,
244        line: ReleaseLine::Both,
245    },
246    // GitHub-compatible routes served exclusively by `arks hub` (`forge :3920`)
247    ApiRouteDef {
248        method: "GET",
249        pattern: "/repos/{owner}/{repo}/issues/{number}/comments",
250        op_id: "listIssueCommentsForge",
251        tag: "Forge Listener (:3920)",
252        summary: "List comments on an issue or pull request (forge listener)",
253        scopes: &["repo:read"],
254        surface: ApiSurface::Forge,
255        line: ReleaseLine::Both,
256    },
257    ApiRouteDef {
258        method: "GET",
259        pattern: "/repos/{owner}/{repo}/pulls/{number}",
260        op_id: "getRepoPullForge",
261        tag: "Forge Listener (:3920)",
262        summary: "Get a pull request by number (forge listener)",
263        scopes: &["repo:read"],
264        surface: ApiSurface::Forge,
265        line: ReleaseLine::Both,
266    },
267    ApiRouteDef {
268        method: "PUT",
269        pattern: "/repos/{owner}/{repo}/pulls/{number}/merge",
270        op_id: "mergeRepoPullForge",
271        tag: "Forge Listener (:3920)",
272        summary: "Merge a pull request (forge listener)",
273        scopes: &["repo:write"],
274        surface: ApiSurface::Forge,
275        line: ReleaseLine::Both,
276    },
277    ApiRouteDef {
278        method: "GET",
279        pattern: "/repos/{owner}/{repo}/commits/{ref}/status",
280        op_id: "getCommitStatusForge",
281        tag: "Forge Listener (:3920)",
282        summary: "Get combined commit status (forge listener)",
283        scopes: &["repo:read"],
284        surface: ApiSurface::Forge,
285        line: ReleaseLine::Both,
286    },
287    ApiRouteDef {
288        method: "GET",
289        pattern: "/repos/{owner}/{repo}/rulesets",
290        op_id: "listRepoRulesetsForge",
291        tag: "Forge Listener (:3920)",
292        summary: "List repository branch protection rulesets (forge listener)",
293        scopes: &["repo:read"],
294        surface: ApiSurface::Forge,
295        line: ReleaseLine::Both,
296    },
297    // Git LFS Batch API (`serve`)
298    ApiRouteDef {
299        method: "POST",
300        pattern: "/info/lfs/objects/batch",
301        op_id: "lfsBatch",
302        tag: "Native Ops & LFS",
303        summary: "Git LFS Batch API (download / upload object negotiation)",
304        scopes: &["repo:read"],
305        surface: ApiSurface::Serve,
306        line: ReleaseLine::Both,
307    },
308    // Operational probes & Prometheus metrics (`ops`)
309    ApiRouteDef {
310        method: "GET",
311        pattern: "/livez",
312        op_id: "getLivez",
313        tag: "Native Ops & LFS",
314        summary: "Process liveness probe",
315        scopes: &[],
316        surface: ApiSurface::Ops,
317        line: ReleaseLine::Both,
318    },
319    ApiRouteDef {
320        method: "GET",
321        pattern: "/readyz",
322        op_id: "getReadyz",
323        tag: "Native Ops & LFS",
324        summary: "Readiness probe (shutdown state, writable data dir, healthy store)",
325        scopes: &[],
326        surface: ApiSurface::Ops,
327        line: ReleaseLine::Both,
328    },
329    ApiRouteDef {
330        method: "GET",
331        pattern: "/healthz",
332        op_id: "getHealthz",
333        tag: "Native Ops & LFS",
334        summary: "Readiness probe alias (/readyz)",
335        scopes: &[],
336        surface: ApiSurface::Ops,
337        line: ReleaseLine::Both,
338    },
339    ApiRouteDef {
340        method: "GET",
341        pattern: "/metrics",
342        op_id: "getMetrics",
343        tag: "Native Ops & LFS",
344        summary: "Prometheus metrics (loopback or Bearer ARKS_METRICS_TOKEN)",
345        scopes: &[],
346        surface: ApiSurface::Ops,
347        line: ReleaseLine::Both,
348    },
349];
350
351/// Generate the canonical OpenAPI 3.1.0 JSON document from [`API_ROUTES`].
352///
353/// `include_v2` must be `false` on `v1.0` (ensuring zero Kinetic paths) and `true` on `v2.0`.
354pub fn openapi_document(include_v2: bool) -> Value {
355    let mut paths: Map<String, Value> = Map::new();
356    for route in API_ROUTES {
357        if !include_v2 && route.line == ReleaseLine::V2Only {
358            continue;
359        }
360        let path_entry = paths
361            .entry(route.pattern.to_string())
362            .or_insert_with(|| Value::Object(Map::new()));
363        let Some(path_obj) = path_entry.as_object_mut() else {
364            continue;
365        };
366        let method_key = route.method.to_ascii_lowercase();
367        let params = extract_path_params(route.pattern);
368        let mut op = Map::new();
369        op.insert("operationId".into(), json!(route.op_id));
370        op.insert("tags".into(), json!([route.tag]));
371        op.insert("summary".into(), json!(route.summary));
372        op.insert("x-arks-surface".into(), json!(route.surface.as_str()));
373        if !route.scopes.is_empty() {
374            op.insert("x-arks-scopes".into(), json!(route.scopes));
375        }
376        if !params.is_empty() {
377            op.insert("parameters".into(), Value::Array(params));
378        }
379        op.insert(
380            "responses".into(),
381            json!({
382                "200": { "description": "Successful response" },
383                "400": { "$ref": "#/components/responses/Problem" },
384                "401": { "$ref": "#/components/responses/Problem" },
385                "403": { "$ref": "#/components/responses/Problem" },
386                "404": { "$ref": "#/components/responses/Problem" }
387            }),
388        );
389        path_obj.insert(method_key, Value::Object(op));
390    }
391
392    json!({
393        "openapi": "3.1.0",
394        "jsonSchemaDialect": "https://spec.openapis.org/oas/3.1/dialect/base",
395        "info": {
396            "title": "arks serve REST API",
397            "version": env!("CARGO_PKG_VERSION"),
398            "summary": "GitHub-compatible forge REST API and native ops, Git LFS, and lease endpoints served by single-binary arks serve.",
399            "description": "Generated directly from API_ROUTES in arks-server. Operations are tagged by listener surface (x-arks-surface: serve | forge | ops). Errors use RFC 9457 application/problem+json with message and documentation_url extensions.",
400            "license": {
401                "name": "Apache-2.0 OR MIT",
402                "url": "https://github.com/modootoday/arks/blob/main/LICENSE"
403            }
404        },
405        "servers": [
406            {
407                "url": "http://127.0.0.1:8080",
408                "description": "arks serve HTTP listener (Web UI, /api/v1/*, unified REST, Git Smart HTTP, LFS, ops probes)",
409                "x-arks-surface": "serve"
410            },
411            {
412                "url": "http://127.0.0.1:3920",
413                "description": "arks hub forge listener (GitHub-class REST surface for arks hub client)",
414                "x-arks-surface": "forge"
415            },
416            {
417                "url": "https://{host}",
418                "description": "Production self-hosted arks serve instance behind TLS",
419                "x-arks-surface": "serve",
420                "variables": {
421                    "host": {
422                        "default": "forge.example.com"
423                    }
424                }
425            }
426        ],
427        "security": [
428            { "bearerAuth": [] },
429            { "basicAuth": [] }
430        ],
431        "tags": [
432            {
433                "name": "Discovery",
434                "description": "API index and runtime OpenAPI 3.1.0 specification."
435            },
436            {
437                "name": "GitHub-Compatible",
438                "description": "Drop-in /repos/{owner}/{repo}/* endpoints on the arks serve listener."
439            },
440            {
441                "name": "Forge Listener (:3920)",
442                "description": "GitHub-class endpoints served by the companion arks hub forge listener."
443            },
444            {
445                "name": "Native Ops & LFS",
446                "description": "Multi-session leases, Git LFS Batch API, health probes, and Prometheus metrics."
447            }
448        ],
449        "components": {
450            "securitySchemes": {
451                "bearerAuth": {
452                    "type": "http",
453                    "scheme": "bearer",
454                    "description": "Personal Access Token (PAT) scoped by RBAC role (reader, writer, admin)."
455                },
456                "basicAuth": {
457                    "type": "http",
458                    "scheme": "basic",
459                    "description": "HTTP Basic authentication with username and PAT (or password when 2FA is disabled)."
460                }
461            },
462            "responses": {
463                "Problem": {
464                    "description": "RFC 9457 Problem Details error response",
465                    "content": {
466                        "application/problem+json": {
467                            "schema": { "$ref": "#/components/schemas/ProblemDetails" }
468                        }
469                    }
470                }
471            },
472            "schemas": {
473                "ProblemDetails": {
474                    "type": "object",
475                    "required": ["type", "title", "status", "detail", "instance", "message"],
476                    "properties": {
477                        "type": { "type": "string", "format": "uri" },
478                        "title": { "type": "string" },
479                        "status": { "type": "integer" },
480                        "detail": { "type": "string" },
481                        "instance": { "type": "string" },
482                        "message": { "type": "string" },
483                        "documentation_url": { "type": "string", "format": "uri" },
484                        "errors": {
485                            "type": "array",
486                            "items": {
487                                "type": "object",
488                                "properties": {
489                                    "field": { "type": "string" },
490                                    "code": { "type": "string" },
491                                    "message": { "type": "string" }
492                                }
493                            }
494                        }
495                    }
496                }
497            }
498        },
499        "paths": Value::Object(paths),
500        "webhooks": {
501            "push": {
502                "post": {
503                    "summary": "Repository ref push event",
504                    "responses": { "200": { "description": "Webhook received" } }
505                }
506            },
507            "issues": {
508                "post": {
509                    "summary": "Issue created or updated event",
510                    "responses": { "200": { "description": "Webhook received" } }
511                }
512            },
513            "pull_request": {
514                "post": {
515                    "summary": "Pull request opened or merged event",
516                    "responses": { "200": { "description": "Webhook received" } }
517                }
518            },
519            "release": {
520                "post": {
521                    "summary": "Release published event",
522                    "responses": { "200": { "description": "Webhook received" } }
523                }
524            }
525        }
526    })
527}
528
529/// Deterministic pretty-printed JSON string (with trailing newline) for CLI and drift tests.
530pub fn openapi_json_pretty(include_v2: bool) -> String {
531    let doc = openapi_document(include_v2);
532    let mut out = serde_json::to_string_pretty(&doc).expect("serialize OpenAPI 3.1 document");
533    out.push('\n');
534    out
535}
536
537fn extract_path_params(pattern: &str) -> Vec<Value> {
538    let mut out = Vec::new();
539    for seg in pattern.split('/') {
540        if let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
541            out.push(json!({
542                "name": name,
543                "in": "path",
544                "required": true,
545                "schema": { "type": "string" }
546            }));
547        }
548    }
549    out
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    #[test]
557    fn openapi_spec_is_valid_3_1_with_per_surface_servers_and_zero_kinetic_on_v1() {
558        let doc = openapi_document(false);
559        assert_eq!(doc["openapi"], "3.1.0");
560        assert_eq!(
561            doc["jsonSchemaDialect"],
562            "https://spec.openapis.org/oas/3.1/dialect/base"
563        );
564        let servers = doc["servers"].as_array().unwrap();
565        assert!(servers.iter().any(|s| s["x-arks-surface"] == "serve"));
566        assert!(servers.iter().any(|s| s["x-arks-surface"] == "forge"));
567
568        let paths = doc["paths"].as_object().unwrap();
569        assert!(paths.contains_key("/api/v1/openapi.json"));
570        assert!(paths.contains_key("/livez"));
571        assert!(paths.contains_key("/readyz"));
572        for key in paths.keys() {
573            assert!(
574                !key.contains("kinetic"),
575                "v1.0 OpenAPI must stay Kinetic-free: {key}"
576            );
577        }
578        assert!(doc["webhooks"].as_object().unwrap().contains_key("release"));
579    }
580
581    #[test]
582    fn openapi_artifact_matches_generated_spec() {
583        let generated = openapi_json_pretty(false);
584        let artifact =
585            include_str!("../../../../../docs/assets/data/openapi.json").replace("\r\n", "\n");
586        assert_eq!(
587            artifact, generated,
588            "docs/assets/data/openapi.json drifted from API_ROUTES; run `arks serve openapi > docs/assets/data/openapi.json`"
589        );
590    }
591}