1#![deny(missing_docs)]
29
30use std::collections::BTreeMap;
31use std::error::Error as StdError;
32use std::fmt;
33use std::fs::{self, File, OpenOptions};
34use std::io::{self, Write};
35use std::path::{Path, PathBuf};
36use std::sync::atomic::{AtomicU64, Ordering};
37
38use serde::{Deserialize, Serialize};
39use serde_json::Value;
40use utoipa::ToSchema;
41use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme};
42use utoipa::openapi::{Components, OpenApi, Server};
43
44mod error_responses;
45mod naming;
46mod precondition;
47mod response_descriptions;
48
49pub use error_responses::{
50 ErrorResponseRules, OperationCondition, REQUEST_ID_HEADER, RETRY_AFTER_HEADER,
51 ResponseSelector, WWW_AUTHENTICATE_HEADER, request_id_header, retry_after_header,
52 www_authenticate_header,
53};
54pub use naming::{NameKind, NamingViolation, find_naming_violations, is_camel_case};
55pub use precondition::{
56 ETAG_HEADER, IF_MATCH_HEADER, INVALID_IF_MATCH_CODE, IfMatchRequirement,
57 PRECONDITION_FAILED_CODE, PRECONDITION_REQUIRED_CODE, document_etag, document_if_match,
58 etag_header, if_match_parameter,
59};
60pub use response_descriptions::fill_missing_response_descriptions;
61
62pub const BEARER_AUTH_SCHEME: &str = "bearerAuth";
64
65#[derive(Clone)]
73pub struct OpenApiMetadata {
74 title: String,
75 version: String,
76 description: String,
77 servers: Vec<Server>,
78 bearer_auth: bool,
79}
80
81impl OpenApiMetadata {
82 pub fn new<T, V, D>(title: T, version: V, description: D) -> Self
84 where
85 T: Into<String>,
86 V: Into<String>,
87 D: Into<String>,
88 {
89 Self {
90 title: title.into(),
91 version: version.into(),
92 description: description.into(),
93 servers: vec![Server::new("/")],
94 bearer_auth: false,
95 }
96 }
97
98 #[must_use]
103 pub fn servers<I>(mut self, servers: I) -> Self
104 where
105 I: IntoIterator<Item = Server>,
106 {
107 self.servers = servers.into_iter().collect();
108 self
109 }
110
111 #[must_use]
116 pub const fn bearer_auth(mut self) -> Self {
117 self.bearer_auth = true;
118 self
119 }
120
121 pub fn apply_to(&self, openapi: &mut OpenApi) {
123 fill_missing_response_descriptions(openapi);
124 openapi.info.title.clone_from(&self.title);
125 openapi.info.version.clone_from(&self.version);
126 openapi.info.description = Some(self.description.clone());
127 openapi.servers = (!self.servers.is_empty()).then(|| self.servers.clone());
128
129 if self.bearer_auth {
130 let components = openapi.components.get_or_insert_with(Components::new);
131 let bearer = HttpBuilder::new()
132 .scheme(HttpAuthScheme::Bearer)
133 .bearer_format("JWT")
134 .description(Some("OIDC access token supplied as an HTTP bearer JWT."))
135 .build();
136 components.add_security_scheme(BEARER_AUTH_SCHEME, SecurityScheme::Http(bearer));
137 }
138 }
139}
140
141#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
146pub struct ErrorEnvelope {
147 pub error: ErrorBody,
149}
150
151#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
153#[serde(rename_all = "camelCase")]
154pub struct ErrorBody {
155 pub code: String,
157 pub message: String,
159 pub request_id: String,
161 pub details: BTreeMap<String, Value>,
163}
164
165#[derive(
173 Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, ToSchema,
174)]
175#[schema(value_type = String, format = DateTime)]
176pub struct Rfc3339DateTime(#[serde(with = "time::serde::rfc3339")] pub time::OffsetDateTime);
177
178impl Rfc3339DateTime {
179 pub const fn new(value: time::OffsetDateTime) -> Self {
181 Self(value)
182 }
183
184 pub const fn into_inner(self) -> time::OffsetDateTime {
186 self.0
187 }
188}
189
190impl From<time::OffsetDateTime> for Rfc3339DateTime {
191 fn from(value: time::OffsetDateTime) -> Self {
192 Self::new(value)
193 }
194}
195
196impl From<Rfc3339DateTime> for time::OffsetDateTime {
197 fn from(value: Rfc3339DateTime) -> Self {
198 value.into_inner()
199 }
200}
201
202impl fmt::Display for Rfc3339DateTime {
203 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204 let rendered = self
205 .0
206 .format(&time::format_description::well_known::Rfc3339)
207 .map_err(|_| fmt::Error)?;
208 formatter.write_str(&rendered)
209 }
210}
211
212impl std::str::FromStr for Rfc3339DateTime {
213 type Err = time::error::Parse;
214
215 fn from_str(value: &str) -> Result<Self, Self::Err> {
216 time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339).map(Self)
217 }
218}
219
220#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
228pub struct ResponseEnvelope<T, M> {
229 pub data: T,
231 pub meta: M,
233}
234
235impl<T, M> ResponseEnvelope<T, M> {
236 pub const fn new(data: T, meta: M) -> Self {
238 Self { data, meta }
239 }
240
241 pub fn map<U>(self, map: impl FnOnce(T) -> U) -> ResponseEnvelope<U, M> {
243 ResponseEnvelope {
244 data: map(self.data),
245 meta: self.meta,
246 }
247 }
248}
249
250#[derive(Debug)]
255pub struct SchemaError {
256 kind: SchemaErrorKind,
257}
258
259#[derive(Debug)]
260enum SchemaErrorKind {
261 Serialize(serde_json::Error),
262 Io {
263 action: &'static str,
264 path: PathBuf,
265 source: io::Error,
266 },
267 Drift {
268 path: PathBuf,
269 line: usize,
270 committed: Option<String>,
271 generated: Option<String>,
272 committed_line_count: usize,
273 generated_line_count: usize,
274 },
275 Naming(Vec<NamingViolation>),
276}
277
278impl SchemaError {
279 fn io(action: &'static str, path: &Path, source: io::Error) -> Self {
280 Self {
281 kind: SchemaErrorKind::Io {
282 action,
283 path: path.to_owned(),
284 source,
285 },
286 }
287 }
288
289 fn drift(path: &Path, committed: &str, generated: &str) -> Self {
290 let committed_lines: Vec<_> = committed.split('\n').collect();
291 let generated_lines: Vec<_> = generated.split('\n').collect();
292 let difference = committed_lines
293 .iter()
294 .zip(&generated_lines)
295 .position(|(left, right)| left != right)
296 .unwrap_or_else(|| committed_lines.len().min(generated_lines.len()));
297
298 Self {
299 kind: SchemaErrorKind::Drift {
300 path: path.to_owned(),
301 line: difference + 1,
302 committed: committed_lines.get(difference).map(ToString::to_string),
303 generated: generated_lines.get(difference).map(ToString::to_string),
304 committed_line_count: committed_lines.len(),
305 generated_line_count: generated_lines.len(),
306 },
307 }
308 }
309
310 #[must_use]
312 pub fn is_drift(&self) -> bool {
313 matches!(self.kind, SchemaErrorKind::Drift { .. })
314 }
315
316 #[must_use]
319 pub fn naming_violations(&self) -> &[NamingViolation] {
320 match &self.kind {
321 SchemaErrorKind::Naming(violations) => violations,
322 _ => &[],
323 }
324 }
325}
326
327impl fmt::Display for SchemaError {
328 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
329 match &self.kind {
330 SchemaErrorKind::Serialize(error) => {
331 write!(formatter, "could not serialize OpenAPI schema: {error}")
332 }
333 SchemaErrorKind::Io {
334 action,
335 path,
336 source,
337 } => write!(
338 formatter,
339 "could not {action} OpenAPI schema at {}: {source}",
340 path.display()
341 ),
342 SchemaErrorKind::Drift {
343 path,
344 line,
345 committed,
346 generated,
347 committed_line_count,
348 generated_line_count,
349 } => write!(
350 formatter,
351 "schema drift detected for {} (first difference at line {line}; committed: {}; generated: {}; line counts: {committed_line_count} committed, {generated_line_count} generated)\n\
352 - committed: {}\n\
353 + generated: {}\n\
354 run the openapi binary and commit the generated schema",
355 path.display(),
356 line_value(committed.as_deref()),
357 line_value(generated.as_deref()),
358 line_value(committed.as_deref()),
359 line_value(generated.as_deref()),
360 ),
361 SchemaErrorKind::Naming(violations) => {
362 write!(
363 formatter,
364 "{} OpenAPI name(s) are not camelCase; rename the serde field or exempt a standard-defined name",
365 violations.len()
366 )?;
367 violations
368 .iter()
369 .try_for_each(|violation| write!(formatter, "\n - {violation}"))
370 }
371 }
372 }
373}
374
375impl StdError for SchemaError {
376 fn source(&self) -> Option<&(dyn StdError + 'static)> {
377 match &self.kind {
378 SchemaErrorKind::Serialize(error) => Some(error),
379 SchemaErrorKind::Io { source, .. } => Some(source),
380 SchemaErrorKind::Drift { .. } | SchemaErrorKind::Naming(_) => None,
381 }
382 }
383}
384
385impl From<serde_json::Error> for SchemaError {
386 fn from(error: serde_json::Error) -> Self {
387 Self {
388 kind: SchemaErrorKind::Serialize(error),
389 }
390 }
391}
392
393fn line_value(line: Option<&str>) -> String {
394 line.map_or_else(|| "<end of file>".to_owned(), |line| format!("{line:?}"))
395}
396
397pub fn serialize_schema(openapi: &OpenApi) -> Result<String, SchemaError> {
403 let mut openapi = openapi.clone();
404 fill_missing_response_descriptions(&mut openapi);
405 let mut value = serde_json::to_value(openapi)?;
406 sort_json_objects(&mut value);
407 let mut json = serde_json::to_string_pretty(&value)?;
408 json.push('\n');
409 Ok(json)
410}
411
412fn sort_json_objects(value: &mut Value) {
413 match value {
414 Value::Array(values) => values.iter_mut().for_each(sort_json_objects),
415 Value::Object(map) => {
416 let mut entries: Vec<_> = std::mem::take(map).into_iter().collect();
417 for (_, child) in &mut entries {
418 sort_json_objects(child);
419 }
420 entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
421 map.extend(entries);
422 }
423 _ => {}
424 }
425}
426
427pub fn write_schema(openapi: &OpenApi, path: impl AsRef<Path>) -> Result<(), SchemaError> {
432 let path = path.as_ref();
433 let json = serialize_schema(openapi)?;
434 let parent = path
435 .parent()
436 .filter(|parent| !parent.as_os_str().is_empty())
437 .unwrap_or_else(|| Path::new("."));
438 fs::create_dir_all(parent)
439 .map_err(|error| SchemaError::io("create parent directories for", path, error))?;
440
441 let (mut temporary, temporary_path) = create_temporary_file(path, parent)?;
442 let write_result = (|| {
443 temporary
444 .write_all(json.as_bytes())
445 .map_err(|error| SchemaError::io("write temporary", &temporary_path, error))?;
446 temporary
447 .sync_all()
448 .map_err(|error| SchemaError::io("sync temporary", &temporary_path, error))?;
449 drop(temporary);
450 fs::rename(&temporary_path, path).map_err(|error| SchemaError::io("replace", path, error))
451 })();
452
453 if write_result.is_err() {
454 let _ignored = fs::remove_file(&temporary_path);
455 }
456 write_result
457}
458
459static TEMPORARY_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
460
461fn create_temporary_file(path: &Path, parent: &Path) -> Result<(File, PathBuf), SchemaError> {
462 let file_name = path.file_name().ok_or_else(|| {
463 SchemaError::io(
464 "resolve destination for",
465 path,
466 io::Error::new(io::ErrorKind::InvalidInput, "path has no file name"),
467 )
468 })?;
469
470 for _attempt in 0..100 {
471 let sequence = TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
472 let temporary_path = parent.join(format!(
473 ".{}.{}.{}.tmp",
474 file_name.to_string_lossy(),
475 std::process::id(),
476 sequence
477 ));
478 match OpenOptions::new()
479 .write(true)
480 .create_new(true)
481 .open(&temporary_path)
482 {
483 Ok(file) => return Ok((file, temporary_path)),
484 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
485 Err(error) => {
486 return Err(SchemaError::io("create temporary", &temporary_path, error));
487 }
488 }
489 }
490
491 Err(SchemaError::io(
492 "create temporary",
493 path,
494 io::Error::new(
495 io::ErrorKind::AlreadyExists,
496 "could not allocate a unique temporary file name",
497 ),
498 ))
499}
500
501pub fn check_no_drift(
506 openapi: &OpenApi,
507 committed_path: impl AsRef<Path>,
508) -> Result<(), SchemaError> {
509 let committed_path = committed_path.as_ref();
510 let generated = serialize_schema(openapi)?;
511 let committed = match fs::read_to_string(committed_path) {
512 Ok(committed) => committed,
513 Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(),
514 Err(error) => return Err(SchemaError::io("read committed", committed_path, error)),
515 };
516
517 if committed == generated {
518 Ok(())
519 } else {
520 Err(SchemaError::drift(committed_path, &committed, &generated))
521 }
522}
523
524#[track_caller]
531pub fn assert_no_drift(openapi: &OpenApi, committed_path: impl AsRef<Path>) {
532 if let Err(error) = check_no_drift(openapi, committed_path) {
533 panic!("{error}");
534 }
535}
536
537pub fn check_camel_case_names(openapi: &OpenApi, exemptions: &[&str]) -> Result<(), SchemaError> {
542 let document = serde_json::to_value(openapi)?;
543 let violations = find_naming_violations(&document, exemptions);
544 if violations.is_empty() {
545 Ok(())
546 } else {
547 Err(SchemaError {
548 kind: SchemaErrorKind::Naming(violations),
549 })
550 }
551}
552
553#[track_caller]
560pub fn assert_camel_case_names(openapi: &OpenApi, exemptions: &[&str]) {
561 if let Err(error) = check_camel_case_names(openapi, exemptions) {
562 panic!("{error}");
563 }
564}
565
566#[cfg(test)]
567mod tests {
568 use std::collections::BTreeMap;
569 use std::fs;
570
571 use serde::{Deserialize, Serialize};
572 use serde_json::{Value, json};
573 use tempfile::tempdir;
574 use utoipa::openapi::extensions::Extensions;
575 use utoipa::openapi::security::{HttpAuthScheme, SecurityScheme};
576 use utoipa::openapi::{Info, OpenApi, Paths, RefOr, Server};
577 use utoipa::{PartialSchema, ToSchema};
578
579 use super::{
580 BEARER_AUTH_SCHEME, ErrorBody, ErrorEnvelope, OpenApiMetadata, ResponseEnvelope,
581 Rfc3339DateTime, assert_no_drift, check_no_drift, serialize_schema, write_schema,
582 };
583
584 fn document() -> OpenApi {
585 OpenApi::new(Info::new("Unconfigured", "0.0.0"), Paths::new())
586 }
587
588 #[test]
589 fn metadata_applies_identity_servers_and_opted_in_bearer_scheme() {
590 let mut openapi = document();
591 openapi.info.contact = Some(
592 utoipa::openapi::ContactBuilder::new()
593 .name(Some("Support"))
594 .build(),
595 );
596 OpenApiMetadata::new("Inventory API", "2.4.0", "Inventory operations")
597 .servers([
598 Server::new("https://api.example.com"),
599 Server::new("http://localhost:3000"),
600 ])
601 .bearer_auth()
602 .apply_to(&mut openapi);
603
604 assert_eq!(openapi.info.title, "Inventory API");
605 assert_eq!(openapi.info.version, "2.4.0");
606 assert_eq!(
607 openapi.info.description.as_deref(),
608 Some("Inventory operations")
609 );
610 assert!(openapi.info.contact.is_some());
611 let servers = openapi.servers.as_deref();
612 assert_eq!(servers.map(|items| items.len()), Some(2));
613 assert_eq!(
614 servers
615 .and_then(|items| items.first())
616 .map(|server| server.url.as_str()),
617 Some("https://api.example.com")
618 );
619
620 let scheme = openapi
621 .components
622 .as_ref()
623 .and_then(|components| components.security_schemes.get(BEARER_AUTH_SCHEME));
624 match scheme {
625 Some(RefOr::T(SecurityScheme::Http(http))) => {
626 assert_eq!(http.bearer_format.as_deref(), Some("JWT"));
627 assert!(matches!(&http.scheme, HttpAuthScheme::Bearer));
628 }
629 _ => panic!("expected the standard HTTP bearer scheme"),
630 }
631 assert!(openapi.security.is_none());
632 }
633
634 #[test]
635 fn metadata_defaults_to_relative_server() {
636 let mut openapi = document();
637 OpenApiMetadata::new("Inventory API", "2.4.0", "Inventory operations")
638 .apply_to(&mut openapi);
639 assert_eq!(
640 openapi
641 .servers
642 .as_ref()
643 .and_then(|servers| servers.first())
644 .map(|server| server.url.as_str()),
645 Some("/")
646 );
647 assert!(openapi.components.as_ref().is_none_or(|components| {
648 !components.security_schemes.contains_key(BEARER_AUTH_SCHEME)
649 }));
650 }
651
652 #[test]
653 fn error_envelope_serializes_to_the_standard_shape() -> Result<(), Box<dyn std::error::Error>> {
654 let envelope = ErrorEnvelope {
655 error: ErrorBody {
656 code: "validation_failed".to_owned(),
657 message: "The request is invalid".to_owned(),
658 request_id: "req-123".to_owned(),
659 details: BTreeMap::new(),
660 },
661 };
662
663 assert_eq!(
664 serde_json::to_value(envelope)?,
665 json!({
666 "error": {
667 "code": "validation_failed",
668 "message": "The request is invalid",
669 "requestId": "req-123",
670 "details": {}
671 }
672 })
673 );
674 Ok(())
675 }
676
677 #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
678 #[serde(rename_all = "camelCase")]
679 struct TimestampDto {
680 observed_at: Rfc3339DateTime,
681 }
682
683 #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
684 #[serde(rename_all = "camelCase")]
685 struct TestMeta {
686 request_id: String,
687 }
688
689 #[test]
690 fn api_datetime_uses_rfc3339_json_and_date_time_schema()
691 -> Result<(), Box<dyn std::error::Error>> {
692 let timestamp = "2026-08-09T12:34:56.123456789+02:00".parse::<Rfc3339DateTime>()?;
693 let dto = TimestampDto {
694 observed_at: timestamp,
695 };
696
697 let json = serde_json::to_value(&dto)?;
698 assert_eq!(json["observedAt"], "2026-08-09T12:34:56.123456789+02:00");
699 assert_eq!(serde_json::from_value::<TimestampDto>(json)?, dto);
700
701 let schema = serde_json::to_value(Rfc3339DateTime::schema())?;
702 assert_eq!(schema["type"], "string");
703 assert_eq!(schema["format"], "date-time");
704 Ok(())
705 }
706
707 #[test]
708 fn typed_response_envelope_keeps_concrete_payload_and_metadata_schemas()
709 -> Result<(), Box<dyn std::error::Error>> {
710 let schema = serde_json::to_value(
711 <ResponseEnvelope<TimestampDto, TestMeta> as PartialSchema>::schema(),
712 )?;
713 let rendered = schema.to_string();
714
715 assert!(rendered.contains("TimestampDto"), "{rendered}");
716 assert!(rendered.contains("TestMeta"), "{rendered}");
717 assert!(!rendered.contains("serde_json.Value"), "{rendered}");
718 Ok(())
719 }
720
721 #[test]
722 fn serialization_is_stable_and_recursively_sorts_maps() -> Result<(), Box<dyn std::error::Error>>
723 {
724 let mut first = document();
725 first.extensions = Some(
726 [
727 ("x-zeta", json!({"second": 2, "first": 1})),
728 ("x-alpha", json!({"z": 2, "a": 1})),
729 ]
730 .into_iter()
731 .collect::<Extensions>(),
732 );
733
734 let mut second = document();
735 second.extensions = Some(
736 [
737 ("x-alpha", json!({"a": 1, "z": 2})),
738 ("x-zeta", json!({"first": 1, "second": 2})),
739 ]
740 .into_iter()
741 .collect::<Extensions>(),
742 );
743
744 let first_once = serialize_schema(&first)?;
745 let first_twice = serialize_schema(&first)?;
746 assert_eq!(first_once, first_twice);
747 assert_eq!(first_once, serialize_schema(&second)?);
748 assert!(first_once.ends_with('\n'));
749
750 let parsed: Value = serde_json::from_str(&first_once)?;
751 assert_eq!(parsed["x-alpha"], json!({"a": 1, "z": 2}));
752 assert!(first_once.find("\"x-alpha\"") < first_once.find("\"x-zeta\""));
753 Ok(())
754 }
755
756 #[test]
757 fn writer_creates_parents_and_round_trips() -> Result<(), Box<dyn std::error::Error>> {
758 let directory = tempdir()?;
759 let path = directory.path().join("generated/openapi.json");
760 let openapi = document();
761
762 write_schema(&openapi, &path)?;
763
764 assert_eq!(fs::read_to_string(&path)?, serialize_schema(&openapi)?);
765 Ok(())
766 }
767
768 #[test]
769 fn drift_check_accepts_matching_schema_and_rejects_changes_in_both_directions()
770 -> Result<(), Box<dyn std::error::Error>> {
771 let directory = tempdir()?;
772 let path = directory.path().join("openapi.json");
773 let base = document();
774 write_schema(&base, &path)?;
775 check_no_drift(&base, &path)?;
776 assert_no_drift(&base, &path);
777
778 let mut generated_has_more = document();
779 generated_has_more.info.description = Some("Additional documentation".to_owned());
780 let error = match check_no_drift(&generated_has_more, &path) {
781 Err(error) => error,
782 Ok(()) => panic!("generated addition should be detected as drift"),
783 };
784 assert!(error.is_drift());
785 assert!(error.to_string().contains("schema drift detected"));
786 assert!(
787 error
788 .to_string()
789 .contains("run the openapi binary and commit")
790 );
791
792 write_schema(&generated_has_more, &path)?;
793 let error = match check_no_drift(&base, &path) {
794 Err(error) => error,
795 Ok(()) => panic!("generated removal should be detected as drift"),
796 };
797 assert!(error.is_drift());
798 Ok(())
799 }
800
801 #[test]
802 fn missing_committed_schema_is_drift() -> Result<(), Box<dyn std::error::Error>> {
803 let directory = tempdir()?;
804 let error = match check_no_drift(&document(), directory.path().join("missing.json")) {
805 Err(error) => error,
806 Ok(()) => panic!("a missing committed schema should be detected as drift"),
807 };
808 assert!(error.is_drift());
809 Ok(())
810 }
811}
812
813#[doc = include_str!("../README.md")]
815#[cfg(doctest)]
816struct ReadmeDoctests;