Learning pathsPricingChecking sign-in…
Core Concepts

Security and Tenant Isolation

Enforce trusted tenant, object and field permissions across APIs, caches, projections and asynchronous work.

Security and Tenant Isolation

A multi-tenant service must ensure that an authenticated caller can act only on resources and fields currently permitted to that caller. A valid session proves an identity under its authentication contract; it does not authorize every object whose ID the caller knows. Make trust boundaries and enforcement points visible in the design, including asynchronous jobs, caches, search projections and administrative operations.

Start with the protected operation

This original exercise serves district-scoped notification drafts and exports. Tenant T1's editor Ana may read and edit permitted drafts in T1. Ben belongs to T2. A background worker may render a specific approved export; it is not a universal administrator. A support operator has a narrowly authorized, audited recovery workflow rather than ordinary unrestricted access to customer content.

AssetThreat/failure to preventEnforcing authority
Draft D1 in T1Ben supplies its ID from T2Service object policy and scoped data access
Private cached responseOne user receives another user's payloadScope-aware cache policy plus current authorization
Queued exportOld permission or forged queue fields grant accessAuthenticated workload identity and current job/resource policy
Search/vector snippetRevoked content leaks from a stale indexCandidate scoping and current permission check before disclosure
Privileged correctionSupport action changes money or messages without evidenceLeast-privilege operation, approval where the product requires it, immutable audit evidence

Define adversaries and exclusions. The examples cover cross-tenant access, stale permissions and confused-deputy mistakes. They are not a complete defense against compromised hosts, arbitrary database administrators or every browser/network attack. Separate account, tenant, resource, action and field-level permissions; “belongs to this tenant” can still be too broad for a private draft.

Establish authenticated context at the boundary

Validate the selected credential protocol: signature/key trust, expected issuer/audience, validity interval and supported algorithms where relevant. Session revocation and rotation depend on the deployment's actual contract. Derive the active tenant through trusted membership/policy, not directly from an X-Tenant-ID value supplied by the caller. A tenant selector may request a scope; the service must verify it.

Pass a bounded internal context to downstream services over an authenticated channel. Each owner still enforces its resource/action policy. Strip or validate forwarded identity headers at the trusted boundary so bypassing a gateway cannot mint an identity. Do not put authorization authority into a trace ID or untrusted tracing baggage.

Contract / pseudocode
authenticated_context(principal_id, selected_tenant, session_id, policy_evidence)
resource(id, tenant_id, owner_id, classification, acl_version, deleted_at)
allow(context, action, resource, current_membership, current_acl)
  requires authenticated identity
  requires selected_tenant == resource.tenant_id
  requires current membership and action/field permission
  requires resource not deleted and required policy evidence available
  otherwise deny

This is policy pseudocode, not a token-validation library. Permissions must be checked for detail reads, lists, mutations, downloads and status lookups. A list page having filtered D1 earlier does not authorize a later detail endpoint. Prefer explicit allow rules and default denial; define safe unavailable behavior when a required policy authority cannot be consulted.

Scope storage and constraints together

A detail query needs a tenant-qualified access pattern, followed by any finer object/field policy:

sql
SELECT id, tenant_id, owner_id, acl_version, subject
FROM draft
WHERE tenant_id = :authorized_tenant AND id = :draft_id
  AND deleted_at IS NULL;

Parameterize values and constrain result columns. A caller-controlled tenant parameter is not an authorized tenant. Apply the same boundary to writes and bulk jobs. Use composite identity/foreign-key rules where necessary so T1 cannot attach a child record to T2's parent by ID alone. Tenant-scoped uniqueness for client operation keys avoids cross-tenant interference and result disclosure.

Database row-level security can add defense in depth, but its role and execution behavior matter. PostgreSQL table owners normally bypass row policies, and privileged bypass roles have their own behavior. Separate owner/migration roles from application access, cover read and write checks, test connection-pool context reset and review security-definer paths. A custom session setting is not magically trustworthy if arbitrary SQL can change it. Consult the PostgreSQL row security documentation for the deployed version; a policy name in a diagram is not an isolation proof.

Cache and projection scope are part of authorization

For this exercise, a private rendered response cache key includes tenant, resource version, representation and the permission scope that determines its fields. The service checks current access before returning a sensitive hit. If two permitted users see different fields, tenant-only cache keys are still insufficient. A current policy/ACL generation can help invalidate permission-sensitive entries, but reading that generation from an equally stale cache cannot establish immediate revocation.

Tenant isolation history: T1 editor caches a permitted draft; T2 caller submits the same object ID; service derives T2 from authenticated membership; current object policy denies access before reading cached content; no title, snippet or body is disclosed
Object ID knowledge and a warm cache do not grant access.
Read the diagram

