Part 03 · Web এর ভাষা
Headers, Cookies and Content Types
প্রতিটা request এর সাথে যে metadata যায়, আর cookie কীভাবে তোমাকে মনে রাখে।
⏱ 1-2 ঘণ্টা · Station 30 / 153
How does a stateless server remember you logged in?
Module 1 বলেছিল ভালো server দুই request এর মাঝে কিছুই মনে রাখে না (stateless)। আর lesson 1 বলেছে HTTP design করেই stateless। তবুও তুমি একবার একটা shop এ login করো, tab বন্ধ করো, পরদিন ফিরে আসো, আর দেখো এখনো logged in, cart ও ভরা।
কেউ একজন মনে রাখছে। TCP connection না (ওটা কয়েক ঘণ্টা আগেই বন্ধ)। Server এর memory ও না (request হয়তো অন্য server এ যাবে)। মনে রাখছে কয়েকটা byte, যেগুলো browser রেখে দেয় আর প্রতিটা request এ ফেরত পাঠায়: একটা cookie।
Cookie শুধু একটা header। একই কৌশল, মানে প্রতিটা message এর সাথে ছোট ছোট Name: value লাইন, দিয়েই HTTP format, compression, caching, ভাষা, authentication আর security rule বর্ণনা করে। এই lesson এ রোজ দেখা header গুলো দেখবো। Cookie থাকবে আলোচনার কেন্দ্রে, কারণ বেশিরভাগ real bug আর security hole এখানেই থাকে।
The problem: the body alone can't say enough
Response body শুধু কিছু byte। ঠিকভাবে ব্যবহার করতে দুই পক্ষেরই এটা নিয়ে, আর কথোপকথন নিয়ে কিছু তথ্য লাগে:
| দরকার | Header | উদাহরণ |
|---|---|---|
| Body কোন format এ? | Content-Type | application/json; charset=utf-8 |
| Client কোন format নিতে পারে? | Accept | application/json |
| Compress করা? | Accept-Encoding / Content-Encoding | gzip, br / gzip |
| কোন ভাষা? | Accept-Language / Content-Language | bn, en;q=0.8 |
| এ কে? | Cookie, Authorization | session=abc123, Bearer eyJ... |
| পরের বারের জন্য এটা মনে রাখো | Set-Cookie | session=abc123; HttpOnly; Secure |
| আবার ব্যবহার করা যাবে? | Cache-Control, ETag | max-age=60 |
সবচেয়ে কঠিন হলো identity। HTTP এর কোনো memory নেই, তাই প্রতিটা request কে প্রমাণ করতে হয় সে কার কাছ থেকে এসেছে। Cookie এর সমাধান করে browser কে দিয়ে প্রমাণটা নিজে থেকেই বারবার দেখিয়ে।
Think of a cinema hand stamp
Cinema তে টাকা দিলে, staff তোমার হাতে একটা সিল মেরে দেয়: "Hall 3, আজ"।
- Popcorn কিনতে বাইরে গেলে। ফিরে এসে শুধু হাত দেখাও। কারো তোমার চেহারা মনে রাখার দরকার নেই।
- সিলটা শুধু এই cinema তে চলে, আর শুধু hall 3 এর জন্য।
- কাল পর্যন্ত ধুয়ে যায়।
- এটা অদৃশ্য কালি: সহজে অন্য কারো হাতে copy করা যায় না।
এটাই cookie। Server Set-Cookie দিয়ে browser এ "সিল" মারে। Browser মেয়াদ শেষ না হওয়া পর্যন্ত ওই site আর path এর প্রতিটা request এ সিলটা (Cookie) দেখায়। HttpOnly, Secure আর SameSite এর মতো attribute হলো অদৃশ্য কালি: সিলটা কে দেখতে আর copy করতে পারবে, তার নিয়ম।
Analogy টা কোথায় খাটে না। হাতের সিল check করে একজন মানুষ, যে হয়তো নকল ধরে ফেলবে। Cookie শুধু text। কেউ value টা চুরি করলে server এর কাছে সে-ই তুমি। এজন্যই security attribute এত জরুরি, আর session ID লম্বা আর random হতে হয়।
The building blocks
- Header হলো metadata, data না। নাম case-insensitive, অচেনাগুলো ignore হয় (lesson 2)। Request header বর্ণনা করে request টা কী আর client কী চায়। Response header body র বর্ণনা দেয় আর নির্দেশ দেয়।
- Content negotiation। Client বলে সে কী নিতে পারে (
Accept: application/json,Accept-Encoding: gzip, br,Accept-Language: bn)। Server বাছে, আর কী বেছেছে সেটা বলে (Content-Type,Content-Encoding,Content-Language)। মাঝে cache থাকলে serverVary: Accept-Encodingযোগ করে, যাতে cache আলাদা আলাদা version আলাদা করে রাখে। - Content-Type হলো byte গুলো নিয়ে একটা promise।
application/json,text/html; charset=utf-8,image/png, upload এর জন্যmultipart/form-data; boundary=...। Client এটা দেখেই ঠিক করে কীভাবে parse করবে, আর browser ঠিক করে render করবে নাকি download। - Cookie: server বসায়, browser ফেরত দেয়। Response:
Set-Cookie: name=value; attributes। পরে match করা প্রতিটা request এ যায়Cookie: name=value; other=value। Server শুধু নাম আর value দেখে, attribute কখনো না। - Attribute ঠিক করে cookie কখন যাবে:
Domain/ host: শুধু যে site বসিয়েছে সেখানে (Domainদেওয়া থাকলে তার subdomain এও)।Path: শুধু ওই path এর নিচের URL এ।Max-AgeবাExpires: কখন পর্যন্ত। দুইটার কোনোটাই না থাকলে এটা session cookie, browser session শেষ হলেই গায়েব।Secure: শুধু HTTPS দিয়ে।SameSite:Strict(cross-site request এ কখনো না),Lax(শুধু safe method এর top-level navigation এ, যেমন link এ click করা),None(সবসময়,Secureলাগবেই)। Modern browser SameSite না দিলে সেটাকেLaxধরে।
- আর কে পড়তে পারবে:
HttpOnlycookie টাকে JavaScript (document.cookie) থেকে লুকিয়ে রাখে, তাই কোনো XSS bug এটা চুরি করতে পারে না। - Cookie ছোট, আর সবখানে যায়। প্রতিটা cookie প্রায় 4 KB, আর match করা প্রতিটা request সবগুলো নিয়ে যায়, image এর request ও। Cookie তে একটা ID রাখো, data রাখো server এ।
তোমার session cookie Secure; HttpOnly; SameSite=Lax দিয়ে বসানো। evil.com এর একটা page এ লুকানো একটা form আছে, যেটা https://bank.com/transfer এ POST করে, আর JavaScript দিয়ে নিজে থেকেই submit হয়। Browser কি bank এর session cookie টা জুড়ে দেবে?
Behind the scenes: login, then every request after
একটা session cookie র জীবন
ধাপ 1/6 Password সহ POST /login
এই session এ password একবারই wire পার হয় (TLS দিয়ে)।
- sent
- email + password
The picture to keep in your head
Header হলো খামের উপরের label, আর cookie হলো browser এর বয়ে বেড়ানো একটা সিল:
- Content-Type / Accept / Encoding: ভেতরে কী আছে আর কীভাবে প্যাক করা, দুই পক্ষ মিলে ঠিক করে।
- Set-Cookie (server → browser): "এই সিলটা বয়ে বেড়াও, এই নিয়মে"।
- Cookie (browser → server): সিলটা, match করা প্রতিটা request এ নিজে থেকেই দেখানো।
- সিলের নিয়ম: কোন site আর path, কখন পর্যন্ত, শুধু HTTPS, script কে না, cross-site request এ না।
Server stateless থাকে। Browser একটা ছোট ID বয়ে বেড়ায়। আসল state থাকে একটা store এ, ID যেটার দিকে দেখায়।
Try it: is this cookie safe?
ভালো cookie নাকি ঝুঁকিপূর্ণ?
Set-Cookie: session=9f8c...e1; Path=/; Secure; HttpOnly; SameSite=Lax
Code from first principles
একটা browser এর cookie jar। setCookie Set-Cookie header parse করে attribute সহ রেখে দেয়। cookieHeader পরের প্রতিটা request এর জন্য ঠিক করে কোন cookie গুলো Cookie header এ যাবে: site, path, মেয়াদ, Secure আর SameSite এর rule খাটিয়ে। scriptCookies দেখায় JavaScript কী পড়তে পারতো। সময় second হিসেবে পাঠানো হয়েছে, তাই output stable।
package main
import (
"fmt"
"strconv"
"strings"
)
type cookie struct {
name, value, domain, path, sameSite string
expires int // time in seconds when it stops being sent
secure, httpOnly bool
}
var jar []cookie // what the browser remembers, in the order it was set
// setCookie parses one Set-Cookie header the server sent from `domain` at time `now`.
func setCookie(header, domain string, now int) {
parts := strings.Split(header, "; ")
name, value, _ := strings.Cut(parts[0], "=")
c := cookie{name: name, value: value, domain: domain, path: "/", sameSite: "Lax", expires: 1 << 30}
for _, attr := range parts[1:] {
k, v, _ := strings.Cut(attr, "=")
switch strings.ToLower(k) {
case "path":
c.path = v
case "max-age":
n, _ := strconv.Atoi(v)
c.expires = now + n
case "secure":
c.secure = true
case "httponly":
c.httpOnly = true
case "samesite":
c.sameSite = v
}
}
jar = append(jar, c)
}
// cookieHeader is what the browser attaches to a request: only cookies that match all the rules.
func cookieHeader(now int, scheme, host, path string, crossSitePost bool) string {
sent := []string{}
for _, c := range jar {
switch {
case host != c.domain: // other sites never see it
case !strings.HasPrefix(path, c.path): // outside its path
case now >= c.expires: // expired
case c.secure && scheme != "https": // Secure: never over plain HTTP
case crossSitePost && c.sameSite != "None": // Lax/Strict: not on a POST from another site
default:
sent = append(sent, c.name+"="+c.value)
}
}
if len(sent) == 0 {
return "(none)"
}
return strings.Join(sent, "; ")
}
// scriptCookies is what JavaScript on a page at `path` can read with document.cookie.
func scriptCookies(now int, path string) string {
seen := []string{}
for _, c := range jar {
if !c.httpOnly && now < c.expires && strings.HasPrefix(path, c.path) {
seen = append(seen, c.name+"="+c.value)
}
}
return strings.Join(seen, "; ")
}
func main() {
for _, h := range []string{
"session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
"theme=dark; Path=/; Max-Age=31536000",
"cart=7; Path=/cart; Max-Age=600",
"promo=EID; Path=/; Max-Age=60",
} {
setCookie(h, "shop.com", 0)
fmt.Println("Set-Cookie: " + h)
}
reqs := []struct {
now int
scheme, host, path string
crossSitePost bool
label string
}{
{10, "https", "shop.com", "/", false, "t=10s GET https://shop.com/"},
{10, "https", "shop.com", "/cart/items", false, "t=10s GET https://shop.com/cart/items"},
{10, "http", "shop.com", "/", false, "t=10s GET http://shop.com/ (plain HTTP)"},
{10, "https", "evil.com", "/", false, "t=10s GET https://evil.com/"},
{10, "https", "shop.com", "/transfer", true, "t=10s POST https://shop.com/transfer from a form on evil.com"},
{120, "https", "shop.com", "/", false, "t=120s GET https://shop.com/"},
{4000, "https", "shop.com", "/", false, "t=4000s GET https://shop.com/"},
}
for _, r := range reqs {
fmt.Printf("%s\n Cookie: %s\n", r.label, cookieHeader(r.now, r.scheme, r.host, r.path, r.crossSitePost))
}
fmt.Println("document.cookie on https://shop.com/ at t=10s: " + scriptCookies(10, "/"))
}const jar = []; // what the browser remembers, in the order it was set
// setCookie parses one Set-Cookie header the server sent from `domain` at time `now`.
function setCookie(header, domain, now) {
const [first, ...attrs] = header.split("; ");
const eq = first.indexOf("=");
const c = { name: first.slice(0, eq), value: first.slice(eq + 1), domain, path: "/", sameSite: "Lax",
expires: 2 ** 30, secure: false, httpOnly: false };
for (const attr of attrs) {
const [k, v] = attr.split("=");
switch (k.toLowerCase()) {
case "path": c.path = v; break;
case "max-age": c.expires = now + Number(v); break;
case "secure": c.secure = true; break;
case "httponly": c.httpOnly = true; break;
case "samesite": c.sameSite = v; break;
}
}
jar.push(c);
}
// cookieHeader is what the browser attaches to a request: only cookies that match all the rules.
function cookieHeader(now, scheme, host, path, crossSitePost) {
const sent = jar.filter(
(c) =>
host === c.domain && // other sites never see it
path.startsWith(c.path) && // inside its path
now < c.expires && // not expired
!(c.secure && scheme !== "https") && // Secure: never over plain HTTP
!(crossSitePost && c.sameSite !== "None"), // Lax/Strict: not on a POST from another site
);
return sent.length ? sent.map((c) => `${c.name}=${c.value}`).join("; ") : "(none)";
}
// scriptCookies is what JavaScript on a page at `path` can read with document.cookie.
const scriptCookies = (now, path) =>
jar.filter((c) => !c.httpOnly && now < c.expires && path.startsWith(c.path)).map((c) => `${c.name}=${c.value}`).join("; ");
for (const h of [
"session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
"theme=dark; Path=/; Max-Age=31536000",
"cart=7; Path=/cart; Max-Age=600",
"promo=EID; Path=/; Max-Age=60",
]) {
setCookie(h, "shop.com", 0);
console.log("Set-Cookie: " + h);
}
const reqs = [
[10, "https", "shop.com", "/", false, "t=10s GET https://shop.com/"],
[10, "https", "shop.com", "/cart/items", false, "t=10s GET https://shop.com/cart/items"],
[10, "http", "shop.com", "/", false, "t=10s GET http://shop.com/ (plain HTTP)"],
[10, "https", "evil.com", "/", false, "t=10s GET https://evil.com/"],
[10, "https", "shop.com", "/transfer", true, "t=10s POST https://shop.com/transfer from a form on evil.com"],
[120, "https", "shop.com", "/", false, "t=120s GET https://shop.com/"],
[4000, "https", "shop.com", "/", false, "t=4000s GET https://shop.com/"],
];
for (const [now, scheme, host, path, cross, label] of reqs) {
console.log(`${label}\n Cookie: ${cookieHeader(now, scheme, host, path, cross)}`);
}
console.log("document.cookie on https://shop.com/ at t=10s: " + scriptCookies(10, "/"));struct Cookie {
name: String,
value: String,
domain: String,
path: String,
same_site: String,
expires: u32, // time in seconds when it stops being sent
secure: bool,
http_only: bool,
}
// set_cookie parses one Set-Cookie header the server sent from `domain` at time `now`.
fn set_cookie(jar: &mut Vec<Cookie>, header: &str, domain: &str, now: u32) {
let mut parts = header.split("; ");
let (name, value) = parts.next().unwrap().split_once('=').unwrap();
let mut c = Cookie {
name: name.into(),
value: value.into(),
domain: domain.into(),
path: "/".into(),
same_site: "Lax".into(),
expires: 1 << 30,
secure: false,
http_only: false,
};
for attr in parts {
let (k, v) = attr.split_once('=').unwrap_or((attr, ""));
match k.to_lowercase().as_str() {
"path" => c.path = v.into(),
"max-age" => c.expires = now + v.parse::<u32>().unwrap(),
"secure" => c.secure = true,
"httponly" => c.http_only = true,
"samesite" => c.same_site = v.into(),
_ => {}
}
}
jar.push(c);
}
// cookie_header is what the browser attaches to a request: only cookies that match all the rules.
fn cookie_header(jar: &[Cookie], now: u32, scheme: &str, host: &str, path: &str, cross_site_post: bool) -> String {
let sent: Vec<String> = jar
.iter()
.filter(|c| {
host == c.domain // other sites never see it
&& path.starts_with(&c.path) // inside its path
&& now < c.expires // not expired
&& !(c.secure && scheme != "https") // Secure: never over plain HTTP
&& !(cross_site_post && c.same_site != "None") // Lax/Strict: not on a POST from another site
})
.map(|c| format!("{}={}", c.name, c.value))
.collect();
if sent.is_empty() { "(none)".into() } else { sent.join("; ") }
}
// script_cookies is what JavaScript on a page at `path` can read with document.cookie.
fn script_cookies(jar: &[Cookie], now: u32, path: &str) -> String {
let seen: Vec<String> = jar
.iter()
.filter(|c| !c.http_only && now < c.expires && path.starts_with(&c.path))
.map(|c| format!("{}={}", c.name, c.value))
.collect();
seen.join("; ")
}
fn main() {
let mut jar = Vec::new(); // what the browser remembers, in the order it was set
for h in [
"session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
"theme=dark; Path=/; Max-Age=31536000",
"cart=7; Path=/cart; Max-Age=600",
"promo=EID; Path=/; Max-Age=60",
] {
set_cookie(&mut jar, h, "shop.com", 0);
println!("Set-Cookie: {h}");
}
let reqs = [
(10, "https", "shop.com", "/", false, "t=10s GET https://shop.com/"),
(10, "https", "shop.com", "/cart/items", false, "t=10s GET https://shop.com/cart/items"),
(10, "http", "shop.com", "/", false, "t=10s GET http://shop.com/ (plain HTTP)"),
(10, "https", "evil.com", "/", false, "t=10s GET https://evil.com/"),
(10, "https", "shop.com", "/transfer", true, "t=10s POST https://shop.com/transfer from a form on evil.com"),
(120, "https", "shop.com", "/", false, "t=120s GET https://shop.com/"),
(4000, "https", "shop.com", "/", false, "t=4000s GET https://shop.com/"),
];
for (now, scheme, host, path, cross, label) in reqs {
println!("{label}\n Cookie: {}", cookie_header(&jar, now, scheme, host, path, cross));
}
println!("document.cookie on https://shop.com/ at t=10s: {}", script_cookies(&jar, 10, "/"));
}jar = [] # what the browser remembers, in the order it was set
def set_cookie(header, domain, now):
"""Parse one Set-Cookie header the server sent from `domain` at time `now`."""
first, *attrs = header.split("; ")
name, _, value = first.partition("=")
c = {"name": name, "value": value, "domain": domain, "path": "/", "same_site": "Lax",
"expires": 2**30, "secure": False, "http_only": False}
for attr in attrs:
k, _, v = attr.partition("=")
k = k.lower()
if k == "path":
c["path"] = v
elif k == "max-age":
c["expires"] = now + int(v)
elif k == "secure":
c["secure"] = True
elif k == "httponly":
c["http_only"] = True
elif k == "samesite":
c["same_site"] = v
jar.append(c)
def cookie_header(now, scheme, host, path, cross_site_post):
"""What the browser attaches to a request: only cookies that match all the rules."""
sent = [
f"{c['name']}={c['value']}"
for c in jar
if host == c["domain"] # other sites never see it
and path.startswith(c["path"]) # inside its path
and now < c["expires"] # not expired
and not (c["secure"] and scheme != "https") # Secure: never over plain HTTP
and not (cross_site_post and c["same_site"] != "None") # Lax/Strict: not on a POST from another site
]
return "; ".join(sent) if sent else "(none)"
def script_cookies(now, path):
"""What JavaScript on a page at `path` can read with document.cookie."""
return "; ".join(
f"{c['name']}={c['value']}" for c in jar if not c["http_only"] and now < c["expires"] and path.startswith(c["path"])
)
for h in [
"session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
"theme=dark; Path=/; Max-Age=31536000",
"cart=7; Path=/cart; Max-Age=600",
"promo=EID; Path=/; Max-Age=60",
]:
set_cookie(h, "shop.com", 0)
print("Set-Cookie: " + h)
reqs = [
(10, "https", "shop.com", "/", False, "t=10s GET https://shop.com/"),
(10, "https", "shop.com", "/cart/items", False, "t=10s GET https://shop.com/cart/items"),
(10, "http", "shop.com", "/", False, "t=10s GET http://shop.com/ (plain HTTP)"),
(10, "https", "evil.com", "/", False, "t=10s GET https://evil.com/"),
(10, "https", "shop.com", "/transfer", True, "t=10s POST https://shop.com/transfer from a form on evil.com"),
(120, "https", "shop.com", "/", False, "t=120s GET https://shop.com/"),
(4000, "https", "shop.com", "/", False, "t=4000s GET https://shop.com/"),
]
for now, scheme, host, path, cross, label in reqs:
print(f"{label}\n Cookie: {cookie_header(now, scheme, host, path, cross)}")
print("document.cookie on https://shop.com/ at t=10s: " + script_cookies(10, "/"))import java.util.*;
public class Main {
static class Cookie {
String name, value, domain, path = "/", sameSite = "Lax";
int expires = 1 << 30; // time in seconds when it stops being sent
boolean secure, httpOnly;
}
static List<Cookie> jar = new ArrayList<>(); // what the browser remembers, in the order it was set
// setCookie parses one Set-Cookie header the server sent from `domain` at time `now`.
static void setCookie(String header, String domain, int now) {
String[] parts = header.split("; ");
Cookie c = new Cookie();
int eq = parts[0].indexOf('=');
c.name = parts[0].substring(0, eq);
c.value = parts[0].substring(eq + 1);
c.domain = domain;
for (int i = 1; i < parts.length; i++) {
String[] kv = parts[i].split("=", 2);
String v = kv.length > 1 ? kv[1] : "";
switch (kv[0].toLowerCase()) {
case "path" -> c.path = v;
case "max-age" -> c.expires = now + Integer.parseInt(v);
case "secure" -> c.secure = true;
case "httponly" -> c.httpOnly = true;
case "samesite" -> c.sameSite = v;
default -> {}
}
}
jar.add(c);
}
// cookieHeader is what the browser attaches to a request: only cookies that match all the rules.
static String cookieHeader(int now, String scheme, String host, String path, boolean crossSitePost) {
StringJoiner sent = new StringJoiner("; ");
for (Cookie c : jar) {
if (!host.equals(c.domain)) continue; // other sites never see it
if (!path.startsWith(c.path)) continue; // outside its path
if (now >= c.expires) continue; // expired
if (c.secure && !scheme.equals("https")) continue; // Secure: never over plain HTTP
if (crossSitePost && !c.sameSite.equals("None")) continue; // Lax/Strict: not on a POST from another site
sent.add(c.name + "=" + c.value);
}
return sent.length() == 0 ? "(none)" : sent.toString();
}
// scriptCookies is what JavaScript on a page at `path` can read with document.cookie.
static String scriptCookies(int now, String path) {
StringJoiner seen = new StringJoiner("; ");
for (Cookie c : jar) if (!c.httpOnly && now < c.expires && path.startsWith(c.path)) seen.add(c.name + "=" + c.value);
return seen.toString();
}
public static void main(String[] args) {
for (String h : new String[] {
"session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
"theme=dark; Path=/; Max-Age=31536000",
"cart=7; Path=/cart; Max-Age=600",
"promo=EID; Path=/; Max-Age=60",
}) {
setCookie(h, "shop.com", 0);
System.out.println("Set-Cookie: " + h);
}
Object[][] reqs = {
{10, "https", "shop.com", "/", false, "t=10s GET https://shop.com/"},
{10, "https", "shop.com", "/cart/items", false, "t=10s GET https://shop.com/cart/items"},
{10, "http", "shop.com", "/", false, "t=10s GET http://shop.com/ (plain HTTP)"},
{10, "https", "evil.com", "/", false, "t=10s GET https://evil.com/"},
{10, "https", "shop.com", "/transfer", true, "t=10s POST https://shop.com/transfer from a form on evil.com"},
{120, "https", "shop.com", "/", false, "t=120s GET https://shop.com/"},
{4000, "https", "shop.com", "/", false, "t=4000s GET https://shop.com/"},
};
for (Object[] r : reqs) {
System.out.println(r[5] + "\n Cookie: " + cookieHeader((Integer) r[0], (String) r[1], (String) r[2], (String) r[3], (Boolean) r[4]));
}
System.out.println("document.cookie on https://shop.com/ at t=10s: " + scriptCookies(10, "/"));
}
}Output (পাঁচটা language এই একই):
Set-Cookie: session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=31536000
Set-Cookie: cart=7; Path=/cart; Max-Age=600
Set-Cookie: promo=EID; Path=/; Max-Age=60
t=10s GET https://shop.com/
Cookie: session=abc123; theme=dark; promo=EID
t=10s GET https://shop.com/cart/items
Cookie: session=abc123; theme=dark; cart=7; promo=EID
t=10s GET http://shop.com/ (plain HTTP)
Cookie: theme=dark; promo=EID
t=10s GET https://evil.com/
Cookie: (none)
t=10s POST https://shop.com/transfer from a form on evil.com
Cookie: (none)
t=120s GET https://shop.com/
Cookie: session=abc123; theme=dark
t=4000s GET https://shop.com/
Cookie: theme=dark
document.cookie on https://shop.com/ at t=10s: theme=dark; promo=EID
Output টা পড়ি:
/বনাম/cart/items:cartএরPath=/cart, তাই এটা শুধু cart এর URL এর সাথে যায়। বাকিরা site এর সবখানে যায়।- Plain HTTP:
sessionহলোSecure, তাই আটকে রাখা হয়েছে। Plain HTTP request কেউ আড়ি পেতে দেখলে শুধুthemeআরpromoদেখবে। - evil.com: কিছুই না। Cookie কখনো অন্য site এ যায় না।
- Cross-site POST: কিছুই না,
themeও না। এখানের প্রতিটা cookieLax(স্পষ্টভাবে, বা modern default এ), তাই অন্য site এর form এগুলো নিয়ে যেতে পারে না। - t=120s:
promoএরMax-Age=60ছিল, তাই নেই। t=4000s:sessionএক ঘণ্টা পর মেয়াদ শেষ, আরcart10 মিনিট পর। থাকে শুধু এক বছরেরtheme। - document.cookie: JavaScript দেখে
themeআরpromo, কিন্তু কখনোsessionনা (HttpOnly), আরcartও না (এই page এর জন্য ভুল path)।
Real server, real header:
$ curl -s -D - -o /dev/null https://github.com/ | tr -d '\r' | grep -i "^set-cookie" | sed -E 's/^(set-cookie: _gh_sess=)[^;]*/\1.../'
set-cookie: _gh_sess=...; path=/; HttpOnly; secure; SameSite=Lax
set-cookie: _octo=GH1.1.1051490817.1795139962; expires=Sat, 20 Nov 2027 01:59:22 GMT; domain=.github.com; path=/; secure; SameSite=Lax
set-cookie: logged_in=no; expires=Sat, 20 Nov 2027 01:59:22 GMT; domain=.github.com; path=/; HttpOnly; secure; SameSite=Lax
$ curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' https://example.com/ | tr -d '\r' | grep -iE "^(content-encoding|content-type|vary)"
content-type: text/html; charset=utf-8
content-encoding: gzip
_gh_sessএর কোনোexpiresনেই: একটা session cookie, browser বন্ধ হলেই গায়েব। এটাHttpOnly,secureআরSameSite=Lax, ঠিক এই lesson এর flag গুলো (লম্বা value টা এখানেsedদিয়ে লুকানো)।domain=.github.comদেওয়ায়_octoআরlogged_insubdomain এও যায় (যেমনgist.github.com)।- Content negotiation: request বলেছে "আমি gzip নিতে পারি", আর server উত্তর দিয়েছে
content-encoding: gzipদিয়ে। তাই body র byte গুলো compress করা, client কে unzip করতে হবে।
Real engineering
- Session cookie:
Secure; HttpOnly; SameSite=Lax(admin panel এর জন্যStrict), একটা লম্বা random value (128 bit বা বেশি), আর server এর দিকে একটা মেয়াদ। Session fixation ঠেকাতে login এর সময় session ID বদলে দাও। - Cookie ছোট রাখো। প্রতিটা request এর সাথে যায়, image আর API call সহ। বড় cookie প্রতিটা request ধীর করে, header limit (431) ও ছুঁয়ে ফেলতে পারে।
- ঠিকভাবে logout করো। Server এ session মুছে দাও আর cookie ও মুছে দাও (
Max-Age=0)। শুধু cookie মুছলে চুরি হওয়া copy তখনো valid থাকে। - Cookie বনাম
Authorizationheader। Browser cookie নিজে থেকেই পাঠায় (সুবিধাজনক, কিন্তু SameSite ছাড়া CSRF এর ঝুঁকিতে)। Mobile app আর service থেকে service call সাধারণত স্পষ্ট করেAuthorization: Bearer <token>পাঠায়। Module 9 এ গভীরে তুলনা করবো। - সবসময়
Content-Typeদাও, আর text compress করো। JSON আর HTML এর জন্য gzip বা brotli। Image আর video already compress করা, ওগুলোতে compression বাদ দাও। - Cookie consent একটা আইনি বিষয়, শুধু technical না। অনেক দেশে tracking cookie র জন্য user এর সম্মতি লাগে। একদম দরকারি cookie (session, CSRF) সাধারণত লাগে না।
When it breaks
একটা failure বাছো
cookie set, but never sent back
Think before you read on
একটা cookie site এর প্রতিটা request এর সাথে নিজে থেকেই যায়, এমনকি request টা অন্য কোনো website শুরু করলেও (যেমন একটা forum এ <img src="https://shop.com/api/cart/clear">)। SameSite আসার আগে এটা কোন attack সম্ভব করতো, আর আজ এর সুরক্ষা কী?
Reveal
Cross-site request forgery (CSRF): অন্য একটা site তোমার browser কে দিয়ে shop.com এ একটা request পাঠায়, browser তোমার session cookie জুড়ে দেয়, আর shop.com ভাবে কাজটা তুমিই করেছো। আজকের সুরক্ষা: session cookie তে SameSite=Lax বা Strict (cross-site POST আর subresource request আর এগুলো নিয়ে যায় না), GET এ কখনো state না বদলানো (lesson 4, তাই <img> এর কৌশল কিছুই করে না), form এ CSRF token (একটা গোপন value যেটা অন্য site পড়তে পারে না), আর state বদলানো request এ Origin header check করা।
Check yourself
1. Set-Cookie আর Cookie এর পার্থক্য কী?
Answer
Set-Cookie একটা response header: server browser কে attribute সহ একটা cookie রাখতে বলে। Cookie একটা request header: browser match করা সব cookie এর নাম আর value ফেরত পাঠায়, attribute ছাড়া।
2. HttpOnly, Secure আর SameSite=Lax প্রত্যেকটা কীসের বিরুদ্ধে রক্ষা করে?
Answer
HttpOnly: script (XSS সহ) cookie পড়তে পারে না। Secure: cookie কখনো plain HTTP দিয়ে যায় না, যেখানে আড়ি পাতা যেতো। SameSite=Lax: অন্য site cross-site POST (আর বেশিরভাগ subresource request) দিয়ে এটা পাঠাতে পারে না, যেটা বেশিরভাগ CSRF আটকায়।
3. Cookie তে user এর data না রেখে session ID কেন রাখা উচিত?
Answer
Cookie client এর হাতে, সে বদলাতে পারে। আর প্রতিটা byte প্রতিটা request এ যায়। আন্দাজ করা যায় না এমন একটা ID কিছুই ফাঁস করে না, আর edit করে কাজের কিছু বানানোও যায় না। আসল data থাকে server এ।
4. Vary: Accept-Encoding একটা cache কে কী বলে?
Answer
যে response টা request এর Accept-Encoding header এর উপর নির্ভর করে। তাই cache কে আলাদা আলাদা version রাখতে আর দিতে হবে (যেমন gzip আর uncompressed), সবাইকে একই byte দেওয়া যাবে না।
Your challenge: SameSite=Strict and top-level links
Jar এর rule বাড়াও:
- Cross-site request এর ধরনের জন্য একটা parameter যোগ করো:
"none"(একই site),"link"(একটা top-level GET navigation, যেমন অন্য site থেকে একটা link এ click), বা"post"(একটা cross-site form POST)। - Rule:
Strictcookie যায় শুধু একই site এর request এ।Laxcookie cross-sitelinknavigation এও যায়, কিন্তুpostএ না।Nonecookie (যেটাSecureহতেই হবে) HTTPS এর সবকিছুতে যায়। - পঞ্চম একটা cookie যোগ করো,
admin=1; Path=/; Secure; HttpOnly; SameSite=Strict, আর evil.com থেকেhttps://shop.com/এ একটা link click test করো।
Run করার আগে predict করো, link click এর সাথে কোন cookie গুলো আসবে।
তুমি সফল যখন link click নিয়ে আসে session, theme আর promo, কিন্তু admin না, cross-site POST তখনো কিছুই নিয়ে আসে না, আর একই site এর request এ admin ও যায়।
The mental model
Header হলো প্রতিটা HTTP message এর label: body কী (Content-Type), কীভাবে প্যাক করা (Content-Encoding), client কী নিতে পারে, আর caching এর মতো নির্দেশ। Cookie একটা stateless protocol এ memory যোগ করে: server একবার Set-Cookie পাঠায়, আর browser match করা প্রতিটা request এ value টা দেখায়, site, path আর মেয়াদ অনুযায়ী। এতে শুধু একটা random ID রাখো, data রাখো server এ, আর Secure, HttpOnly আর SameSite দিয়ে শক্ত করে আটকাও।
Station stamp
Chapter শেষ করো
পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +10 XP পেতে।
Pro নিয়ে XP পাও →