ZCore LogoZCore
Core concepts

Zchema & Context Shielding

Understand how ZCore intercepts Pydantic V2 to provide dynamic, role-based field pruning across validation, serialization, and OpenAPI schema generation.

Maintaining distinct Pydantic models for different user roles (e.g., TaskCreatePublic, TaskCreateAdmin, TaskResponseUser, TaskResponseAdmin) leads to massive code duplication and violates the DRY principle. ZCore solves this with Zchema, an intelligent schema abstraction that intercepts Pydantic V2 core compilation and execution hooks.


1. The Triple Pruning Pipeline

Zchema enforces security boundaries across all three phases of the HTTP data lifecycle:

1. Inbound Request 2. Outbound Response 3. Schema Introspection Incoming HTTP JSON @model_validator before Drop Restricted Fields: Mass Assignment Safe Validated Pydantic Instance @model_serializer wrap Prune Restricted Keys Recursively Filtered Response JSON GET /endpoint/_schema __get_pydantic_json_schema__ Remove from properties & required Masked JSON Schema Specification
  1. Input Validation (Mass Assignment Prevention): By intercepting @model_validator(mode="before"), Zchema inspects incoming JSON payloads. If an unauthorized user attempts to inject restricted fields (e.g., submitting is_superuser: true or salary: 100000), the forbidden fields are silently stripped before Pydantic initializes the model.
  2. Output Serialization (Data Leakage Prevention): By wrapping @model_serializer(mode="wrap"), Zchema intercepts the serialized dictionary before it is rendered to JSON. It recursively traverses nested dictionaries and lists to purge any restricted attributes.
  3. JSON Schema Generation (OpenAPI & Dynamic Forms): By overriding __get_pydantic_json_schema__, Zchema dynamically alters the generated Draft-7 JSON Schema. Forbidden fields are stripped from both the properties definition and the required validation array.

Guest Masking (__private__) & Performance Early-Exit

  • Unauthenticated Contexts (__private__): In addition to active user permissions, Zchema allows declaring sensitive attributes that should never appear for guests:
    class ProductResponse(Zchema):
        __model__ = "products"
        __private__ = {"wholesale_cost", "margin"}  # Hidden when ctx.user_id is None
    When ctx.user_id is missing, fields listed in __private__ are automatically merged into the relative restriction paths across validation, serialization, and schema queries.
  • Zero-Overhead Serialization: Zchema implements early-exit guards. If a request context contains no active restrictions (or if serialized payloads evaluate to non-dictionary primitives), data pruning bypasses recursive traversal entirely, serializing clean payloads with native Pydantic V2 speed.

2. Context-Aware Path Resolution

Zchema computes relative restriction paths by cross-referencing ctx.restricted_fields against the schema's __model__ attribute:

# schemas.py
from zcore import Zchema

class TaskResponse(Zchema):
    __model__ = "tasks"  # Binds this schema domain
    
    id: uuid.UUID
    title: str
    salary: float
    assignee: AssigneeInfo | None = None

Supported Path Resolution Syntax

  • Action-Scoped Restrictions: If ctx.restricted_fields contains "tasks.view.salary", Zchema strips salary strictly on view (GET) operations. Standard actions recognized include listview, view, create, update, delete, and lookup.
  • Global Domain Restrictions: If restricted_fields contains "tasks.salary", Zchema strips salary across all actions (create, update, view).
  • Recursive Nested Restrictions: If restricted_fields contains "tasks.view.assignee.email", Zchema traverses the nested assignee dictionary/list and prunes only the email key.
  • Full-Model Masking (Wildcard): If restricted_fields contains "tasks.view" or "tasks", Zchema prunes the entire model (*), returning an empty representation.

Action Context: ZCoreAPIRoute automatically populates ctx.set("action", "view" | "create" | "update" | "delete") based on the active HTTP method or custom OpenAPI route metadata.


3. Dedicated Schema Introspection (/_schema) & CDN Safety

To orchestrate Zchema seamlessly with routing and caching, ZCore combines BaseRouter endpoints with specialized ZCoreAPIRoute behaviors:

Dedicated Schema Introspection (GET /_schema)

Instead of intercepting arbitrary query parameters, BaseRouter exposes a dedicated GET /_schema endpoint:

  1. It supports optional authentication via get_optional_user_stub, ensuring unauthenticated guests receive schemas with __private__ fields masked, while authenticated users receive schemas pruned based on their active role scopes.
  2. It accepts an optional ?action= query parameter (create, update, view, lookup).
  3. Under the hood, it executes target_schema.model_json_schema() inside an isolated with ctx.scope(action=normalized_action) block, guaranteeing that action-scoped restriction rules (e.g. tasks.create.password) are evaluated accurately against the target schema.

Action Context & HTTP Cache Invalidation (Vary Header)

ZCoreAPIRoute automatically binds the active operational action to ctx.action on every HTTP request. Additionally, if an endpoint returns data where restricted fields have been pruned, ZCoreAPIRoute automatically appends:

Vary: Authorization, Cookie

This prevents downstream CDNs, reverse proxies, and browser caches from serving masked responses to high-privilege administrative users.

On this page