Skip to content

15 min read

CSRF vs SSRF: what they are, how to stop them

In one sentence: In a CSRF, another site makes your browser send a request to the shop with your cookie; SameSite=Lax and checking the Origin header stop it. In an SSRF, someone gives the server a URL to visit, and it reaches what only the server can reach; checking which address it points to before connecting stops it.

What you will learn

  • Explain how another site can use your session, and what SameSite=Lax and the Origin header stop.
  • Know when you have to send Origin with curl from this lesson on.
  • Check a URL someone else gives you before visiting it, piece by piece.

Before you start, read: 06-injection.md

Carmen is signed in to the shop. In another tab she opens a link from an email: “You’ve won a prize!” She clicks the button, and that page sends the shop an order for ten units. With her cookie. As far as the shop knows, Carmen ordered it.

At the same time, Fast Delivery wants the shop to notify it of every paid order, and gives it a URL. What if the URL is http://localhost:5432, the database? The one making the request is the shop’s server, from the inside.

They’re two attacks with similar names, and in both there’s a request you didn’t make:

  • In CSRFCSRF stands for Cross-Site Request Forgery.An attack in which a page makes your browser send a request to a site where you’re logged in, with your cookies, to do something on your behalf, such as changing your email or buying something. CORS doesn’t prevent it, because many requests reach the server even if the page can’t read the response.Go to definition, your browser sends it, because another site asks it to.
  • In SSRFSSRF stands for Server-Side Request Forgery.An attack in which someone gives a server a URL to visit, and the server’s request reaches places only it can reach, like its own database, the internal network or the credentials the cloud gives it. It’s stopped by checking which IP address the URL points to before connecting.Go to definition, your server sends it, because someone gave it the address.

The analogy

You have an assistant who carries your membership card everywhere. A stranger hands them an envelope: “Take this to the club.” At the club they see your card and do what the envelope says. That’s CSRF. The defense: the assistant doesn’t show your card with other people’s envelopes (SameSite), and the club asks, “Who gave you this?” (Origin).

Now it’s the other way around. A visitor asks the club’s receptionist to take a package “to this address”: the manager’s office, where the visitor can’t go and she can. That’s SSRF. The defense: look at the address before leaving, go to that one and no other, and accept no detours on the way.

Where the analogy breaks down

  • The assistant could read the envelope; the browser doesn’t look at what the request does, only which site it goes to and which one it comes from.
  • A street address doesn’t change while you’re on your way. An internet name can point somewhere else between when you check it and when you connect: that’s why the server connects to the address it checked.
Section titled “Another site, your browser and your cookie”
  1. Carmen's browser → Other site (127.0.0.1:4000)GET /
  2. Other site (127.0.0.1:4000) → Carmen's browser“You've won a prize!”
    a hidden form
  3. Carmen's browser → Shop (localhost:3000)POST /v2/orders
    Cookie: session=… (no SameSite)
  4. Shop (localhost:3000)The cookie is Carmen's:
    an order for 10 in her name

The other site never sees the cookie, and doesn’t need to: the browser adds the shop’s cookie on its own to every request that goes to the shop, no matter who asks for it. That’s how cookies have worked since Phase 2.

CORSCORS stands for Cross-Origin Resource Sharing.The way a server tells the browser which other origins may read its responses from a page’s code, with headers such as Access-Control-Allow-Origin. The browser enforces it, not the server.Go to definition doesn’t stop it. As you saw in the CORS lesson, CORS decides whether the page reads the response, not whether the request arrives. And a form is a simple request: it goes out without asking.

The shop has two walls.

Since lesson 2, “Sessions,” the session cookie carries SameSite=Lax: the browser doesn’t send it in a POST that comes from another site. You saw it in the cookies lesson in Phase 2. The order arrives without a cookie, and the shop answers 401.

For the browser, 127.0.0.1 and localhost are two different sites, even though both are your computer. That’s why the practice “other site” is at 127.0.0.1:4000.

Why isn’t it enough? Because SameSite looks at the site, not the Origin (on the web)What identifies a website to the browser: the scheme (http or https), the server name and the port. https://shop.example and https://www.shop.example are different origins; the path doesn’t count.Go to definition: blog.shop.example is the same site as shop.example, and if someone gets into the blog, the cookie travels. And because an old browser may not follow it.

