SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 36
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 36 of 90

Web security foundations and the OWASP Top 10

same-origin policy (SOP)originCORSpreflight requestsAccess-Control-Allow-Origin pitfallsbrowser security modelnever trust the clientinput validation vs output encodingallowlist validationOWASPOWASP Top 10 2021 and 2025 listshow the Top 10 is compiled

These are the notes for Cybersecurity Fundamentals (defensive), episode 36, the first episode of the web security part of the course. Episode 35 verified every request with zero trust. Today we look inside the browser, where your bank and a random quiz site sit side by side in two tabs. We build a browser with no rules and watch it leak, then invent the same-origin policy (SOP) and the origin, CORS and preflight requests, the Access-Control-Allow-Origin pitfalls, the browser security model, never trust the client, input validation vs output encoding with allowlist validation, and meet OWASP and the OWASP Top 10 (2021 and 2025), including how the Top 10 is compiled. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Neha, bank.example, quiz-fun.example, shop.example and every value here are made up (.example names are reserved for documentation), and everything runs locally on toy data: the "browsers" and "servers" are small Python functions that model the rules. Every code sample runs with Python 3 (standard library only); outputs are real, copied from actual runs.

The problems you'll solve

Problem Idea it teaches
Any web page can read any site's replies Browser security model, same-origin policy
What counts as "the same site"? Origin = scheme + host + port
The bank's own app can't read its own API CORS, Origin, Access-Control-Allow-Origin, preflight
CORS set up wrongly Reflecting origins, suffix checks, null, credentials
A shop that believes the price the page sends Never trust the client; server-side checks
Data that might be dangerous Input validation (allowlist vs denylist) and output encoding
Which web mistakes matter most? OWASP, the Top 10 2021 vs 2025, how it's compiled

Problem 1: two tabs, one browser

Neha is logged in to her bank in one tab: as in episode 28, the browser saved a session cookie and sends it with every request to the bank. In another tab she plays a quiz on some random site. Every web page can run JavaScript: small programs the browser downloads and runs for that page. What stops the quiz page's JavaScript from asking the bank for Neha's balance, with her cookie attached automatically?

Demo 1: a toy browser with no rules

# A toy browser WITHOUT the same-origin policy: any page may read any site's response
cookies = {"bank.example": "session=neha-7f2c"}            # Neha is logged in to her bank
servers = {"bank.example": lambda c: "balance: Rs 84,200" if c == "session=neha-7f2c" else "login page"}

def page_fetch(page_site, url_site):
    cookie = cookies.get(url_site)                         # the browser attaches the bank's cookie
    return servers[url_site](cookie)                       # ... and hands the reply to the page

print("bank's own page reads:", page_fetch("bank.example", "bank.example"))
print("quiz site's page reads:", page_fetch("quiz-fun.example", "bank.example"))

Output:

bank's own page reads: balance: Rs 84,200
quiz site's page reads: balance: Rs 84,200

Why? The browser attaches the bank's cookie no matter which page asked, and then hands the reply to that page. Any site you visit could read your email, your bank, your company wiki. We need a rule about which page may read which reply.

The same-origin policy (SOP)

Real-life example: letterboxes in a building.

In a building In the browser
Each flat has its own letterbox Each origin has its own data: cookies, storage, page content
Flat 4B can't open 7A's box Same-origin policy: a page's script may freely read responses only from its own origin
4B can still post a letter into 7A's box Pages can still send many cross-origin requests (forms, images, links); the policy mostly stops them reading the reply

The browser security model is the set of rules a browser uses to keep websites apart while running all their code side by side; the same-origin policy is its most important rule. The "sending is still allowed" detail is the root of CSRF (episode 42).

What is an origin?

An origin is three parts of a URL:

Part Meaning Example
Scheme The protocol https
Host The server's name bank.example
Port A number that picks the program on that server; 443 is the default for https, 80 for http 443

All three must match exactly. The path (/api/balance) does not matter.

Demo 2: same origin or not?

# The same-origin policy: an origin = scheme + host + port. All three must match.
from urllib.parse import urlsplit
DEFAULT_PORT = {"http": 80, "https": 443}

def origin(url):
    u = urlsplit(url)
    return (u.scheme, u.hostname, u.port or DEFAULT_PORT[u.scheme])

