spikard 0.3.6 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/LICENSE +1 -1
- data/README.md +674 -659
- data/ext/spikard_rb/Cargo.toml +17 -17
- data/ext/spikard_rb/extconf.rb +13 -10
- data/ext/spikard_rb/src/lib.rs +6 -6
- data/lib/spikard/app.rb +405 -386
- data/lib/spikard/background.rb +27 -27
- data/lib/spikard/config.rb +396 -396
- data/lib/spikard/converters.rb +13 -13
- data/lib/spikard/handler_wrapper.rb +113 -113
- data/lib/spikard/provide.rb +214 -214
- data/lib/spikard/response.rb +173 -173
- data/lib/spikard/schema.rb +243 -243
- data/lib/spikard/sse.rb +111 -111
- data/lib/spikard/streaming_response.rb +44 -44
- data/lib/spikard/testing.rb +256 -221
- data/lib/spikard/upload_file.rb +131 -131
- data/lib/spikard/version.rb +5 -5
- data/lib/spikard/websocket.rb +59 -59
- data/lib/spikard.rb +43 -43
- data/sig/spikard.rbs +366 -366
- data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
- data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
- data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
- data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
- data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
- data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
- data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
- data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
- data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
- data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
- data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
- data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
- data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
- data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
- data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
- data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
- data/vendor/crates/spikard-core/Cargo.toml +40 -40
- data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
- data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
- data/vendor/crates/spikard-core/src/debug.rs +127 -63
- data/vendor/crates/spikard-core/src/di/container.rs +702 -726
- data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
- data/vendor/crates/spikard-core/src/di/error.rs +118 -118
- data/vendor/crates/spikard-core/src/di/factory.rs +534 -538
- data/vendor/crates/spikard-core/src/di/graph.rs +506 -545
- data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
- data/vendor/crates/spikard-core/src/di/resolved.rs +405 -411
- data/vendor/crates/spikard-core/src/di/value.rs +281 -283
- data/vendor/crates/spikard-core/src/errors.rs +69 -39
- data/vendor/crates/spikard-core/src/http.rs +415 -153
- data/vendor/crates/spikard-core/src/lib.rs +29 -29
- data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -422
- data/vendor/crates/spikard-core/src/metadata.rs +389 -0
- data/vendor/crates/spikard-core/src/parameters.rs +2525 -722
- data/vendor/crates/spikard-core/src/problem.rs +344 -310
- data/vendor/crates/spikard-core/src/request_data.rs +1154 -189
- data/vendor/crates/spikard-core/src/router.rs +510 -249
- data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
- data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
- data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -0
- data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
- data/vendor/crates/spikard-http/Cargo.toml +62 -68
- data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
- data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
- data/vendor/crates/spikard-http/src/auth.rs +296 -247
- data/vendor/crates/spikard-http/src/background.rs +1860 -249
- data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
- data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
- data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
- data/vendor/crates/spikard-http/src/cors.rs +1005 -490
- data/vendor/crates/spikard-http/src/debug.rs +128 -63
- data/vendor/crates/spikard-http/src/di_handler.rs +1668 -423
- data/vendor/crates/spikard-http/src/handler_response.rs +901 -190
- data/vendor/crates/spikard-http/src/handler_trait.rs +838 -228
- data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -284
- data/vendor/crates/spikard-http/src/lib.rs +534 -529
- data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -149
- data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -428
- data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -285
- data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -86
- data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -147
- data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -287
- data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
- data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -190
- data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -308
- data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -195
- data/vendor/crates/spikard-http/src/query_parser.rs +793 -369
- data/vendor/crates/spikard-http/src/response.rs +720 -399
- data/vendor/crates/spikard-http/src/server/handler.rs +1650 -87
- data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -98
- data/vendor/crates/spikard-http/src/server/mod.rs +1593 -805
- data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -119
- data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -0
- data/vendor/crates/spikard-http/src/sse.rs +1409 -447
- data/vendor/crates/spikard-http/src/testing/form.rs +52 -14
- data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
- data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -285
- data/vendor/crates/spikard-http/src/testing.rs +406 -377
- data/vendor/crates/spikard-http/src/websocket.rs +1404 -324
- data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
- data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
- data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
- data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
- data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
- data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
- data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
- data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
- data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
- data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
- data/vendor/crates/spikard-rb/Cargo.toml +48 -42
- data/vendor/crates/spikard-rb/build.rs +199 -8
- data/vendor/crates/spikard-rb/src/background.rs +63 -63
- data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
- data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +285 -294
- data/vendor/crates/spikard-rb/src/conversion.rs +554 -453
- data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
- data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +375 -409
- data/vendor/crates/spikard-rb/src/handler.rs +618 -625
- data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
- data/vendor/crates/spikard-rb/src/lib.rs +1806 -2771
- data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -274
- data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
- data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -0
- data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
- data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
- data/vendor/crates/spikard-rb/src/server.rs +305 -283
- data/vendor/crates/spikard-rb/src/sse.rs +231 -231
- data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +538 -404
- data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
- data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +143 -143
- data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -0
- data/vendor/crates/spikard-rb/src/websocket.rs +377 -233
- metadata +60 -13
- data/vendor/crates/spikard-http/src/parameters.rs +0 -1
- data/vendor/crates/spikard-http/src/problem.rs +0 -1
- data/vendor/crates/spikard-http/src/router.rs +0 -1
- data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
- data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
- data/vendor/crates/spikard-http/src/validation.rs +0 -1
- data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
|
@@ -1,699 +1,457 @@
|
|
|
1
|
-
//! Request/response validation using JSON Schema
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
use
|
|
6
|
-
use
|
|
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
|
-
let
|
|
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
|
-
} else {
|
|
178
|
-
instance_path
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
vec!["body".to_string()]
|
|
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
|
-
"too_short".to_string(),
|
|
461
|
-
format!("List should have at least {} item after validation", min_items),
|
|
462
|
-
Some(ctx),
|
|
463
|
-
)
|
|
464
|
-
} else if schema_path_str.contains("/maxItems") {
|
|
465
|
-
let ctx = serde_json::json!({
|
|
466
|
-
"max_length": 1
|
|
467
|
-
});
|
|
468
|
-
(
|
|
469
|
-
"too_long".to_string(),
|
|
470
|
-
"List should have at most N items after validation".to_string(),
|
|
471
|
-
Some(ctx),
|
|
472
|
-
)
|
|
473
|
-
} else {
|
|
474
|
-
("validation_error".to_string(), err.to_string(), None)
|
|
475
|
-
};
|
|
476
|
-
|
|
477
|
-
ValidationErrorDetail {
|
|
478
|
-
error_type,
|
|
479
|
-
loc: loc_parts,
|
|
480
|
-
msg,
|
|
481
|
-
input: input_value,
|
|
482
|
-
ctx,
|
|
483
|
-
}
|
|
484
|
-
})
|
|
485
|
-
.collect();
|
|
486
|
-
|
|
487
|
-
debug_log_module!("validation", "Returning {} validation errors", errors.len());
|
|
488
|
-
for (i, error) in errors.iter().enumerate() {
|
|
489
|
-
debug_log_module!(
|
|
490
|
-
"validation",
|
|
491
|
-
" Error {}: type={}, loc={:?}, msg={}, input={}, ctx={:?}",
|
|
492
|
-
i,
|
|
493
|
-
error.error_type,
|
|
494
|
-
error.loc,
|
|
495
|
-
error.msg,
|
|
496
|
-
error.input,
|
|
497
|
-
error.ctx
|
|
498
|
-
);
|
|
499
|
-
}
|
|
500
|
-
#[allow(clippy::collapsible_if)]
|
|
501
|
-
if crate::debug::is_enabled() {
|
|
502
|
-
if let Ok(json_errors) = serde_json::to_value(&errors) {
|
|
503
|
-
if let Ok(json_str) = serde_json::to_string_pretty(&json_errors) {
|
|
504
|
-
debug_log_module!("validation", "Serialized errors:\n{}", json_str);
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
Err(ValidationError { errors })
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
/// Validate and parse JSON bytes
|
|
513
|
-
pub fn validate_json(&self, json_bytes: &[u8]) -> Result<Value, ValidationError> {
|
|
514
|
-
let value: Value = serde_json::from_slice(json_bytes).map_err(|e| ValidationError {
|
|
515
|
-
errors: vec![ValidationErrorDetail {
|
|
516
|
-
error_type: "json_parse_error".to_string(),
|
|
517
|
-
loc: vec!["body".to_string()],
|
|
518
|
-
msg: format!("Invalid JSON: {}", e),
|
|
519
|
-
input: Value::Null,
|
|
520
|
-
ctx: None,
|
|
521
|
-
}],
|
|
522
|
-
})?;
|
|
523
|
-
|
|
524
|
-
self.validate(&value)?;
|
|
525
|
-
|
|
526
|
-
Ok(value)
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/// Validation error containing one or more validation failures
|
|
531
|
-
#[derive(Debug, Clone)]
|
|
532
|
-
pub struct ValidationError {
|
|
533
|
-
pub errors: Vec<ValidationErrorDetail>,
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
/// Individual validation error detail (FastAPI-compatible format)
|
|
537
|
-
#[derive(Debug, Clone, serde::Serialize)]
|
|
538
|
-
pub struct ValidationErrorDetail {
|
|
539
|
-
#[serde(rename = "type")]
|
|
540
|
-
pub error_type: String,
|
|
541
|
-
pub loc: Vec<String>,
|
|
542
|
-
pub msg: String,
|
|
543
|
-
pub input: Value,
|
|
544
|
-
#[serde(skip_serializing_if = "Option::is_none")]
|
|
545
|
-
pub ctx: Option<Value>,
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
impl std::fmt::Display for ValidationError {
|
|
549
|
-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
550
|
-
write!(f, "Validation failed: {} errors", self.errors.len())
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
impl std::error::Error for ValidationError {}
|
|
555
|
-
|
|
556
|
-
#[cfg(test)]
|
|
557
|
-
mod tests {
|
|
558
|
-
use super::*;
|
|
559
|
-
use serde_json::json;
|
|
560
|
-
|
|
561
|
-
#[test]
|
|
562
|
-
fn test_validator_creation() {
|
|
563
|
-
let schema = json!({
|
|
564
|
-
"type": "object",
|
|
565
|
-
"properties": {
|
|
566
|
-
"name": {"type": "string"},
|
|
567
|
-
"age": {"type": "integer"}
|
|
568
|
-
},
|
|
569
|
-
"required": ["name"]
|
|
570
|
-
});
|
|
571
|
-
|
|
572
|
-
let validator = SchemaValidator::new(schema).unwrap();
|
|
573
|
-
assert!(validator.compiled.is_valid(&json!({"name": "Alice", "age": 30})));
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
#[test]
|
|
577
|
-
fn test_validation_success() {
|
|
578
|
-
let schema = json!({
|
|
579
|
-
"type": "object",
|
|
580
|
-
"properties": {
|
|
581
|
-
"email": {"type": "string", "format": "email"}
|
|
582
|
-
}
|
|
583
|
-
});
|
|
584
|
-
|
|
585
|
-
let validator = SchemaValidator::new(schema).unwrap();
|
|
586
|
-
let data = json!({"email": "test@example.com"});
|
|
587
|
-
|
|
588
|
-
assert!(validator.validate(&data).is_ok());
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
#[test]
|
|
592
|
-
fn test_validation_failure() {
|
|
593
|
-
let schema = json!({
|
|
594
|
-
"type": "object",
|
|
595
|
-
"properties": {
|
|
596
|
-
"age": {"type": "integer", "minimum": 0}
|
|
597
|
-
},
|
|
598
|
-
"required": ["age"]
|
|
599
|
-
});
|
|
600
|
-
|
|
601
|
-
let validator = SchemaValidator::new(schema).unwrap();
|
|
602
|
-
let data = json!({"age": -5});
|
|
603
|
-
|
|
604
|
-
assert!(validator.validate(&data).is_err());
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
#[test]
|
|
608
|
-
fn test_validation_error_serialization() {
|
|
609
|
-
let schema = json!({
|
|
610
|
-
"type": "object",
|
|
611
|
-
"properties": {
|
|
612
|
-
"name": {
|
|
613
|
-
"type": "string",
|
|
614
|
-
"maxLength": 10
|
|
615
|
-
}
|
|
616
|
-
},
|
|
617
|
-
"required": ["name"]
|
|
618
|
-
});
|
|
619
|
-
|
|
620
|
-
let validator = SchemaValidator::new(schema).unwrap();
|
|
621
|
-
let data = json!({"name": "this_is_way_too_long"});
|
|
622
|
-
|
|
623
|
-
let result = validator.validate(&data);
|
|
624
|
-
assert!(result.is_err());
|
|
625
|
-
|
|
626
|
-
let err = result.unwrap_err();
|
|
627
|
-
assert_eq!(err.errors.len(), 1);
|
|
628
|
-
|
|
629
|
-
let error_detail = &err.errors[0];
|
|
630
|
-
assert_eq!(error_detail.error_type, "string_too_long");
|
|
631
|
-
assert_eq!(error_detail.loc, vec!["body", "name"]);
|
|
632
|
-
assert_eq!(error_detail.msg, "String should have at most 10 characters");
|
|
633
|
-
assert_eq!(error_detail.input, Value::String("this_is_way_too_long".to_string()));
|
|
634
|
-
assert_eq!(error_detail.ctx, Some(json!({"max_length": 10})));
|
|
635
|
-
|
|
636
|
-
let json_output = serde_json::to_value(&err.errors).unwrap();
|
|
637
|
-
println!(
|
|
638
|
-
"Serialized JSON: {}",
|
|
639
|
-
serde_json::to_string_pretty(&json_output).unwrap()
|
|
640
|
-
);
|
|
641
|
-
|
|
642
|
-
let serialized_error = &json_output[0];
|
|
643
|
-
assert!(serialized_error.get("type").is_some());
|
|
644
|
-
assert!(serialized_error.get("loc").is_some());
|
|
645
|
-
assert!(serialized_error.get("msg").is_some());
|
|
646
|
-
assert!(
|
|
647
|
-
serialized_error.get("input").is_some(),
|
|
648
|
-
"Missing 'input' field in serialized JSON!"
|
|
649
|
-
);
|
|
650
|
-
assert!(
|
|
651
|
-
serialized_error.get("ctx").is_some(),
|
|
652
|
-
"Missing 'ctx' field in serialized JSON!"
|
|
653
|
-
);
|
|
654
|
-
|
|
655
|
-
assert_eq!(
|
|
656
|
-
serialized_error["input"],
|
|
657
|
-
Value::String("this_is_way_too_long".to_string())
|
|
658
|
-
);
|
|
659
|
-
assert_eq!(serialized_error["ctx"], json!({"max_length": 10}));
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
#[test]
|
|
663
|
-
fn test_exclusive_minimum() {
|
|
664
|
-
let schema = json!({
|
|
665
|
-
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
666
|
-
"type": "object",
|
|
667
|
-
"required": ["id", "name", "price"],
|
|
668
|
-
"properties": {
|
|
669
|
-
"id": {
|
|
670
|
-
"type": "integer"
|
|
671
|
-
},
|
|
672
|
-
"name": {
|
|
673
|
-
"type": "string",
|
|
674
|
-
"minLength": 3
|
|
675
|
-
},
|
|
676
|
-
"price": {
|
|
677
|
-
"type": "number",
|
|
678
|
-
"exclusiveMinimum": 0
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
});
|
|
682
|
-
|
|
683
|
-
let validator = SchemaValidator::new(schema).unwrap();
|
|
684
|
-
|
|
685
|
-
let data = json!({
|
|
686
|
-
"id": 1,
|
|
687
|
-
"name": "X",
|
|
688
|
-
"price": -10
|
|
689
|
-
});
|
|
690
|
-
|
|
691
|
-
let result = validator.validate(&data);
|
|
692
|
-
eprintln!("Validation result: {:?}", result);
|
|
693
|
-
|
|
694
|
-
assert!(result.is_err(), "Should have validation errors");
|
|
695
|
-
let err = result.unwrap_err();
|
|
696
|
-
eprintln!("Errors: {:?}", err.errors);
|
|
697
|
-
assert_eq!(err.errors.len(), 2, "Should have 2 errors");
|
|
698
|
-
}
|
|
699
|
-
}
|
|
1
|
+
//! Request/response validation using JSON Schema
|
|
2
|
+
|
|
3
|
+
pub mod error_mapper;
|
|
4
|
+
|
|
5
|
+
use crate::debug_log_module;
|
|
6
|
+
use jsonschema::Validator;
|
|
7
|
+
use serde_json::Value;
|
|
8
|
+
use std::sync::Arc;
|
|
9
|
+
|
|
10
|
+
use self::error_mapper::{ErrorCondition, ErrorMapper};
|
|
11
|
+
|
|
12
|
+
/// Schema validator that compiles and validates JSON Schema
|
|
13
|
+
#[derive(Clone)]
|
|
14
|
+
pub struct SchemaValidator {
|
|
15
|
+
compiled: Arc<Validator>,
|
|
16
|
+
schema: Value,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
impl SchemaValidator {
|
|
20
|
+
/// Create a new validator from a JSON Schema
|
|
21
|
+
pub fn new(schema: Value) -> Result<Self, String> {
|
|
22
|
+
let compiled = jsonschema::options()
|
|
23
|
+
.with_draft(jsonschema::Draft::Draft202012)
|
|
24
|
+
.should_validate_formats(true)
|
|
25
|
+
.with_pattern_options(jsonschema::PatternOptions::regex())
|
|
26
|
+
.build(&schema)
|
|
27
|
+
.map_err(|e| {
|
|
28
|
+
anyhow::anyhow!("Invalid JSON Schema")
|
|
29
|
+
.context(format!("Schema compilation failed: {}", e))
|
|
30
|
+
.to_string()
|
|
31
|
+
})?;
|
|
32
|
+
|
|
33
|
+
Ok(Self {
|
|
34
|
+
compiled: Arc::new(compiled),
|
|
35
|
+
schema,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Get the underlying JSON Schema
|
|
40
|
+
pub fn schema(&self) -> &Value {
|
|
41
|
+
&self.schema
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Pre-process data to convert file objects to strings for format: "binary" validation
|
|
45
|
+
///
|
|
46
|
+
/// Files uploaded via multipart are converted to objects like:
|
|
47
|
+
/// {"filename": "...", "size": N, "content": "...", "content_type": "..."}
|
|
48
|
+
///
|
|
49
|
+
/// But schemas define them as: {"type": "string", "format": "binary"}
|
|
50
|
+
///
|
|
51
|
+
/// This method recursively processes the data and converts file objects to their content strings
|
|
52
|
+
/// so that validation passes, while preserving the original structure for handlers to use.
|
|
53
|
+
fn preprocess_binary_fields(&self, data: &Value) -> Value {
|
|
54
|
+
self.preprocess_value_with_schema(data, &self.schema)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
#[allow(clippy::only_used_in_recursion)]
|
|
58
|
+
fn preprocess_value_with_schema(&self, data: &Value, schema: &Value) -> Value {
|
|
59
|
+
if let Some(schema_obj) = schema.as_object() {
|
|
60
|
+
let is_string_type = schema_obj.get("type").and_then(|t| t.as_str()) == Some("string");
|
|
61
|
+
let is_binary_format = schema_obj.get("format").and_then(|f| f.as_str()) == Some("binary");
|
|
62
|
+
|
|
63
|
+
#[allow(clippy::collapsible_if)]
|
|
64
|
+
if is_string_type && is_binary_format {
|
|
65
|
+
if let Some(data_obj) = data.as_object() {
|
|
66
|
+
if data_obj.contains_key("filename")
|
|
67
|
+
&& data_obj.contains_key("content")
|
|
68
|
+
&& data_obj.contains_key("size")
|
|
69
|
+
&& data_obj.contains_key("content_type")
|
|
70
|
+
{
|
|
71
|
+
return data_obj.get("content").unwrap_or(&Value::Null).clone();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return data.clone();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
#[allow(clippy::collapsible_if)]
|
|
78
|
+
if schema_obj.get("type").and_then(|t| t.as_str()) == Some("array") {
|
|
79
|
+
if let Some(items_schema) = schema_obj.get("items") {
|
|
80
|
+
if let Some(data_array) = data.as_array() {
|
|
81
|
+
let processed_array: Vec<Value> = data_array
|
|
82
|
+
.iter()
|
|
83
|
+
.map(|item| self.preprocess_value_with_schema(item, items_schema))
|
|
84
|
+
.collect();
|
|
85
|
+
return Value::Array(processed_array);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#[allow(clippy::collapsible_if)]
|
|
91
|
+
if schema_obj.get("type").and_then(|t| t.as_str()) == Some("object") {
|
|
92
|
+
if let Some(properties) = schema_obj.get("properties").and_then(|p| p.as_object()) {
|
|
93
|
+
if let Some(data_obj) = data.as_object() {
|
|
94
|
+
let mut processed_obj = serde_json::Map::new();
|
|
95
|
+
for (key, value) in data_obj {
|
|
96
|
+
if let Some(prop_schema) = properties.get(key) {
|
|
97
|
+
processed_obj
|
|
98
|
+
.insert(key.clone(), self.preprocess_value_with_schema(value, prop_schema));
|
|
99
|
+
} else {
|
|
100
|
+
processed_obj.insert(key.clone(), value.clone());
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return Value::Object(processed_obj);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
data.clone()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Validate JSON data against the schema
|
|
113
|
+
pub fn validate(&self, data: &Value) -> Result<(), ValidationError> {
|
|
114
|
+
let processed_data = self.preprocess_binary_fields(data);
|
|
115
|
+
|
|
116
|
+
let validation_errors: Vec<_> = self.compiled.iter_errors(&processed_data).collect();
|
|
117
|
+
|
|
118
|
+
if validation_errors.is_empty() {
|
|
119
|
+
return Ok(());
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let errors: Vec<ValidationErrorDetail> = validation_errors
|
|
123
|
+
.into_iter()
|
|
124
|
+
.map(|err| {
|
|
125
|
+
let instance_path = err.instance_path().to_string();
|
|
126
|
+
let schema_path_str = err.schema_path().as_str();
|
|
127
|
+
let error_msg = err.to_string();
|
|
128
|
+
|
|
129
|
+
let param_name = if schema_path_str.ends_with("/required") {
|
|
130
|
+
let field_name = if let Some(start) = error_msg.find('"') {
|
|
131
|
+
if let Some(end) = error_msg[start + 1..].find('"') {
|
|
132
|
+
error_msg[start + 1..start + 1 + end].to_string()
|
|
133
|
+
} else {
|
|
134
|
+
"".to_string()
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
"".to_string()
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
if !instance_path.is_empty() && instance_path.starts_with('/') && instance_path.len() > 1 {
|
|
141
|
+
let base_path = &instance_path[1..];
|
|
142
|
+
if !field_name.is_empty() {
|
|
143
|
+
format!("{}/{}", base_path, field_name)
|
|
144
|
+
} else {
|
|
145
|
+
base_path.to_string()
|
|
146
|
+
}
|
|
147
|
+
} else if !field_name.is_empty() {
|
|
148
|
+
field_name
|
|
149
|
+
} else {
|
|
150
|
+
"body".to_string()
|
|
151
|
+
}
|
|
152
|
+
} else if schema_path_str.contains("/additionalProperties") {
|
|
153
|
+
if let Some(start) = error_msg.find('(') {
|
|
154
|
+
if let Some(quote_start) = error_msg[start..].find('\'') {
|
|
155
|
+
let abs_start = start + quote_start + 1;
|
|
156
|
+
if let Some(quote_end) = error_msg[abs_start..].find('\'') {
|
|
157
|
+
let property_name = error_msg[abs_start..abs_start + quote_end].to_string();
|
|
158
|
+
if !instance_path.is_empty()
|
|
159
|
+
&& instance_path.starts_with('/')
|
|
160
|
+
&& instance_path.len() > 1
|
|
161
|
+
{
|
|
162
|
+
format!("{}/{}", &instance_path[1..], property_name)
|
|
163
|
+
} else {
|
|
164
|
+
property_name
|
|
165
|
+
}
|
|
166
|
+
} else {
|
|
167
|
+
instance_path[1..].to_string()
|
|
168
|
+
}
|
|
169
|
+
} else {
|
|
170
|
+
instance_path[1..].to_string()
|
|
171
|
+
}
|
|
172
|
+
} else if instance_path.starts_with('/') && instance_path.len() > 1 {
|
|
173
|
+
instance_path[1..].to_string()
|
|
174
|
+
} else {
|
|
175
|
+
"body".to_string()
|
|
176
|
+
}
|
|
177
|
+
} else if instance_path.starts_with('/') && instance_path.len() > 1 {
|
|
178
|
+
instance_path[1..].to_string()
|
|
179
|
+
} else if instance_path.is_empty() {
|
|
180
|
+
"body".to_string()
|
|
181
|
+
} else {
|
|
182
|
+
instance_path
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
let loc_parts: Vec<String> = if param_name.contains('/') {
|
|
186
|
+
let mut parts = vec!["body".to_string()];
|
|
187
|
+
parts.extend(param_name.split('/').map(|s| s.to_string()));
|
|
188
|
+
parts
|
|
189
|
+
} else if param_name == "body" {
|
|
190
|
+
vec!["body".to_string()]
|
|
191
|
+
} else {
|
|
192
|
+
vec!["body".to_string(), param_name.clone()]
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
let input_value = if schema_path_str == "/required" {
|
|
196
|
+
data.clone()
|
|
197
|
+
} else {
|
|
198
|
+
err.instance().clone().into_owned()
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
let schema_prop_path = if param_name.contains('/') {
|
|
202
|
+
format!("/properties/{}", param_name.replace('/', "/properties/"))
|
|
203
|
+
} else {
|
|
204
|
+
format!("/properties/{}", param_name)
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
let mut error_condition = ErrorCondition::from_schema_error(schema_path_str, &error_msg);
|
|
208
|
+
|
|
209
|
+
error_condition = match error_condition {
|
|
210
|
+
ErrorCondition::TypeMismatch { .. } => {
|
|
211
|
+
let expected_type = self
|
|
212
|
+
.schema
|
|
213
|
+
.pointer(&format!("{}/type", schema_prop_path))
|
|
214
|
+
.and_then(|v| v.as_str())
|
|
215
|
+
.unwrap_or("unknown")
|
|
216
|
+
.to_string();
|
|
217
|
+
ErrorCondition::TypeMismatch { expected_type }
|
|
218
|
+
}
|
|
219
|
+
ErrorCondition::AdditionalProperties { .. } => {
|
|
220
|
+
let unexpected_field = if param_name.contains('/') {
|
|
221
|
+
param_name.split('/').next_back().unwrap_or(¶m_name).to_string()
|
|
222
|
+
} else {
|
|
223
|
+
param_name.clone()
|
|
224
|
+
};
|
|
225
|
+
ErrorCondition::AdditionalProperties {
|
|
226
|
+
field: unexpected_field,
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
other => other,
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
let (error_type, msg, ctx) =
|
|
233
|
+
ErrorMapper::map_error(&error_condition, &self.schema, &schema_prop_path, &error_msg);
|
|
234
|
+
|
|
235
|
+
ValidationErrorDetail {
|
|
236
|
+
error_type,
|
|
237
|
+
loc: loc_parts,
|
|
238
|
+
msg,
|
|
239
|
+
input: input_value,
|
|
240
|
+
ctx,
|
|
241
|
+
}
|
|
242
|
+
})
|
|
243
|
+
.collect();
|
|
244
|
+
|
|
245
|
+
debug_log_module!("validation", "Returning {} validation errors", errors.len());
|
|
246
|
+
for (i, error) in errors.iter().enumerate() {
|
|
247
|
+
debug_log_module!(
|
|
248
|
+
"validation",
|
|
249
|
+
" Error {}: type={}, loc={:?}, msg={}, input={}, ctx={:?}",
|
|
250
|
+
i,
|
|
251
|
+
error.error_type,
|
|
252
|
+
error.loc,
|
|
253
|
+
error.msg,
|
|
254
|
+
error.input,
|
|
255
|
+
error.ctx
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
#[allow(clippy::collapsible_if)]
|
|
259
|
+
if crate::debug::is_enabled() {
|
|
260
|
+
if let Ok(json_errors) = serde_json::to_value(&errors) {
|
|
261
|
+
if let Ok(json_str) = serde_json::to_string_pretty(&json_errors) {
|
|
262
|
+
debug_log_module!("validation", "Serialized errors:\n{}", json_str);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
Err(ValidationError { errors })
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/// Validate and parse JSON bytes
|
|
271
|
+
pub fn validate_json(&self, json_bytes: &[u8]) -> Result<Value, ValidationError> {
|
|
272
|
+
let value: Value = serde_json::from_slice(json_bytes).map_err(|e| ValidationError {
|
|
273
|
+
errors: vec![ValidationErrorDetail {
|
|
274
|
+
error_type: "json_parse_error".to_string(),
|
|
275
|
+
loc: vec!["body".to_string()],
|
|
276
|
+
msg: format!("Invalid JSON: {}", e),
|
|
277
|
+
input: Value::Null,
|
|
278
|
+
ctx: None,
|
|
279
|
+
}],
|
|
280
|
+
})?;
|
|
281
|
+
|
|
282
|
+
self.validate(&value)?;
|
|
283
|
+
|
|
284
|
+
Ok(value)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/// Validation error containing one or more validation failures
|
|
289
|
+
#[derive(Debug, Clone)]
|
|
290
|
+
pub struct ValidationError {
|
|
291
|
+
pub errors: Vec<ValidationErrorDetail>,
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/// Individual validation error detail (FastAPI-compatible format)
|
|
295
|
+
#[derive(Debug, Clone, serde::Serialize)]
|
|
296
|
+
pub struct ValidationErrorDetail {
|
|
297
|
+
#[serde(rename = "type")]
|
|
298
|
+
pub error_type: String,
|
|
299
|
+
pub loc: Vec<String>,
|
|
300
|
+
pub msg: String,
|
|
301
|
+
pub input: Value,
|
|
302
|
+
#[serde(skip_serializing_if = "Option::is_none")]
|
|
303
|
+
pub ctx: Option<Value>,
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
impl std::fmt::Display for ValidationError {
|
|
307
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
308
|
+
write!(f, "Validation failed: {} errors", self.errors.len())
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
impl std::error::Error for ValidationError {}
|
|
313
|
+
|
|
314
|
+
#[cfg(test)]
|
|
315
|
+
mod tests {
|
|
316
|
+
use super::*;
|
|
317
|
+
use serde_json::json;
|
|
318
|
+
|
|
319
|
+
#[test]
|
|
320
|
+
fn test_validator_creation() {
|
|
321
|
+
let schema = json!({
|
|
322
|
+
"type": "object",
|
|
323
|
+
"properties": {
|
|
324
|
+
"name": {"type": "string"},
|
|
325
|
+
"age": {"type": "integer"}
|
|
326
|
+
},
|
|
327
|
+
"required": ["name"]
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
let validator = SchemaValidator::new(schema).unwrap();
|
|
331
|
+
assert!(validator.compiled.is_valid(&json!({"name": "Alice", "age": 30})));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
#[test]
|
|
335
|
+
fn test_validation_success() {
|
|
336
|
+
let schema = json!({
|
|
337
|
+
"type": "object",
|
|
338
|
+
"properties": {
|
|
339
|
+
"email": {"type": "string", "format": "email"}
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
let validator = SchemaValidator::new(schema).unwrap();
|
|
344
|
+
let data = json!({"email": "test@example.com"});
|
|
345
|
+
|
|
346
|
+
assert!(validator.validate(&data).is_ok());
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
#[test]
|
|
350
|
+
fn test_validation_failure() {
|
|
351
|
+
let schema = json!({
|
|
352
|
+
"type": "object",
|
|
353
|
+
"properties": {
|
|
354
|
+
"age": {"type": "integer", "minimum": 0}
|
|
355
|
+
},
|
|
356
|
+
"required": ["age"]
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
let validator = SchemaValidator::new(schema).unwrap();
|
|
360
|
+
let data = json!({"age": -5});
|
|
361
|
+
|
|
362
|
+
assert!(validator.validate(&data).is_err());
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
#[test]
|
|
366
|
+
fn test_validation_error_serialization() {
|
|
367
|
+
let schema = json!({
|
|
368
|
+
"type": "object",
|
|
369
|
+
"properties": {
|
|
370
|
+
"name": {
|
|
371
|
+
"type": "string",
|
|
372
|
+
"maxLength": 10
|
|
373
|
+
}
|
|
374
|
+
},
|
|
375
|
+
"required": ["name"]
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
let validator = SchemaValidator::new(schema).unwrap();
|
|
379
|
+
let data = json!({"name": "this_is_way_too_long"});
|
|
380
|
+
|
|
381
|
+
let result = validator.validate(&data);
|
|
382
|
+
assert!(result.is_err());
|
|
383
|
+
|
|
384
|
+
let err = result.unwrap_err();
|
|
385
|
+
assert_eq!(err.errors.len(), 1);
|
|
386
|
+
|
|
387
|
+
let error_detail = &err.errors[0];
|
|
388
|
+
assert_eq!(error_detail.error_type, "string_too_long");
|
|
389
|
+
assert_eq!(error_detail.loc, vec!["body", "name"]);
|
|
390
|
+
assert_eq!(error_detail.msg, "String should have at most 10 characters");
|
|
391
|
+
assert_eq!(error_detail.input, Value::String("this_is_way_too_long".to_string()));
|
|
392
|
+
assert_eq!(error_detail.ctx, Some(json!({"max_length": 10})));
|
|
393
|
+
|
|
394
|
+
let json_output = serde_json::to_value(&err.errors).unwrap();
|
|
395
|
+
println!(
|
|
396
|
+
"Serialized JSON: {}",
|
|
397
|
+
serde_json::to_string_pretty(&json_output).unwrap()
|
|
398
|
+
);
|
|
399
|
+
|
|
400
|
+
let serialized_error = &json_output[0];
|
|
401
|
+
assert!(serialized_error.get("type").is_some());
|
|
402
|
+
assert!(serialized_error.get("loc").is_some());
|
|
403
|
+
assert!(serialized_error.get("msg").is_some());
|
|
404
|
+
assert!(
|
|
405
|
+
serialized_error.get("input").is_some(),
|
|
406
|
+
"Missing 'input' field in serialized JSON!"
|
|
407
|
+
);
|
|
408
|
+
assert!(
|
|
409
|
+
serialized_error.get("ctx").is_some(),
|
|
410
|
+
"Missing 'ctx' field in serialized JSON!"
|
|
411
|
+
);
|
|
412
|
+
|
|
413
|
+
assert_eq!(
|
|
414
|
+
serialized_error["input"],
|
|
415
|
+
Value::String("this_is_way_too_long".to_string())
|
|
416
|
+
);
|
|
417
|
+
assert_eq!(serialized_error["ctx"], json!({"max_length": 10}));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
#[test]
|
|
421
|
+
fn test_exclusive_minimum() {
|
|
422
|
+
let schema = json!({
|
|
423
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
424
|
+
"type": "object",
|
|
425
|
+
"required": ["id", "name", "price"],
|
|
426
|
+
"properties": {
|
|
427
|
+
"id": {
|
|
428
|
+
"type": "integer"
|
|
429
|
+
},
|
|
430
|
+
"name": {
|
|
431
|
+
"type": "string",
|
|
432
|
+
"minLength": 3
|
|
433
|
+
},
|
|
434
|
+
"price": {
|
|
435
|
+
"type": "number",
|
|
436
|
+
"exclusiveMinimum": 0
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
let validator = SchemaValidator::new(schema).unwrap();
|
|
442
|
+
|
|
443
|
+
let data = json!({
|
|
444
|
+
"id": 1,
|
|
445
|
+
"name": "X",
|
|
446
|
+
"price": -10
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
let result = validator.validate(&data);
|
|
450
|
+
eprintln!("Validation result: {:?}", result);
|
|
451
|
+
|
|
452
|
+
assert!(result.is_err(), "Should have validation errors");
|
|
453
|
+
let err = result.unwrap_err();
|
|
454
|
+
eprintln!("Errors: {:?}", err.errors);
|
|
455
|
+
assert_eq!(err.errors.len(), 2, "Should have 2 errors");
|
|
456
|
+
}
|
|
457
|
+
}
|