Appearance
Secure Architecture
40. How do you securely handle file uploads?
The short answer
Treat every uploaded file as hostile. Limit the size and the number of files. Check the real type from the file's first bytes, not from the name or the Content-Type the client sent. Allow only the few types you need. Rename the file to a random ID, never use the user's filename as a path. Store it outside the web root, ideally in object storage such as S3, in a bucket that does not execute anything. Serve it from a separate domain with Content-Disposition: attachment and nosniff. Scan for malware, strip image metadata, and re-encode images when you can.
Each rule, and the attack it stops:
| Rule | Attack it stops |
|---|---|
| Size and count limits | Filling the disk or memory, a denial of service |
| Check magic bytes, allow-list types | shell.php renamed to cat.jpg |
| Random server-side name | ../../etc/passwd path traversal, overwriting files |
| Store outside the web root | The server running an uploaded script |
| Separate download domain | An uploaded HTML file running scripts on your main origin |
nosniff and attachment | The browser treating the file as a page (the nosniff question) |
| Malware scan | Spreading viruses to other users |
| Re-encode images | Hidden payloads and GPS location in metadata |
ts
import multer from 'multer'
import { fileTypeFromBuffer } from 'file-type'
import { randomUUID } from 'node:crypto'
const ALLOWED = new Set(['image/png', 'image/jpeg', 'application/pdf'])
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024, files: 1 }, // (1)
})
app.post('/api/receipts', requireUser, upload.single('receipt'), async (req, res) => {
const file = req.file
if (!file) throw new HttpError(400, 'No file')
const type = await fileTypeFromBuffer(file.buffer) // (2)
if (!type || !ALLOWED.has(type.mime)) throw new HttpError(415, 'Unsupported file type')
const key = `receipts/${req.user.id}/${randomUUID()}.${type.ext}` // (3)
await s3.putObject({ Bucket: UPLOADS_BUCKET, Key: key, Body: file.buffer, ContentType: type.mime }) // (4)
res.status(201).json({ id: key })
})- 5 MB and one file at most. Multer stops reading and returns an error past the limit, so a huge upload never fills memory.
- Read the magic bytes. A PNG always starts with the same eight bytes. This catches a script renamed to
.png. - A random name the server chooses, under the user's own folder. The client's filename is never used as a path.
- Private object storage, with the type we detected, not the one the client claimed.
Large files skip your server entirely. Give the browser a short-lived presigned URL and let it upload straight to S3. Your server only checks the result (the large uploads question).
41. What are the risks of trusting X-Forwarded-* headers?
The short answer
X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host are added by proxies to tell the app the original client IP, scheme and host. But any client can send these headers too. If the app trusts them blindly, an attacker can fake their IP to dodge rate limits and IP allow-lists, pretend the request came over HTTPS, or poison password-reset links with their own host. Trust them only from your own proxies: in Express, set trust proxy to the exact number of proxy hops, or to your proxies' addresses, never to true on the open internet.
How the header grows, and which part to believe. Each proxy appends the address it received the request from:
text
X-Forwarded-For: 6.6.6.6, 203.0.113.7, 10.0.0.5
│ │ └ added by your load balancer: the CDN's address
│ └ added by the CDN: the real client
└ typed by the client: anything at allRead the list from the right. Skip the hops you control. The first address you did not add yourself is the real client. The left-most entry is whatever the client chose to send.
| Faked header | Attack |
|---|---|
X-Forwarded-For: 10.0.0.1 | Look like an internal address and pass an IP allow-list |
X-Forwarded-For: <random> | A fresh IP on every request, so rate limits never trigger |
X-Forwarded-Proto: https | Make the app think a plain-HTTP request is secure |
X-Forwarded-Host: evil.example | Password-reset emails link to the attacker's site, leaking the token |
The Express setting:
ts
app.set('trust proxy', 1) // exactly one proxy, the load balancer, sits in front
// or: app.set('trust proxy', ['10.0.0.0/8']) // trust only addresses in your private networkWith 1, req.ip is the address the load balancer saw, and anything the client added further left is ignored (the trust proxy question).
Never build links from request headers. Generate password-reset and email links from a configured PUBLIC_URL, not from Host or X-Forwarded-Host.
42. How do reverse proxies affect application security?
The short answer
A reverse proxy, such as Nginx, a cloud load balancer or a CDN, sits between the internet and your app. It helps a lot: it ends TLS, hides your servers, absorbs some attacks, enforces size limits and timeouts, adds headers, and is where a web application firewall and rate limits live. It also adds risks: the app now sees the proxy's IP and must trust forwarded headers correctly, the proxy and app may parse requests differently, which enables request smuggling, and traffic behind it may be unencrypted. Lock the app so it only accepts traffic from the proxy.
What the proxy gives you, and what it costs:
| Gives | Costs |
|---|---|
| One place for TLS and certificates | Traffic behind it may be plain HTTP |
| App servers hidden from the internet | App sees the proxy's IP, needs trust proxy (question 41) |
| Size limits and slow-client timeouts | Two parsers that may disagree, enabling smuggling (the smuggling question) |
| Firewall and rate limits at the edge | A misconfigured proxy can expose internal paths such as /admin or /metrics |
| Caching static files | Caching a private page serves one user's data to another |
Checklist for the proxy in front of an Express app:
- Only the proxy may reach the app's port. Enforce it with security groups or firewall rules.
- Set
trust proxyto the exact hop count. - Use HTTP/2 or HTTP/1.1 with keep-alive between proxy and app, with the proxy normalising or rejecting ambiguous requests.
- Send
Cache-Control: private, no-storeon personal responses so the CDN never caches them. - Block internal-only routes at the proxy.
- Re-encrypt to the app if your threat model includes the internal network (question 44).
43. What is defence in depth?
The short answer
Defence in depth means using several independent layers of protection, so that when one fails, and one eventually will, the next still stops or limits the attack. No single control is trusted to be perfect. For a web app the layers are the network, the edge proxy, the app's own checks, the data layer and monitoring. For example, SQL injection is stopped by parameterised queries, but the database user also cannot drop tables, the data is encrypted, and an alert fires on strange queries.
One attack, many layers: an attacker tries to steal customer data.
| Layer | Control | Stops or limits |
|---|---|---|
| Edge | Web application firewall, rate limits | Known attack patterns, automated scanning |
| Transport | TLS, HSTS | Snooping and tampering on the network |
| Identity | MFA, short-lived tokens | Stolen passwords |
| App | Input validation, parameterised queries, authorisation checks | Injection, reading others' data |
| Browser | CSP, cookie flags | XSS turning into account takeover |
| Data | Least-privilege database user, encryption at rest | Damage after a breach |
| Detection | Audit logs, alerts | A breach going unnoticed for months |
The interview point: each layer assumes the one before it has already failed. The app validates input even though the firewall filters. The database user has limited rights even though the app uses parameterised queries. That is why one bug does not become a full breach.
Where it goes wrong: layers that are not really independent. If one admin password unlocks the firewall, the servers and the database, there is only one layer.
44. What is Zero Trust security?
The short answer
Zero Trust means no request is trusted because of where it comes from. The old model trusted anything inside the corporate network, which let one compromised laptop reach everything. Zero Trust instead checks every request, from users and services alike: who is asking, is their device healthy, are they allowed this exact action right now. It relies on strong identity everywhere, encryption everywhere including inside the network, least-privilege access, and continuous monitoring. The short form is "never trust, always verify".
What Zero Trust looks like in practice:
| Old habit | Zero Trust version |
|---|---|
| VPN puts you "inside" | Per-application access through an identity-aware proxy |
| Services trust anything on the private network | Each service checks a token or client certificate |
| Plain HTTP inside the data centre | mTLS between services (question 46) |
| Admin access forever | Just-in-time access that expires after hours |
| Check at login only | Re-check risk continuously: new device, new country, odd behaviour |
It is a direction, not a product. A vendor cannot sell you Zero Trust in one box. It is many changes, made over time, that all remove "trusted because it is inside".
45. What is the principle of least privilege?
The short answer
Give every user, service and process only the permissions it needs to do its job, and only for as long as it needs them. Nothing more. Then when one part is compromised, the attacker gets only that small set of rights. Examples: the orders service's database user can read and write only its own tables, and cannot drop them. A CI job can deploy one app, not every app in the account. A container runs as a non-root user with a read-only file system.
Least privilege at every level:
| Level | Too much | Least privilege |
|---|---|---|
| Database user | Owner of the whole database | SELECT, INSERT, UPDATE on its own schema |
| Cloud role | AdministratorAccess | Read one bucket, write one queue |
| Container | Runs as root, writable file system | Non-root user, read-only root, dropped Linux capabilities |
| CI token | Admin on the organisation | Deploy one service, expires after the job |
| Human access | Permanent production admin | Requested, approved, expires in a few hours |
| API key | Full account access | Scoped to one action, such as orders:read |
A database example:
sql
CREATE ROLE orders_app LOGIN PASSWORD :'pw';
GRANT USAGE ON SCHEMA orders TO orders_app;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA orders TO orders_app; -- no DELETE, no DROP
-- migrations run as a separate role, only during deploysIf the orders service has a SQL injection bug, the attacker cannot read the billing schema or drop tables.
Why teams drift away from it. Broad permissions make things "just work". Fix this with tools, not willpower: start with nothing, add only what errors ask for, and review unused permissions regularly. Cloud providers report which granted permissions were never used.
46. What is mutual TLS (mTLS), and when should it be used?
The short answer
In normal TLS only the server proves who it is with a certificate. In mutual TLS, the client also presents a certificate, and the server checks it before accepting the connection. Both sides are authenticated, and the traffic is encrypted. It is used for service-to-service calls inside a system, especially in Zero Trust networks, for partner and bank APIs, and for IoT devices. It is rarely used for browsers, because managing a certificate on every user's device is hard. A service mesh such as Istio or Linkerd can add mTLS between services automatically.
Requiring a client certificate in Node:
ts
import https from 'node:https'
import { readFileSync } from 'node:fs'
import type { TLSSocket } from 'node:tls'
https.createServer({
key: readFileSync('payments.key'),
cert: readFileSync('payments.crt'),
ca: readFileSync('internal-ca.crt'), // (1)
requestCert: true, // (2)
rejectUnauthorized: true, // (3)
}, (req, res) => {
const caller = (req.socket as TLSSocket).getPeerCertificate().subject.CN // (4)
if (caller !== 'orders') { res.writeHead(403); return res.end() }
// handle the payment request
}).listen(8443)- Trust only your internal certificate authority for client certificates.
- Ask every client for a certificate.
- Refuse the connection if there is none, or it was not signed by that CA.
- Authorise by identity. A valid certificate proves who is calling. You still decide what that caller may do.
mTLS versus a token between services:
| mTLS | Token, such as a JWT | |
|---|---|---|
| Proves | Which service is connecting | Which service, and often which user it acts for |
| Checked at | Connection | Every request |
| Hard part | Issuing and rotating certificates | Issuing, signing and validating tokens |
| Common pattern | Both: mTLS for the service, a token for the end user |
The hard part is certificates, not the handshake. Every service needs a certificate that rotates often, ideally every few hours or days. Do this with automation, such as a service mesh or a workload identity system like SPIFFE, never by hand (the certificate rotation question).
47. How should a microservices architecture be secured?
The short answer
Secure the edge and every hop inside. At the edge, an API gateway handles TLS, authenticates users, rate limits and rejects bad input. Inside, each service authenticates its caller with mTLS or a signed token, and authorises every request itself instead of trusting the gateway alone. Pass the user's identity along as a signed token, not a plain header. Give each service its own database credentials and its own narrow permissions. Keep secrets in a vault. Restrict which services may talk to which with network policies. Log and trace every call so a breach can be followed.
The checklist, layer by layer:
| Layer | Do |
|---|---|
| Edge | API gateway: TLS, token check, rate limits, size limits |
| Service identity | mTLS or signed service tokens on every internal call |
| User identity | Forward the signed access token, or exchange it for a narrower one |
| Authorisation | Every service checks permissions for its own data (the object-level check) |
| Network | Default deny; allow only the calls the design needs |
| Data | One database per service, its own least-privilege credentials |
| Secrets | Vault, per-service policies, rotation |
| Supply chain | Scan images and dependencies, sign builds |
| Detection | Central logs, distributed tracing, alerts on unusual calls |
The mistake interviewers look for: "The gateway checks the token, so internal services trust any request with an X-User-Id header." Then anyone who reaches one internal service, through SSRF (the SSRF question) or a compromised pod, can act as any user by setting a header. Services must verify a signed token themselves.
Token exchange keeps damage small. Instead of forwarding the user's broad token everywhere, the orders service can swap it for a token valid only for payments and only for this one action. If payments is compromised, the token it holds is useless elsewhere.