page = "https://bank.example/home"
for other in ["https://bank.example/api/balance", "https://bank.example:443/x",
              "http://bank.example/api", "https://api.bank.example/v1",
              "https://bank.example:8443/api", "https://quiz-fun.example/"]:
    print(f"{other:34} same origin? {origin(other) == origin(page)}")

Output:

https://bank.example/api/balance   same origin? True
https://bank.example:443/x         same origin? True
http://bank.example/api            same origin? False
https://api.bank.example/v1        same origin? False
https://bank.example:8443/api      same origin? False
https://quiz-fun.example/          same origin? False

A different path: same origin. Writing the default port out: same. http vs https, a subdomain such as api., or another port: different origins.

Problem 2: CORS

The bank's web app lives at https://app.bank.example, but its data comes from an API at https://api.bank.example: a different origin. The same-origin policy blocks the bank's own app from reading its own API. We need a safe way for a server to say "this other origin may read my replies".

CORS, cross-origin resource sharing, is that permission slip:

  1. The browser adds an Origin header to the request, naming the page's origin: Origin: https://app.bank.example.
  2. The server answers with Access-Control-Allow-Origin: https://app.bank.example if it allows that origin.
  3. The browser compares them. Match: the reply is given to the page. No match: the reply is hidden, and the developer console shows a CORS error.

Preflight requests. Some requests could change things in ways old web pages never could: methods like PUT or DELETE, a JSON body (Content-Type: application/json), or custom headers. For these, the browser first sends a preflight: an OPTIONS request asking "may I?" (with Access-Control-Request-Method and -Headers). Only if the server answers with matching Access-Control-Allow-Methods / -Headers does the real request go. "Simple" requests (GET, HEAD, POST with form-style content) skip the preflight.

CORS relaxes the SOP; it never adds protection. Every origin you allow is trusted to read your replies.

Demo 3: a toy CORS check

# CORS: the API server tells the browser which OTHER origins may read its replies
ALLOWED = {"https://app.bank.example"}                     # the bank's own web app

def api_server(method, origin):                            # api.bank.example
    h = {}
    if origin in ALLOWED:
        h["Access-Control-Allow-Origin"] = origin
        h["Access-Control-Allow-Methods"] = "GET, PUT"
    return h

def browser(page_origin, method):
    if method not in ("GET", "HEAD", "POST"):              # not a "simple" request: ask first
        pre = api_server("OPTIONS", page_origin)
        if method not in pre.get("Access-Control-Allow-Methods", ""):
            return f"{method} blocked by preflight"
    h = api_server(method, page_origin)
    ok = h.get("Access-Control-Allow-Origin") == page_origin
    return f"{method} reply {'given to the page' if ok else 'hidden from the page (CORS error)'}"

print("app.bank.example :", browser("https://app.bank.example", "GET"))
print("app.bank.example :", browser("https://app.bank.example", "PUT"))
print("quiz-fun.example :", browser("https://quiz-fun.example", "GET"))
print("quiz-fun.example :", browser("https://quiz-fun.example", "PUT"))

Output:

app.bank.example : GET reply given to the page
app.bank.example : PUT reply given to the page
quiz-fun.example : GET reply hidden from the page (CORS error)
quiz-fun.example : PUT blocked by preflight

Note that the quiz site's simple GET was still sent; only the reply was hidden. A server must never rely on CORS to stop requests that change things: that's what CSRF defences are for (episode 42).

CORS pitfalls

Demo 4: how a server decides an origin is "ours"

# CORS pitfalls: how a server decides whether an Origin is "ours"
def reflect_any(origin):  return True                              # echo back whatever came
def suffix(origin):       return origin.endswith("bank.example")   # looks safe ... isn't
def null_ok(origin):      return origin in ("https://app.bank.example", "null")
def exact(origin):        return origin in {"https://app.bank.example"}   # an exact allowlist

for o in ["https://app.bank.example", "https://evilbank.example", "null", "https://quiz-fun.example"]:
    print(f"{o:26} reflect:{reflect_any(o)!s:5} suffix:{suffix(o)!s:5} "
          f"null-ok:{null_ok(o)!s:5} exact:{exact(o)}")

