5 Identity permissions and secure boundaries
Write down assets, actors, entry points, trust boundaries, and failure consequences. Assets include credentials, private text, job results, administrative access, and compute budget.
Outcome: identify who may perform each operation and prove that rejected requests cannot cross the boundary. Prerequisites: the API and data chapters. Environment: a disposable lab with synthetic data. Reference: [OWASP API Security](https://owasp.org/projects/api-security-project).
Start with a threat model
Write down assets, actors, entry points, trust boundaries, and failure consequences. Assets include credentials, private text, job results, administrative access, and compute budget. Actors include a legitimate tenant, another tenant, an unauthenticated caller, an operator, an upstream service, and an AI agent. Entry points include HTTP bodies, headers, webhooks, uploaded files, dependency packages, and model tool arguments.
For each boundary ask: who supplies this value; who validates it; which identity authorizes the action; what is recorded; and what is the maximum possible effect? A private network reduces exposure but does not remove the need for application authorization. A model's explanation is not proof of permission.
Authentication versus authorization
Authentication establishes an identity. Authorization decides whether that identity may perform an action on a resource. Tenant isolation is authorization scoped to an organization or account. A bearer token is usable by whoever possesses it, so store and transmit it accordingly.
The lab stores SHA-256 digests of random service tokens with tenant, scope, expiry and revocation state. Presented tokens are looked up by digest; every job lookup also includes the authenticated tenant. Generated bootstrap secrets remain in private operator configuration. Chapter 15 adds scrypt password login and short sessions; this is not a full identity provider.
For human login use a maintained identity implementation and understand its protocol. OAuth delegates authorization; OpenID Connect adds identity information. JWT is a token representation, not an authentication system by itself. Validate signature, permitted algorithms, issuer, audience, time bounds, and required permissions using the provider's supported libraries. Do not accept a token intended for another API merely because its signature is valid.
Cookies need appropriate Secure, HttpOnly, and SameSite attributes. Cookie-authenticated state changes may require CSRF defenses. The sample API uses an explicit Authorization header and no session cookies; do not blindly copy that threat assessment into a browser login flow. CORS allowlists and cookie policy must match the intended frontend origins and authentication flow.
Permissions at the operation and object level
Define actions such as submit job, read owned job, cancel owned job, inspect all jobs, and replay failed work. An administrator capability should be separate from an ordinary client's credential. Avoid a generic “admin” boolean that accidentally bypasses every control without an audit trail.
For a database query, include the authorized tenant in the predicate. For object storage, generate short-lived scoped access only after checking ownership. For a queue, preserve authenticated tenant context from the trusted ingestion point; never replace it with a field from a task payload. Test both missing permissions and valid permissions applied to another tenant's object.
Secrets and rotation
Generate credentials with a cryptographic random generator. Keep them out of source, container images, command histories, logs, and screenshots. A local .env file is a lab convenience. A deployed service should receive secrets through an appropriately controlled mechanism, with restricted readers and a documented rotation process.
A rotation needs overlap or coordinated clients: issue a new credential, distribute it securely, verify use, revoke the old credential, and check rejection. Restarting a process may be required if it reads configuration only at startup. Rotating a database password also affects connection pools and worker processes. Practice with a disposable identity first.
The Docker build excludes .env, databases, and dumps. The worker and schema initializer receive database credentials but not API tenant tokens. A process should receive only the secrets it needs. Host or Docker administrators can inspect container environment values; choose a stronger secret delivery mechanism where that trust model is unacceptable.
Validate more than JSON shape
Bound body size, text length, execution time, concurrency, and output size. The sample bounds request bodies and their read duration. A reverse proxy or gateway must also constrain unauthenticated connection and request abuse. Per-tenant application limiting does not stop all traffic before authentication and does not coordinate across replicas.
For file upload, validate content independently of the claimed MIME type, assign server-generated storage names, prevent path traversal, isolate parsing, and enforce decompressed-size limits. Never make an uploaded file executable. For an outbound URL, consider SSRF: private addresses, redirects, DNS changes, and cloud metadata endpoints. Prefer fixed upstream destinations and allowlisted operations.
Use safe database parameters. Escape output according to its destination. HTML escaping does not make a string safe in a shell, SQL query, or URL. Return generic internal-error responses with an opaque incident identifier, while retaining carefully redacted diagnostic evidence internally.
Supply chain and service privileges
Lock dependencies, scan them, and evaluate findings rather than automatically applying every suggested upgrade. Pin release images by digest for a deployed release, record their origin, and rebuild regularly. Image tags in the teaching Compose file are convenient moving references; the deployment procedure explains how to record exact digests.
Run application containers as a non-root user, drop unused capabilities, use a read-only filesystem where feasible, and restrict writable paths. Resource limits reduce accidental exhaustion but do not establish tenant fairness on their own. Do not mount the Docker socket into an application; access to it can grant control of the host.
A database runtime role should not be a superuser. This reference architecture separates lab_owner migration ownership from lab_app runtime DML. The native PostgreSQL drill verifies runtime schema creation is denied. Granting a service the ability to migrate does not mean every request handler should have that privilege.
Security acceptance exercises
- A missing or invalid token produces 401.
- A valid token for tenant B cannot read tenant A's object.
- Client fields cannot replace trusted tenant identity.
- Duplicate submissions do not bypass authorization or create duplicate effects.
- Oversized and slow bodies fail within bounded resource use.
- Database errors do not reveal SQL parameters or secrets in the response.
- A rotated credential stops working after the documented transition.
- A workload cannot write outside its designated storage or invoke arbitrary commands.
These are tests of behavior, not a complete compliance certification. Review the application in its actual deployment context before using sensitive data.
Incident drill
Assume a disposable token was exposed. Identify its scope, revoke it, deploy the replacement safely, inspect its usage without copying sensitive payloads, and check whether related secrets or data were accessed. Record a timeline and corrective actions. Do not erase logs before investigating. You pass when you can contain exposure and restore authorized access without changing unrelated identities.
Lock in what you just learned (3 quick questions)
tenant_id strictly from verified server-side session/JWT claims rather than client request bodies?