T1 editor caches a permitted private draft → T2 caller submits the same object ID → Service derives T2 from authenticated membership → Current object policy rejects cross-tenant access → No cached title, snippet or body is disclosed

Open original
Security and Tenant Isolation
Tenant isolation history: T1 editor caches a permitted draft; T2 caller submits the same object ID; service derives T2 from authenticated membership; current object policy denies access before reading cached content; no title, snippet or body is disclosed

Object ID knowledge and a warm cache do not grant access.

A search index may retain D1 after a permission change. Scope candidate retrieval and recheck current permissions before returning titles, snippets, embeddings-derived text or download grants. Filtering only after the text has entered an LLM context is too late. Completed answer caches and conversation histories must follow permission and deletion policy too. Do not silently use a public fallback that reveals a private item's existence or content.

Carry jobs across the trust boundary safely

Queue payloads are data, not credentials. Bind a job to tenant, requesting principal, resource version and permitted operation when accepting it. A worker authenticates as a workload principal, then checks the job's current eligibility and resource policy under its scoped delegation model. Avoid giving every worker a credential that can read all tenants merely for convenience.

In this exercise, rendering the full export requires the current editor permission; a viewer may read only its permitted fields. If Ana is removed or demoted to viewer before an export starts, this exercise suppresses the unstarted export at its authoritative eligibility boundary. A deletion or role change during processing needs a publication/download decision too; deciding access only at job acceptance leaves stale grants. An already released file cannot always be recalled, so state the revocation boundary and retention policy explicitly.

For agent tools, retrieved documents and model confidence cannot authorize an action. A typed proposal goes through deterministic caller/resource/limit policy and the product's required confirmation step, then a retry-safe destination operation. This is the same trust distinction as a queue message carrying another tenant's ID.

Protect bytes, credentials and browser/API paths

TLS protects transport; encryption at rest limits a different threat. Neither determines who may decrypt or view a particular draft. Store key identifiers and rotation state under controlled ownership, restrict decryption grants and test old-data recovery during rotation. Recovery-region credentials and keys must be available under the disaster policy without granting ordinary clients administrative access.

Signed download URLs are bearer capabilities for their lifetime. Keep their object/version, operation and expiry narrow, avoid logging them and choose an explicit cache policy. Revoking an application session does not automatically invalidate an already issued storage URL. Immediate revocation may require an enforcing access gateway or another supported revocation mechanism; short expiry bounds exposure but is not instant recall.

For cookie-authenticated state changes, apply the appropriate CSRF/session protections. CORS controls browser cross-origin behavior; it is not object authorization. Validate structured input and parameterize database operations. Untrusted fetch/export callbacks also need SSRF defenses at connection and redirect/egress boundaries, not just a superficial URL prefix check. Use established security libraries and platform controls rather than treating this chapter's pseudocode as complete cryptographic or network validation.

Audit and bound the abuse path

Record actor/workload identity, tenant, action, resource reference, decision/reason, policy version and correlation ID where appropriate. Minimize sensitive content in the audit record. Access to audit search, retention and privileged correction needs its own policy. A support tool that dumps all draft bodies into debug logs creates a second data-access surface.

Apply tenant quotas, payload limits, query bounds and export concurrency limits. Authorization cannot make an unbounded export safe for neighboring tenants. Track denial spikes and unusual cross-tenant resource attempts without placing every user ID in an unbounded metrics label. Expected denials and policy-authority failures should be distinguishable in secured diagnostics.

Check your understanding

Question: Ben has a valid T2 session and knows the ID of T1's draft. Can the service return its cached title before checking the body permission?

Show answer and explanation

Answer: No. Titles and existence can be sensitive too. Derive trusted scope and enforce the resource/field policy before disclosure, including cached or indexed data.

Question: An export was accepted while Ana was an editor. Does its queue message authorize a worker to publish it after her removal?

Show answer and explanation

Answer: Not under this exercise's current-eligibility policy. The worker must validate its scoped delegation and current job/resource policy. The queue payload cannot mint authority.

Question: A signed object URL expires in ten minutes. Does revoking the user's app session immediately prevent that URL being used?

Show answer and explanation

Answer: Not automatically. The object service enforces its own capability contract. State the remaining window or use an architecture that enforces current access at download time.

Transfer exercise and scoring

For API Design, Customer Support Bot and Distributed Blob Store, identify the authenticated context, object/field policy, cache/projection scope, asynchronous delegation and revocation/audit boundary. Score one point for each concrete enforcement point. Test both a cross-tenant caller and a formerly permitted same-tenant caller before claiming isolation.

Continue with Idempotency and Delivery Semantics for scoped retries and Multi-region Disaster Recovery for recovery identities/keys.

Primary references and scope

The tenant, resource, worker and cache examples are original teaching scenarios. Repository checks exercise a small policy model, not real JWT verification, RLS integration, cryptographic key rotation or a penetration test.

Your study notes