Output:

https://app.bank.example   reflect:True  suffix:True  null-ok:True  exact:True
https://evilbank.example   reflect:True  suffix:True  null-ok:False exact:False
null                       reflect:True  suffix:False null-ok:True  exact:False
https://quiz-fun.example   reflect:True  suffix:False null-ok:False exact:False
Pitfall What goes wrong
Reflecting any Origin (echoing the request's Origin back) Every site is allowed: the same as no policy
Suffix / substring checks (endswith("bank.example")) Look-alikes such as evilbank.example pass
Allowing null The null origin can be produced by sandboxed iframes and local files, so attackers can send it
Access-Control-Allow-Origin: * with credentials Browsers refuse * together with credentials, so developers "fix" it by reflecting the origin, which is worse
Access-Control-Allow-Credentials: true on a loose policy The page can read replies made with the user's cookies: the worst case
Missing Vary: Origin on a dynamic header A cache may serve one origin's CORS answer to another

Rules: an exact allowlist of full origins (scheme + host + port), never reflect, never allow null, and allow credentials only where truly needed.

Problem 3: never trust the client

Real-life example: a sweet shop where customers write their own bill ("2 kg barfi: Rs 2"). A sensible shopkeeper uses his own price list. In a web app, the client is whatever sends requests to your server: a browser, a mobile app, or any script an attacker writes. It can send anything.

Demo 5: a shop that believes the price

# Never trust the client: the shop's page sends the price, and the server believes it
PRICES = {"masala-chai-1kg": 450}

def checkout_trusting(req):                         # the obvious way
    return f"charged Rs {req['qty'] * req['price']}"

def checkout_safe(req):                             # the server looks up what it already knows
    if req["item"] not in PRICES:                return "400 unknown item"
    if not (isinstance(req["qty"], int) and 1 <= req["qty"] <= 20): return "400 bad quantity"
    return f"charged Rs {req['qty'] * PRICES[req['item']]}"

normal = {"item": "masala-chai-1kg", "qty": 2, "price": 450}   # what the web page sends
edited = {"item": "masala-chai-1kg", "qty": 2, "price": 1}     # the same request, edited
weird  = {"item": "masala-chai-1kg", "qty": -5, "price": 450}
for name, r in [("normal", normal), ("edited price", edited), ("negative qty", weird)]:
    print(f"{name:13} trusting: {checkout_trusting(r):16} safe: {checkout_safe(r)}")

Output:

normal        trusting: charged Rs 900   safe: charged Rs 900
edited price  trusting: charged Rs 2     safe: charged Rs 900
negative qty  trusting: charged Rs -2250 safe: 400 bad quantity

The trusting checkout charges Rs 2 for two kilos, and minus Rs 2,250 (a refund for nothing) for a negative quantity. Editing a request needs no hacking skill: the browser's developer tools or a few lines of code will do it. So hidden form fields, disabled buttons and JavaScript checks are for user convenience only. Every security decision (prices, quantities, permissions, who owns what) happens on the server. The browser's rules protect users from other websites; they do nothing to protect your server from its own users.

Problem 4: input validation vs output encoding

Two habits sit behind most secure web code:

Habit When What it does Example
Input validation When data arrives Checks it is what you expect; rejects anything else A pincode must be 6 digits
Output encoding When data leaves your code for an interpreter Converts it so it's treated as data, not code, for that destination < becomes &lt; in HTML
  • Allowlist validation: define exactly what is valid (type, length, characters, range) and reject the rest. Strong.
  • Denylist validation: block the bad things you thought of. Weak: attackers find a variant you didn't think of.
  • Free text (names, comments, addresses) can't be fully allowlisted, so output encoding does the main job: encode for HTML, use parameters for SQL (episode 38), avoid the shell or pass argument arrays (episode 39), encode for URLs.
  • Canonicalisation (turning input into its one standard form, for example decoding %2e%2e) must happen before validation, or encoded variants slip past (episode 47).

Demo 6: allowlist vs denylist, and encoding

# Input validation (at the door) vs output encoding (at the page). You need both.
import re, html

def valid_pincode(s):                     # ALLOWLIST: exactly 6 digits, nothing else
    return re.fullmatch(r"[1-9][0-9]{5}", s) is not None

def denylist_ok(s):                       # DENYLIST: block the "bad" things you thought of
    return "<script>" not in s.lower()

for pin in ["110001", "11000", "110001<b>", "<ScRiPt >x"]:
    print(f"{pin!r:14} allowlist: {valid_pincode(pin)!s:5}  denylist: {denylist_ok(pin)}")

name = 'Neha <img src=x onerror="alert(1)">'   # a free-text field: can't allowlist it all
print("raw     -> <p>Hi " + name + "</p>")
print("encoded -> <p>Hi " + html.escape(name) + "</p>")

Output:

'110001'       allowlist: True   denylist: True
'11000'        allowlist: False  denylist: True
'110001<b>'    allowlist: False  denylist: True
'<ScRiPt >x'   allowlist: False  denylist: True
raw     -> <p>Hi Neha <img src=x onerror="alert(1)"></p>
encoded -> <p>Hi Neha &lt;img src=x onerror=&quot;alert(1)&quot;&gt;</p>

The allowlist accepts only the real pincode; the denylist says True to all four, even the variant with odd capitals and a space. The raw name becomes a real <img> tag whose onerror would run JavaScript: that's how cross-site scripting (XSS) starts (episode 40). html.escape turns <, >, " and & into HTML entities such as &lt;, which a browser shows as characters but never runs.

Problem 5: OWASP and the Top 10

Real-life example: road safety. There are thousands of possible accidents, but a short ranked list of top causes tells you where to train first. There are also thousands of ways to get web security wrong: episode 8's CWE (Common Weakness Enumeration) list has hundreds of weakness types.

OWASP, the Open Worldwide Application Security Project (called the Open Web Application Security Project until February 2023), is a non-profit foundation started in 2001 that publishes free security guides, standards and tools. Its best-known document is the OWASP Top 10: an awareness list of the ten most important web application security risks, first published in 2003. The 2025 edition (the 8th) was presented on 6 November 2025 at OWASP Global AppSec DC.

Demo 7: 2025 vs 2021

# OWASP Top 10: how each 2025 category moved since 2021 (official lists, typed in)
top2021 = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design",
           "Security Misconfiguration", "Vulnerable and Outdated Components",
           "Identification and Authentication Failures", "Software and Data Integrity Failures",
           "Security Logging and Monitoring Failures", "Server-Side Request Forgery"]
