Part 03 · Web এর ভাষা
CORS: Why Browsers Say No
Browser কেন কিছু cross-origin call আটকায়, আর server কীভাবে permission দেয়।
⏱ 1-2 ঘণ্টা · Station 35 / 153
It works in Postman, so why not in the browser?
তুমি https://api.shop.com এ একটা API বানালে, আর https://app.shop.com এ frontend। curl আর Postman এ সব request ঠিকঠাক চলে। তারপর frontend থেকে fetch দিয়ে call করলে, আর console লাল হয়ে গেলো:
Access to fetch at 'https://api.shop.com/cart' from origin 'https://app.shop.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.
তোমার API তে কোনো সমস্যা নেই। curl আর Postman শুধু byte পাঠানো program। কে চাইলো, সেটা নিয়ে ওদের মাথাব্যথা নেই। কিন্তু browser আলাদা। Browser হাজার হাজার website এর code run করে। এদের যেকোনোটা চাইতে পারে তোমার logged-in cookie use করে তোমার bank, email বা অফিসের dashboard পড়ে ফেলতে। তাই browser একটা কড়া নিয়ম মানে: একটা page শুধু তার নিজের origin এর response পড়তে পারবে। অন্য server যদি নিজে না বলে "হ্যাঁ, এই page এর permission আছে"।
এই "হ্যাঁ" টাই CORS, মানে Cross-Origin Resource Sharing। এটা কিছু HTTP header, যেটা server পাঠায়, আর কিছু rule, যেটা browser মানে। একবার বুঝে গেলে যে permission দেয় server আর enforce করে browser, তখন console এর লাল error ঠিক করা সহজ হয়ে যায়। আর এমনভাবে "fix" করা বন্ধ করবে, যেটা security hole খুলে দেয়।
The problem: the browser holds your keys
তুমি bank.com এ logged in থাকলে browser এর কাছে ওটার session cookie থাকে। এবার আরেকটা tab এ evil.example খুললে। ওই page এর JavaScript এটা চেষ্টা করতে পারে:
fetch("https://bank.com/api/balance", { credentials: "include" })
Browser তোমার bank এর cookie নিজে থেকেই লাগিয়ে দেবে (lesson 6)। এরপর page টা যদি response পড়তে পারতো, তাহলে তুমি যে website এ ঢুকতে, সেটাই তোমার balance, message আর private data পড়ে ফেলতে পারতো।
| কে request পাঠাচ্ছে | তোমার cookie আছে? | Response পড়া যাবে কিনা কে ঠিক করে |
|---|---|---|
| curl, Postman, একটা backend service | না (যা দেবে শুধু তাই) | কেউ না, program সোজা পড়ে ফেলে |
| একই origin এর একটা page | হ্যাঁ | কেউ না, same origin কে trust করা হয় |
| অন্য origin এর একটা page | হ্যাঁ, browser লাগিয়ে দেয় | server, CORS header দিয়ে; enforce করে browser |
Same-origin policy হলো default "না"। আর CORS হলো server এর জন্য নির্দিষ্ট কিছু origin কে controlled ভাবে "হ্যাঁ" বলার উপায়।
Think of a school gate
School এর gatekeeper বাচ্চাদের বাবা-মা এর হাতে তুলে দেয়। একজন অচেনা লোক এসে বললো "আমি রাফিকে নিতে এসেছি"।
- Gatekeeper নিজে থেকে ঠিক করে না। সে দেখে বাবা-মা school কে যে list দিয়েছে সেটা: এই বাচ্চাকে কে কে নিতে পারবে।
- লোকটা list এ থাকলে বাচ্চা তার সাথে যায়। না থাকলে বাচ্চা ভেতরেই থাকে।
- Gatekeeper রক্ষা করে বাচ্চাকে (response এর ভেতরের তোমার data)। অচেনা লোককে gate পর্যন্ত এসে কথা বলা থেকে আটকায় না (request তবুও পৌঁছায়)।
Browser হলো gatekeeper, list লেখে server (CORS header), আর response হলো বাচ্চা।
Analogy টা কোথায় খাটে না। Gatekeeper কিছু হওয়ার আগেই অচেনা লোককে থামিয়ে দেয়। কিন্তু "simple" request এর বেলায় browser আগে request পাঠিয়ে দেয়, পরে শুধু response টা লুকায়। Server এর handler ঠিকই run হয়। এজন্যই CORS তোমার server কে protect করে না। Protect করে শুধু তোমার user এর data।
The building blocks
- Origin = scheme + host + port।
https://app.shop.comআরhttps://api.shop.comআলাদা origin (host আলাদা)।http://shop.comআরhttps://shop.comও আলাদা (scheme আলাদা)।localhost:3000আরlocalhost:8080ও আলাদা (port আলাদা)। Path এ কিছু যায় আসে না। - Browser
Originপাঠায়। Cross-origin request এ browser যোগ করেOrigin: https://app.shop.com। Page এটা fake করতে পারে না, কারণ JavaScript কে এই header set করতে দেওয়া হয় না। - Server উত্তর দেয়
Access-Control-Allow-Originদিয়ে। হয় ঠিক ওই origin টা (https://app.shop.com), নয়তো*(যে কেউ)। Header না থাকলে বা match না করলে browser JavaScript কে response পড়তে দেয় না। - Simple request সরাসরি চলে যায়। GET, HEAD বা POST, শুধু basic header সহ (কোনো
Authorizationনেই, আরContent-Typeশুধুtext/plain, form data বা multipart)। এগুলো সাথে সাথে পাঠানো হয়। কারণ একটা HTML form সবসময়ই এই request গুলো পাঠাতে পারতো। তাই এগুলো বের হতে দিলে নতুন কোনো risk তৈরি হয় না। - বাকি সবকিছুর জন্য preflight। PUT, DELETE, PATCH, JSON
Content-TypeবাAuthorizationheader থাকলে browser আগেOPTIONSপাঠায়, সাথেAccess-Control-Request-MethodআরAccess-Control-Request-Headers। উত্তরে ওই origin, method আর header allow করা থাকলে তবেই আসল request যায়। - Preflight এর result cache হয়।
Access-Control-Max-Age: 600থাকলে browser ওই URL এর জন্য 10 মিনিট preflight skip করতে পারে। না থাকলে প্রতিটা non-simple call এ একটা বাড়তি round trip। - Cookie এর জন্য বাড়তি permission লাগে।
credentials: "include"থাকলে server কে ঠিক origin টা পাঠাতে হবে (*না), সাথেAccess-Control-Allow-Credentials: true। Credentials এর সাথে wildcard সবসময় reject হয়। তাই public*API কখনো user এর cookie দিয়ে পড়া যায় না। Vary: Origin। Response যদিOriginheader অনুযায়ী বদলায়, সেটা বলে দাও। নাহলে কোনো cache বা CDN এক origin এর CORS header আরেক origin কে দিয়ে দিতে পারে।
https://evil.example এর একটা page simple GET দিয়ে fetch('https://api.shop.com/cart', { credentials: 'include' }) চালায়। api.shop.com কোনো CORS header পাঠায় না। Server এ কী হবে?
Behind the scenes: a DELETE from another origin
Frontend একটা cart item delete করে
ধাপ 1/5 Page fetch call করে
https://app.shop.com এর JavaScript call করে fetch('https://api.shop.com/cart/7', { method: 'DELETE', headers: { Authorization: 'Bearer t1' } })।
- origin
- https://app.shop.com
- method
- DELETE
The picture to keep in your head
CORS হলো একটা permission slip, লেখে server, check করে browser।
- Server লেখে:
Access-Control-Allow-Originআর তার সাথের header গুলো, প্রতিটা origin এর জন্য। - Browser check করে: JavaScript কে response দেওয়ার আগে, আর risky request পাঠানোর আগে (preflight)।
- Browser ছাড়া অন্য client এটা ignore করে: curl, mobile app আর অন্য server এই slip এর দিকে তাকায়ও না।
- এটা user এর data protect করে, তোমার server না: authentication, authorization আর CSRF defence এখনো server এই রাখতে হবে।
Try it: will the browser allow it?
Allow হবে, নাকি block?
no CORS headers needed
Code from first principles
একটা ছোট API server, সাথে একটা CORS policy (শুধু https://app.shop.com কে trust করে, আর /public সবার জন্য খোলা, cookie ছাড়া)। সাথে একটা ছোট্ট "browser", যেটা CORS এর rule মানে: simple request সোজা চলে যায়, বাকিগুলোর preflight হয়, আর header allow করলে তবেই response page কে দেয়। Server এর কাছে যত request পৌঁছায় সব log করে, যাতে দেখতে পারো CORS কী আটকায় আর কী আটকায় না।
package main
import (
"bufio"
"fmt"
"io"
"net"
"strings"
)
const api = "https://api.shop.com" // the server's own origin
var allowed = map[string]bool{"https://app.shop.com": true}
var seen []string // every request that reached the server
type resp struct {
status int
headers map[string]string
body string
}
// parseHead reads a request or response head and returns its first line and lower-cased headers.
func parseHead(r *bufio.Reader) (string, map[string]string) {
first, _ := r.ReadString('\n')
h := map[string]string{}
for {
line, err := r.ReadString('\n')
if err != nil || line == "\r\n" {
break
}
k, v, _ := strings.Cut(strings.TrimRight(line, "\r\n"), ": ")
h[strings.ToLower(k)] = v
}
return strings.TrimSpace(first), h
}
// The API server and its CORS policy.
func handle(conn net.Conn) {
defer conn.Close()
line, h := parseHead(bufio.NewReader(conn))
parts := strings.Fields(line)
method, path := parts[0], parts[1]
seen = append(seen, method+" "+path)
origin := h["origin"]
out := map[string]string{}
status, body := 200, ""
switch {
case method == "OPTIONS": // preflight: say what's allowed, only to origins we trust
status = 204
if allowed[origin] {
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Methods"] = "GET, POST, DELETE"
out["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
out["Access-Control-Max-Age"] = "600"
}
case path == "/public": // public data: any site may read it, but not with cookies
out["Access-Control-Allow-Origin"] = "*"
body = `{"news":"sale"}`
default:
if allowed[origin] {
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Credentials"] = "true"
}
if method == "DELETE" {
body = `{"deleted":7}`
} else {
body = `{"items":2}`
}
}
reason := map[int]string{200: "OK", 204: "No Content"}[status]
fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\nVary: Origin\r\n", status, reason, len(body))
for _, k := range []string{"Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"} {
if v, ok := out[k]; ok {
fmt.Fprintf(conn, "%s: %s\r\n", k, v)
}
}
fmt.Fprintf(conn, "Connection: close\r\n\r\n%s", body)
}
func send(method, path string, headers [][2]string) resp {
conn, _ := net.Dial("tcp", "127.0.0.1:8097")
defer conn.Close()
req := method + " " + path + " HTTP/1.1\r\nHost: api.shop.com\r\n"
for _, kv := range headers {
req += kv[0] + ": " + kv[1] + "\r\n"
}
io.WriteString(conn, req+"Connection: close\r\n\r\n")
r := bufio.NewReader(conn)
first, h := parseHead(r)
var status int
fmt.Sscanf(first, "HTTP/1.1 %d", &status)
body, _ := io.ReadAll(r)
return resp{status, h, string(body)}
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
func fetch(page, method, path, auth string, cookies bool) string {
extra := ""
if cookies {
extra = " +cookies"
}
label := fmt.Sprintf("%s %s from %s%s", method, path, page, extra)
var hs [][2]string
if cookies {
hs = append(hs, [2]string{"Cookie", "session=abc"})
}
if auth != "" {
hs = append(hs, [2]string{"Authorization", auth})
}
if page == api { // same origin: no CORS check at all
r := send(method, path, hs)
return fmt.Sprintf("%s (same origin): %d, JS reads %s", label, r.status, r.body)
}
pre := ""
simple := (method == "GET" || method == "HEAD" || method == "POST") && auth == ""
if !simple { // ask permission first
p := send("OPTIONS", path, [][2]string{{"Origin", page},
{"Access-Control-Request-Method", method}, {"Access-Control-Request-Headers", "authorization"}})
ok := p.headers["access-control-allow-origin"] == page &&
strings.Contains(p.headers["access-control-allow-methods"], method) &&
strings.Contains(strings.ToLower(p.headers["access-control-allow-headers"]), "authorization")
if !ok {
return fmt.Sprintf("%s: preflight failed, %s never sent", label, method)
}
pre = "preflight ok, "
}
r := send(method, path, append([][2]string{{"Origin", page}}, hs...))
acao := r.headers["access-control-allow-origin"]
blocked := ""
switch {
case acao == "":
blocked = "no Access-Control-Allow-Origin"
case acao == "*" && cookies:
blocked = "wildcard * not allowed with cookies"
case acao != "*" && acao != page:
blocked = "origin does not match"
case cookies && r.headers["access-control-allow-credentials"] != "true":
blocked = "credentials not allowed"
}
if blocked != "" {
return fmt.Sprintf("%s: %s%d, blocked: %s", label, pre, r.status, blocked)
}
return fmt.Sprintf("%s: %s%d, JS reads %s", label, pre, r.status, r.body)
}
func main() {
ln, _ := net.Listen("tcp", "127.0.0.1:8097")
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
handle(c)
}
}()
app, evil := "https://app.shop.com", "https://evil.example"
lines := []string{
fetch(api, "GET", "/cart", "", true),
fetch(app, "GET", "/cart", "", true),
fetch(evil, "GET", "/cart", "", true),
fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "GET", "/public", "", false),
fetch(app, "GET", "/public", "", true),
}
for i, l := range lines {
fmt.Printf("%d. %s\n", i+1, l)
}
fmt.Printf("server saw %d requests: %s\n", len(seen), strings.Join(seen, ", "))
}const net = require("net");
const api = "https://api.shop.com"; // the server's own origin
const allowed = new Set(["https://app.shop.com"]);
const seen = []; // every request that reached the server
// parseHead splits a request or response head into its first line and lower-cased headers.
function parseHead(text) {
const [first, ...lines] = text.split("\r\n");
const h = {};
for (const line of lines) {
const i = line.indexOf(": ");
if (i > 0) h[line.slice(0, i).toLowerCase()] = line.slice(i + 2);
}
return [first, h];
}
// The API server and its CORS policy.
function handle(conn, head) {
const [line, h] = parseHead(head);
const [method, path] = line.split(" ");
seen.push(method + " " + path);
const origin = h["origin"];
const out = {};
let status = 200, body = "";
if (method === "OPTIONS") { // preflight: say what's allowed, only to origins we trust
status = 204;
if (allowed.has(origin)) {
out["Access-Control-Allow-Origin"] = origin;
out["Access-Control-Allow-Methods"] = "GET, POST, DELETE";
out["Access-Control-Allow-Headers"] = "Authorization, Content-Type";
out["Access-Control-Max-Age"] = "600";
}
} else if (path === "/public") { // public data: any site may read it, but not with cookies
out["Access-Control-Allow-Origin"] = "*";
body = '{"news":"sale"}';
} else {
if (allowed.has(origin)) {
out["Access-Control-Allow-Origin"] = origin;
out["Access-Control-Allow-Credentials"] = "true";
}
body = method === "DELETE" ? '{"deleted":7}' : '{"items":2}';
}
const reason = { 200: "OK", 204: "No Content" }[status];
let res = `HTTP/1.1 ${status} ${reason}\r\nContent-Length: ${body.length}\r\nVary: Origin\r\n`;
for (const k of ["Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"]) {
if (k in out) res += `${k}: ${out[k]}\r\n`;
}
conn.end(res + "Connection: close\r\n\r\n" + body);
}
function send(method, path, headers) {
return new Promise((resolve) => {
const conn = net.connect(8097, "127.0.0.1");
let req = `${method} ${path} HTTP/1.1\r\nHost: api.shop.com\r\n`;
for (const [k, v] of headers) req += `${k}: ${v}\r\n`;
conn.write(req + "Connection: close\r\n\r\n");
let data = "";
conn.on("data", (d) => (data += d));
conn.on("end", () => {
const cut = data.indexOf("\r\n\r\n");
const [first, h] = parseHead(data.slice(0, cut));
resolve({ status: Number(first.split(" ")[1]), headers: h, body: data.slice(cut + 4) });
});
});
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
async function fetchAs(page, method, path, auth, cookies) {
const label = `${method} ${path} from ${page}${cookies ? " +cookies" : ""}`;
const hs = [];
if (cookies) hs.push(["Cookie", "session=abc"]);
if (auth) hs.push(["Authorization", auth]);
if (page === api) { // same origin: no CORS check at all
const r = await send(method, path, hs);
return `${label} (same origin): ${r.status}, JS reads ${r.body}`;
}
let pre = "";
const simple = ["GET", "HEAD", "POST"].includes(method) && !auth;
if (!simple) { // ask permission first
const p = await send("OPTIONS", path, [["Origin", page],
["Access-Control-Request-Method", method], ["Access-Control-Request-Headers", "authorization"]]);
const ok = p.headers["access-control-allow-origin"] === page &&
(p.headers["access-control-allow-methods"] || "").includes(method) &&
(p.headers["access-control-allow-headers"] || "").toLowerCase().includes("authorization");
if (!ok) return `${label}: preflight failed, ${method} never sent`;
pre = "preflight ok, ";
}
const r = await send(method, path, [["Origin", page], ...hs]);
const acao = r.headers["access-control-allow-origin"] || "";
let blocked = "";
if (acao === "") blocked = "no Access-Control-Allow-Origin";
else if (acao === "*" && cookies) blocked = "wildcard * not allowed with cookies";
else if (acao !== "*" && acao !== page) blocked = "origin does not match";
else if (cookies && r.headers["access-control-allow-credentials"] !== "true") blocked = "credentials not allowed";
if (blocked) return `${label}: ${pre}${r.status}, blocked: ${blocked}`;
return `${label}: ${pre}${r.status}, JS reads ${r.body}`;
}
const server = net.createServer((conn) => {
let head = "";
conn.on("data", (d) => {
head += d;
if (head.includes("\r\n\r\n")) handle(conn, head.slice(0, head.indexOf("\r\n\r\n")));
});
});
server.listen(8097, "127.0.0.1", async () => {
const app = "https://app.shop.com", evil = "https://evil.example";
const lines = [
await fetchAs(api, "GET", "/cart", "", true),
await fetchAs(app, "GET", "/cart", "", true),
await fetchAs(evil, "GET", "/cart", "", true),
await fetchAs(app, "DELETE", "/cart/7", "Bearer t1", false),
await fetchAs(evil, "DELETE", "/cart/7", "Bearer t1", false),
await fetchAs(evil, "GET", "/public", "", false),
await fetchAs(app, "GET", "/public", "", true),
];
lines.forEach((l, i) => console.log(`${i + 1}. ${l}`));
console.log(`server saw ${seen.length} requests: ${seen.join(", ")}`);
server.close();
});use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
const API: &str = "https://api.shop.com"; // the server's own origin
const ALLOWED: [&str; 1] = ["https://app.shop.com"];
struct Resp {
status: u16,
headers: HashMap<String, String>,
body: String,
}
// parse_head reads a request or response head and returns its first line and lower-cased headers.
fn parse_head(r: &mut BufReader<TcpStream>) -> (String, HashMap<String, String>) {
let mut first = String::new();
r.read_line(&mut first).unwrap();
let mut h = HashMap::new();
loop {
let mut line = String::new();
if r.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
if let Some((k, v)) = line.trim_end().split_once(": ") {
h.insert(k.to_lowercase(), v.to_string());
}
}
(first.trim().to_string(), h)
}
// The API server and its CORS policy.
fn handle(conn: TcpStream, seen: &Mutex<Vec<String>>) {
let mut r = BufReader::new(conn.try_clone().unwrap());
let (line, h) = parse_head(&mut r);
let parts: Vec<&str> = line.split_whitespace().collect();
let (method, path) = (parts[0], parts[1]);
seen.lock().unwrap().push(format!("{} {}", method, path));
let origin = h.get("origin").map(String::as_str).unwrap_or("");
let ok_origin = ALLOWED.contains(&origin);
let mut out: HashMap<&str, String> = HashMap::new();
let (mut status, mut body) = (200, "");
if method == "OPTIONS" {
// preflight: say what's allowed, only to origins we trust
status = 204;
if ok_origin {
out.insert("Access-Control-Allow-Origin", origin.to_string());
out.insert("Access-Control-Allow-Methods", "GET, POST, DELETE".into());
out.insert("Access-Control-Allow-Headers", "Authorization, Content-Type".into());
out.insert("Access-Control-Max-Age", "600".into());
}
} else if path == "/public" {
// public data: any site may read it, but not with cookies
out.insert("Access-Control-Allow-Origin", "*".into());
body = r#"{"news":"sale"}"#;
} else {
if ok_origin {
out.insert("Access-Control-Allow-Origin", origin.to_string());
out.insert("Access-Control-Allow-Credentials", "true".into());
}
body = if method == "DELETE" { r#"{"deleted":7}"# } else { r#"{"items":2}"# };
}
let reason = if status == 200 { "OK" } else { "No Content" };
let mut res = format!("HTTP/1.1 {} {}\r\nContent-Length: {}\r\nVary: Origin\r\n", status, reason, body.len());
for k in ["Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"] {
if let Some(v) = out.get(k) {
res += &format!("{}: {}\r\n", k, v);
}
}
res += "Connection: close\r\n\r\n";
res += body;
let mut conn = conn;
conn.write_all(res.as_bytes()).unwrap();
}
fn send(method: &str, path: &str, headers: &[(&str, &str)]) -> Resp {
let mut conn = TcpStream::connect("127.0.0.1:8097").unwrap();
let mut req = format!("{} {} HTTP/1.1\r\nHost: api.shop.com\r\n", method, path);
for (k, v) in headers {
req += &format!("{}: {}\r\n", k, v);
}
req += "Connection: close\r\n\r\n";
conn.write_all(req.as_bytes()).unwrap();
let mut r = BufReader::new(conn);
let (first, h) = parse_head(&mut r);
let status = first.split_whitespace().nth(1).unwrap().parse().unwrap();
let mut body = String::new();
r.read_to_string(&mut body).unwrap();
Resp { status, headers: h, body }
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
fn fetch(page: &str, method: &str, path: &str, auth: &str, cookies: bool) -> String {
let label = format!("{} {} from {}{}", method, path, page, if cookies { " +cookies" } else { "" });
let mut hs: Vec<(&str, &str)> = Vec::new();
if cookies {
hs.push(("Cookie", "session=abc"));
}
if !auth.is_empty() {
hs.push(("Authorization", auth));
}
if page == API {
// same origin: no CORS check at all
let r = send(method, path, &hs);
return format!("{} (same origin): {}, JS reads {}", label, r.status, r.body);
}
let get = |h: &HashMap<String, String>, k: &str| h.get(k).cloned().unwrap_or_default();
let mut pre = "";
let simple = ["GET", "HEAD", "POST"].contains(&method) && auth.is_empty();
if !simple {
// ask permission first
let p = send("OPTIONS", path, &[("Origin", page),
("Access-Control-Request-Method", method), ("Access-Control-Request-Headers", "authorization")]);
let ok = get(&p.headers, "access-control-allow-origin") == page
&& get(&p.headers, "access-control-allow-methods").contains(method)
&& get(&p.headers, "access-control-allow-headers").to_lowercase().contains("authorization");
if !ok {
return format!("{}: preflight failed, {} never sent", label, method);
}
pre = "preflight ok, ";
}
let mut all = vec![("Origin", page)];
all.extend(hs);
let r = send(method, path, &all);
let acao = get(&r.headers, "access-control-allow-origin");
let blocked = if acao.is_empty() {
"no Access-Control-Allow-Origin"
} else if acao == "*" && cookies {
"wildcard * not allowed with cookies"
} else if acao != "*" && acao != page {
"origin does not match"
} else if cookies && get(&r.headers, "access-control-allow-credentials") != "true" {
"credentials not allowed"
} else {
""
};
if !blocked.is_empty() {
return format!("{}: {}{}, blocked: {}", label, pre, r.status, blocked);
}
format!("{}: {}{}, JS reads {}", label, pre, r.status, r.body)
}
fn main() {
let seen = Arc::new(Mutex::new(Vec::new())); // every request that reached the server
let ln = TcpListener::bind("127.0.0.1:8097").unwrap();
let s = seen.clone();
thread::spawn(move || {
for c in ln.incoming() {
handle(c.unwrap(), &s);
}
});
let (app, evil) = ("https://app.shop.com", "https://evil.example");
let lines = [
fetch(API, "GET", "/cart", "", true),
fetch(app, "GET", "/cart", "", true),
fetch(evil, "GET", "/cart", "", true),
fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "GET", "/public", "", false),
fetch(app, "GET", "/public", "", true),
];
for (i, l) in lines.iter().enumerate() {
println!("{}. {}", i + 1, l);
}
let seen = seen.lock().unwrap();
println!("server saw {} requests: {}", seen.len(), seen.join(", "));
}import socket
import threading
API = "https://api.shop.com" # the server's own origin
ALLOWED = {"https://app.shop.com"}
seen = [] # every request that reached the server
def parse_head(text):
"""Split a request or response head into its first line and lower-cased headers."""
first, *lines = text.split("\r\n")
h = {}
for line in lines:
k, sep, v = line.partition(": ")
if sep:
h[k.lower()] = v
return first, h
def read_all(conn):
data = b""
while chunk := conn.recv(4096):
data += chunk
return data.decode()
def handle(conn):
"""The API server and its CORS policy."""
head = b""
while b"\r\n\r\n" not in head:
head += conn.recv(4096)
line, h = parse_head(head.decode().split("\r\n\r\n")[0])
method, path = line.split()[:2]
seen.append(f"{method} {path}")
origin = h.get("origin")
out = {}
status, body = 200, ""
if method == "OPTIONS": # preflight: say what's allowed, only to origins we trust
status = 204
if origin in ALLOWED:
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Methods"] = "GET, POST, DELETE"
out["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
out["Access-Control-Max-Age"] = "600"
elif path == "/public": # public data: any site may read it, but not with cookies
out["Access-Control-Allow-Origin"] = "*"
body = '{"news":"sale"}'
else:
if origin in ALLOWED:
out["Access-Control-Allow-Origin"] = origin
out["Access-Control-Allow-Credentials"] = "true"
body = '{"deleted":7}' if method == "DELETE" else '{"items":2}'
reason = {200: "OK", 204: "No Content"}[status]
res = f"HTTP/1.1 {status} {reason}\r\nContent-Length: {len(body)}\r\nVary: Origin\r\n"
for k in ["Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"]:
if k in out:
res += f"{k}: {out[k]}\r\n"
conn.sendall((res + "Connection: close\r\n\r\n" + body).encode())
conn.close()
def send(method, path, headers):
conn = socket.create_connection(("127.0.0.1", 8097))
req = f"{method} {path} HTTP/1.1\r\nHost: api.shop.com\r\n"
for k, v in headers:
req += f"{k}: {v}\r\n"
conn.sendall((req + "Connection: close\r\n\r\n").encode())
data = read_all(conn)
conn.close()
head, _, body = data.partition("\r\n\r\n")
first, h = parse_head(head)
return int(first.split()[1]), h, body
def fetch(page, method, path, auth, cookies):
"""A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything."""
label = f"{method} {path} from {page}{' +cookies' if cookies else ''}"
hs = []
if cookies:
hs.append(("Cookie", "session=abc"))
if auth:
hs.append(("Authorization", auth))
if page == API: # same origin: no CORS check at all
status, _, body = send(method, path, hs)
return f"{label} (same origin): {status}, JS reads {body}"
pre = ""
simple = method in ("GET", "HEAD", "POST") and not auth
if not simple: # ask permission first
_, p, _ = send("OPTIONS", path, [("Origin", page),
("Access-Control-Request-Method", method), ("Access-Control-Request-Headers", "authorization")])
ok = (p.get("access-control-allow-origin") == page
and method in p.get("access-control-allow-methods", "")
and "authorization" in p.get("access-control-allow-headers", "").lower())
if not ok:
return f"{label}: preflight failed, {method} never sent"
pre = "preflight ok, "
status, h, body = send(method, path, [("Origin", page)] + hs)
acao = h.get("access-control-allow-origin", "")
blocked = ""
if acao == "":
blocked = "no Access-Control-Allow-Origin"
elif acao == "*" and cookies:
blocked = "wildcard * not allowed with cookies"
elif acao != "*" and acao != page:
blocked = "origin does not match"
elif cookies and h.get("access-control-allow-credentials") != "true":
blocked = "credentials not allowed"
if blocked:
return f"{label}: {pre}{status}, blocked: {blocked}"
return f"{label}: {pre}{status}, JS reads {body}"
def serve(ln):
while True:
conn, _ = ln.accept()
handle(conn)
ln = socket.socket()
ln.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ln.bind(("127.0.0.1", 8097))
ln.listen()
threading.Thread(target=serve, args=(ln,), daemon=True).start()
app, evil = "https://app.shop.com", "https://evil.example"
lines = [
fetch(API, "GET", "/cart", "", True),
fetch(app, "GET", "/cart", "", True),
fetch(evil, "GET", "/cart", "", True),
fetch(app, "DELETE", "/cart/7", "Bearer t1", False),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", False),
fetch(evil, "GET", "/public", "", False),
fetch(app, "GET", "/public", "", True),
]
for i, l in enumerate(lines, 1):
print(f"{i}. {l}")
print(f"server saw {len(seen)} requests: {', '.join(seen)}")import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
static final String API = "https://api.shop.com"; // the server's own origin
static final Set<String> ALLOWED = Set.of("https://app.shop.com");
static final List<String> seen = Collections.synchronizedList(new ArrayList<>()); // every request that reached the server
record Resp(int status, Map<String, String> headers, String body) {}
// readLine reads one CRLF-terminated line from a raw stream.
static String readLine(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
int c;
while ((c = in.read()) != -1) {
sb.append((char) c);
if (c == '\n') break;
}
return sb.toString();
}
// parseHead reads a request or response head: its first line, then lower-cased headers.
static Map<String, String> parseHead(InputStream in, String[] first) throws IOException {
first[0] = readLine(in).trim();
Map<String, String> h = new HashMap<>();
while (true) {
String line = readLine(in);
if (line.isEmpty() || line.equals("\r\n")) break;
String t = line.stripTrailing();
int i = t.indexOf(": ");
if (i > 0) h.put(t.substring(0, i).toLowerCase(), t.substring(i + 2));
}
return h;
}
// The API server and its CORS policy.
static void handle(Socket conn) throws IOException {
String[] line = new String[1];
Map<String, String> h = parseHead(conn.getInputStream(), line);
String[] parts = line[0].split(" ");
String method = parts[0], path = parts[1];
seen.add(method + " " + path);
String origin = h.getOrDefault("origin", "");
Map<String, String> out = new HashMap<>();
int status = 200;
String body = "";
if (method.equals("OPTIONS")) { // preflight: say what's allowed, only to origins we trust
status = 204;
if (ALLOWED.contains(origin)) {
out.put("Access-Control-Allow-Origin", origin);
out.put("Access-Control-Allow-Methods", "GET, POST, DELETE");
out.put("Access-Control-Allow-Headers", "Authorization, Content-Type");
out.put("Access-Control-Max-Age", "600");
}
} else if (path.equals("/public")) { // public data: any site may read it, but not with cookies
out.put("Access-Control-Allow-Origin", "*");
body = "{\"news\":\"sale\"}";
} else {
if (ALLOWED.contains(origin)) {
out.put("Access-Control-Allow-Origin", origin);
out.put("Access-Control-Allow-Credentials", "true");
}
body = method.equals("DELETE") ? "{\"deleted\":7}" : "{\"items\":2}";
}
String reason = status == 200 ? "OK" : "No Content";
StringBuilder res = new StringBuilder("HTTP/1.1 " + status + " " + reason + "\r\nContent-Length: " + body.length() + "\r\nVary: Origin\r\n");
for (String k : List.of("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age")) {
if (out.containsKey(k)) res.append(k).append(": ").append(out.get(k)).append("\r\n");
}
res.append("Connection: close\r\n\r\n").append(body);
conn.getOutputStream().write(res.toString().getBytes(StandardCharsets.UTF_8));
conn.close();
}
static Resp send(String method, String path, List<String[]> headers) throws IOException {
try (Socket conn = new Socket("127.0.0.1", 8097)) {
StringBuilder req = new StringBuilder(method + " " + path + " HTTP/1.1\r\nHost: api.shop.com\r\n");
for (String[] kv : headers) req.append(kv[0]).append(": ").append(kv[1]).append("\r\n");
req.append("Connection: close\r\n\r\n");
conn.getOutputStream().write(req.toString().getBytes(StandardCharsets.UTF_8));
InputStream in = conn.getInputStream();
String[] first = new String[1];
Map<String, String> h = parseHead(in, first);
String body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
return new Resp(Integer.parseInt(first[0].split(" ")[1]), h, body);
}
}
// A tiny browser: it follows the CORS rules before letting the page's JavaScript see anything.
static String fetch(String page, String method, String path, String auth, boolean cookies) throws IOException {
String label = method + " " + path + " from " + page + (cookies ? " +cookies" : "");
List<String[]> hs = new ArrayList<>();
if (cookies) hs.add(new String[]{"Cookie", "session=abc"});
if (!auth.isEmpty()) hs.add(new String[]{"Authorization", auth});
if (page.equals(API)) { // same origin: no CORS check at all
Resp r = send(method, path, hs);
return label + " (same origin): " + r.status() + ", JS reads " + r.body();
}
String pre = "";
boolean simple = List.of("GET", "HEAD", "POST").contains(method) && auth.isEmpty();
if (!simple) { // ask permission first
Resp p = send("OPTIONS", path, List.of(new String[]{"Origin", page},
new String[]{"Access-Control-Request-Method", method}, new String[]{"Access-Control-Request-Headers", "authorization"}));
boolean ok = page.equals(p.headers().get("access-control-allow-origin"))
&& p.headers().getOrDefault("access-control-allow-methods", "").contains(method)
&& p.headers().getOrDefault("access-control-allow-headers", "").toLowerCase().contains("authorization");
if (!ok) return label + ": preflight failed, " + method + " never sent";
pre = "preflight ok, ";
}
List<String[]> all = new ArrayList<>();
all.add(new String[]{"Origin", page});
all.addAll(hs);
Resp r = send(method, path, all);
String acao = r.headers().getOrDefault("access-control-allow-origin", "");
String blocked = "";
if (acao.isEmpty()) blocked = "no Access-Control-Allow-Origin";
else if (acao.equals("*") && cookies) blocked = "wildcard * not allowed with cookies";
else if (!acao.equals("*") && !acao.equals(page)) blocked = "origin does not match";
else if (cookies && !"true".equals(r.headers().get("access-control-allow-credentials"))) blocked = "credentials not allowed";
if (!blocked.isEmpty()) return label + ": " + pre + r.status() + ", blocked: " + blocked;
return label + ": " + pre + r.status() + ", JS reads " + r.body();
}
public static void main(String[] args) throws Exception {
ServerSocket ln = new ServerSocket(8097, 50, InetAddress.getByName("127.0.0.1"));
Thread t = new Thread(() -> {
while (true) {
try { handle(ln.accept()); } catch (IOException e) { return; }
}
});
t.setDaemon(true);
t.start();
String app = "https://app.shop.com", evil = "https://evil.example";
List<String> lines = List.of(
fetch(API, "GET", "/cart", "", true),
fetch(app, "GET", "/cart", "", true),
fetch(evil, "GET", "/cart", "", true),
fetch(app, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "DELETE", "/cart/7", "Bearer t1", false),
fetch(evil, "GET", "/public", "", false),
fetch(app, "GET", "/public", "", true));
for (int i = 0; i < lines.size(); i++) System.out.println((i + 1) + ". " + lines.get(i));
System.out.println("server saw " + seen.size() + " requests: " + String.join(", ", seen));
}
}Output (পাঁচটা language এই একই):
1. GET /cart from https://api.shop.com +cookies (same origin): 200, JS reads {"items":2}
2. GET /cart from https://app.shop.com +cookies: 200, JS reads {"items":2}
3. GET /cart from https://evil.example +cookies: 200, blocked: no Access-Control-Allow-Origin
4. DELETE /cart/7 from https://app.shop.com: preflight ok, 200, JS reads {"deleted":7}
5. DELETE /cart/7 from https://evil.example: preflight failed, DELETE never sent
6. GET /public from https://evil.example: 200, JS reads {"news":"sale"}
7. GET /public from https://app.shop.com +cookies: 200, blocked: wildcard * not allowed with cookies
server saw 8 requests: GET /cart, GET /cart, GET /cart, OPTIONS /cart/7, DELETE /cart/7, OPTIONS /cart/7, GET /public, GET /public
Output টা পড়ি:
- Line 1, same origin: কোনো CORS check নেই। Page cart পড়ে ফেলে।
- Line 2, cookie সহ trusted origin: Server
https://app.shop.comআরAllow-Credentials: trueফেরত দিয়েছে, তাই JavaScript পড়তে পারে। - Line 3 টাই আসল। evil.example এর GET পেয়েছে 200। মানে server user এর cookie দিয়ে handler run করেছে। Browser শুধু page কে response পড়তে দেয়নি। শেষ লাইন দেখো: server তিনটা
GET /cartপেয়েছে, evil এরটাও। - Line 4 আর 5, DELETE: trusted page পেয়েছে
preflight ok, তারপর DELETE। evil.example এর বেলায় preflight এর উত্তরে কোনো allow header ছিল না। তাই DELETE browser থেকে বেরই হয়নি। Server log এ ওর জন্য শুধুOPTIONS /cart/7, দ্বিতীয় কোনো DELETE নেই। - Line 6:
/publicপাঠায়*, তাই cookie ছাড়া evil.example ও পড়তে পারে। - Line 7: একই
*cookie সহ হলে block, trusted origin এর জন্যও। Wildcard আর credentials কখনো একসাথে চলে না।
এবার একটা আসল API, GitHub, বানানো একটা origin এর preflight এর উত্তর দিচ্ছে:
$ curl -s -o /dev/null -D - -X OPTIONS https://api.github.com/user -H "Origin: https://evil.example" -H "Access-Control-Request-Method: DELETE" -H "Access-Control-Request-Headers: authorization" | grep -iE "^(HTTP|access-control-allow-(origin|methods)|access-control-max-age)"
HTTP/2 204
access-control-max-age: 86400
access-control-allow-methods: GET, POST, PATCH, PUT, DELETE
access-control-allow-origin: *
$ curl -s -o /dev/null -D - https://www.google.com/ -H "Origin: https://evil.example" | grep -ciE "^access-control"
0
204সাথেallow-origin: *: GitHub এর API যেকোনো website কে call করতে দেয়। ওদের জন্য এটা safe, কারণ API তে authentication হয়Authorizationheader এর token দিয়ে, cookie দিয়ে না। আর*কখনো cookie এর সাথে চলে না।max-age: 86400: browser এই preflight সর্বোচ্চ এক দিন cache করতে পারে (Chrome 2 ঘণ্টায় আটকে দেয়)।- google.com এর home page 0টা CORS header পাঠায়: এটা HTML page, API না। তাই অন্য কোনো site এটা
fetchদিয়ে পড়তে পারবে না।
Real engineering
- Origin এর একটা explicit allowlist রাখো, প্রতিটা environment এর জন্য আলাদা: production এ
https://app.shop.com,http://localhost:3000শুধু development এ। String হুবহু compare করো। - নিজে header না লিখে framework এর CORS middleware use করো (Go তে
rs/cors, Express এcors, Spring এ@CrossOrigin/CorsConfiguration, FastAPI তেCORSMiddleware)। আর "allow all" চালু না করে ঠিকমতো configure করো। - Auth এর আগে
OPTIONSএর উত্তর দাও। Preflight এ কোনো cookie বা token থাকে না। তোমার auth middleware যদি এগুলোকে 401 দিয়ে reject করে, প্রতিটা non-simple request fail করবে। Access-Control-Max-Ageset করো, যাতে preflight এর round trip কমে। আর allowed origin যদি request অনুযায়ী বদলায়,Vary: Originপাঠাও।- Frontend এর যে header লাগে, সেগুলো expose করো। Default ভাবে JavaScript response এর অল্প কয়েকটা header পড়তে পারে। বাকিগুলোর জন্য
Access-Control-Expose-Headers: ETag, Location, X-Request-Id। - পারলে CORS পুরোটাই এড়িয়ে যাও: একটা reverse proxy দিয়ে frontend আর API একই origin থেকে serve করো (
shop.comআরshop.com/api)। কোনো preflight নেই, কোনো configuration নেই, cookie এমনিই কাজ করে। - CORS কোনো CSRF protection না। Simple cross-origin POST তবুও cookie সহ তোমার server এ পৌঁছায়। Data বদলানো request এর জন্য
SameSitecookie, CSRF token use করো, অথবা JSON content type বাধ্যতামূলক করো।
When it breaks
একটা failure বেছে নাও
No 'Access-Control-Allow-Origin' header is present
Think before you read on
CORS যদি simple cross-origin POST কে server এ পৌঁছানো থেকে আটকাতেই না পারে, তাহলে DELETE আর JSON request এর জন্য browser preflight নিয়ে মাথা ঘামায় কেন?
Reveal
কারণ CORS আসার আগেই যা করা যেত, সেটার জন্য। যেকোনো website এর একটা HTML <form> সবসময়ই অন্য যেকোনো site এ cookie সহ form encoding এ POST করতে পারতো। Server গুলোকে এমনিতেই এর বিরুদ্ধে defence রাখতে হতো (CSRF)। তাই fetch কে একই ধরনের request পাঠাতে দিলে নতুন কোনো বিপদ নেই। কিন্তু পুরনো কোনো web page অন্য site এ DELETE, JSON body বা custom Authorization header পাঠাতে পারতো না। অনেক server ধরে নিয়ে লেখা হয়েছিল যে এগুলো শুধু তাদের নিজের page থেকেই আসবে। Preflight এই server গুলোকে বাঁচায়। আগে জিজ্ঞেস করে, আর CORS এর কিছুই জানে না এমন পুরনো server allow header ছাড়াই উত্তর দেয়। ফলে risky request টা কখনো যায়ই না।
Check yourself
1. দুইটা URL কখন same origin হয়?
Answer
Scheme, host আর port একই হলে। https://shop.com/a আর https://shop.com/b same origin। https://shop.com আর https://api.shop.com না।
2. CORS কে enforce করে: server নাকি browser?
Answer
Browser। Server শুধু header পাঠিয়ে বলে কোন origin, method আর header সে allow করে। curl, mobile app আর অন্য server এগুলো ignore করে।
3. কোন request এ preflight হয়?
Answer
যেকোনো request যেটা simple না: GET, HEAD আর POST ছাড়া অন্য method, Authorization এর মতো custom header, অথবা text/plain, form data বা multipart ছাড়া অন্য কোনো Content-Type (যেমন application/json)।
4. Cookie এর সাথে Access-Control-Allow-Origin: * কেন use করা যায় না?
Answer
কারণ তাহলে যেকোনো website user এর cookie দিয়ে করা request এর response পড়তে পারতো। Credentials থাকলে browser চায় ঠিক origin টা, সাথে Access-Control-Allow-Credentials: true।
Your challenge: add a preflight cache
Code এর ছোট্ট browser টা বাড়াও:
(origin, method, path)key দিয়ে একটা preflight cache রাখো। Preflight সফল হলেAccess-Control-Max-Ageথেকে একটা expiry সহ store করো। একটা fake clock use করো, যেটা হাতে এগিয়ে দেবে।- Preflight করার আগে cache দেখো। Fresh entry থাকলে
OPTIONSrequest skip করো। https://app.shop.comথেকে তিনবারDELETE /cart/7পাঠাও, clock 700 second এগিয়ে দাও, তারপর আরেকবার পাঠাও।
Run করার আগে predict করো: server কয়টা OPTIONS request দেখবে?
তুমি সফল যখন server log এ থাকবে 2টা OPTIONS /cart/7 আর 4টা DELETE /cart/7, আর server এর Max-Age 0 করলে হবে 4টা আর 4টা।
The mental model
Browser user এর cookie সব জায়গায় নিয়ে যায়, তাই same-origin policy একটা page কে অন্য origin এর response পড়তে দেয় না। CORS দিয়ে server header পাঠিয়ে exception দিতে পারে: Allow-Origin, Allow-Methods, Allow-Headers, Allow-Credentials। Browser এগুলো enforce করে: simple request সাথে সাথে পাঠায়, বাকিগুলোর আগে OPTIONS দিয়ে preflight করে। Exact allowlist রাখো, auth এর আগে preflight এর উত্তর দাও,
*কখনো credentials এর সাথে দিও না, আর মনে রাখো CORS browser এ user এর data protect করে, তোমার server কে না।
Station stamp
Chapter শেষ করো
পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +10 XP পেতে।
Pro নিয়ে XP পাও →