Field-Level Security in FastAPI: Dynamic Masking and Restrictions

Authentication & Security

Protect sensitive FastAPI fields with role-aware reads, write allowlists, Pydantic DTOs, SQL projections, and auditable masking without unsafe mass assignment.

TL;DR

  • Field-level security decides which properties a caller may read or change. Enforce it separately from tenant membership, object access, and function authorization.
  • Use explicit response DTOs and per-operation input models. A hidden field in JSON output does not prevent an unauthorized write, and an input allowlist does not prevent leaking a field in a response.
  • Derive field permissions from verified server-side identity and policy. Never accept a role, field grant, or tenant claim directly from request parameters.
  • Use SQL projection to avoid loading unnecessary sensitive values where practical, but do not treat ORM projection as the authorization boundary.
  • Masking is a presentation choice, not access control or encryption. Apply policy before serialization and check logs, exports, caches, and background jobs too.

Field-level security fills the gap between rows and actions

Row-level authorization decides whether a principal may access a record. Function-level authorization decides whether they may call an operation. Field-level security decides which properties on that record may be read or changed. A support user might see a customer’s account but not a full tax identifier. A billing administrator may update a payment contact but not the settlement status. A clinician may read a chart but not a restricted note outside their care relationship.

These controls answer different questions. Tenant scoping cannot protect a sensitive field from every authorized member of the same tenant. A response serializer cannot stop a caller from submitting a protected field in an update payload. An endpoint role check cannot express that one role may read a property but not modify it. OWASP’s API3:2023 groups excessive data exposure and mass assignment under Broken Object Property Level Authorization because both arise when the API fails to authorize properties. OWASP API3:2023: Broken Object Property Level Authorization

Build a policy for each operation and direction. A read policy answers which properties can appear in this response for this principal, resource, and purpose. A write policy answers which submitted properties the caller may change. Treat create, update, export, search, and aggregation as separate operations if their data exposure differs.

Before adding a dynamic serializer, inventory sensitive properties and data flows. Include nested objects, generated fields, computed values, audit metadata, error messages, and export columns. For each property, name its owner, sensitivity, allowed purposes, read and write conditions, and retention expectations. That inventory is more useful than a single global “admin can see all” flag.

Model policy as explicit read and write decisions

Start with data classification that product and security teams can review. For example, a basic profile may include public display name, tenant-only work phone, finance-only credit limit, and tightly restricted government identifier. Those labels do not determine the final policy by themselves. The decision may also depend on the resource’s tenant, the caller’s relationship, the current operation, and an approved purpose.

Represent the decision in a server-side policy function with a narrow input: verified principal, tenant-scoped resource, operation, and allowed purpose. Return an allowlist of readable or writable property names, or deny the operation. Prefer deny-by-default behavior for new fields. A schema change that adds a property should not make it readable or writable for every existing role by accident.

Keep policy code separate from serialization. The endpoint first authenticates, checks tenant and object access, and obtains an explicit field decision. It then builds the response using only permitted properties. The update endpoint validates a request model containing only client-editable fields and still checks which of those fields the caller may change.

Do not use a client-provided list such as fields=ssn,credit_limit as authority. A client can ask for fields it is not allowed to see, but the server computes the effective projection by intersecting requested fields with the authorized set. Return consistent errors that do not reveal whether a hidden property exists unless the product intentionally supports that discovery.

Separate write schemas from database models

Mass assignment occurs when the application binds client input into a broad internal object and persists properties the operation was never meant to accept. Define a dedicated request model per operation with only user-editable fields. Avoid constructing that model directly from an ORM model or accepting an arbitrary dictionary of attributes.

from pydantic import BaseModel, ConfigDict, Field

class ContactUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    display_name: str | None = Field(default=None, max_length=120)
    work_phone: str | None = Field(default=None, max_length=40)

async def update_contact(principal, tenant_id, account_id, payload):
    account = await load_account_in_tenant(tenant_id, account_id)
    await authorize(principal, account, action="account.contact.update")

    changes = payload.model_dump(exclude_unset=True)
    policy.require_writable(principal, account, changes.keys())

    for name, value in changes.items():
        setattr(account, name, value)

    await save(account)
    return account