top2025 = ["Broken Access Control", "Security Misconfiguration", "Software Supply Chain Failures",
           "Cryptographic Failures", "Injection", "Insecure Design", "Authentication Failures",
           "Software or Data Integrity Failures", "Security Logging & Alerting Failures",
           "Mishandling of Exceptional Conditions"]
was = {"Software Supply Chain Failures": "Vulnerable and Outdated Components",   # expanded
       "Authentication Failures": "Identification and Authentication Failures",  # renamed
       "Software or Data Integrity Failures": "Software and Data Integrity Failures",
       "Security Logging & Alerting Failures": "Security Logging and Monitoring Failures"}

for rank, name in enumerate(top2025, 1):
    old = was.get(name, name)
    move = f"was #{top2021.index(old) + 1}" if old in top2021 else "NEW"
    print(f"A{rank:02d}:2025 {name:38} {move}")
print("2021's #10, SSRF, is now part of Broken Access Control")

Output:

A01:2025 Broken Access Control                  was #1
A02:2025 Security Misconfiguration              was #5
A03:2025 Software Supply Chain Failures         was #6
A04:2025 Cryptographic Failures                 was #2
A05:2025 Injection                              was #3
A06:2025 Insecure Design                        was #4
A07:2025 Authentication Failures                was #7
A08:2025 Software or Data Integrity Failures    was #8
A09:2025 Security Logging & Alerting Failures   was #9
A10:2025 Mishandling of Exceptional Conditions  NEW
2021's #10, SSRF, is now part of Broken Access Control
Rank OWASP Top 10:2021 OWASP Top 10:2025 Change
A01 Broken Access Control Broken Access Control Still #1; SSRF (2021's A10) folded in
A02 Cryptographic Failures Security Misconfiguration Misconfiguration up from #5
A03 Injection Software Supply Chain Failures Expands 2021's "Vulnerable and Outdated Components" (#6)
A04 Insecure Design Cryptographic Failures Down from #2
A05 Security Misconfiguration Injection Down from #3
A06 Vulnerable and Outdated Components Insecure Design Down from #4
A07 Identification and Authentication Failures Authentication Failures Renamed
A08 Software and Data Integrity Failures Software or Data Integrity Failures Same place
A09 Security Logging and Monitoring Failures Security Logging & Alerting Failures Renamed: alerting, not just monitoring
A10 Server-Side Request Forgery (SSRF) Mishandling of Exceptional Conditions New category

