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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
mod request_body;
mod request_parameter;
mod scope;
use crate::error::ValidationErrorType;
use crate::traverser::OpenApiTraverser;
use crate::types::json_path::JsonPath;
use crate::types::version::OpenApiVersion;
use crate::types::{HttpLike, Operation, ParameterLocation};
use crate::validator::request_body::RequestBodyValidator;
use crate::validator::request_parameter::RequestParameterValidator;
use crate::validator::scope::RequestScopeValidator;
use crate::{OPENAPI_FIELD, REF_FIELD};
use http::HeaderMap;
use jsonschema::{Resource, ValidationOptions, Validator as JsonValidator};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
pub struct OpenApiPayloadValidator {
traverser: OpenApiTraverser,
options: ValidationOptions,
}
impl OpenApiPayloadValidator {
pub fn new(mut value: Value) -> Result<Self, ValidationErrorType> {
// Assign ID for schema validation in the future.
value["$id"] = json!("@@root");
let version = match OpenApiTraverser::get_as_str(&value, OPENAPI_FIELD) {
Ok(version) => version,
Err(e) => {
return Err(ValidationErrorType::traversal_failed(
e,
"Failed to get 'openapi' from provided specification.",
));
}
};
let version = match OpenApiVersion::from_str(version) {
Ok(version) => version,
Err(e) => {
return Err(ValidationErrorType::version_failed(
e,
"Failed to parse version from provided specification.",
));
}
};
let draft = version.get_draft();
// Create this resource once and re-use it for multiple validation calls.
let resource = match Resource::from_contents(value.clone()) {
Ok(res) => res,
Err(e) => {
return Err(ValidationErrorType::resource_load_error(
e,
"Failed to create resource from provided specification",
));
}
};
// Assign draft and provide resource
let options = JsonValidator::options()
.with_draft(draft)
.with_resource("@@inner", resource);
// Create the traverser with owned value
let traverser = match OpenApiTraverser::new(value) {
Ok(traverser) => traverser,
Err(e) => {
return Err(ValidationErrorType::traversal_failed(
e,
"Failed to create traverser from provided specification.",
));
}
};
Ok(Self { traverser, options })
}
pub fn traverser(&self) -> &OpenApiTraverser {
&self.traverser
}
/// Extracts the content type from HTTP headers.
///
/// This function parses the "content-type" header from a HeaderMap and returns the
/// primary content type value (e.g., "application/json") without any parameters.
///
/// # Arguments
///
/// * `headers_instance` - A reference to a HeaderMap containing HTTP headers
///
/// # Returns
///
/// * `Some(String)` - The extracted content type if found and valid
/// * `None` - If no valid content type was found or if parsing failed
fn extract_content_type(headers_instance: &HeaderMap) -> Option<&str> {
if let Some(content_type_header) = headers_instance.get("content-type") {
if let Ok(content_type_header) = content_type_header.to_str() {
if let Some(split_content_type) = content_type_header
.split(";")
.find(|content_type_segment| content_type_segment.contains("/"))
{
return Some(split_content_type.trim());
}
}
}
None
}
/// # find_operation
///
/// Retrieves an OpenAPI Operation object that matches the specified path and HTTP method.
///
/// This function acts as a wrapper around the internal traverser's `get_operation` method.
/// It searches through the OpenAPI specification document to find an operation that matches
/// the provided request path and method.
///
/// ## Arguments
///
/// * `path` - A string slice representing the request path to match against paths defined
/// in the OpenAPI specification
/// * `method` - A string slice representing the HTTP method (GET, POST, etc.) to match
/// against methods defined in the OpenAPI specification
///
/// ## Returns
///
/// * `Ok(Arc<Operation>)` - Pointer to the Operation object if a matching path and method combination is found in the specification.
/// * `Err(ValidationErrorType)` - An error indicating why the operation couldn't be found,
/// typically `ValidationErrorType::FieldExpected` when no matching path+method is found
///
/// ## Example
///
/// ```rust
/// use oasert::validator::OpenApiPayloadValidator;
///
/// // Mini-spec for testing
/// let schema = serde_json::json!({
/// "openapi": "3.1.0",
/// "paths": {
/// "/pets": {
/// "get": {
/// "responses": {
/// "200": {
/// "description": "OK"
/// }
/// }
/// }
/// }
/// }
/// });
///
/// let validator = OpenApiPayloadValidator::new(schema).unwrap();
/// match validator.find_operation("/pets", "get") {
/// Ok(operation) => {
/// // Use the operation for validation or other purposes
/// println!("Found operation: {:?}", operation);
/// },
/// Err(err) => {
/// println!("Operation not found: {:?}", err);
/// }
/// }
/// ```
pub fn find_operation(
&self,
path: &str,
method: &str,
) -> Result<Arc<Operation>, ValidationErrorType> {
match self
.traverser
.get_operation_from_path_and_method(path, method)
{
Ok(op) => Ok(op),
Err(_) => todo!(),
}
}
/// # validate_request_body
///
/// Validates an HTTP request body against an OpenAPI operation specification.
///
/// # Arguments
///
/// * `operation` - The OpenAPI operation specification to validate against
/// * `request` - The HTTP request containing the body and headers to validate
///
/// # Returns
///
/// * `Ok(())` - If the request body is valid, according to the OpenAPI specification
/// * `Err(ValidationErrorType)` - If validation fails, with specific error details:
/// - `SectionExpected` - If the request has a body but the operation doesn't define a request body
/// - `FieldExpected` - If a required Content-Type header is missing
/// - `SchemaValidationFailed` - If the body doesn't match the schema
/// - Various other error types for specific validation failures
///
/// # Example
///
/// ```rust
/// use http::Request;
/// use oasert::validator::OpenApiPayloadValidator;
/// use serde_json::json;
///
/// // Mini-spec for testing
/// let schema = json!({
/// "openapi": "3.1.0",
/// "paths": {
/// "/my-path": {
/// "post": {
/// "requestBody": {
/// "content": {
/// "application/json": {
/// "schema": {
/// "type": "object",
/// "required": ["name"],
/// "properties": {
/// "name": {
/// "type": "string"
/// }
/// }
/// }
/// }
/// }
/// }
/// }
/// }
/// }
/// });
///
/// let validator = OpenApiPayloadValidator::new(schema).unwrap();
/// let operation = validator.find_operation("/my-path", "POST").unwrap();
/// let request = Request::builder()
/// .header("content-type", "application/json")
/// .body(json!({ "name": "example" }))
/// .unwrap();
///
/// match validator.validate_request_body(&operation, &request) {
/// Ok(()) => println!("Request body is valid"),
/// Err(err) => println!("Validation error: {:?}", err),
/// }
/// ```
pub fn validate_request_body<T>(
&self,
operation: &Operation,
request: &impl HttpLike<T>,
) -> Result<(), ValidationErrorType>
where
T: serde::ser::Serialize,
{
let content_type = Self::extract_content_type(&request.headers());
let body_instance = request.body();
match serde_json::to_value(body_instance) {
Ok(body) => {
let validator = RequestBodyValidator::new(Some(&body), content_type);
validator.validate(&self.traverser, operation, &self.options)
}
Err(_) => {
let validator = RequestBodyValidator::new(None, content_type);
validator.validate(&self.traverser, operation, &self.options)
}
}
}
/// # validate_request
///
/// Validates an HTTP request against an OpenAPI specification.
///
/// This function validates different aspects of an HTTP request, including:
/// - Matching the request path and method against a defined operation in the OpenAPI spec
/// - Validating the request body against the schema for the specified content type
/// - Validating request headers against parameter requirements
/// - Validating query parameters against parameter requirements
/// - Validating that the request has the required scopes (if applicable)
///
/// # Arguments
///
/// * `request` - An implementation of the `HttpLike` trait that provides access to request components
/// (method, path, headers, body, query parameters)
/// * `scopes` - An optional vector of authorization scopes that the request has
///
/// # Returns
///
/// * `Ok(())` - If the request is valid, according to the OpenAPI specification
/// * `Err(ValidationErrorType)` - If any validation fails, with details about the failure
pub fn validate_request<T>(
&self,
request: &impl HttpLike<T>,
scopes: Option<&Vec<String>>,
) -> Result<(), ValidationErrorType>
where
T: serde::ser::Serialize,
{
let operation = self.find_operation(request.path(), request.method().as_str())?;
self.validate_request_body(&operation, request)?;
self.validate_request_header_params(&operation, request.headers())?;
if let Some(query_params) = request.query() {
self.validate_request_query_parameters(&operation, query_params)?;
}
if let Some(scopes) = scopes {
self.validate_request_scopes(&operation, scopes)?;
}
Ok(())
}
/// # validate_request_header_params
///
/// Validates HTTP request headers against OpenAPI operation specification parameters.
/// The function converts the HTTP headers into a map of string key-value pairs, then creates
/// a RequestParameterValidator to validate these headers against the operation's header parameters.
///
/// ## Arguments
///
/// * `operation` - A reference to an Operation that contains the OpenAPI operation definition
/// with parameter specifications to validate against
/// * `headers` - A reference to a HeaderMap containing the HTTP request headers to validate
///
/// ## Returns
///
/// * `Ok(())` - If all required header parameters are present and valid according to their schemas
/// * `Err(ValidationErrorType)` - If validation fails, with the specific error type indicating the reason:
/// - `FieldExpected` - If a required header parameter is missing
/// - `SchemaValidationFailed` - If a header value doesn't match its schema
/// - `UnexpectedType` - If a header value has an incorrect type
/// - Other error types depending on specific validation failures
///
/// ## Example
///
/// ```rust
/// use http::HeaderMap;
/// use oasert::validator::OpenApiPayloadValidator;
///
/// // Mini-spec for testing
/// let schema = serde_json::json!({
/// "openapi": "3.1.0",
/// "paths": {
/// "/my-path": {
/// "get": {
/// "parameters": [
/// {
/// "name": "Content-Type",
/// "in": "header",
/// "required": true,
/// }
/// ]
/// }
/// }
/// }
/// });
///
/// let validator = OpenApiPayloadValidator::new(schema).unwrap();
/// let operation = validator.find_operation("/my-path", "GET").unwrap();
/// let mut headers = HeaderMap::new();
/// headers.insert("Content-Type", "application/json".parse().unwrap());
///
/// match validator.validate_request_header_params(&operation, &headers) {
/// Ok(()) => println!("Headers validated successfully"),
/// Err(err) => println!("Header validation failed: {:?}", err),
/// }
/// ```
pub fn validate_request_header_params(
&self,
operation: &Operation,
headers: &HeaderMap,
) -> Result<(), ValidationErrorType> {
let headers: HashMap<String, String> = headers
.iter()
.filter_map(|(key, value)| {
if let (key, Ok(value)) = (key.to_string(), value.to_str()) {
Some((key, value.to_string()))
} else {
None
}
})
.collect();
let validator = RequestParameterValidator::new(&headers, ParameterLocation::Header);
validator.validate(&self.traverser, operation, &self.options)
}
/// # validate_request_query_parameters
///
/// Validates query parameters against an OpenAPI operation definition.
///
/// Parses the query string into a HashMap of key-value pairs and validates them against
/// the parameters defined in the OpenAPI operation specification. The function uses
/// the RequestParameterValidator to perform the actual validation.
///
/// ## Arguments
///
/// * `operation` - A reference to an Operation object containing the OpenAPI operation definition
/// * `query_params` - A string containing the raw URL query parameters in the format "key1=value1&key2=value2"
///
/// ## Returns
///
/// * `Ok(())` - If all query parameters are valid according to the operation definition
/// * `Err(ValidationErrorType)` - If validation fails, returns one of several possible error types:
/// - `FieldExpected` - When a required parameter is missing
/// - `SchemaValidationFailed` - When a parameter value doesn't match the schema
/// - `UnexpectedType` - When a parameter value type doesn't match the expected type
/// - Various other validation errors depending on the specific validation failure
///
/// ## Example
///
/// ```
///
/// use oasert::validator::OpenApiPayloadValidator;
///
/// // Mini-spec for testing
/// let schema = serde_json::json!({
/// "openapi": "3.1.0",
/// "paths": {
/// "/my-path": {
/// "get": {
/// "parameters": [
/// {
/// "name": "limit",
/// "in": "query",
/// "required": true,
/// }
/// ]
/// }
/// }
/// }
/// });
/// let validator = OpenApiPayloadValidator::new(schema).unwrap();
/// let operation = validator.find_operation("/my-path", "GET").unwrap();
/// let query_string = "limit=10&status=available";
///
/// match validator.validate_request_query_parameters(&operation, query_string) {
/// Ok(()) => println!("Query parameters are valid!"),
/// Err(e) => println!("Validation error: {:?}", e),
/// }
/// ```
pub fn validate_request_query_parameters(
&self,
operation: &Operation,
query_params: &str,
) -> Result<(), ValidationErrorType> {
let query_params: HashMap<String, String> = query_params
.split("&")
.filter_map(|pair| {
let mut parts = pair.split('=');
match (parts.next(), parts.next()) {
(Some(key), Some(value)) => {
let key = percent_encoding::percent_decode_str(key)
.decode_utf8_lossy()
.to_string();
let value = percent_encoding::percent_decode_str(value)
.decode_utf8_lossy()
.to_string();
Some((key, value))
}
(Some(key), None) => {
let key = percent_encoding::percent_decode_str(key)
.decode_utf8_lossy()
.to_string();
Some((key, "".to_string()))
}
_ => {
log::warn!("Invalid query parameter: {}", pair);
None
}
}
})
.collect();
let validator = RequestParameterValidator::new(&query_params, ParameterLocation::Query);
validator.validate(&self.traverser, operation, &self.options)
}
/// # validate_request_scopes
///
/// Validates that the provided request scopes satisfy the security requirements defined in the OpenAPI specification.
///
/// This function checks whether the given scopes are sufficient to access the specified operation
/// according to the security definitions in the OpenAPI document. It creates a `RequestScopeValidator`
/// and delegates the validation logic to it.
///
/// # Arguments
///
/// * `operation` - A reference to an `Operation` struct representing the API operation being validated
/// * `scopes` - A reference to a vector of strings containing the authorization scopes provided in the request
///
/// # Returns
///
/// * `Ok(())` - If the provided scopes satisfy the security requirements for the operation
/// * `Err(ValidationErrorType)` - If validation fails, with the specific error type describing the reason
///
/// # Example
///
/// ```rust
/// use oasert::types::Operation;
/// use oasert::validator::OpenApiPayloadValidator;
///
/// // Mini-spec for testing
/// let schema = serde_json::json!({
/// "openapi": "3.1.0",
/// "paths": {
/// "/my-path": {
/// "get": {
/// "security": [
/// {
/// "oauth2": [
/// "read:items",
/// "write:items"
/// ]
/// }
/// ]
/// }
/// }
/// }
/// });
///
/// let validator = OpenApiPayloadValidator::new(schema).unwrap();
/// let operation = validator.find_operation("/my-path", "GET").unwrap();
///
/// let scopes = vec!["read:items".to_string(), "write:items".to_string()];
///
/// match validator.validate_request_scopes(&operation, &scopes) {
/// Ok(()) => println!("Request scopes are valid"),
/// Err(e) => println!("Validation failed: {:?}", e),
/// }
/// ```
pub fn validate_request_scopes(
&self,
operation: &Operation,
scopes: &Vec<String>,
) -> Result<(), ValidationErrorType> {
let validator = RequestScopeValidator::new(scopes);
validator.validate(&self.traverser, operation, &self.options)
}
}
pub(crate) trait Validator {
/// # validate
///
/// Validates an OpenAPI operation against a set of validation rules.
///
/// # Arguments
///
/// * `traverser` - Reference to an OpenApiTraverser that provides access to the full OpenAPI specification
/// and previously resolved references and operations.
/// * `operation` - Reference to the Operation being validated, containing the operation data and JSON path.
/// * `validation_options` - Reference to ValidationOptions that configure the validation behavior.
///
/// # Returns
///
/// * `Ok(())` - If the validation passes without errors.
/// * `Err(ValidationErrorType)` - If validation fails, returns one of several error types:
/// - UnsupportedSpecVersion - When the OpenAPI version is not supported
/// - SchemaValidationFailed - When schema validation fails
/// - ValueExpected - When a required value is missing
/// - SectionExpected - When a required section is missing
/// - FieldExpected - When a required field is missing
/// - UnexpectedType - When a value's type doesn't match the expected type
/// - UnableToParse - When data cannot be parsed correctly
/// - CircularReference - When a circular reference is detected
/// - InvalidRef - When a reference is invalid
fn validate(
&self,
traverser: &OpenApiTraverser,
operation: &Operation,
validation_options: &ValidationOptions,
) -> Result<(), ValidationErrorType>;
/// Validates a JSON instance against a schema referenced by a JSON path.
///
/// # Arguments
/// * `options` - The validation options used to configure the validator
/// * `json_path` - A path reference to the schema to validate against
/// * `instance` - The JSON value to validate
/// * `section` - The section context for error reporting
///
/// # Returns
/// * `Ok(())` - If validation succeeds
/// * `Err(ValidationErrorType)` - If validation fails, containing the specific error type
fn complex_validation_by_path<'a>(
options: &ValidationOptions,
json_path: &JsonPath,
instance: &Value,
) -> Result<(), ValidationErrorType> {
let full_pointer_path = format!("@@root#/{}", json_path.format_path());
let schema = json!({
REF_FIELD: full_pointer_path
});
let validator = Self::build_validator(options, &schema)?;
Self::do_validate(&validator, instance)
}
/// Validates a JSON instance against a JSON schema.
///
/// This function takes a JSON schema and an instance, builds a validator based on the provided options,
/// and performs validation of the instance against the schema.
///
/// # Arguments
///
/// * `options` - Configuration options for the validation process
/// * `schema` - The JSON schema to validate against
/// * `instance` - The JSON instance to be validated
/// * `section` - Indicates which part of the document is being validated (Specification or Payload)
///
/// # Returns
///
/// * `Ok(())` - If validation succeeds
/// * `Err(ValidationErrorType)` - If validation fails, containing details about the validation error
fn complex_validation_by_schema(
options: &ValidationOptions,
schema: &Value,
instance: &Value,
) -> Result<(), ValidationErrorType> {
let validator = Self::build_validator(options, schema)?;
Self::do_validate(&validator, instance)
}
/// Validates a JSON instance against a JSON Schema validator.
///
/// # Arguments
/// * `validator` - A reference to a JSON Schema validator that will perform the validation.
/// * `instance` - A reference to a JSON Value to be validated against the schema.
/// * `section` - The section of the document where the validation is taking place, used in error reporting.
///
/// # Returns
/// * `Ok(())` - If the validation passes.
/// * `Err(ValidationErrorType::SchemaValidationFailed)` - If validation fails, containing the error message and section where the failure occurred.
fn do_validate(
validator: &jsonschema::Validator,
instance: &Value,
) -> Result<(), ValidationErrorType> {
match validator.validate(instance) {
Ok(_) => Ok(()),
Err(e) => Err(ValidationErrorType::schema_validation_failed(
e,
&format!("Instance {} failed validation", instance.to_string()),
)),
}
}
/// Builds a JSON schema validator using the provided validation options and schema.
///
/// # Arguments
///
/// * `validation_options` - The validation options that configure how the schema validation should be performed
/// * `schema` - The JSON schema used for validation, represented as a serde_json Value
///
/// # Returns
///
/// * `Ok(JsonValidator)` - A successfully built JSON validator
/// * `Err(ValidationErrorType::SchemaValidationFailed)` - If the schema validation fails during validator construction
fn build_validator<'a>(
validation_options: &ValidationOptions,
schema: &Value,
) -> Result<JsonValidator, ValidationErrorType> {
let validator = match validation_options.build(&schema) {
Ok(val) => val,
Err(e) => {
return Err(ValidationErrorType::schema_validation_failed(
e,
&format!(
"Failed to build validator for schema {}",
schema.to_string()
),
));
}
};
Ok(validator)
}
}
#[cfg(test)]
mod test {
use super::*;
use http::{HeaderMap, HeaderValue, Method, Request, Uri};
use serde_json::json;
// Helper function to create a validator for testing
fn create_test_validator() -> OpenApiPayloadValidator {
// Create a minimal OpenAPI spec for testing
let spec = json!({
"openapi": "3.0.0",
"info": {
"title": "Test API",
"version": "1.0.0"
},
"paths": {
"/test": {
"get": {
"parameters": [
{
"name": "required_header",
"in": "header",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "optional_query",
"in": "query",
"required": false,
"schema": {
"type": "string",
"minLength": 3,
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["name"],
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" }
}
}
}
}
},
"security": [
{
"oauth2": ["read", "write"]
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
});
OpenApiPayloadValidator::new(spec).unwrap()
}
#[test]
fn test_validate_valid_request() {
let validator = create_test_validator();
let mut headers = HeaderMap::new();
headers.insert("required_header", HeaderValue::from_static("value"));
headers.insert("content-type", HeaderValue::from_static("application/json"));
let body = json!({
"name": "Test User",
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query("/test?optional_query=value")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("required_header", "value")
.header("content-type", "application/json")
.body(body)
.unwrap();
let scopes = vec!["read".to_string(), "write".to_string()];
let result = validator.validate_request(&request, Some(&scopes));
assert!(result.is_ok());
}
#[test]
fn test_invalid_request_body() {
let validator = create_test_validator();
let mut headers = HeaderMap::new();
headers.insert("required_header", HeaderValue::from_static("value"));
headers.insert("content-type", HeaderValue::from_static("application/json"));
let body = json!({
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query("/test")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("required_header", "value")
.header("content-type", "application/json")
.body(body)
.unwrap();
let result = validator.validate_request(&request, None);
assert!(result.is_err());
}
#[test]
fn test_missing_required_header() {
let validator = create_test_validator();
let body = json!({
"name": "Test User",
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query("/test")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("content-type", "application/json")
.body(body)
.unwrap();
let result = validator.validate_request(&request, None);
assert!(result.is_err());
}
#[test]
fn test_query_parameter_validation() {
let validator = create_test_validator();
let body = json!({
"name": "Test User",
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
// min length is set to 3, so this query parameter is invalid
.path_and_query("/test?optional_query=aa")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("required_header", "value")
.header("content-type", "application/json")
.body(body)
.unwrap();
let result = validator.validate_request(&request, None);
assert!(result.is_err());
}
#[test]
fn test_missing_scopes() {
let validator = create_test_validator();
let body = json!({
"name": "Test User",
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query("/test")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("required_header", "value")
.header("content-type", "application/json")
.body(body)
.unwrap();
let scopes = vec!["read".to_string()]; // Missing 'write' scope
let result = validator.validate_request(&request, Some(&scopes));
assert!(result.is_err());
}
#[test]
fn test_no_query_parameters() {
let validator = create_test_validator();
let body = json!({
"name": "Test User",
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query("/test")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("required_header", "value")
.header("content-type", "application/json")
.body(body)
.unwrap();
let scopes = vec!["read".to_string(), "write".to_string()];
let result = validator.validate_request(&request, Some(&scopes));
assert!(result.is_ok());
}
#[test]
fn test_no_scopes_provided() {
let validator = create_test_validator();
let body = json!({
"name": "Test User",
"age": 30
});
let uri = Uri::builder()
.scheme("https")
.authority("example.com")
.path_and_query("/test")
.build()
.unwrap();
let request = Request::builder()
.method(Method::GET)
.uri(uri)
.header("required_header", "value")
.header("content-type", "application/json")
.body(body)
.unwrap();
let result = validator.validate_request(&request, None);
assert!(result.is_ok());
}
}