Skip to content

Interview PrepArchitecture · Advanced

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:

RuleAttack it stops
Size and count limitsFilling the disk or memory, a denial of service
Check magic bytes, allow-list typesshell.php renamed to cat.jpg
Random server-side name../../etc/passwd path traversal, overwriting files
Store outside the web rootThe server running an uploaded script
Separate download domainAn uploaded HTML file running scripts on your main origin
nosniff and attachmentThe browser treating the file as a page (the nosniff question)
Malware scanSpreading viruses to other users
Re-encode imagesHidden 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 })
})
  1. 5 MB and one file at most. Multer stops reading and returns an error past the limit, so a huge upload never fills memory.
  2. Read the magic bytes. A PNG always starts with the same eight bytes. This catches a script renamed to .png.
  3. A random name the server chooses, under the user's own folder. The client's filename is never used as a path.
  4. 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 all

Read 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 headerAttack
X-Forwarded-For: 10.0.0.1Look 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: httpsMake the app think a plain-HTTP request is secure
X-Forwarded-Host: evil.examplePassword-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 network

With 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.

internetanyonereverse proxyends TLSfirewall rules · rate limitsbody size limits · timeoutsadds X-Forwarded-Forsecurity headersprivate networkapp instance Aapp instance Baccepts traffic onlyfrom the proxydirect path must be blocked by the firewall
The proxy is a guard at the only door. It filters and limits traffic before your code sees it. That only works if the dashed path, straight from the internet to the app's port, is closed by network rules.

What the proxy gives you, and what it costs:

GivesCosts
One place for TLS and certificatesTraffic behind it may be plain HTTP
App servers hidden from the internetApp sees the proxy's IP, needs trust proxy (question 41)
Size limits and slow-client timeoutsTwo parsers that may disagree, enabling smuggling (the smuggling question)
Firewall and rate limits at the edgeA misconfigured proxy can expose internal paths such as /admin or /metrics
Caching static filesCaching a private page serves one user's data to another

Checklist for the proxy in front of an Express app:

  1. Only the proxy may reach the app's port. Enforce it with security groups or firewall rules.
  2. Set trust proxy to the exact hop count.
  3. Use HTTP/2 or HTTP/1.1 with keep-alive between proxy and app, with the proxy normalising or rejecting ambiguous requests.
  4. Send Cache-Control: private, no-store on personal responses so the CDN never caches them.
  5. Block internal-only routes at the proxy.
  6. 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.

LayerControlStops or limits
EdgeWeb application firewall, rate limitsKnown attack patterns, automated scanning
TransportTLS, HSTSSnooping and tampering on the network
IdentityMFA, short-lived tokensStolen passwords
AppInput validation, parameterised queries, authorisation checksInjection, reading others' data
BrowserCSP, cookie flagsXSS turning into account takeover
DataLeast-privilege database user, encryption at restDamage after a breach
DetectionAudit logs, alertsA 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".

castle and moatfirewall: inside means trustedHR appbillingdatabasehacked laptopzero trustHR appbillingdatabasecheck: who · device · policyany request
Location stops meaning trust. On the left, one compromised laptop inside the wall reaches every system. On the right, every request to every system, from anywhere, passes the same identity and policy check, so a compromised laptop gets only what its user was allowed.

What Zero Trust looks like in practice:

Old habitZero Trust version
VPN puts you "inside"Per-application access through an identity-aware proxy
Services trust anything on the private networkEach service checks a token or client certificate
Plain HTTP inside the data centremTLS between services (question 46)
Admin access foreverJust-in-time access that expires after hours
Check at login onlyRe-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:

LevelToo muchLeast privilege
Database userOwner of the whole databaseSELECT, INSERT, UPDATE on its own schema
Cloud roleAdministratorAccessRead one bucket, write one queue
ContainerRuns as root, writable file systemNon-root user, read-only root, dropped Linux capabilities
CI tokenAdmin on the organisationDeploy one service, expires after the job
Human accessPermanent production adminRequested, approved, expires in a few hours
API keyFull account accessScoped 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 deploys

If 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.

ordersclient certCN=orderspaymentsserver certCN=paymentsinternal CA① here is my certificate② orders checks it against the internal CA③ now show me yours④ orders sends its certificate; payments checks it⑤ both sides known · channel encrypted
Both sides show ID. ① and ② are ordinary TLS: the client checks the server. ③ and ④ are the extra half: the server asks for and checks the client's certificate. ⑤ Payments now knows for certain the caller is orders, before any HTTP request is read.

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)
  1. Trust only your internal certificate authority for client certificates.
  2. Ask every client for a certificate.
  3. Refuse the connection if there is none, or it was not signed by that CA.
  4. Authorise by identity. A valid certificate proves who is calling. You still decide what that caller may do.

mTLS versus a token between services:

mTLSToken, such as a JWT
ProvesWhich service is connectingWhich service, and often which user it acts for
Checked atConnectionEvery request
Hard partIssuing and rotating certificatesIssuing, signing and validating tokens
Common patternBoth: 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.

useraccess token① API gatewayTLS · verify tokenrate limit · validate② orderschecks token againown DB user③ paymentsmTLS: is it orders?token: which user?④ vaultper-service secrets⑤ logs and tracesevery call recordedmTLS
Check at the door, and again at every room. ① The gateway stops the obvious attacks. ② Orders re-checks the token, so a request that slipped past the gateway still fails. ③ Payments checks both who is calling, orders, through mTLS, and for which user, through the token. ④ Each service gets only its own secrets. ⑤ Every call is traced.

The checklist, layer by layer:

LayerDo
EdgeAPI gateway: TLS, token check, rate limits, size limits
Service identitymTLS or signed service tokens on every internal call
User identityForward the signed access token, or exchange it for a narrower one
AuthorisationEvery service checks permissions for its own data (the object-level check)
NetworkDefault deny; allow only the calls the design needs
DataOne database per service, its own least-privilege credentials
SecretsVault, per-service policies, rotation
Supply chainScan images and dependencies, sign builds
DetectionCentral 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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Web & API Security
Attacks
Browser rules
Abuse
Secrets
Architecture
Other topics
Nothing picked yet