Episodes 37-48 of this course walk through these risks one by one.

How the Top 10 is compiled

  1. Data: organisations contributed testing data covering more than 2.8 million applications. Each finding is mapped to a CWE.
  2. 589 CWEs were analysed; 248 of them are grouped into the ten categories (at most 40 per category).
  3. Eight categories are ranked from the data, using how often they occur plus exploit and impact scores derived from CVSS (episode 8).
  4. Two categories (A03 Software Supply Chain Failures and A09 Security Logging & Alerting Failures) were promoted by a community survey of practitioners, because data shows past findings and some risks aren't yet testable at scale.
  5. Categories aim at root causes rather than symptoms where possible (for example "Cryptographic Failures" rather than "sensitive data exposure").

The Top 10 is an awareness list and a starting point, not a complete standard. For a full checklist, OWASP's Application Security Verification Standard (ASVS) (episode 51) lists testable requirements; the OWASP Cheat Sheet Series gives how-to guidance.

The next problem

We now have the foundations: origins, CORS, and the rule that the server decides everything. But what if Neha's order page is /orders/1042, she changes it to /orders/1043, and the server shows her someone else's order? That's broken access control and IDOR, number one on the list: episode 37.

The whole chain

Step Problem Invention
1 Any page reads any site The same-origin policy
2 What is "the same site"? Origin = scheme + host + port
3 The bank's own app is blocked CORS headers, preflight requests
4 CORS done wrong Exact allowlist of origins; no reflection, no null
5 Edited requests Never trust the client: decide on the server
6 Dangerous data Allowlist validation in, output encoding out
7 Where to start OWASP and the Top 10

Common mistakes (and what they print)

Mistake What you see Why it's wrong Fix
Reflecting any Origin https://evilbank.example reflect:True Same as no policy Exact allowlist
endswith() origin check https://evilbank.example reflect:True suffix:True Look-alike names match Compare full origins
Allowing null null reflect:True suffix:False null-ok:True Sandboxed pages can send null Never allow null
Relying on CORS to stop actions The GET still reached the server CORS hides replies, doesn't stop requests CSRF defences (episode 42)
Trusting the client's price edited price trusting: charged Rs 2 The client sends anything Look up prices on the server
No range check on quantity negative qty trusting: charged Rs -2250 Negative numbers flip the maths Validate type and range
Denylist validation '<ScRiPt >x' allowlist: False denylist: True Always misses a variant Allowlist + output encoding
Putting raw input into HTML raw -> <p>Hi Neha <img src=x onerror="alert(1)"></p> The browser runs it html.escape / an auto-escaping template
"We fixed it in JavaScript" The check is skipped with a direct request Client checks are UX only Repeat every check on the server

Mini project: a tea shop API

An exact CORS allowlist with Vary: Origin, preflight handling, server-side prices, allowlist validation of the pincode, and HTML encoding of the free-text note.

# Mini project: a tea shop API with an exact CORS allowlist, preflight handling and server-side checks
import html, re
ALLOWED_ORIGINS = {"https://shop.example", "https://m.shop.example"}
PRICES = {"masala-chai-1kg": 450, "green-tea-250g": 220}

def cors_headers(origin):
    if origin not in ALLOWED_ORIGINS: return {}
    return {"Access-Control-Allow-Origin": origin, "Access-Control-Allow-Credentials": "true", "Vary": "Origin"}