This sketch leaves framework wiring out, but the boundary is important. Reject unknown input properties so a newly added internal field cannot silently become client-editable. Check each submitted property against the authenticated principal’s effective permissions. Do this before assignment and persistence, including in bulk update paths and background jobs that reuse request payloads.

Separate create and update models when they accept different fields. A user may set a display name during onboarding but not alter an internal risk score. A partial update must distinguish an omitted value from an explicit null. Pydantic’s unset handling can preserve that distinction, but validation does not supply authorization. FastAPI response models filter output according to declared models; they do not replace the service-level policy that decides what the caller may receive. FastAPI response models and data filtering · Pydantic serialization and include/exclude controls

For high-risk mutations, make the persistence operation narrow as well. Update a reviewed set of columns, use optimistic concurrency or row locking where required, and record who changed which field and under what authorization decision. A generic ORM merge of a partially trusted object makes the write surface difficult to audit.

Build responses from an authorized projection

Do not return a database model directly and hope that a serializer’s default behavior stays safe. Use stable output DTOs for ordinary roles and a policy-aware projection for legitimate role variations. An explicit response model helps document and validate the output shape. If one role may see a protected attribute, have a separate reviewed response model or an explicit projection function that adds it only after policy approval.

For a small API response, construct a dictionary from the approved field set. For larger result sets, generate a typed DTO using only the authorized values. Keep the policy check close to the data access and response boundary so a future endpoint does not reuse a permissive serializer without realizing it.

def account_view(account, readable_fields):
    fields = {
        "id": account.id,
        "display_name": account.display_name,
        "work_phone": account.work_phone,
        "credit_limit": account.credit_limit,
        "tax_identifier": account.tax_identifier,
    }
    return {
        name: value
        for name, value in fields.items()
        if name in readable_fields
    }

async def get_account_view(principal, tenant_id, account_id):
    account = await load_account_in_tenant(tenant_id, account_id)
    await authorize(principal, account, action="account.read")
    allowed = policy.readable_fields(principal, account, purpose="support")
    return account_view(account, allowed)

Never pass an arbitrary field list from the request straight into an ORM serializer or SQL string. Map external names through a fixed allowlist and bind values as parameters. Keep nested object policies explicit. If a caller may view the parent but not one nested collection, do not serialize that collection by default and attempt to redact it afterward.

Pydantic supports include and exclude options for serialization. Those are useful for shaping a response after the authorized field set is known. A static field exclusion is not a dynamic policy, and a convenience option should not become the only control around sensitive data. FastAPI can also return a raw Response directly, which bypasses normal response-model filtering, so review those routes separately. FastAPI response model filtering · Pydantic field inclusion and exclusion

Use database projection carefully

Selecting only authorized columns can reduce unnecessary sensitive data in application memory, query results, and debug tooling. With SQLAlchemy, an explicit select list or load_only can fetch the fields the operation requires. For a given operation, build that list from a trusted map of model attributes rather than interpolating request strings into SQL. SQLAlchemy column loading options

Projection is an optimization and an additional privacy boundary, not a replacement for authorization. ORM deferred fields may lazy-load later if accessed. Another code path may issue a broader query. An endpoint might export through raw SQL. Test generated statements and prevent unexpected lazy loads where the architecture supports it.

PostgreSQL supports column-level SELECT, INSERT, and UPDATE privileges. Those grants can be useful when different database roles have fixed column access. They are not a substitute for per-principal application policy when every tenant member shares one service database role. Row-level security and tenant-scoped queries still address a different axis from property policy. PostgreSQL privileges, including column grants

For especially sensitive data, consider separating storage or using a narrow data-access service with its own database role. This adds operational complexity and should solve a concrete threat-model need. Avoid claiming that a selected-column query makes data encrypted or inaccessible to privileged database operators.

Distinguish masking from authorization and encryption

