1use utoipa::openapi::header::{Header, HeaderBuilder};
2use utoipa::openapi::path::{Operation, Parameter, ParameterBuilder, ParameterIn};
3use utoipa::openapi::{ObjectBuilder, RefOr, Required, Type};
4
5use crate::error_responses::insert_error_response;
6
7pub const IF_MATCH_HEADER: &str = "If-Match";
9
10pub const ETAG_HEADER: &str = "ETag";
12
13pub const PRECONDITION_REQUIRED_CODE: &str = "precondition_required";
15
16pub const PRECONDITION_FAILED_CODE: &str = "precondition_failed";
18
19pub const INVALID_IF_MATCH_CODE: &str = "invalid_if_match";
21
22const STATUS_BAD_REQUEST: &str = "400";
23const STATUS_PRECONDITION_FAILED: &str = "412";
24const STATUS_PRECONDITION_REQUIRED: &str = "428";
25const SUCCESS_STATUS_PREFIX: char = '2';
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum IfMatchRequirement {
30 Required,
32 Optional,
34}
35
36impl IfMatchRequirement {
37 const fn is_required(self) -> bool {
38 matches!(self, Self::Required)
39 }
40}
41
42#[must_use]
44pub fn if_match_parameter(requirement: IfMatchRequirement) -> Parameter {
45 let missing = match requirement {
46 IfMatchRequirement::Required => {
47 format!("A missing header returns 428 `{PRECONDITION_REQUIRED_CODE}`.")
48 }
49 IfMatchRequirement::Optional => "Omit it to write unconditionally.".to_owned(),
50 };
51 let required = if requirement.is_required() {
52 Required::True
53 } else {
54 Required::False
55 };
56 ParameterBuilder::new()
57 .name(IF_MATCH_HEADER)
58 .parameter_in(ParameterIn::Header)
59 .required(required)
60 .description(Some(format!(
61 "The strong ETag from the latest read of this resource. {missing} A stale ETag \
62 returns 412 `{PRECONDITION_FAILED_CODE}`. `*`, weak ETags, lists, and ETags of \
63 another resource return 400 `{INVALID_IF_MATCH_CODE}`."
64 )))
65 .schema(Some(ObjectBuilder::new().schema_type(Type::String)))
66 .build()
67}
68
69#[must_use]
71pub fn etag_header() -> Header {
72 HeaderBuilder::new()
73 .schema(ObjectBuilder::new().schema_type(Type::String))
74 .description(Some(
75 "Strong revision validator. Send it unchanged in If-Match to update or delete this \
76 resource.",
77 ))
78 .build()
79}
80
81pub fn document_if_match(operation: &mut Operation, requirement: IfMatchRequirement) {
87 let parameters = operation.parameters.get_or_insert_with(Vec::new);
88 parameters.retain(|parameter| !is_if_match(parameter));
89 parameters.push(if_match_parameter(requirement));
90
91 insert_error_response(
92 operation,
93 STATUS_BAD_REQUEST,
94 &format!("`{INVALID_IF_MATCH_CODE}`: If-Match is not one strong ETag for this resource"),
95 );
96 insert_error_response(
97 operation,
98 STATUS_PRECONDITION_FAILED,
99 &format!("`{PRECONDITION_FAILED_CODE}`: the resource changed since it was read"),
100 );
101 if requirement.is_required() {
102 insert_error_response(
103 operation,
104 STATUS_PRECONDITION_REQUIRED,
105 &format!("`{PRECONDITION_REQUIRED_CODE}`: If-Match is required"),
106 );
107 }
108}
109
110pub fn document_etag(operation: &mut Operation) {
114 for (status, response) in &mut operation.responses.responses {
115 if !status.starts_with(SUCCESS_STATUS_PREFIX) {
116 continue;
117 }
118 if let RefOr::T(response) = response {
119 response
120 .headers
121 .insert(ETAG_HEADER.to_owned(), etag_header());
122 }
123 }
124}
125
126fn is_if_match(parameter: &Parameter) -> bool {
127 parameter.parameter_in == ParameterIn::Header
128 && parameter.name.eq_ignore_ascii_case(IF_MATCH_HEADER)
129}
130
131#[cfg(test)]
132mod tests {
133 use serde_json::{Value, json};
134 use utoipa::OpenApi as _;
135
136 use super::{
137 ETAG_HEADER, IF_MATCH_HEADER, IfMatchRequirement, document_etag, document_if_match,
138 };
139 use crate::{ErrorEnvelope, serialize_schema};
140
141 #[derive(serde::Serialize, utoipa::ToSchema)]
142 struct Item {
143 name: String,
144 }
145
146 #[utoipa::path(
147 put,
148 path = "/items/{id}",
149 params(
150 ("id" = String, Path, description = "Item id"),
151 ("if-match" = Option<String>, Header, description = "Hand-written")
152 ),
153 responses(
154 (status = 200, description = "Updated", body = Item),
155 (status = 400, description = "Invalid item", body = ErrorEnvelope),
156 (status = 404, description = "Missing", body = ErrorEnvelope)
157 )
158 )]
159 #[allow(dead_code)]
160 fn update_item() {}
161
162 #[utoipa::path(
163 patch,
164 path = "/settings",
165 responses((status = 200, description = "Updated", body = Item))
166 )]
167 #[allow(dead_code)]
168 fn patch_settings() {}
169
170 #[utoipa::path(
171 get,
172 path = "/items/{id}",
173 params(("id" = String, Path, description = "Item id")),
174 responses(
175 (status = 200, description = "Found", body = Item),
176 (status = 404, description = "Missing", body = ErrorEnvelope)
177 )
178 )]
179 #[allow(dead_code)]
180 fn get_item() {}
181
182 #[derive(utoipa::OpenApi)]
183 #[openapi(
184 paths(update_item, patch_settings, get_item),
185 components(schemas(ErrorEnvelope, Item))
186 )]
187 struct ApiDoc;
188
189 fn documented() -> Value {
190 let mut document = ApiDoc::openapi();
191 let paths = &mut document.paths.paths;
192 let item = paths.get_mut("/items/{id}").expect("item path");
193 document_if_match(
194 item.put.as_mut().expect("put"),
195 IfMatchRequirement::Required,
196 );
197 document_etag(item.put.as_mut().expect("put"));
198 document_etag(item.get.as_mut().expect("get"));
199 let settings = paths.get_mut("/settings").expect("settings path");
200 document_if_match(
201 settings.patch.as_mut().expect("patch"),
202 IfMatchRequirement::Optional,
203 );
204 let json = serialize_schema(&document).expect("serializable");
205 serde_json::from_str(&json).expect("valid JSON")
206 }
207
208 fn if_match_parameters(operation: &Value) -> Vec<&Value> {
209 operation["parameters"]
210 .as_array()
211 .expect("parameters")
212 .iter()
213 .filter(|parameter| {
214 parameter["in"] == "header"
215 && parameter["name"]
216 .as_str()
217 .is_some_and(|name| name.eq_ignore_ascii_case(IF_MATCH_HEADER))
218 })
219 .collect()
220 }
221
222 #[test]
223 fn required_precondition_replaces_hand_written_parameter_and_adds_errors() {
224 let document = documented();
225 let put = &document["paths"]["/items/{id}"]["put"];
226
227 let parameters = if_match_parameters(put);
228 assert_eq!(parameters.len(), 1);
229 assert_eq!(parameters[0]["name"], IF_MATCH_HEADER);
230 assert_eq!(parameters[0]["required"], true);
231 assert_eq!(parameters[0]["schema"], json!({"type": "string"}));
232 let description = parameters[0]["description"].as_str().expect("description");
233 for code in [
234 "precondition_required",
235 "precondition_failed",
236 "invalid_if_match",
237 ] {
238 assert!(description.contains(code), "{code}");
239 }
240
241 let responses = &put["responses"];
242 assert_eq!(responses["400"]["description"], "Invalid item");
243 for status in ["412", "428"] {
244 assert_eq!(
245 responses[status]["content"]["application/json"]["schema"]["$ref"],
246 "#/components/schemas/ErrorEnvelope",
247 "{status}"
248 );
249 }
250 assert_eq!(responses["404"]["description"], "Missing");
251 }
252
253 #[test]
254 fn optional_precondition_documents_no_428() {
255 let document = documented();
256 let patch = &document["paths"]["/settings"]["patch"];
257
258 let parameters = if_match_parameters(patch);
259 assert_eq!(parameters.len(), 1);
260 assert_eq!(parameters[0]["required"], false);
261 let responses = patch["responses"].as_object().expect("responses");
262 assert!(responses.contains_key("400"));
263 assert!(responses.contains_key("412"));
264 assert!(!responses.contains_key("428"));
265 }
266
267 #[test]
268 fn etag_is_documented_on_success_responses_only() {
269 let document = documented();
270 for method in ["put", "get"] {
271 let responses = &document["paths"]["/items/{id}"][method]["responses"];
272 assert_eq!(
273 responses["200"]["headers"][ETAG_HEADER]["schema"],
274 json!({"type": "string"}),
275 "{method}"
276 );
277 assert!(responses["404"].get("headers").is_none(), "{method}");
278 }
279 let settings = &document["paths"]["/settings"]["patch"]["responses"]["200"];
280 assert!(settings.get("headers").is_none());
281 }
282
283 #[test]
284 fn documenting_twice_is_stable() {
285 let mut document = ApiDoc::openapi();
286 let item = document
287 .paths
288 .paths
289 .get_mut("/items/{id}")
290 .expect("item path");
291 let put = item.put.as_mut().expect("put");
292 document_if_match(put, IfMatchRequirement::Optional);
293 document_if_match(put, IfMatchRequirement::Required);
294 document_etag(put);
295 document_etag(put);
296 let operation = serde_json::to_value(put.clone()).expect("serializable");
297 assert_eq!(if_match_parameters(&operation).len(), 1);
298 assert_eq!(if_match_parameters(&operation)[0]["required"], true);
299 assert_eq!(
300 operation["responses"]["200"]["headers"]
301 .as_object()
302 .expect("headers")
303 .len(),
304 1
305 );
306 }
307}