def handle(method, origin, body=None):
    h = cors_headers(origin)
    if method == "OPTIONS":                                   # preflight
        if not h: return 403, {}, "origin not allowed"
        return 204, {**h, "Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Headers": "Content-Type"}, ""
    item, qty, note = body["item"], body["qty"], body.get("note", "")
    if item not in PRICES:                                     return 400, h, "unknown item"
    if not (isinstance(qty, int) and 1 <= qty <= 20):           return 400, h, "bad quantity"
    if not re.fullmatch(r"[1-9][0-9]{5}", body["pincode"]):    return 400, h, "bad pincode"
    receipt = f"<p>{qty} x {item} = Rs {qty * PRICES[item]}. Note: {html.escape(note)}</p>"
    return 200, h, receipt

def show(label, result):
    status, headers, body = result
    print(f"{label:18} {status} allow-origin={headers.get('Access-Control-Allow-Origin')} {body}")

show("preflight, shop", handle("OPTIONS", "https://shop.example"))
show("preflight, evil", handle("OPTIONS", "https://evil.example"))
show("order, price=1", handle("POST", "https://shop.example", {"item": "masala-chai-1kg", "qty": 2, "price": 1,
                                                            "pincode": "560001", "note": "<b>ring twice</b>"}))
show("order, qty=0", handle("POST", "https://shop.example", {"item": "masala-chai-1kg", "qty": 0, "pincode": "560001"}))

Output:

preflight, shop    204 allow-origin=https://shop.example 
preflight, evil    403 allow-origin=None origin not allowed
order, price=1     200 allow-origin=https://shop.example <p>2 x masala-chai-1kg = Rs 900. Note: &lt;b&gt;ring twice&lt;/b&gt;</p>
order, qty=0       400 allow-origin=https://shop.example bad quantity

The client's price: 1 is ignored (Rs 900 is charged), the note's <b> arrives as harmless &lt;b&gt;, the evil origin's preflight is refused, and qty: 0 is rejected. Ideas to extend it: return 403 for POSTs from unknown origins too, add a coupon table, and log every rejected request.

Practice

1. A local development origin. Allow http://localhost:3000 in Demo 3's allowlist, but only in development.

Solution
# Practice 1: allow the developer's local app too, but ONLY in development
ENV = "development"
ALLOWED = {"https://app.bank.example"}
if ENV == "development":
    ALLOWED |= {"http://localhost:3000"}           # never ship this into production

def allow_origin_header(origin):
    return {"Access-Control-Allow-Origin": origin} if origin in ALLOWED else {}

for o in ["http://localhost:3000", "http://localhost:3001", "https://app.bank.example"]:
    print(f"{o:26} -> {allow_origin_header(o)}")
http://localhost:3000      -> {'Access-Control-Allow-Origin': 'http://localhost:3000'}
http://localhost:3001      -> {}
https://app.bank.example   -> {'Access-Control-Allow-Origin': 'https://app.bank.example'}

2. Fix the suffix check. Parse the origin, require https on the default port, and match whole host labels.

Solution
# Practice 2: fix the suffix check. Parse the origin, require https, and match whole host labels.
from urllib.parse import urlsplit

def is_ours(origin):
    u = urlsplit(origin)
    if u.scheme != "https" or u.port not in (None, 443): return False
    host = u.hostname or ""
    return host == "bank.example" or host.endswith(".bank.example")    # note the leading dot

for o in ["https://app.bank.example", "https://evilbank.example", "http://app.bank.example",
          "https://bank.example.evil.example", "null"]:
    print(f"{o:35} ours? {is_ours(o)}")
https://app.bank.example            ours? True
https://evilbank.example            ours? False
http://app.bank.example             ours? False
https://bank.example.evil.example   ours? False
null                                ours? False

Note this still trusts every subdomain: if any one of them is taken over (episode 20), it can read your replies. An exact list of origins is safer.

3. Allowlist a phone number. Accept a 10-digit Indian mobile number starting with 6-9, with an optional +91.

Solution
# Practice 3: allowlist an Indian mobile number: 10 digits, first digit 6-9, optional +91
import re
MOBILE = re.compile(r"(\+91)?[6-9][0-9]{9}")

for s in ["9876543210", "+919876543210", "1234567890", "98765 43210", "9876543210; DROP"]:
    print(f"{s!r:20} valid? {MOBILE.fullmatch(s) is not None}")