Masking transforms a value for display, such as returning the last four digits of an account number. It can support a legitimate workflow while reducing accidental exposure, but the underlying value has already been accessed by the application. Masking does not grant permission to use the full value elsewhere, protect database storage, or prevent a privileged process from reading it.

Apply masking only after the access policy determines that the caller may receive the masked representation. A user who may not see a government identifier should not receive a mask that reveals its last four digits unless that limited disclosure is explicitly permitted. Use distinct output types for raw, masked, and absent values so a template or CSV exporter cannot accidentally serialize the full value.

Encryption at rest and in transit protects other boundaries. It does not determine whether the current application user may read a property after the service decrypts it. Likewise, field-level authorization does not replace key management or transport security. Write down each control’s threat it addresses.

Minimize sensitive values in logs, traces, analytics, cache keys, notifications, and error reports. A response that hides a field while an audit log records the complete model still leaks it. Cache entries must include the effective authorization scope or contain only a safe representation, and revocation must invalidate or expire them. Exports and scheduled reports should use the same property policy as interactive APIs.

Make policy changes observable and testable

Record a structured authorization decision with principal identifier, tenant, resource type and ID, operation, policy version, and allowed field names. Avoid recording the sensitive values themselves. For a denied write, record the submitted property names only if the names are safe and the logging policy permits it. Keep security audit records separate from verbose application debugging.

Test read and write behavior as separate matrices. Cover each role and tenant context, each operation, allowed properties, denied properties, omitted values, explicit nulls, nested objects, bulk updates, exports, and raw-response routes. Assert not only the HTTP response but also the database row and downstream events. A denied field should not be changed indirectly by model defaults or hooks.

Add regression cases for newly introduced fields. A safe default is that a new property is absent from every response and rejected in every request until a policy and DTO explicitly include it. Check generated OpenAPI schemas for unexpected properties, but do not rely on the schema as a runtime authorization gate.

Use synthetic sensitive values that are easy to search in tests. Verify they do not appear in response bodies, logs, traces, cache values, or error messages for principals without permission. For an authorized masked view, verify only the intended representation appears. Include a test that changes a role or tenant mapping and confirms that stale cached output is not served.

Privacy obligations need a scope-specific review

Data minimization and access controls can support privacy and security programs, but a field-level filter alone does not make an application compliant. Under HIPAA, the minimum necessary standard has defined requirements and exceptions, including treatment disclosures. GDPR includes data minimization and security principles that require context-specific technical and organizational measures. Map product workflows, data purposes, contracts, covered-entity or controller roles, and applicable exceptions with qualified privacy counsel. 45 CFR 164.502, including the minimum necessary standard · EU General Data Protection Regulation

For engineering, the useful outcome is a traceable policy: which properties each operation needs, which roles may receive them, and how access is reviewed and revoked. Keep legal interpretation separate from the serializer implementation.

Frequently asked questions

Does a FastAPI response model enforce field-level authorization?

A response model validates and filters the output shape declared for an endpoint. It does not decide which fields a particular principal may see. Compute the allowed fields from server-side identity and resource policy, then construct or select the appropriate response. Review raw Response routes because they can bypass normal response-model filtering.

Is masking the same as denying access?

No. Masking returns a transformed value, while denial returns no value. A masked identifier may still reveal information, and the application has already accessed the underlying data. Authorize the masked representation as its own disclosure and keep raw values out of logs and caches.

Should SQLAlchemy select only fields a user can see?

Use a trusted column projection when it reduces unnecessary sensitive data in memory or query results. Still enforce authorization in the service and response boundary. Deferred ORM columns may load later, and other routes can issue broader queries, so test data access paths and lazy-loading behavior.

How do I prevent mass assignment in a partial update endpoint?

Use a dedicated request model with only user-editable fields, reject unknown properties, and authorize each submitted field before assignment. Distinguish an omitted property from explicit null, and apply the same checks to bulk updates, exports, background jobs, and alternative API routes.

If you are adding fine-grained field access to a multi-tenant API, talk to Dumb Potato about policy modeling, response projections, and regression tests.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with application security

Discuss your project