Coverage for fastblocks / _validation_integration.py: 22%
359 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Oneiric Validation Service integration for FastBlocks.
3This module provides validation capabilities using Oneiric-compatible validation,
4with custom implementations for sanitization and validation.
6Author: lesleslie <les@wedgwoodwebworks.com>
7Created: 2025-10-01
9Key Features:
10- Template context validation and sanitization
11- Form input validation with XSS prevention
12- API contract validation for endpoints
13- Custom validation schemas for FastBlocks patterns
14- Decorators for automatic validation
15- Oneiric-compatible dependency injection
17Usage:
18 # Template context validation
19 @validate_template_context
20 async def render_template(request, template, context):
21 ...
23 # Form input validation and sanitization
24 @validate_form_input
25 async def handle_form_submit(request, form_data):
26 ...
28 # API contract validation
29 @validate_api_contract(request_schema=UserCreateSchema, response_schema=UserSchema)
30 async def create_user(request):
31 ...
32"""
34import functools
35import typing as t
36from contextlib import suppress
37from dataclasses import dataclass
38from enum import Enum
40# Oneiric imports for dependency injection
41from oneiric.core.resolution import Resolver
42from fastblocks.adapters.oneiric_helper import register_candidate
44# Custom Oneiric-compatible validation system
45depends = Resolver()
48# Validation system availability
49oneiric_validation_available = True
52# Custom Oneiric-compatible Validation System
53class InputSanitizer:
54 """Simple HTML sanitizer for XSS prevention."""
56 def sanitize_html(self, value: str) -> str:
57 """Sanitize HTML content to prevent XSS attacks."""
58 import html
60 # Basic HTML escaping
61 sanitized = html.escape(value)
63 # Remove script tags and event handlers
64 sanitized = sanitized.replace("javascript:", "")
65 sanitized = sanitized.replace("onerror=", "")
66 sanitized = sanitized.replace("onclick=", "")
68 return sanitized
71class OutputValidator:
72 """Simple output validator for data validation."""
74 def validate(self, data: dict[str, t.Any], schema: dict[str, t.Any]) -> bool:
75 """Validate data against a schema."""
76 # Simple validation - would be enhanced in production
77 return True
80class ValidationService:
81 """Simple validation service for Oneiric-compatible validation."""
83 def __init__(self):
84 self.sanitizer = InputSanitizer()
85 self.validator = OutputValidator()
88class ValidationType(str, Enum):
89 """Types of validation performed by FastBlocks."""
91 TEMPLATE_CONTEXT = "template_context"
92 FORM_INPUT = "form_input"
93 API_REQUEST = "api_request"
94 API_RESPONSE = "api_response"
95 ROUTE_PARAMS = "route_params"
96 QUERY_PARAMS = "query_params"
99@dataclass
100class ValidationConfig:
101 """Configuration for FastBlocks validation integration."""
103 # Enable/disable specific validation types
104 validate_templates: bool = True
105 validate_forms: bool = True
106 validate_api: bool = True
108 # Security settings
109 prevent_xss: bool = True
110 prevent_sql_injection: bool = True
111 prevent_path_traversal: bool = True
113 # Performance settings
114 cache_validation_results: bool = True
115 validation_timeout_ms: float = 100.0
117 # Reporting
118 collect_validation_metrics: bool = True
119 log_validation_failures: bool = True
122class FastBlocksValidationService:
123 """FastBlocks validation service with Oneiric integration."""
125 _instance: t.ClassVar["FastBlocksValidationService | None"] = None
126 _config: t.ClassVar[ValidationConfig] = ValidationConfig()
128 def __new__(cls) -> "FastBlocksValidationService":
129 """Singleton pattern - ensure only one instance exists."""
130 if cls._instance is None:
131 cls._instance = super().__new__(cls)
132 return cls._instance
134 def __init__(self) -> None:
135 """Initialize validation service with Oneiric integration."""
136 if not hasattr(self, "_initialized"):
137 self._service = ValidationService() # Oneiric-compatible validation service
138 self._sanitizer = self._service.sanitizer
139 self._validator = self._service.validator
140 self._initialized = True
142 @property
143 def available(self) -> bool:
144 """Check if validation service is available."""
145 return True # Always available with Oneiric
147 def _sanitize_context_value(
148 self,
149 key: str,
150 value: t.Any,
151 errors: list[str],
152 ) -> t.Any:
153 """Sanitize a single context value.
155 Args:
156 key: Context key
157 value: Context value
158 errors: Error list to append to
160 Returns:
161 Sanitized value
162 """
163 # Skip non-string values (they're safe)
164 if not isinstance(value, str):
165 return value
167 # Sanitize string values for XSS
168 if self._config.prevent_xss and self._sanitizer:
169 try:
170 return self._sanitizer.sanitize_html(value)
171 except Exception as e:
172 errors.append(f"Failed to sanitize {key}: {e}")
173 return value
175 return value
177 def _check_sql_injection_in_context(
178 self,
179 sanitized: dict[str, t.Any],
180 errors: list[str],
181 strict: bool,
182 ) -> bool:
183 """Check for SQL injection patterns in sanitized context.
185 Args:
186 sanitized: Sanitized context data
187 errors: Error list to append to
188 strict: If True, return False immediately on finding issues
190 Returns:
191 False if strict and issues found, True otherwise
192 """
193 if not self._config.prevent_sql_injection:
194 return True
196 for key, value in sanitized.items():
197 if isinstance(value, str) and self._contains_sql_injection(value):
198 errors.append(f"Potential SQL injection in {key}")
199 if strict:
200 return False
202 return True
204 async def validate_template_context(
205 self,
206 context: dict[str, t.Any],
207 template_name: str,
208 strict: bool = False,
209 ) -> tuple[bool, dict[str, t.Any], list[str]]:
210 """Validate and sanitize template context data.
212 Args:
213 context: Template context dictionary
214 template_name: Name of the template being rendered
215 strict: If True, fail on any validation warnings
217 Returns:
218 Tuple of (is_valid, sanitized_context, error_messages)
219 """
220 # Guard clause: skip if validation disabled
221 if not self._config.validate_templates:
222 return True, context, []
224 errors: list[str] = []
226 try:
227 # Sanitize each context value
228 sanitized = {
229 key: self._sanitize_context_value(key, value, errors)
230 for key, value in context.items()
231 }
233 # Check for SQL injection patterns
234 if not self._check_sql_injection_in_context(sanitized, errors, strict):
235 return False, context, errors
237 # Validation passed (or warnings only)
238 return len(errors) == 0 or not strict, sanitized, errors
240 except Exception as e:
241 errors.append(f"Validation error: {e}")
242 return False, context, errors
244 async def validate_form_input(
245 self,
246 form_data: dict[str, t.Any],
247 schema: dict[str, t.Any] | None = None,
248 strict: bool = True,
249 ) -> tuple[bool, dict[str, t.Any], list[str]]:
250 """Validate and sanitize form input data.
252 Args:
253 form_data: Form data to validate
254 schema: Optional validation schema (field_name -> rules)
255 strict: If True, fail on any validation errors
257 Returns:
258 Tuple of (is_valid, sanitized_data, error_messages)
259 """
260 # Guard clause: skip if validation disabled
261 if not self._config.validate_forms:
262 return True, form_data, []
264 errors: list[str] = []
266 try:
267 # Sanitize and validate fields
268 sanitized = self._sanitize_form_fields(form_data, errors)
270 # Apply schema validation if provided
271 if schema:
272 self._apply_schema_validation(sanitized, schema, errors)
274 return len(errors) == 0, sanitized, errors
276 except Exception as e:
277 errors.append(f"Validation error: {e}")
278 return False, form_data, errors
280 def _sanitize_form_fields(
281 self,
282 form_data: dict[str, t.Any],
283 errors: list[str],
284 ) -> dict[str, t.Any]:
285 """Sanitize all form fields and perform security checks.
287 Args:
288 form_data: Raw form data
289 errors: Error list to append to
291 Returns:
292 Sanitized form data
293 """
294 sanitized = {}
296 for key, value in form_data.items():
297 sanitized[key] = self._sanitize_field(key, value, errors)
299 # Security checks for string values
300 if isinstance(value, str):
301 self._check_security_issues(key, value, errors)
303 return sanitized
305 def _apply_schema_validation(
306 self,
307 sanitized_data: dict[str, t.Any],
308 schema: dict[str, t.Any],
309 errors: list[str],
310 ) -> None:
311 """Apply schema validation rules to sanitized data.
313 Args:
314 sanitized_data: Sanitized form data
315 schema: Validation schema (field_name -> rules)
316 errors: Error list to append to
317 """
318 for field_name, rules in schema.items():
319 value = sanitized_data.get(field_name)
320 self._validate_field_schema(field_name, value, rules, errors)
322 async def validate_api_request(
323 self,
324 request_data: dict[str, t.Any],
325 schema: t.Any = None,
326 ) -> tuple[bool, dict[str, t.Any], list[str]]:
327 """Validate API request data against a schema.
329 Args:
330 request_data: Request data to validate
331 schema: Validation schema (Pydantic, msgspec, etc.)
333 Returns:
334 Tuple of (is_valid, validated_data, error_messages)
335 """
336 # Guard clause: skip if disabled
337 if not self._config.validate_api:
338 return True, request_data, []
340 errors: list[str] = []
342 try:
343 # Try schema validation first
344 if schema:
345 result = self._validate_with_schema(request_data, schema, errors)
346 if result is not None:
347 return result
349 # Fallback: basic sanitization
350 sanitized = self._sanitize_api_data(request_data)
351 return True, sanitized, []
353 except Exception as e:
354 errors.append(f"Validation error: {e}")
355 return False, request_data, errors
357 def _validate_with_schema(
358 self,
359 data: dict[str, t.Any],
360 schema: t.Any,
361 errors: list[str],
362 ) -> tuple[bool, dict[str, t.Any], list[str]] | None:
363 """Attempt validation with Pydantic or msgspec schema.
365 Args:
366 data: Data to validate
367 schema: Validation schema
368 errors: Error list to append to
370 Returns:
371 Validation result tuple if successful, None to continue with fallback
372 """
373 # Try Pydantic validation
374 if hasattr(schema, "model_validate"):
375 try:
376 validated = schema.model_validate(data)
377 return True, validated.model_dump(), []
378 except Exception as e:
379 errors.append(f"Pydantic validation failed: {e}")
380 return False, data, errors
382 # Try msgspec validation
383 if hasattr(schema, "__struct_fields__"):
384 try:
385 import msgspec
387 validated = msgspec.convert(data, type=schema)
388 return True, msgspec.to_builtins(validated), []
389 except Exception as e:
390 errors.append(f"msgspec validation failed: {e}")
391 return False, data, errors
393 return None
395 def _sanitize_api_data(self, data: dict[str, t.Any]) -> dict[str, t.Any]:
396 """Apply basic XSS sanitization to API data.
398 Args:
399 data: Data to sanitize
401 Returns:
402 Sanitized data
403 """
404 sanitized = {}
405 for key, value in data.items():
406 if isinstance(value, str) and self._config.prevent_xss and self._sanitizer:
407 sanitized[key] = self._sanitizer.sanitize_html(value)
408 else:
409 sanitized[key] = value
410 return sanitized
412 async def validate_api_response(
413 self,
414 response_data: dict[str, t.Any],
415 schema: t.Any = None,
416 ) -> tuple[bool, dict[str, t.Any], list[str]]:
417 """Validate API response data against a schema.
419 Args:
420 response_data: Response data to validate
421 schema: Validation schema (Pydantic, msgspec, etc.)
423 Returns:
424 Tuple of (is_valid, validated_data, error_messages)
425 """
426 # Guard clause: skip if disabled
427 if not self._config.validate_api:
428 return True, response_data, []
430 errors: list[str] = []
432 try:
433 # Try schema validation if provided
434 if schema:
435 result = self._validate_response_with_schema(
436 response_data, schema, errors
437 )
438 if result is not None:
439 return result
441 return True, response_data, []
443 except Exception as e:
444 errors.append(f"Validation error: {e}")
445 return False, response_data, errors
447 def _validate_response_with_schema(
448 self,
449 data: dict[str, t.Any],
450 schema: t.Any,
451 errors: list[str],
452 ) -> tuple[bool, dict[str, t.Any], list[str]] | None:
453 """Attempt response validation with Pydantic or msgspec schema.
455 Args:
456 data: Response data to validate
457 schema: Validation schema
458 errors: Error list to append to
460 Returns:
461 Validation result tuple if successful, None otherwise
462 """
463 # Try Pydantic validation
464 if hasattr(schema, "model_validate"):
465 try:
466 validated = schema.model_validate(data)
467 return True, validated.model_dump(), []
468 except Exception as e:
469 errors.append(f"Response validation failed: {e}")
470 return False, data, errors
472 # Try msgspec validation
473 if hasattr(schema, "__struct_fields__"):
474 try:
475 import msgspec
477 validated = msgspec.convert(data, type=schema)
478 return True, msgspec.to_builtins(validated), []
479 except Exception as e:
480 errors.append(f"Response validation failed: {e}")
481 return False, data, errors
483 return None
485 def _contains_sql_injection(self, value: str) -> bool:
486 """Check for common SQL injection patterns."""
487 sql_patterns = [
488 "union select",
489 "union all select",
490 "drop table",
491 "delete from",
492 "insert into",
493 "update set",
494 "'; --",
495 "'--",
496 "' or '1'='1",
497 "' or 1=1",
498 '" or "1"="1',
499 "or 1=1",
500 "' or 'x'='x",
501 '" or "x"="x',
502 "admin'--",
503 'admin"--',
504 "') or ('1'='1",
505 '") or ("1"="1',
506 "exec(",
507 "execute(",
508 "xp_cmdshell",
509 "sp_executesql",
510 ]
511 value_lower = value.lower()
512 return any(pattern in value_lower for pattern in sql_patterns)
514 def _contains_path_traversal(self, value: str) -> bool:
515 """Check for path traversal attempts."""
516 traversal_patterns = ["../", "..\\", "%2e%2e", "....//"]
517 return any(pattern in value.lower() for pattern in traversal_patterns)
519 def _sanitize_field(
520 self,
521 key: str,
522 value: t.Any,
523 errors: list[str],
524 ) -> t.Any:
525 """Sanitize a single form field.
527 Args:
528 key: Field name
529 value: Field value
530 errors: Error list to append to
532 Returns:
533 Sanitized value
534 """
535 # Skip non-string values
536 if not isinstance(value, str):
537 return value
539 # Sanitize for XSS (only if ACB available)
540 if self.available and self._config.prevent_xss and self._sanitizer:
541 try:
542 return self._sanitizer.sanitize_html(value)
543 except Exception as e:
544 errors.append(f"Failed to sanitize {key}: {e}")
545 return value
547 return value
549 def _check_security_issues(
550 self,
551 key: str,
552 value: str,
553 errors: list[str],
554 ) -> None:
555 """Check for security issues in form field.
557 Args:
558 key: Field name
559 value: Field value
560 errors: Error list to append to
561 """
562 if not self.available:
563 return
565 # Check for SQL injection
566 if self._config.prevent_sql_injection:
567 if self._contains_sql_injection(value):
568 errors.append(f"Potential SQL injection in {key}")
570 # Check for path traversal
571 if self._config.prevent_path_traversal:
572 if self._contains_path_traversal(value):
573 errors.append(f"Potential path traversal in {key}")
575 def _validate_field_schema(
576 self,
577 field_name: str,
578 value: t.Any,
579 rules: dict[str, t.Any],
580 errors: list[str],
581 ) -> None:
582 """Validate a field against its schema rules.
584 Args:
585 field_name: Field name
586 value: Field value
587 rules: Validation rules
588 errors: Error list to append to
589 """
590 # Check required field
591 if self._check_required_field(field_name, value, rules, errors):
592 return # Field missing, skip other validations
594 # Guard clause: skip if value is None
595 if value is None:
596 return
598 # Apply validation rules
599 self._validate_field_type(field_name, value, rules, errors)
600 self._validate_string_length(field_name, value, rules, errors)
601 self._validate_field_pattern(field_name, value, rules, errors)
603 def _check_required_field(
604 self,
605 field_name: str,
606 value: t.Any,
607 rules: dict[str, t.Any],
608 errors: list[str],
609 ) -> bool:
610 """Check if required field is missing.
612 Args:
613 field_name: Field name
614 value: Field value
615 rules: Validation rules
616 errors: Error list to append to
618 Returns:
619 True if field is required and missing, False otherwise
620 """
621 if not rules.get("required"):
622 return False
624 is_missing = value is None or (isinstance(value, str) and not value.strip())
625 if is_missing:
626 errors.append(f"Required field missing: {field_name}")
628 return is_missing
630 def _validate_field_type(
631 self,
632 field_name: str,
633 value: t.Any,
634 rules: dict[str, t.Any],
635 errors: list[str],
636 ) -> None:
637 """Validate field type.
639 Args:
640 field_name: Field name
641 value: Field value
642 rules: Validation rules
643 errors: Error list to append to
644 """
645 if "type" not in rules:
646 return
648 expected_type = rules["type"]
649 if not isinstance(value, expected_type):
650 errors.append(
651 f"Invalid type for {field_name}: expected {expected_type.__name__}"
652 )
654 def _validate_string_length(
655 self,
656 field_name: str,
657 value: t.Any,
658 rules: dict[str, t.Any],
659 errors: list[str],
660 ) -> None:
661 """Validate string length constraints.
663 Args:
664 field_name: Field name
665 value: Field value
666 rules: Validation rules
667 errors: Error list to append to
668 """
669 if not isinstance(value, str):
670 return
672 if "min_length" in rules and len(value) < rules["min_length"]:
673 errors.append(f"{field_name} too short (min: {rules['min_length']})")
675 if "max_length" in rules and len(value) > rules["max_length"]:
676 errors.append(f"{field_name} too long (max: {rules['max_length']})")
678 def _validate_field_pattern(
679 self,
680 field_name: str,
681 value: t.Any,
682 rules: dict[str, t.Any],
683 errors: list[str],
684 ) -> None:
685 """Validate field against regex pattern.
687 Args:
688 field_name: Field name
689 value: Field value
690 rules: Validation rules
691 errors: Error list to append to
692 """
693 if not value or "pattern" not in rules:
694 return
696 import re
698 if not re.match(
699 rules["pattern"], str(value)
700 ): # REGEX OK: User-provided validation pattern from schema
701 errors.append(f"{field_name} does not match required pattern")
704# Singleton instance
705_validation_service: FastBlocksValidationService | None = None
708def get_validation_service() -> FastBlocksValidationService:
709 """Get the singleton FastBlocksValidationService instance."""
710 global _validation_service
711 if _validation_service is None:
712 _validation_service = FastBlocksValidationService()
713 return _validation_service
716# Decorators for automatic validation
719def _extract_template_context(
720 args: tuple[t.Any, ...], kwargs: dict[str, t.Any]
721) -> tuple[dict[str, t.Any], str]:
722 """Extract context and template name from decorator arguments."""
723 raw_context: t.Any = kwargs.get("context") or (args[3] if len(args) > 3 else {})
724 context: dict[str, t.Any] = raw_context if isinstance(raw_context, dict) else {}
725 template = kwargs.get("template") or (args[2] if len(args) > 2 else "unknown")
726 return context, str(template)
729async def _log_template_validation_errors(
730 errors: list[str],
731 template: str,
732 service: FastBlocksValidationService,
733) -> None:
734 """Log validation errors if configured."""
735 if not (errors and service._config.log_validation_failures):
736 return
738 with suppress(Exception):
739 logger = await depends.resolve("fastblocks", "logger")
740 if logger:
741 logger.warning(
742 f"Template context validation warnings for {template}: {errors}"
743 )
746def _update_context_in_args(
747 args: tuple[t.Any, ...],
748 kwargs: dict[str, t.Any],
749 sanitized_context: dict[str, t.Any],
750) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
751 """Update args/kwargs with sanitized context."""
752 if "context" in kwargs:
753 kwargs["context"] = sanitized_context
754 elif len(args) > 3:
755 args = (*args[:3], sanitized_context, *args[4:])
756 return args, kwargs
759def validate_template_context(
760 strict: bool = False,
761) -> t.Callable[
762 [t.Callable[..., t.Awaitable[t.Any]]], t.Callable[..., t.Awaitable[t.Any]]
763]:
764 """Decorator to validate template context before rendering.
766 Refactored to reduce cognitive complexity.
768 Usage:
769 @validate_template_context(strict=False)
770 async def render_template(self, request, template, context):
771 ...
772 """
774 def decorator(
775 func: t.Callable[..., t.Awaitable[t.Any]],
776 ) -> t.Callable[..., t.Awaitable[t.Any]]:
777 @functools.wraps(func)
778 async def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
779 # Extract context and template name
780 context, template = _extract_template_context(args, kwargs)
782 # Skip validation if context is empty
783 if not context:
784 return await func(*args, **kwargs)
786 # Validate context
787 service = get_validation_service()
788 (
789 _is_valid,
790 sanitized_context,
791 errors,
792 ) = await service.validate_template_context(
793 context=context,
794 template_name=template,
795 strict=strict,
796 )
798 # Log validation errors if configured
799 await _log_template_validation_errors(errors, template, service)
801 # Update with sanitized context
802 args, kwargs = _update_context_in_args(args, kwargs, sanitized_context)
804 # Call original function
805 return await func(*args, **kwargs)
807 return wrapper
809 return decorator
812def _extract_form_data(
813 args: tuple[t.Any, ...], kwargs: dict[str, t.Any]
814) -> dict[str, t.Any]:
815 """Extract form data from decorator arguments."""
816 raw_data: t.Any = kwargs.get("form_data") or (args[2] if len(args) > 2 else {})
817 return raw_data if isinstance(raw_data, dict) else {}
820def _update_form_data(
821 args: tuple[t.Any, ...],
822 kwargs: dict[str, t.Any],
823 sanitized_data: dict[str, t.Any],
824) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
825 """Update args/kwargs with sanitized form data."""
826 if "form_data" in kwargs:
827 kwargs["form_data"] = sanitized_data
828 elif len(args) > 2:
829 args = (*args[:2], sanitized_data, *args[3:])
830 return args, kwargs
833async def _handle_form_validation_errors(
834 is_valid: bool,
835 errors: list[str],
836 service: FastBlocksValidationService,
837 strict: bool,
838) -> None:
839 """Handle form validation errors (logging or raising exception)."""
840 if not is_valid and strict:
841 from .exceptions import ErrorCategory, FastBlocksException
843 raise FastBlocksException(
844 message=f"Form validation failed: {'; '.join(errors)}",
845 category=ErrorCategory.VALIDATION,
846 status_code=400,
847 )
849 if errors and service._config.log_validation_failures:
850 with suppress(Exception):
851 logger = await depends.resolve("fastblocks", "logger")
852 if logger:
853 logger.warning(f"Form validation errors: {errors}")
856def validate_form_input(
857 schema: dict[str, t.Any] | None = None,
858 strict: bool = True,
859) -> t.Callable[
860 [t.Callable[..., t.Awaitable[t.Any]]], t.Callable[..., t.Awaitable[t.Any]]
861]:
862 """Decorator to validate and sanitize form input.
864 Usage:
865 @validate_form_input(schema={"email": {"required": True, "type": str}})
866 async def handle_form(self, request, form_data):
867 ...
868 """
870 def decorator(
871 func: t.Callable[..., t.Awaitable[t.Any]],
872 ) -> t.Callable[..., t.Awaitable[t.Any]]:
873 @functools.wraps(func)
874 async def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
875 # Extract form data
876 form_data = _extract_form_data(args, kwargs)
878 # Skip validation if no form data
879 if not form_data:
880 return await func(*args, **kwargs)
882 # Validate form data
883 service = get_validation_service()
884 is_valid, sanitized_data, errors = await service.validate_form_input(
885 form_data=form_data,
886 schema=schema,
887 strict=strict,
888 )
890 # Handle validation errors
891 await _handle_form_validation_errors(is_valid, errors, service, strict)
893 # Update with sanitized data
894 args, kwargs = _update_form_data(args, kwargs, sanitized_data)
896 # Call original function
897 return await func(*args, **kwargs)
899 return wrapper
901 return decorator
904def _extract_request_data(
905 args: tuple[t.Any, ...], kwargs: dict[str, t.Any]
906) -> dict[str, t.Any]:
907 """Extract request data from args or kwargs."""
908 raw_data: t.Any = kwargs.get("data") or (args[2] if len(args) > 2 else {})
909 return raw_data if isinstance(raw_data, dict) else {}
912def _update_args_with_data(
913 args: tuple[t.Any, ...],
914 kwargs: dict[str, t.Any],
915 validated_data: dict[str, t.Any],
916) -> tuple[tuple[t.Any, ...], dict[str, t.Any]]:
917 """Update args/kwargs with validated data."""
918 if "data" in kwargs:
919 kwargs["data"] = validated_data
920 elif len(args) > 2:
921 args_list = list(args)
922 args_list[2] = validated_data
923 args = tuple(args_list)
924 return args, kwargs
927async def _validate_request(
928 service: FastBlocksValidationService,
929 request_data: dict[str, t.Any],
930 schema: t.Any,
931) -> dict[str, t.Any]:
932 """Validate request data and raise exception if invalid."""
933 is_valid, validated_data, errors = await service.validate_api_request(
934 request_data=request_data,
935 schema=schema,
936 )
938 if not is_valid:
939 from .exceptions import ErrorCategory, FastBlocksException
941 raise FastBlocksException(
942 message=f"Request validation failed: {'; '.join(errors)}",
943 category=ErrorCategory.VALIDATION,
944 status_code=400,
945 )
947 return validated_data
950async def _validate_response(
951 service: FastBlocksValidationService,
952 response_data: dict[str, t.Any],
953 schema: t.Any,
954) -> dict[str, t.Any]:
955 """Validate response data and log errors if invalid."""
956 is_valid, validated_response, errors = await service.validate_api_response(
957 response_data=response_data,
958 schema=schema,
959 )
961 if not is_valid:
962 with suppress(Exception):
963 logger = await depends.resolve("fastblocks", "logger")
964 if logger:
965 logger.error(f"Response validation failed: {errors}")
967 return validated_response
970def validate_api_contract(
971 request_schema: t.Any = None,
972 response_schema: t.Any = None,
973) -> t.Callable[
974 [t.Callable[..., t.Awaitable[t.Any]]], t.Callable[..., t.Awaitable[t.Any]]
975]:
976 """Decorator to validate API request/response contracts.
978 Usage:
979 @validate_api_contract(
980 request_schema=UserCreateSchema,
981 response_schema=UserSchema
982 )
983 async def create_user(self, request, data):
984 ...
985 """
987 def decorator(
988 func: t.Callable[..., t.Awaitable[t.Any]],
989 ) -> t.Callable[..., t.Awaitable[t.Any]]:
990 @functools.wraps(func)
991 async def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
992 service = get_validation_service()
994 # Validate request if schema provided
995 if request_schema:
996 request_data = _extract_request_data(args, kwargs)
997 if request_data:
998 validated_data = await _validate_request(
999 service, request_data, request_schema
1000 )
1001 args, kwargs = _update_args_with_data(args, kwargs, validated_data)
1003 # Call original function
1004 result = await func(*args, **kwargs)
1006 # Validate response if schema provided
1007 if response_schema and isinstance(result, dict):
1008 return await _validate_response(service, result, response_schema)
1010 return result
1012 return wrapper
1014 return decorator
1017async def register_fastblocks_validation() -> bool:
1018 """Register FastBlocks validation service with Oneiric.
1020 Returns:
1021 True if registration successful, False otherwise
1022 """
1023 try:
1024 # Initialize validation service
1025 validation_service = get_validation_service()
1027 # Register with depends
1028 register_candidate(
1029 depends,
1030 domain="fastblocks",
1031 key="validation",
1032 factory=lambda: validation_service,
1033 metadata={
1034 "class": "ValidationService",
1035 "module": "fastblocks._validation_integration",
1036 },
1037 )
1039 return validation_service.available
1041 except Exception:
1042 return False
1045__all__ = [
1046 "FastBlocksValidationService",
1047 "ValidationConfig",
1048 "ValidationType",
1049 "get_validation_service",
1050 "validate_template_context",
1051 "validate_form_input",
1052 "validate_api_contract",
1053 "register_fastblocks_validation",
1054]