TL;DR
- An insecure direct object reference (IDOR) occurs when a caller can use an object identifier to read or change a resource without a server-side authorization check.
- Random UUIDs and hidden buttons do not authorize access. Derive the user's tenant and permissions from verified server-side identity, then scope every database operation to them.
- Check authorization on reads, writes, downloads, exports, nested resources, and bulk operations. A route dependency helps, but the query and mutation must enforce the same boundary.
- Use 404 when your disclosure policy intentionally conceals whether a resource exists. Use 403 when revealing existence is acceptable and the caller is authenticated but lacks permission.
- Automate cross-tenant tests with two tenants and multiple roles, and cover indirect paths such as search, attachments, background jobs, and cached responses.
How an IDOR becomes a cross-tenant incident
An insecure direct object reference is an access-control failure in which an application accepts a caller-controlled identifier and does not verify that the caller may access the referenced object. The identifier may be an integer in a URL, a UUID in JSON, a filename, a payment ID, or a nested resource key. If changing that value lets one customer read or modify another customer's data, the application has a broken object-level authorization problem.
Consider an invoice route such as GET /api/invoices/8412. A developer checks that the caller has a valid session, then loads invoice 8412 by its primary key. Authentication proves which user made the request. It does not prove that the user belongs to the tenant that owns the invoice or may perform the requested action. OWASP's IDOR guidance describes this missing object-level authorization check as the core vulnerability. OWASP IDOR prevention guidance
Numeric identifiers make enumeration easy, but replacing them with UUIDs does not fix the authorization flaw. An identifier can leak through an email, browser history, support ticket, webhook, or another authorized endpoint. A secret-looking ID can reduce casual discovery. It cannot substitute for a permission check.
Multi-tenant products need to answer two separate questions for every object operation: does the authenticated principal belong to the relevant organization, and is that principal allowed to perform this action on this particular resource? The answer can differ by operation. A user may read a project but not archive it, and an organization administrator may manage members but not access a private HR record.
Build authorization from verified identity context
After validating a session or access token, construct a server-side principal that contains stable identifiers and trusted claims: user ID, tenant memberships, role or policy references, token scopes, and authentication state where relevant. Do not use an untrusted tenant_id from a request body, route, header, or query string as the authorization source. A request may select an organization the user belongs to, but the server must verify that membership before using it.
In FastAPI, dependencies are a useful way to resolve an authenticated principal and enforce broad route requirements. They are not a magical boundary around the database. A route can correctly require a logged-in user and still contain an unsafe query. Keep object-level checks close to the data access operation so another handler, worker, or export path cannot accidentally skip them. FastAPI dependency injection
Model permissions around subject, action, resource, and relevant context. For a project read, that might require a tenant membership plus one of owner, active project grant, or organization administrator. For a delete, it may require a more restrictive permission and a state precondition. Centralize the policy so route handlers do not each invent slightly different rules. Compare authorization models for enterprise SaaS
Scope object queries by tenant and permission
When the tenant boundary is known from verified identity, include it in the database predicate used to find the object. This prevents a global primary-key lookup from becoming the only guard. Then apply resource-specific authorization, either in the same query or immediately before returning the resource. Avoid fetching an unrestricted object and relying on a front-end check or a later serializer to hide fields.
@router.get("/projects/{project_id}")
def get_project(
project_id: UUID,
actor: Annotated[Principal, Depends(current_principal)],
session: Session = Depends(get_session),
):
project = session.scalar(
select(Project).where(
Project.id == project_id,
Project.tenant_id == actor.active_tenant_id,
project_read_predicate(actor),
)
)
if project is None:
raise HTTPException(status_code=404, detail="Project not found")
return ProjectOut.model_validate(project)
The exact principal type and policy function are application-specific. The important property is that tenant scope comes from verified context and appears in the query. The example chooses a 404 to conceal the existence of out-of-scope project IDs. A product that intentionally discloses existence may return 403 after establishing that the resource exists, but the policy should be consistent and deliberate.
For update and delete operations, include the scope and authorization predicate in the mutation or lock and re-check the resource in the same transaction. This avoids a check-then-act gap where membership or ownership changes between the authorization read and the write. Database uniqueness and foreign-key constraints should include tenant relationships where they protect cross-tenant invariants.
A composite foreign key can prevent an object in tenant A from referencing a parent in tenant B, even if application code constructs the wrong relationship. For example, store the parent tenant ID on the child and reference a unique pair (tenant_id, parent_id). This adds schema work but gives the database a way to reject invalid cross-tenant associations.
Check every access path, not only detail routes
Direct object endpoints are the obvious place to look, but identifiers appear in many shapes. Audit endpoints for:
- List, search, autocomplete, reporting, and export queries that can return or count another tenant's objects.
- Nested routes such as
/projects/{project_id}/documents/{document_id}where the document may not belong to the supplied project. - File downloads, signed storage URLs, generated previews, and attachment metadata.
- Bulk APIs that accept arrays of IDs and may partially process unauthorized entries.
- Webhooks and callback URLs that accept resource identifiers from an external provider.
- Background tasks that run after the user's request and may use unscoped IDs from a queue payload.
- GraphQL resolvers, admin tools, support impersonation, and cached responses.
Nested resources need both relationships checked. A query that verifies only that the child belongs to the tenant can still accept a mismatched parent in the URL. Query using the full relationship, or load the authorized parent first and constrain the child to it. Bulk operations should define whether one unauthorized ID rejects the whole request or returns per-item outcomes. Avoid processing allowed objects while silently leaking which others exist.
For object storage, the application should authorize before issuing a short-lived URL, and the storage object key should not be accepted as proof of tenant ownership. Keep bucket access private, use server-generated object keys, and bind signed download URLs to the intended object and expiry. Revocation semantics require care because an already issued URL may remain usable until it expires.
Choose 404 or 403 based on disclosure policy
HTTP 403 means the server understood the request but refuses to fulfill it. HTTP 404 means the target resource was not found. RFC 9110 allows a server to use 404 to conceal the existence of a forbidden target. This is a choice about information disclosure, not a substitute for the underlying authorization check. RFC 9110: 404 Not Found
For sensitive multi-tenant resources, returning the same 404 response for an unknown ID and an existing resource outside the caller's scope can reduce a direct existence oracle. Keep response shape, status, and obvious timing behavior consistent where practical. An authenticated user requesting an object that exists but is outside their role may receive 403 in products where existence is not sensitive and client behavior benefits from a clear denial.
Do not use 404 as a cosmetic patch while still performing side effects, logging sensitive details to the response, or making the object discoverable through list counts and search results. Nor should 403 be considered a vulnerability by itself. Define the resource disclosure policy, apply it consistently, and test other channels that could reveal object existence.
Add database defenses for critical tenant boundaries
Application-level query scoping is necessary, but a missed predicate can expose data. PostgreSQL row-level security can provide an additional database enforcement layer when policies and connection context are designed correctly. Under RLS, queries run as a role subject to policies, and tenant context can be set for the transaction. Be careful with table owners, bypass roles, pooled connections, and request context cleanup. Test using the same runtime database role and connection-pool mode used in production. PostgreSQL RLS for multi-tenant systems
RLS does not replace application authorization for every action. It can enforce tenant ownership while the application still decides whether a project editor may archive a project. Conversely, an application policy cannot protect against an alternate code path that runs a query as a role that bypasses RLS. Treat the layers as complementary and test their combined behavior.
Database constraints can enforce structural ownership: composite foreign keys for same-tenant relationships, uniqueness scoped by tenant, and check constraints for valid states. These constraints stop invalid writes regardless of which service path attempted them. They do not decide every read permission, but they narrow the set of states from which an IDOR can arise.
Use caches carefully. A cache key must include the tenant and any access-varying context, or one user's authorized response may be served to another. Permission revocation should invalidate or bypass cached data in accordance with the product's security requirements. If a cached object is rechecked after retrieval, ensure no sensitive fields or timing-dependent metadata were already exposed.
Build automated IDOR tests around adversarial principals
Create at least two tenants with deliberately similar records and identifiers, plus users with different roles inside each tenant. For every route that accepts an object reference, test both an authorized operation and cross-tenant attempts for read, update, delete, download, and export. A test that only checks that one tenant's user can access their own object proves little about isolation.
Test horizontal access (one customer user to another customer's object) and vertical access (a low-privilege user attempting an administrator action). Include nested IDs, IDs in request bodies, bulk lists, search terms, pagination cursors, and relationships. Ensure unauthorized attempts do not change state, enqueue jobs, send email, create audit records that leak names to the caller, or return partial object data.
def test_project_id_cannot_cross_tenants(client, tenant_a, tenant_b):
project = create_project(tenant=tenant_b)
token = issue_token(user=tenant_a.member)
response = client.get(
f"/api/projects/{project.id}",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 404
assert response.json() == {"detail": "Project not found"}
assert not any(key in response.text for key in [project.name, tenant_b.name])
This example assumes the API's disclosure policy uses a concealed 404. If the product chooses 403, assert that contract instead. Tests should also inspect the database after attempted writes and verify no queue or external side effect was initiated. Use factory helpers that make tenant ownership explicit so fixtures do not accidentally place both records in the same organization.
Generate route coverage from your API schema or route registry, then review the endpoints with a human. Automated discovery can show which path parameters look like IDs, but it cannot infer the correct business permission. Add regression tests for every reported authorization bug and exercise background jobs separately from request handlers.
Monitor for attack patterns without logging secrets
Repeated requests for sequential IDs, many 404 responses across unrelated objects, and sudden access denials may indicate probing. Rate-limit sensitive endpoints and alert on patterns appropriate to the product's normal usage. Avoid logging authorization headers, raw session tokens, full personal records, or private document content. Security logs should let responders correlate the actor, tenant, object class, action, decision, and request ID while respecting retention and access controls.
Record denied decisions at a useful granularity. A reason such as tenant_scope_mismatch or missing_project_grant helps diagnose policy errors without returning that detail to the caller. Monitor policy changes, elevated support access, and unusual bulk exports. For administrator or support impersonation, log the initiating operator separately from the represented user and make the access window explicit.
Frequently asked questions
Do UUIDs prevent IDOR vulnerabilities?
No. UUIDs can make identifiers harder to guess, but they do not prove that the caller is allowed to access an object. IDs can leak through links, logs, integrations, or other endpoints. Enforce server-side authorization for every object operation.
Should a multi-tenant API return 404 or 403 for another tenant's object?
Use the status that matches the API's disclosure policy. A 404 can conceal that a forbidden resource exists, while a 403 clearly communicates that access is denied. RFC 9110 permits 404 for concealment. Apply the decision consistently and check for leaks through counts, search, timing, and side effects.
Is a FastAPI route dependency enough to prevent IDOR?
A dependency can authenticate the principal and enforce broad requirements, but the data query still needs object-level authorization. Scope reads and mutations by verified tenant context and resource permissions. Test alternate routes, background tasks, and bulk endpoints that may bypass the original handler.
Can PostgreSQL row-level security replace application authorization?
RLS can enforce database-level tenant boundaries as an additional layer, but the application may still need action-specific rules such as whether a user can edit or delete a record. Configure policies for the actual runtime role and pooled connection behavior, then test the combined application and database rules.
Make object authorization part of every data path
IDOR prevention works when identity, tenant scope, and resource permissions are enforced wherever data moves: request handlers, SQL queries, storage URLs, search, exports, and background tasks. Use unpredictable identifiers only as a secondary measure. Combine explicit policies with database constraints, carefully configured RLS when useful, and tests that attempt both horizontal and vertical privilege abuse.
If you are reviewing a multi-tenant SaaS boundary, talk with our engineering team about an IDOR test plan, scoped queries, and the right enforcement layers for your application.