On every POST, the browser adds the Origin header with the origin of the page sending it. A page’s JavaScript can’t change it. The shop compares it with its list, in src/middleware/session.ts:

src/middleware/session.ts
// CSRF (lesson 7): another site makes your browser send a request here, with your cookie. Two
// walls: SameSite=Lax (above), because of which the browser doesn't send the cookie in a POST that
// comes from another site; and this one, in case an old browser doesn't follow it. Hono's csrf()
// looks at the requests that change something (POST, PUT, DELETE…) and that a form could send
// (without a body, or with a form's): they only pass if they come from a site in ALLOWED_ORIGINS
// (Origin header) or from this same one (Sec-Fetch-Site: same-origin). If not, 403.
// Only when the request carries the cookie: without it there's no session to steal, and a program
// that identifies itself with Authorization: Bearer doesn't send Origin, nor need it (the browser
// never puts that header on its own).
const fromAllowedOrigin = csrf({ origin: config.ALLOWED_ORIGINS });
export const checkOrigin: MiddlewareHandler = (c, next) =>
getCookie(c, COOKIE) === undefined ? next() : fromAllowedOrigin(c, next);
  • csrf({ origin: … }), from Hono, looks at the requests that change something (POST, PUT, DELETE…) and that a form could send: with no body, or with a form’s. They pass if Origin is in ALLOWED_ORIGINS, or if Sec-Fetch-Site, another header the browser sets, says same-origin. If not, 403.
  • ALLOWED_ORIGINS comes from .env: http://localhost:3000 on your computer; in production, https://shop.example.
  • Only with the cookie. Without it there’s no session to steal. And a program that uses Authorization: Bearer doesn’t need Origin: the browser never sets that header on its own.

What about a POST with JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition? It passes without looking at Origin, because another site can’t send it without asking first (the Preflight requestThe check the browser sends to another origin before a request that isn’t simple (for example, one that deletes data or carries custom headers), to ask the server whether it accepts it. It uses the OPTIONS method, and if the server doesn’t allow it, the real request is never sent.Go to definition), and the shop only gives permission to https://shop.example.

Before SameSite, and before browsers always sent Origin, the defense was a CSRF token: the server puts a random value in every form, in a hidden field, and requires it when the form comes back. The other site can’t read it, because of the same-origin policy.

It still works, and frameworks for sites with forms (Django, Rails, Laravel) come with it built in. OWASP asks you to use the protection your framework provides, and accepts the shop’s under conditions the shop meets: no route changes anything with a GET, in production everything goes over HTTPS, and without Sec-Fetch-Site, Origin is checked.

SSRF: the server visits the URL someone gives it

Section titled “SSRF: the server visits the URL someone gives it”

Now Fast Delivery wants a WebhookAn address on your server that another service sends a request to when something happens, such as a completed payment. Instead of you asking every so often whether something has changed, they let you know.Go to definition, like the payment gateway’s in Phase 4, but the other way around: when an order becomes paid, the shop sends it a signed POST. The company gives the URL with PUT /v2/delivery/notification, and the shop saves it in a new table, notifications.

The problem: whoever gives the URL decides where your server calls. And your server reaches places nobody else reaches:

  1. Whoever has the key → Shop's serverPUT /v2/delivery/notification
    url=http://169.254.169.254/…
  2. Shop's serverAn order is paid
  3. Shop's server → Cloud metadataPOST http://169.254.169.254/…
  4. Cloud metadataIt only answers whoever
    is inside the cloud
  • localhost:5432: PostgreSQL, which only listens on the server itself.
  • The internal network: other servers on Private IP addressIP stands for Internet Protocol.An IP address that only works inside a local network, such as 192.168.1.133. The same ones are reused in millions of homes, and they can’t be reached from the internet.Go to definition (10.…, 192.168.…), often without a password because “nobody can reach them from outside.”
  • 169.254.169.254: on AWS, Google Cloud and Azure, the metadata service answers there, and it gives the server its cloud credentials. That’s how the Capital One breach began in 2019, with the data of more than 100 million people.

The shop doesn’t show what the URL answers, and even so: a POST to an internal service can do something, and the timings and errors reveal which ports are open.