'9876543210'         valid? True
'+919876543210'      valid? True
'1234567890'         valid? False
'98765 43210'        valid? False
'9876543210; DROP'   valid? False

4. A coupon from the client. The page sends a coupon code and the discount it "applies". Make the server decide the discount.

Solution
# Practice 4: a coupon code sent by the client. The server decides what it's worth.
COUPONS = {"CHAI10": 10}                 # percent off, known only to the server
PRICE = 450

def total(qty, coupon, discount_from_client):
    pct = COUPONS.get(coupon, 0)         # ignore discount_from_client completely
    return qty * PRICE * (100 - pct) // 100

print("real coupon:       ", total(2, "CHAI10", 10))
print("client claims 99%: ", total(2, "CHAI10", 99))
print("made-up coupon:    ", total(2, "FREE100", 100))
real coupon:        810
client claims 99%:  810
made-up coupon:     900

5. Same origin? For a page at https://shop.example/cart: (a) https://shop.example/api, (b) https://www.shop.example/api, (c) http://shop.example/api, (d) https://shop.example:443/x.

Answer

(a) same (path doesn't matter); (b) different host; (c) different scheme (and port 80); (d) same (443 is the https default).

Quick quiz

A page on https://shop.example/cart fetches https://shop.example:8443/api/cart. Can the page read the reply without CORS? A yes, same host; B yes, same scheme; C no, different port; D no, different path.

Answer

C, no: different port. An origin is scheme + host + port. https://shop.example means port 443; :8443 is a different port, so a different origin. The path never matters.

Interview questions

  1. What is the same-origin policy? A browser rule that lets a page's script read responses and data only from its own origin, keeping websites isolated from each other.
  2. What is an origin? The scheme, host and port of a URL, all of which must match. The path is irrelevant.
  3. Does the SOP stop a page from sending requests to other sites? No. Many cross-origin requests (forms, images, simple fetches) are sent; the SOP mainly stops reading the responses. That's why CSRF exists.
  4. What is CORS? Cross-origin resource sharing: a way for a server to tell the browser, via Access-Control-Allow-Origin and related headers, which other origins may read its responses.
  5. What is a preflight request and when is it sent? An automatic OPTIONS request the browser sends before a non-simple cross-origin request (e.g. PUT/DELETE, JSON body, custom headers) to ask whether the method and headers are allowed.
  6. Name three CORS misconfigurations. Reflecting any Origin; substring/suffix origin checks; allowing null; combined with Access-Control-Allow-Credentials: true they let attackers read authenticated data.
  7. Why can't * be used with credentials? Browsers reject Access-Control-Allow-Origin: * when credentials are included, so a credentialed policy must name exact origins.
  8. What does "never trust the client" mean in practice? Every security decision and calculation is made on the server; client-side checks are only for usability, because attackers can send any request.
  9. Input validation vs output encoding? Validation checks data on arrival (best as an allowlist); encoding transforms data for the context it's placed in (HTML, SQL via parameters, shell, URL). You need both; encoding is the main defence for free text.
  10. Why are denylists weak? They only block patterns you anticipated; attackers use case changes, encodings, whitespace and other variants.
  11. What is OWASP, and what is the Top 10? The Open Worldwide Application Security Project, a non-profit producing free security resources; the Top 10 is its awareness list of the most critical web application risks.
  12. What changed from the 2021 to the 2025 Top 10? Security Misconfiguration rose to #2; Software Supply Chain Failures (expanded from Vulnerable and Outdated Components) is #3; Mishandling of Exceptional Conditions is new at #10; SSRF was merged into Broken Access Control, which stays #1.
  13. How is the Top 10 compiled? From contributed testing data mapped to CWEs (2.8M+ applications for 2025), ranked by incidence and CVSS-based exploit/impact scores for eight categories, plus two categories promoted by a practitioner survey.

Glossary

Term Meaning in plain words Example
Browser security model The rules a browser uses to keep websites apart while running their code SOP, cookies per site
JavaScript The programming language web pages run inside the browser The quiz page's script
Session cookie A cookie that proves you are logged in, sent with every request to that site session=neha-7f2c
Same-origin policy (SOP) A page may read data and replies only from its own origin The quiz page can't read the bank's reply
Origin Scheme + host + port of a URL https://bank.example:443
Scheme The protocol part of a URL https
Host The server's name in a URL api.bank.example
Port A number that picks the program on a server (443 = https default) 8443
Cross-origin Between two different origins app. → api.
CORS Cross-origin resource sharing: server headers that let other origins read replies Access-Control-Allow-Origin
Origin header The header where the browser says which origin a request comes from Origin: https://app.bank.example
Access-Control-Allow-Origin The server's answer naming the origin allowed to read the reply https://app.bank.example
Access-Control-Allow-Credentials Lets the page read replies made with the user's cookies true
Vary: Origin Tells caches the reply depends on the Origin header Stops cache mix-ups
Simple request A cross-origin request that needs no preflight GET, form POST
Preflight request An automatic OPTIONS request asking whether a cross-origin request is allowed Before a PUT
CORS error The browser hiding a reply because the origin wasn't allowed In the developer console
null origin A special origin sent by sandboxed or local pages; never allow it Origin: null
Client Whatever sends requests to your server A browser, an app, a script
Never trust the client Make every security decision and calculation on the server Look up prices server-side
Developer tools The browser's built-in tools for inspecting and editing pages and requests Edit a hidden field
Input validation Checking data when it arrives Pincode = 6 digits
Allowlist validation Accept only what matches an exact definition of valid [1-9][0-9]{5}
Denylist validation Block known-bad patterns; misses variants Block <script>
Regular expression A pattern for matching text (\+91)?[6-9][0-9]{9}
Output encoding Converting data so it's safe for where it's placed < → &lt;
HTML entity An escaped form of a character in HTML &lt;, &quot;
Canonicalisation Converting input to its single standard form before checking it Decoding %2e to .
Cross-site scripting (XSS) Injecting script into a page that other users load (episode 40) The raw <img onerror>
CSRF Cross-site request forgery: making the browser send a request the user didn't intend (episode 42) A form posting to the bank
OWASP Open Worldwide Application Security Project, a non-profit for software security owasp.org
OWASP Top 10 OWASP's awareness list of the ten most critical web app risks A01:2025 Broken Access Control
CWE Common Weakness Enumeration: a catalogue of weakness types (episode 8) CWE-79 (XSS)
CVSS Common Vulnerability Scoring System: severity scores (episode 8) Used for exploit/impact weights
ASVS OWASP Application Security Verification Standard: a testable checklist (episode 51) Level 1-3 requirements
Software supply chain Everything your software is built from: libraries, build tools, pipelines A03:2025
Exceptional condition An unexpected state such as an error, timeout or missing value A10:2025

Summary

  • The browser security model runs every site's code but keeps origins apart. The same-origin policy lets a page read replies only from its own origin (scheme + host + port); sending is often still allowed.
  • CORS lets a server name exact origins in Access-Control-Allow-Origin; preflight OPTIONS requests guard non-simple requests. CORS relaxes the SOP: never reflect origins, never use suffix checks, never allow null, and be careful with credentials.
  • Never trust the client: every security decision and calculation happens on the server.
  • Validate input with allowlists; encode output for its destination. Denylists always miss something.
  • OWASP's Top 10 (2025: Broken Access Control, Security Misconfiguration, Software Supply Chain Failures, Cryptographic Failures, Injection, Insecure Design, Authentication Failures, Software or Data Integrity Failures, Security Logging & Alerting Failures, Mishandling of Exceptional Conditions) is compiled from data on 2.8M+ applications plus a practitioner survey. It's an awareness list; ASVS is the checklist.

Next episode: broken access control and IDOR: horizontal and vertical privilege escalation, missing function-level access control, forced browsing, ownership checks, deny by default in code, and a secure fix on a toy app.

Sources: OWASP, "Introduction - OWASP Top 10:2025" (owasp.org/Top10/2025); SecureFlag, "OWASP Top 10:2025 learning paths" (7 Nov 2025) on the 6 Nov 2025 presentation at Global AppSec DC and SSRF's merge into A01; Palo Alto Networks, "OWASP Top 10:2021 – What's New"; Wikipedia, "OWASP" (name change February 2023, founded 2001, first Top Ten 2003). Code outputs from Python 3. Fetched 6 Nov 2026.