The route only accepts the delivery API key, and before saving, it checks the URL:

src/v2.ts
// The delivery company says which URL to notify. It's its API key that saves it: a person with the
// delivery role doesn't have a URL of their own. Before saving it, it's checked (safe-url.ts): if
// it points inside the server's network, 422.
v2.openapi(contract.setNotification, async (c) => {
const { apiKey } = c.var;
if (!apiKey) return httpProblem(c, 403, "Only with the delivery company's API key");
const checked = await checkUrl(c.req.valid('json').url);
if ('error' in checked) {
return invalidData(c, [{ field: 'url', problem: checked.error }]);
}
const url = checked.url.href;
return c.json({ url, secret: await saveNotification(apiKey.id, url) }, 200);
});
  • c.var.apiKey: the notifications:configure permission belongs to the delivery role, but the URL is the company’s, not a person’s with that role. Without the key, 403.
  • checkUrl returns the checked URL, or the reason to reject it, which goes in a 422.

src/safe-url.ts does the check. First, the scheme:

src/safe-url.ts
let url: URL;
try {
url = new URL(text);
} catch {
return { error: 'It is not a URL' };
}
if (url.username || url.password) {
return { error: 'The URL cannot carry a user or a password' };
}
const name = url.hostname.replace(/^\[(.*)\]$/, '$1'); // an IPv6 goes in brackets: [::1]
const forDevelopment = (options.devHosts ?? config.NOTIFICATION_DEV_HOSTS).includes(name);
// 1. Only https: nobody on the way reads what travels. http, only in development.
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && forDevelopment)) {
return { error: 'It has to start with https://' };
}
  • new URL(text) reads it the way the request will: if it isn’t a URL, it’s out.
  • No user or password inside (https://ana:secret@…).
  • Only https://: the notification carries order data. http:// only for the names in NOTIFICATION_DEV_HOSTS, on your computer.

Next, which addresses the name points to:

src/safe-url.ts
// 2. The name, turned into addresses (if it's already an address, that one).
const family = isIP(name);
const addresses =
family !== 0
? [{ address: name, family }]
: await (options.resolver ?? dnsResolver)(name).catch(() => []);
if (addresses.length === 0) return { error: `${name} cannot be found` };
// 3. None can be internal. Looking at the name isn't enough: anyone can create a name that
// points to 127.0.0.1. What counts is the address.
if (!forDevelopment) {
const internal = addresses.find((address) =>
FORBIDDEN.check(address.address, address.family === 6 ? 'ipv6' : 'ipv4'),
);
if (internal) return { error: `It points to an internal address (${internal.address})` };
}
return { url, address: addresses[0]! };
  • dnsResolver asks DNSDNS stands for Domain Name System.The system that turns names such as example.com into IP addresses (and stores other data about the domain, such as its mail servers). It is a database spread across the whole world, organized as a tree of names.Go to definition for all the name’s addresses (lookup, with all: true).
  • None can be in FORBIDDEN. Looking at the name isn’t enough: 127.0.0.1.nip.io is a public name that points to 127.0.0.1, and anyone can create another one.

The list is at the top of the file, in a Node BlockList:

src/safe-url.ts
// The addresses nothing is ever sent to: the ones that aren't the internet's, but the server's own
// or its network's. An IPv4 address written as IPv6 (::ffff:127.0.0.1) counts too: BlockList
// compares it with the IPv4 rules.
const FORBIDDEN = new BlockList();
FORBIDDEN.addSubnet('0.0.0.0', 8); // "this network"
FORBIDDEN.addSubnet('10.0.0.0', 8); // private
FORBIDDEN.addSubnet('100.64.0.0', 10); // shared by the carriers (CGNAT)
FORBIDDEN.addSubnet('127.0.0.0', 8); // loopback: the server itself
FORBIDDEN.addSubnet('169.254.0.0', 16); // link-local: the cloud's metadata is here
FORBIDDEN.addSubnet('172.16.0.0', 12); // private
FORBIDDEN.addSubnet('192.168.0.0', 16); // private
FORBIDDEN.addSubnet('192.0.0.0', 24); // reserved for protocols
FORBIDDEN.addSubnet('198.18.0.0', 15); // reserved for network testing
FORBIDDEN.addSubnet('224.0.0.0', 4); // multicast
FORBIDDEN.addSubnet('240.0.0.0', 4); // reserved, with 255.255.255.255
FORBIDDEN.addAddress('::', 'ipv6'); // "none"
FORBIDDEN.addAddress('::1', 'ipv6'); // loopback
FORBIDDEN.addSubnet('64:ff9b::', 96, 'ipv6'); // NAT64: an IPv4 hidden inside an IPv6
FORBIDDEN.addSubnet('fc00::', 7, 'ipv6'); // unique-local: IPv6's private ones
FORBIDDEN.addSubnet('fe80::', 10, 'ipv6'); // link-local
FORBIDDEN.addSubnet('ff00::', 8, 'ipv6'); // multicast

They’re the main ranges that aren’t the internet: the server itself (127.0.0.0/8, ::1), the private networks, 169.254.0.0/16 with the metadata, and their IPv6 equivalents. /8 means “the first 8 bits fixed”: 127.0.0.0/8 goes from 127.0.0.0 to 127.255.255.255.

When sending the notification, the shop checks again, and connects to the address it has just checked:

src/safe-url.ts
// 4. It connects to the checked address, without asking DNS again: the second answer could be
// another one (127.0.0.1), and the check would have been for nothing (DNS rebinding).
const withTheChecked = ((_name, dnsOptions, done) => {
if (dnsOptions.all) done(null, [address]);
else done(null, address.address, address.family);
}) as LookupFunction;
const request = url.protocol === 'https:' ? requestHttps : requestHttp;
return new Promise((resolve) => {
const req = request(
url,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
lookup: withTheChecked,
timeout: TIMEOUT, // 5. If it doesn't answer in time, it's cut off
},
  • lookup: withTheChecked replaces the DNS query http.request would make with the address already checked.
  • timeout: TIMEOUT: if 5 seconds go by with nothing arriving, it’s cut off. A server that doesn’t answer doesn’t leave the shop waiting.

Why not ask DNS again? Because of DNS rebinding. Whoever controls a name controls its answers, and its TTL (in DNS)TTL stands for time to live.The number of seconds a DNS answer may be kept in a cache before asking again. It has nothing to do with the TTL of IP packets, which counts how many routers they may go through.Go to definition can be zero seconds. To the first question it answers with a public IP, and the check passes; to the second, the connection’s, it answers 127.0.0.1. If you checked one address and connected to another, the check would have been for nothing.

src/safe-url.ts
(response: IncomingMessage) => {
const status = response.statusCode ?? 0;
// 6. Redirects aren't followed: a 302 could lead to an internal address.
if (status >= 300 && status < 400) {
response.destroy();
return resolve({ error: `It answers ${status}, a redirect: it is not followed` });
}
// 7. The response is read with a cap: one that never ends would keep the server waiting.
let read = 0;
response.on('data', (chunk: Buffer) => {
read += chunk.length;
if (read > MAX_SIZE) {
response.destroy();
resolve({ error: 'The response is too big' });
}
});
response.on('end', () => resolve({ status }));
},
  • A RedirectAn HTTP response that says “what you’re looking for is at another address.” It carries a code starting with 3, such as 301, and the Location header with the new address. The browser requests it on its own, without you doing anything.Go to definition isn’t followed. The public URL could answer 302 with Location: http://169.254.169.254/…, and whoever followed it would get inside without checking anything.
  • The response is cut off at 64 KB: one that never ends would keep the shop reading forever.

And the URL is checked twice: when it’s saved, to tell the company about its mistake, and when each notification is sent, because the name that pointed to the internet yesterday may point somewhere else today.

The goal: see with curl and in the browser how the shop rejects an order that comes from another site, and get it to reject URLs that point inside your computer.

You’re attacking your own shop, on localhost: doing it against someone else’s system, without permission, is a crime.

You start from your project from lesson 6, “Injection”:

  1. In src/middleware/session.ts, checkOrigin; in src/app.ts, app.use(checkOrigin) before loadSession, and the 403 message in onError.
  2. Create src/safe-url.ts and src/notifications.ts. In src/schema.ts, the notifications table; in src/permissions.ts, notifications:configure for delivery; the route, in src/contract.ts, src/schemas.ts and src/v2.ts, and notifyPayment when an order becomes paid. Whatever you haven’t seen here, copy it from the step.
  3. The two new variables in src/config.ts, and in your .env (the marked lines). Without ALLOWED_ORIGINS, the shop won’t start:
.env.example
# Copy this file as .env and change the values. .env isn't uploaded to Git: it's in .gitignore.
PORT=3000
LOG_LEVEL=info
# The secret the shop shares with the payment gateway to sign the webhooks. A different one.
WEBHOOK_SECRET=change-this-to-another-long-secret
# The database: postgres://user:password@server:port/database. The password is the one you gave
# the shop user when you created it.
DATABASE_URL=postgres://shop:change-this-password@localhost:5432/shop
# The identity provider (lesson 4). For practice, the one from npm run provider, on your computer:
# it accepts any id and secret. With Google, the issuer is https://accounts.google.com, and Google
# Cloud gives you the id and the secret when you register the shop (with the exact redirect URL
# below).
OIDC_ISSUER=http://localhost:9000
OIDC_CLIENT_ID=shop
OIDC_CLIENT_SECRET=change-this-to-the-provider-secret
OIDC_REDIRECT_URI=http://localhost:3000/v2/session/provider/callback
# The sites requests with the session cookie are accepted from (lesson 7), separated by commas:
# the shop itself and, if there is one, the site that uses the API.
ALLOWED_ORIGINS=http://localhost:3000
# Only on your computer: names the shop can send the delivery notifications to over http, even if
# they're internal (localhost). On a real server, leave it empty.
NOTIFICATION_DEV_HOSTS=
  1. The other-site script in package.json:
package.json
{
"name": "shop-api",
"version": "1.0.0",
"private": true,
"type": "module",
"engines": {
"node": ">=24"
},
"scripts": {
"start": "node --env-file-if-exists=.env src/server.ts",
"dev": "node --env-file-if-exists=.env --watch src/server.ts",
"test": "node --env-file=test/.env --test --test-concurrency=1",
"check": "tsc --noEmit",
"gateway": "node --env-file-if-exists=.env scripts/payment-gateway.ts",
"db:migrate": "node --env-file-if-exists=.env scripts/migrate.ts",
"db:seed": "node --env-file-if-exists=.env scripts/seed.ts",
"db:many-orders": "node --env-file-if-exists=.env scripts/many-orders.ts",
"db:generate": "drizzle-kit generate",
"create-key": "node --env-file-if-exists=.env scripts/create-key.ts",
"provider": "node scripts/provider.ts",
"other-site": "node scripts/other-site.ts"
},
"dependencies": {
"@hono/node-server": "2.1.8",
"@hono/zod-openapi": "1.6.3",
"@hono/zod-validator": "0.9.1",
"@scalar/hono-api-reference": "0.12.10",
"drizzle-orm": "0.45.3",
"hono": "4.13.18",
"jose": "6.2.12",
"openid-client": "6.8.8",
"pg": "8.23.1",
"pino": "10.4.0",
"protobufjs": "8.8.0",
"ws": "8.22.0",
"zod": "4.6.7"
},
"devDependencies": {
"@types/node": "26.6.4",
"@types/pg": "8.23.1",
"@types/ws": "8.18.2",
"drizzle-kit": "0.31.11",
"oauth2-mock-server": "9.2.0",
"typescript": "7.0.2"
}
}

The other site, the migration and the tests come in this lesson’s folder, with a test/.env that already has ALLOWED_ORIGINS:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/30-csrf-ssrf.tar.gz
tar -xzf 30-csrf-ssrf.tar.gz
cd shop-api
cp ../30-csrf-ssrf/scripts/other-site.ts scripts/
cp ../30-csrf-ssrf/db/migrations/010-notifications.sql db/migrations/
cp ../30-csrf-ssrf/test/*.ts ../30-csrf-ssrf/test/.env test/

1. The notifications table

Ventana de terminal
npm run db:generate -- --name=notifications
npm run db:migrate

What you will see:

> shop-api@1.0.0 db:generate
> drizzle-kit generate --name=notifications
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/ana/backend-course/phase-3/shop-api/drizzle.config.ts'
10 tables
api_keys 6 columns 0 indexes 0 fks
categories 2 columns 0 indexes 0 fks
idempotency_keys 6 columns 0 indexes 0 fks
notifications 4 columns 0 indexes 1 fks
orders 6 columns 2 indexes 2 fks
processed_events 2 columns 0 indexes 0 fks
product_categories 2 columns 1 indexes 2 fks
products 4 columns 0 indexes 0 fks
sessions 4 columns 0 indexes 1 fks
users 6 columns 1 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0007_notifications.sql 🚀
> shop-api@1.0.0 db:migrate
> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 010-notifications.sql

The first command saves drizzle-kit’s snapshot, as in earlier lessons; the second applies the migration you copied. The outputs are from Node 26.11.1 and PostgreSQL 18; your ids, keys and times will be different.

2. This lesson’s tests

Ventana de terminal
npm test -- test/csrf-ssrf.test.ts

What you will see:

> shop-api@1.0.0 test
> node --env-file=test/.env --test --test-concurrency=1 test/csrf-ssrf.test.ts
✔ CSRF: another site's form with the session cookie: 403; from the shop, it passes (58.639731ms)
✔ CSRF: cancelling with the cookie and without Origin, 403; with Bearer, which the browser does not add on its own, yes (7.9437ms)
✔ CSRF: a POST with JSON and the cookie does pass: another site cannot send it without CORS asking (4.095665ms)
✔ scripts/other-site.ts: the page sends a form and a fetch to the shop (0.434697ms)
✔ SSRF: http, localhost, the cloud's metadata, a name that points to 127.0.0.1, ::1… rejected (5.200642ms)
✔ SSRF: a public address is accepted, and it is the one that will be connected to (0.532731ms)
✔ SSRF: a redirect is not followed (6.461131ms)
✔ a paid order's notification arrives signed at the delivery company's URL (7.055384ms)
✔ PUT /v2/delivery/notification: the delivery key saves a public URL; an internal one, 422 (7.451442ms)
ℹ tests 9
ℹ suites 0
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 647.541954

The SSRF tests don’t leave your computer: they use a fake DNS that answers whatever each one asks for. If they fail with Configuration: …, the test/.env is missing.

Start the shop with npm start and, in another terminal, sign in as Carmen:

3. Carmen’s session

Ventana de terminal
curl -s -w '\n' -c carmen.txt --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/session

What you will see:

{"id":5,"email":"carmen@example.com","role":"customer"}

If you get a 400, check the password in the project’s README.

Now send the same thing the other site’s form sends, with its Origin, and then with the shop’s:

4. The form, from outside and from inside

Ventana de terminal
curl -s -w '\n' -b carmen.txt -H 'Origin: http://127.0.0.1:4000' -d 'productId=1&quantity=10' localhost:3000/v2/orders
curl -s -w '\n' -b carmen.txt -H 'Origin: http://localhost:3000' -d 'productId=1&quantity=10' localhost:3000/v2/orders

What you will see:

{"type":"about:blank","title":"Forbidden","status":403,"detail":"The request comes from another site and uses your session: it is not accepted"}
{"type":"about:blank","title":"Unsupported Media Type","status":415,"detail":"The request cannot be read"}

-d sends the body the way a form does. From 127.0.0.1:4000, with the cookie: 403. With the shop’s origin it gets past the wall, and the route answers 415 because it expects JSON. No new order.

curl can write any Origin it wants because it isn’t a browser. That doesn’t matter: to use Carmen’s session it needs her cookie, and CSRF is about the other site not having it.

From this lesson on, a request with the cookie and no body needs -H 'Origin: http://localhost:3000', like signing out or cancelling an order. POSTs with --json don’t:

5. Signing out with curl

Ventana de terminal
curl -s -w '\n' -b carmen.txt -X DELETE localhost:3000/v2/session
curl -s -w '%{http_code}\n' -b carmen.txt -c carmen.txt -H 'Origin: http://localhost:3000' -X DELETE localhost:3000/v2/session

What you will see:

{"type":"about:blank","title":"Forbidden","status":403,"detail":"The request comes from another site and uses your session: it is not accepted"}
204

Without Origin, the shop doesn’t know where it comes from, and rejects it. With it, 204.

6. The other site

Ventana de terminal
npm run other-site

What you will see:

> shop-api@1.0.0 other-site
> node scripts/other-site.ts
The other site, at http://127.0.0.1:4000: it tries to place orders at http://localhost:3000

Leave it running in its own terminal; it stops with Ctrl + C. Its page, in scripts/other-site.ts, has two buttons: one sends a hidden form with productId=1 and quantity=10; the other, a fetch with JSON and credentials: 'include', which asks to carry the cookies.

In Chrome, open http://localhost:3000/v2/me, open DevToolsThe developer tools that come with browsers such as Chrome or Firefox, opened with F12. Their Network tab shows every request the page makes, with its response and headers; the Console, the page’s errors; and Application (Storage, in Firefox), what the site stores in your browser, such as cookies.Go to definition and sign in as Carmen by typing in the Console, as in lesson 2:

await fetch('/v2/session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'carmen@example.com', password: 'carmen-practice-2026' }) })

Reload: /v2/me says you’re Carmen. Now open http://127.0.0.1:4000, with the Network tab open:

  1. The form. The tab ends up at localhost:3000/v2/orders with a 401: “Sign in, or identify yourself with your API key”. In Network, in that request’s headers: Origin: http://127.0.0.1:4000, Sec-Fetch-Site: cross-site, and no Cookie. SameSite stopped it.
  2. The fetch. Go back and click the other button. The page says The browser has not sent it: TypeError: Failed to fetch, and the console: Access to fetch at 'http://localhost:3000/v2/orders' from origin 'http://127.0.0.1:4000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Only the preflight went out; the POST, never.
  3. Carmen’s orders. At http://localhost:3000/v2/orders, the same ones as before.

We checked it with Chromium 153, driven by Playwright in Docker.

Save the Fast Delivery key from lesson 3 with KEY=, followed by yours, and try five URLs with a for loop from the scripts lesson:

7. Five trap URLs

Ventana de terminal
for url in http://localhost:5432/ https://localhost:5432/ https://169.254.169.254/latest/meta-data/ https://127.0.0.1.nip.io/notifications https://delivery.example/notifications; do
curl -s -w '\n' -X PUT -H "Authorization: Bearer $KEY" --json "{\"url\":\"$url\"}" localhost:3000/v2/delivery/notification
done

What you will see:

{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"url","problem":"It has to start with https://"}]}
{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"url","problem":"It points to an internal address (::1)"}]}
{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"url","problem":"It points to an internal address (169.254.169.254)"}]}
{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"url","problem":"It points to an internal address (127.0.0.1)"}]}
{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"url","problem":"delivery.example cannot be found"}]}

Five 422s, each with its reason: http; localhost, which your computer resolves to ::1 (or to 127.0.0.1); the metadata; the public name that points to 127.0.0.1, the trap of looking only at the name; and a name that doesn’t exist. The fourth really asks nip.io, a public DNS: without internet, or if your router blocks those answers, you get 127.0.0.1.nip.io cannot be found. If they all give 401, KEY is empty.

To receive a notification without leaving your computer, allow 127.0.0.1 in development only: in your .env, NOTIFICATION_DEV_HOSTS=127.0.0.1, and restart the shop. In one more terminal, listen with nc -l 127.0.0.1 5000, as in Phase 2. Then:

8. Saving the URL and paying an order

Ventana de terminal
curl -s -w '\n' -X PUT -H "Authorization: Bearer $KEY" --json '{"url":"http://127.0.0.1:5000/notifications"}' localhost:3000/v2/delivery/notification
npm run gateway -- 27

What you will see:

{"url":"http://127.0.0.1:5000/notifications","secret":"-_5VyWNhm0cyBQtaRmIf4Lh52h779mu8F-4xhnqdsSY"}
> shop-api@1.0.0 gateway
> node --env-file-if-exists=.env scripts/payment-gateway.ts 27
→ POST /v2/webhooks/payments {"id":"evt_9a9c1fee-8f3e-4e4c-9b2d-5233a483fad1","type":"payment.completed","orderId":27}
← 200 {"received":"evt_9a9c1fee-8f3e-4e4c-9b2d-5233a483fad1","repeated":false}

The shop saves the URL and returns the secret it will sign each notification with: Fast Delivery uses it to check the signature, like the shop with the gateway. Order 27 is Carmen’s from lesson 5, still pending; the gateway gets its 200 right away, without waiting for the notification.

9. What nc receives

Ventana de terminal
nc -l 127.0.0.1 5000

What you will see:

POST /notifications HTTP/1.1
Content-Type: application/json
X-Signature: sha256=69e97b492187d6b5c02f2297e7ce39c33d046c9f1d7b466ded512e23dd43f435
Host: 127.0.0.1:5000
Connection: keep-alive
Content-Length: 136
{"type":"order.paid","order":{"id":27,"productId":1,"quantity":2,"status":"paid","createdAt":"2026-10-14T04:50:35.248Z","customerId":5}}

The signed notification, in the nc terminal. nc doesn’t answer anything, and five seconds later, in the shop’s terminal:

{"level":40,"time":1791953539031,"pid":591,"hostname":"laptop","url":"http://127.0.0.1:5000/notifications","reason":"It could not be sent: it does not answer in time","msg":"notification not delivered"}

The timeout, for real. If nc gives an error on Linux, try nc -l -p 5000.

Now make nc answer with a redirect to the metadata:

Ventana de terminal
printf 'HTTP/1.1 302 Found\r\nLocation: http://169.254.169.254/latest/meta-data/\r\nContent-Length: 0\r\n\r\n' | nc -l 127.0.0.1 5000
Challenge: sign in as Carmen, place another order with --json and pay for it with the gateway. What does the shop’s terminal say?Show answer

The new order is 28 (yours may be another one): npm run gateway -- 28. nc receives the notification and answers the 302 right away, and the shop doesn’t follow it:

{"level":40,"time":1791953542579,"pid":591,"hostname":"laptop","url":"http://127.0.0.1:5000/notifications","reason":"It answers 302, a redirect: it is not followed","msg":"notification not delivered"}

When you’re done, leave NOTIFICATION_DEV_HOSTS= empty in your .env, restart the shop and delete carmen.txt. The nc URL is still saved, and every payment will leave notification not delivered in the log: It has to start with https://, the check when sending.

  • “Page Expired” when you send a form you left open for hours, on sites made with Laravel: a CSRF token that’s no longer valid.
  • A link preview in WhatsApp or Slack: a server visits the URL you paste. That’s exactly what an SSRF takes advantage of, and that’s why that server has to check it, like the shop.
  • “Import photo from a URL”: the server downloads it for you.
  • Changing something with a GET. SameSite=Lax lets links through, and a link makes a GET.
  • SameSite=None without needing it. It removes the first wall.
  • Accepting a request with the cookie and no Origin. There’s no way to know where it comes from.
  • Checking the URL’s name instead of its address. 127.0.0.1.nip.io doesn’t contain localhost.
  • Checking the address and letting the request ask DNS again. That’s DNS rebinding.
  • Following redirects, or waiting with no limit on time or size.
  • In a CSRF, another site makes your browser send a request with your cookie. CORS doesn’t prevent it: the request arrives.
  • SameSite=Lax doesn’t send the cookie in a POST from another site, and the shop rejects with 403 whatever carries the cookie without an allowed Origin. The CSRF token is the long-standing answer, and it’s still valid.
  • In an SSRF, someone gives your server a URL that points to what only it can reach: localhost, the internal network or the cloud’s metadata.
  • A URL from someone else is checked like this: https, its resolved addresses outside the internal ranges, the connection to the checked address, no redirects, with a maximum time and size.
A shop keeps the session in a cookie without SameSite and doesn’t look at the Origin header. Luis, its admin, opens a page in another tab with a hidden form that deletes a product with a POST. What happens?

The shop checks Origin on form POSTs and on those with no body, but not on POSTs with JSON. Why isn’t that a gap?

From this lesson on, curl -b carmen.txt -X POST localhost:3000/v2/orders/30/cancellation answers 403, even though the order is Carmen’s. What’s going on?

A teammate suggests rejecting notification URLs that contain “localhost”, “127.0.0.1” or “169.254”. Is that enough?

Another API checks that a name’s addresses are public and then calls fetch(url), which asks DNS again. What risk does it run?

The shop runs on a server in the cloud and doesn’t show what the notification URL answers. Someone gets it to send a POST to http://169.254.169.254/. Is it serious?

phase-6 · lesson 7/9