Thuta Learning
API Tutorial
AdvancedWeb Developmentအလယ်အလတ်

CORS & HTTPS

API Tutorialသင်ခန်းစာ 2635 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Origin ဆိုတာ ဘာလဲ၊ CORS ကို server မဟုတ်ဘဲ browser က enforce လုပ်တယ်ဆိုတာ ရှင်းပြနိုင်ဖို့
  • Request တစ်ခုက simple လား preflight လိုလား ခွဲခြားပြီး preflight request/response ကို ဖတ်နိုင်ဖို့
  • Allowlist ကို အခြေခံတဲ့ Access-Control-Allow-Origin echo logic နဲ့ Vary: Origin ကို မှန်မှန်ကန်ကန် ရေးနိုင်ဖို့
  • Credentials နဲ့ wildcard (*) မရောရဘူးဆိုတာနဲ့ ဘာကြောင့် Origin ကို ဘာမှ မစစ်ဘဲ reflect မလုပ်ရလဲ ရှင်းပြနိုင်ဖို့
  • CORS က authentication မဟုတ်ဘူးဆိုတာနဲ့ HTTPS က ဘာတွေ ထပ်ပေးလဲ ခွဲခြားနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Browser ကို သင့် web page ရှိတဲ့ အဆောက်အအုံရဲ့ လုံခြုံရေးအစောင့်တစ်ယောက်လို မြင်ကြည့်ပါ။ Page ထဲက JavaScript က တခြားအဆောက်အအုံ (တခြား website ရဲ့ API) ကို ဆက်သွယ်ချင်ရင် အစောင့်က အဲဒီအဆောက်အအုံကို "ငါ့အဆောက်အအုံက လာတဲ့ ဧည့်သည်ကို လက်ခံလား" လို့ မေးပါတယ်။ ဟုတ်တယ်လို့ header တွေနဲ့ ဖြေမှ အစောင့်က အဖြေကို JavaScript ကို ဖတ်ခွင့်ပေးပါတယ်။

အစောင့်က အသုံးပြုသူ (browser ကို သုံးနေတဲ့ လူ) ကို ကာကွယ်ဖို့ ရှိတာပါ။ curl၊ Postman၊ Node ဒါမှမဟုတ် တခြား server တွေမှာတော့ အစောင့်မရှိလို့ ဒီစည်းမျဉ်းက သက်ရောက်ခြင်း မရှိပါဘူး။ ဒါကြောင့် "curl နဲ့ ရတယ်၊ browser မှာ မရဘူး" ဆိုတာ CORS ပြဿနာရဲ့ အသိသာဆုံး လက္ခဏာပါ။

Problem → Why → Solution

ပြဿနာ: curl မှာ ရတာ browser မှာ ဘာကြောင့် မရတာလဲ

Frontend developer တစ်ယောက်က https://app.example.com မှာ တင်မယ့် app ကို ရေးပြီး https://api.example.com ကို ခေါ်ပါတယ်။ curl နဲ့ Postman မှာ ကောင်းကောင်းအလုပ်လုပ်ပေမယ့် browser console မှာတော့ CORS policy ကြောင့် request ကို block လုပ်လိုက်တယ်ဆိုတဲ့ အနီရောင် error ပေါ်ပါတယ်။ Network tab ကိုကြည့်ရင် ကိုယ်မရေးထားတဲ့ OPTIONS request တစ်ခုလည်း တွေ့ရပါတယ်။

အဲဒီနောက် ကြိုးစားတဲ့ "ဖြေရှင်းနည်း" တွေက အများအားဖြင့် မှားပါတယ်။ mode: "no-cors" ထည့်တာက error ကို ပျောက်စေပေမယ့် response ကို opaque ဖြစ်စေလို့ data ကို ဖတ်မရတော့ပါဘူး။ Client ဘက်က request ထဲမှာ Access-Control-Allow-Origin ထည့်တာကလည်း ဘာမှ မထိရောက်ပါဘူး၊ အဲဒါက server ရဲ့ response header ဖြစ်လို့ပါ။

app.js
// Running in the browser, on the page https://app.example.com
const res = await fetch("https://api.example.com/v1/items", {
  mode: "no-cors", // hides the error, and also hides the data
  headers: {
    "Access-Control-Allow-Origin": "*", // a RESPONSE header: meaningless on a request
    Authorization: "Bearer demo-token",
  },
});
console.log(res.type, res.status); // "opaque" 0 -> the body is unreadable

ဘာကြောင့် client ဘက်က ပြင်လို့ မရတာလဲ

ခွင့်ပြုချက်ပေးရမယ့်သူက ဒေတာကို ပိုင်ဆိုင်တဲ့ server ဖြစ်ပါတယ်၊ ဒေတာကို တောင်းတဲ့ page မဟုတ်ပါဘူး။ Page က "ငါ့ကို ခွင့်ပြုထားတယ်" လို့ ကိုယ့်ဘာသာ ကြေညာလို့ မရပါဘူး။ ဖြေရှင်းနည်းက API server ကို မှန်ကန်တဲ့ Access-Control-* response header တွေ ပို့ခိုင်းတာ၊ ဒါမှမဟုတ် ကိုယ့် backend ကနေ ဖြတ်ခေါ်တာ (same-origin proxy) ပါ။

Core concept: Origin၊ browser enforcement နဲ့ preflight

Origin ဆိုတာ scheme + host + port ပေါင်းထားတာပါ။ https://app.example.com နဲ့ https://api.example.com က host မတူလို့ origin မတူပါဘူး၊ http:// နဲ့ https:// ကွာရင်လည်း မတူ၊ port မတူရင်လည်း မတူပါဘူး။ Browser ရဲ့ same-origin policy အရ page တစ်ခုရဲ့ JavaScript က တခြား origin ကို request ပို့လို့ရပေမယ့် server က ခွင့်ပြုကြောင်း မပြောမချင်း response ကို ဖတ်လို့ မရပါဘူး။ CORS (Cross-Origin Resource Sharing) ဆိုတာ အဲဒီခွင့်ပြုချက်ကို response header တွေနဲ့ ပေးတဲ့ protocol ပါ။

ဒီစစ်ဆေးမှုကို browser က လုပ်တာပါ။ Browser က request မှာ Origin header ကို ထည့်ပေးပြီး server က ပြန်လာတဲ့ response header တွေနဲ့ ဆုံးဖြတ်ပါတယ်၊ အဲဒီနောက် browser က JavaScript ကို response ပေးမပေး ဆုံးဖြတ်ပါတယ်။ ဒါကြောင့် server ကတော့ request ကို လက်ခံပြီး အလုပ်လုပ်ပြီးသား ဖြစ်နေနိုင်ပါတယ်၊ CORS က response ကို ဖတ်တာကိုပဲ တားတာပါ။ ဒါကြောင့် CORS က authentication မဟုတ်ပါဘူး၊ သင့် API ကို curl ကနေ ဘယ်သူမဆို ခေါ်လို့ ရတာမို့ ကိုယ့်ကိုယ်ကို ကာကွယ်ဖို့ token ဒါမှမဟုတ် session စစ်ဆေးမှု ဆက်လိုပါတယ်။

Request အားလုံးက preflight မလိုပါဘူး။ "Simple" request (GET, HEAD, POST ဖြစ်ပြီး header တွေက Accept လို safelisted ဖြစ်၊ Content-Type က form-urlencoded, multipart/form-data, text/plain ထဲက တစ်ခု) ကိုတော့ browser က တိုက်ရိုက်ပို့ပြီး response header တွေကို နောက်မှ စစ်ပါတယ်။ ကျန်တာအကုန် preflight လိုပါတယ် — PUT/PATCH/DELETE၊ Authorization header၊ custom header၊ Content-Type: application/json တို့ပါ။ Preflight ဆိုတာ browser က အရင်ပို့တဲ့ OPTIONS request ဖြစ်ပြီး Origin, Access-Control-Request-Method, Access-Control-Request-Headers ပါပါတယ်။ Server က 2xx နဲ့ ကိုက်ညီတဲ့ Allow header တွေ ပြန်ပေးမှ အစစ်အမှန် request ကို ပို့ပါတယ်။

Response ဘက်မှာ စည်းမျဉ်း အနည်းငယ် ရှိပါတယ်။ Access-Control-Allow-Origin မှာ origin တစ်ခုတည်း၊ * ဒါမှမဟုတ် null ပဲ ထည့်လို့ရပြီး origin စာရင်း ထည့်လို့ မရပါဘူး။ Cookie ဒါမှမဟုတ် Authorization လို credentials ပါရင် * က မရတော့ပါဘူး — origin အတိအကျကို echo လုပ်ပြီး Access-Control-Allow-Credentials: true ထည့်ရပါမယ်။ Origin ကို allowlist နဲ့ တိုက်စစ်ပြီးမှ echo လုပ်ပါ၊ Vary: Origin ကိုပါ ထည့်ပါ၊ မဟုတ်ရင် shared cache က origin တစ်ခုအတွက် response ကို နောက်တစ်ခုကို ပေးမိနိုင်ပါတယ်။ Default အားဖြင့် JavaScript က response header အနည်းငယ်ပဲ မြင်ရလို့ Retry-After လို header တွေကို Access-Control-Expose-Headers နဲ့ ဖော်ပြပေးရပါတယ်။

မှတ်ထားရမယ့် ပုံစံ
  1. Page က request + Origin ပို့
  2. Simple မဟုတ်ရင် OPTIONS preflight
  3. Server က Allow-* header ဖြေ
  4. Browser က response ကို ပေး/ဝှက်

Server က ခွင့်ပြုချက်ပေးပြီး browser က အဲဒီခွင့်ပြုချက်ကို enforce လုပ်ပါတယ်။

အထွေထွေ ပုံစံ: preflight နဲ့ အဖြေ

text
# 1. Preflight, sent by the browser only for non-simple requests
OPTIONS /resource
Origin: <page origin>
Access-Control-Request-Method: <METHOD>
Access-Control-Request-Headers: <header, header>

# 2. Server answers 2xx, then the browser sends the real request
Access-Control-Allow-Origin: <that exact origin>
Access-Control-Allow-Methods: <METHOD, METHOD>
Access-Control-Allow-Headers: <header, header>
Vary: Origin

အပေါ်ပိုင်းက browser ပို့တာ၊ အောက်ပိုင်းက server ဖြေတာပါ။ Allow-Origin က ဝင်လာတဲ့ Origin နဲ့ တိတိကျကျ တူရမယ်၊ Allow-Methods နဲ့ Allow-Headers က preflight မှာ တောင်းထားတာတွေကို ဖုံးရမယ်၊ Vary: Origin ကတော့ cache အတွက်ပါ။

Example: allowlist နဲ့ preflight ကို server မှာ ကြည့်ခြင်း

Node ရဲ့ fetch ကို CORS က တားမှာ မဟုတ်လို့ ဒီမှာ browser block ကို ပြလို့ မရပါဘူး၊ ဒါပေမယ့် server ရဲ့ ဘက်ကို အပြည့်အစုံ ကြည့်လို့ရပါတယ်။ Node ရဲ့ fetch မှာ Origin header ကို ကိုယ်တိုင် ထည့်ပေးနိုင်လို့ browser ပို့မယ့် request တွေကို ဟန်ဆောင်ပို့ကာ server က ဘာ header တွေ ပြန်လဲဆိုတာ ဖတ်ပါမယ်။ Server က origin နှစ်ခုကို allowlist ထားပါတယ်။

ရလဒ်မှာ အရေးကြီးတာ လေးခု ကြည့်ပါ။ Preflight ကို 204 နဲ့ Allow-* header အပြည့်အစုံ ဖြေတယ်။ Allowlist ထဲက origin က echo ရတယ်။ evil.example ကတော့ Allow-Origin မရပေမယ့် server ရဲ့ handler က ဆက် run နေတယ် — browser ကသာ အဲဒီ response ကို JavaScript ဆီ မပေးတာပါ။ Origin မပါတဲ့ request (curl ပုံစံ) ကို CORS က လုံးဝ မသက်ဆိုင်ပါဘူး။

cors-server.mjs
import http from "node:http";

const ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);
let handled = 0;

function corsHeaders(origin) {
  if (!origin || !ALLOWED.has(origin)) return {};
  return { "Access-Control-Allow-Origin": origin };
}

const server = http.createServer((req, res) => {
  const cors = { ...corsHeaders(req.headers.origin), Vary: "Origin" };
  const wantsMethod = req.headers["access-control-request-method"];
  const isPreflight = req.method === "OPTIONS" && wantsMethod;

  if (isPreflight) {
    if (cors["Access-Control-Allow-Origin"]) {
      cors["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE";
      cors["Access-Control-Allow-Headers"] = "Authorization, Content-Type";
      cors["Access-Control-Max-Age"] = "600";
    }
    res.writeHead(204, cors).end();
    return;
  }

  handled += 1; // the handler runs no matter which origin asked
  res.writeHead(200, { ...cors, "Content-Type": "application/json" });
  res.end(JSON.stringify({ items: [] }));
});

await new Promise((resolve) => server.listen(0, resolve));
const url = "http://127.0.0.1:" + server.address().port + "/v1/items";
const APP = "https://app.example.com";
const EVIL = "https://evil.example";

async function show(label, options, names) {
  const res = await fetch(url, options);
  console.log(label);
  console.log("  status:", res.status);
  for (const name of names) {
    console.log("  " + name + ": " + (res.headers.get(name) ?? "(none)"));
  }
}

function postFrom(origin) {
  const headers = { "Content-Type": "application/json" };
  if (origin) headers.Origin = origin;
  return { method: "POST", headers, body: "{}" };
}

const preflight = {
  method: "OPTIONS",
  headers: {
    Origin: APP,
    "Access-Control-Request-Method": "POST",
    "Access-Control-Request-Headers": "authorization, content-type",
  },
};
const everything = [
  "access-control-allow-origin",
  "access-control-allow-methods",
  "access-control-allow-headers",
  "access-control-max-age",
  "vary",
];
const basic = ["access-control-allow-origin", "vary"];

await show("preflight from " + APP, preflight, everything);
await show("POST from " + APP, postFrom(APP), basic);
await show("POST from " + EVIL, postFrom(EVIL), basic);
await show("POST with no Origin header", postFrom(), basic);
console.log("handler ran", handled, "times");
server.close();

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Allowlistconst ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);

    ခွင့်ပြုမယ့် origin တွေကို exact string အဖြစ် Set ထဲ ထည့်ထားပါတယ်။ Wildcard ဒါမှမဟုတ် "endsWith('example.com')" လို တိုက်စစ်ပုံမျိုး မသုံးပါနဲ့၊ evil-example.com လို domain တွေ ပါလာနိုင်လို့ပါ။

  2. Unknown originif (!origin || !ALLOWED.has(origin)) return {};

    Origin မပါတာ ဒါမှမဟုတ် allowlist မှာ မရှိတာဆိုရင် CORS header လုံးဝ မပြန်ပါဘူး။ Browser က Allow-Origin မတွေ့လို့ JavaScript ကို response ပေးမှာ မဟုတ်ပါဘူး။

  3. Echo, not wildcardreturn { "Access-Control-Allow-Origin": origin };

    တောင်းလာတဲ့ origin ကိုပဲ အတိအကျ ပြန်ပေးပါတယ်။ Allowlist စစ်ပြီးမှ echo လုပ်ထားလို့ credentials ပါတဲ့ request တွေအတွက်လည်း ဆက်သုံးလို့ရပါတယ်။

  4. Detect a preflightconst isPreflight = req.method === "OPTIONS" && wantsMethod;

    OPTIONS request အားလုံးက preflight မဟုတ်ပါဘူး။ Access-Control-Request-Method header ပါမှ preflight လို့ သတ်မှတ်ပါတယ်။

  5. Cache the answercors["Access-Control-Max-Age"] = "600";

    Browser က preflight အဖြေကို စက္ကန့် 600 အတွင်း မှတ်ထားလို့ request တိုင်းမှာ OPTIONS ထပ်မပို့ရပါဘူး။ Browser တွေက ကိုယ်ပိုင် အမြင့်ဆုံးကန့်သတ်ချက် ရှိတတ်လို့ ရက်ချီ ထားလို့ မရပါဘူး။

  6. Handler still runshandled += 1;

    evil.example ကလာတဲ့ request အတွက်လည်း ဒီ line က run ပါတယ်။ ဒါက CORS က server ကို ကာကွယ်ပေးတာ မဟုတ်ဘူးဆိုတာကို သက်သေပြတာပါ။

You should see
preflight from https://app.example.com
  status: 204
  access-control-allow-origin: https://app.example.com
  access-control-allow-methods: GET, POST, PUT, DELETE
  access-control-allow-headers: Authorization, Content-Type
  access-control-max-age: 600
  vary: Origin
POST from https://app.example.com
  status: 200
  access-control-allow-origin: https://app.example.com
  vary: Origin
POST from https://evil.example
  status: 200
  access-control-allow-origin: (none)
  vary: Origin
POST with no Origin header
  status: 200
  access-control-allow-origin: (none)
  vary: Origin
handler ran 3 times

Simple request နဲ့ preflight ကို ခွဲခြားခြင်း

Developer တွေ အများဆုံး အံ့ဩရတာက ရိုးရိုး JSON POST တစ်ခုက preflight ဖြစ်သွားတာပါ။ Content-Type: application/json က safelisted မဟုတ်လို့ပါ။ အောက်က function က Fetch standard ရဲ့ စည်းမျဉ်းကို ရိုးရှင်းအောင် ကူးထားတာပါ (header ကန့်သတ်ချက်အချို့ကို ချန်ထားတယ်) — တကယ့်ကို ဆုံးဖြတ်တာ browser ပါ။

needs-preflight.mjs
const SIMPLE_METHODS = new Set(["GET", "HEAD", "POST"]);
const SAFE_HEADERS = new Set([
  "accept",
  "accept-language",
  "content-language",
  "content-type",
]);
const SAFE_TYPES = new Set([
  "application/x-www-form-urlencoded",
  "multipart/form-data",
  "text/plain",
]);

function needsPreflight(method, headers = {}) {
  if (!SIMPLE_METHODS.has(method)) return true;
  for (const [name, value] of Object.entries(headers)) {
    const lower = name.toLowerCase();
    if (!SAFE_HEADERS.has(lower)) return true;
    if (lower === "content-type") {
      const type = value.split(";")[0].trim();
      if (!SAFE_TYPES.has(type)) return true;
    }
  }
  return false;
}

const cases = [
  ["GET", {}],
  ["POST", { "Content-Type": "application/x-www-form-urlencoded" }],
  ["POST", { "Content-Type": "application/json" }],
  ["GET", { Authorization: "Bearer token" }],
  ["PUT", {}],
  ["GET", { "X-Request-Id": "abc" }],
];
for (const [method, headers] of cases) {
  const pairs = Object.entries(headers).map(([k, v]) => k + ": " + v);
  const shown = pairs.join(", ") || "(no headers)";
  const verdict = needsPreflight(method, headers) ? "preflight" : "simple";
  console.log(method.padEnd(5) + shown.padEnd(48) + verdict);
}
text
GET  (no headers)                                    simple
POST Content-Type: application/x-www-form-urlencoded simple
POST Content-Type: application/json                  preflight
GET  Authorization: Bearer token                     preflight
PUT  (no headers)                                    preflight
GET  X-Request-Id: abc                               preflight

curl နဲ့ preflight ကို ကိုယ်တိုင် စမ်းကြည့်လို့ရပါတယ်။ Browser က ပို့မယ့် OPTIONS request ကို ဟန်ဆောင်ပို့ပြီး server ရဲ့ အဖြေကို ဖတ်တာပါ။ ဒါက server ကို စစ်ဖို့ ကောင်းတဲ့နည်းပဲ ဖြစ်ပေမယ့် browser ပုံစံနဲ့ တူတဲ့ block ကိုတော့ မပြနိုင်ပါဘူး၊ အဲဒါကို browser ထဲမှာ ကိုယ်တိုင်ကြည့်ရပါမယ်။

bash
curl -i -X OPTIONS https://api.example.com/v1/items \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: authorization, content-type"
text
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600
Vary: Origin

Credentials နဲ့ wildcard: reflect မလုပ်ရတဲ့ အကြောင်း

Cookie ပါတဲ့ request တွေက သုံးစွဲသူရဲ့ login session ကို သုံးနေတာမို့ အန္တရာယ်ပိုများပါတယ်။ ဒါကြောင့် browser က credentialed request မှာ Access-Control-Allow-Origin: * ကို လက်မခံပါဘူး။ "ဒါဆို ဝင်လာတဲ့ Origin ကို ဘာမှမစစ်ဘဲ ပြန် echo လုပ်ပစ်မယ်" ဆိုတဲ့ shortcut က wildcard ရဲ့ ကာကွယ်မှုကို ကျော်သွားတာပါ — ဘယ် website မဆို ဝင်ကြည့်ထားတဲ့ သုံးစွဲသူရဲ့ session နဲ့ သင့် API ကို ခေါ်ပြီး response ကို ဖတ်နိုင်သွားပါတယ်။

reflect-vs-allowlist.mjs
const ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);
const ACAO = "Access-Control-Allow-Origin";
const ACAC = "Access-Control-Allow-Credentials";

// Dangerous: echoes whatever Origin it is given, and allows cookies.
function reflectEverything(origin) {
  return { [ACAO]: origin, [ACAC]: "true" };
}

// Safe: echoes the origin only when it is on the allowlist.
function allowlisted(origin) {
  if (!ALLOWED.has(origin)) return {};
  return { [ACAO]: origin, [ACAC]: "true", Vary: "Origin" };
}

function describe(headers) {
  if (!headers[ACAO]) return "(no CORS headers)";
  return "allow-origin=" + headers[ACAO] + " credentials=" + headers[ACAC];
}

for (const origin of ["https://app.example.com", "https://evil.example"]) {
  console.log(origin);
  console.log("  reflect-everything:", describe(reflectEverything(origin)));
  console.log("  allowlist:         ", describe(allowlisted(origin)));
}
text
https://app.example.com
  reflect-everything: allow-origin=https://app.example.com credentials=true
  allowlist:          allow-origin=https://app.example.com credentials=true
https://evil.example
  reflect-everything: allow-origin=https://evil.example credentials=true
  allowlist:          (no CORS headers)

Header wildcard ရဲ့ ကန့်သတ်ချက်

Access-Control-Allow-Headers: * လို wildcard ကိုတောင် Authorization header ကို မဖုံးပါဘူး၊ Authorization ကို နာမည်နဲ့ ထင်ရှားစွာ စာရင်းပေးရပါမယ်။ Credentials ပါတဲ့ request တွေမှာလည်း wildcard က ထူးဆန်းတဲ့ literal တန်ဖိုးအဖြစ်ပဲ ဆက်ဆံခံရလို့ header နာမည်တွေကို တိတိကျကျ ရေးပါ။

Browser ထဲမှာ CORS error ကို ဖတ်နည်း

Console message ကို ဂရုတစိုက်ဖတ်ပါ၊ ဘာ header မရှိလို့ block ခံရတာလဲဆိုတာ အများအားဖြင့် ပြောပြပါတယ်။ (ဘယ် browser ရဲ့ စကားလုံးက ကွာနိုင်လို့ ကိုယ့် browser မှာ ဖတ်ပါ။) Network tab မှာ OPTIONS request ကို ရှာပြီး status နဲ့ response header တွေကို ကြည့်ပါ၊ Preflight က 401 ဒါမှမဟုတ် 404 ပြန်နေရင် CORS header မဟုတ်ဘဲ အဲဒီ route ကိုက ပြဿနာပါ။

ပိုရှုပ်တာက server error တွေပါ။ API က 500 ဒါမှမဟုတ် 401 ပြန်ပြီး အဲဒီ response မှာ CORS header မပါရင် browser က JavaScript ကို တကယ့် status နဲ့ body ကို မပေးဘဲ network-style failure တစ်ခုပဲ ပြပါတယ်။ ဒါကြောင့် "CORS error" အဖြစ် မြင်ရပေမယ့် အရင်းခံက server ရဲ့ တခြား bug ဖြစ်နိုင်ပါတယ်။ Error response တွေမှာပါ CORS header ထည့်ပေးတာ အကောင်းဆုံးပါ။

text
HTTP/1.1 429 Too Many Requests
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Expose-Headers: Retry-After, X-RateLimit-Remaining
Vary: Origin
Retry-After: 30
X-RateLimit-Remaining: 0

အပေါ်က response က rate limit သင်ခန်းစာနဲ့ ဆက်စပ်ပါတယ်။ Expose-Headers မပါရင် browser JavaScript က Retry-After ကို response.headers.get() နဲ့ ဖတ်လို့ မရပါဘူး၊ client ရဲ့ retry logic မှာ null ရပြီး backoff နည်းလမ်း မှားသွားနိုင်ပါတယ်။

HTTPS က ဘာတွေ ထပ်ပေးလဲ

HTTPS ဆိုတာ TLS အပေါ်က HTTP ပါ။ ဒါက request တွေကို network ပေါ်မှာ ဖတ်လို့မရအောင် encrypt လုပ်ပြီး ပြင်ဆင်ခံရရင် သိနိုင်အောင်လည်း လုပ်ပါတယ်၊ ပြီးတော့ certificate နဲ့ server အစစ်ဟုတ်မဟုတ် စစ်ပါတယ်။ API key နဲ့ bearer token တွေကို header ထဲ ထည့်ပို့တာကြောင့် HTTPS မပါရင် wifi ထဲက ဘယ်သူမဆို ဖတ်နိုင်ပါတယ်။ ဒါပေမယ့် HTTPS က CORS ကို အစားမထိုးပါဘူး၊ authorization ကိုလည်း အစားမထိုးပါဘူး၊ ပို့လမ်းကြောင်းကိုပဲ လုံခြုံစေတာပါ။

ယန္တရားဘာကို ကာကွယ်လဲ
TLS certificateခေါ်နေတာ server အစစ်ဆိုတာ သက်သေပြ
EncryptionToken နဲ့ body တွေကို network ကနေ ဖတ်မရအောင်
Strict-Transport-SecurityBrowser ကို အမြဲ HTTPS သုံးခိုင်း
Secure cookieCookie ကို plain HTTP ပေါ် မပို့စေ

Browser မှာ HTTPS page က http:// API ကို ခေါ်ရင် mixed content အဖြစ် block လုပ်ပါတယ် (local development အတွက် localhost ကို ခြွင်းချက်ပေးထားပါတယ်)။ Client ဘက်မှာ certificate စစ်ဆေးမှုကို curl -k ဒါမှမဟုတ် NODE_TLS_REJECT_UNAUTHORIZED=0 နဲ့ ပိတ်တာကို production မှာ ဘယ်တော့မှ မလုပ်ပါနဲ့၊ အဲဒါက HTTPS ရဲ့ ကာကွယ်မှုကို ပယ်ဖျက်လိုက်တာပါ။

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Framework တိုင်းမှာ CORS middleware ရှိပါတယ် — Express အတွက် cors package၊ Django အတွက် django-cors-headers၊ Spring အတွက် @CrossOrigin ဆိုတာမျိုးပါ။ Allowlist ကို code ထဲ hard-code မလုပ်ဘဲ environment configuration က ဖတ်ပြီး production နဲ့ staging ကို သီးခြားထားပါတယ်။ http://localhost:3000 ကို dev environment မှာပဲ ခွင့်ပြုပြီး production ထဲ မရောက်စေပါနဲ့။ API gateway ရှေ့မှာ CORS ကို ကိုင်ထားတဲ့ ကိစ္စမှာလည်း origin server နဲ့ ထပ်တူ မဖြစ်အောင် တစ်နေရာတည်းမှာပဲ ကိုင်ပါ။

စမ်းသပ်ဖို့ matrix တစ်ခု ရေးပါ — origin (ခွင့်ပြုထား၊ မခွင့်ပြုထား၊ မပါ) × method × custom header × credentials ကို ဖြတ်ပြီး ဘာ header ပြန်ရမယ်ဆိုတာ စစ်ပါ။ Server-to-server call တစ်ခုကိုလည်း ပါအောင်ထည့်ပါ၊ ဒါမှ Origin မပါတဲ့ ခေါ်ဆိုမှုတွေ မပျက်တာ သေချာပါမယ်။ Frontend dev server မှာ /api ကို backend ဆီ proxy လုပ်ထားရင် browser ကနေ same-origin ဖြစ်သွားလို့ CORS လုံးဝ မလိုတော့ပါဘူး။ Secret key ပါတဲ့ third-party API တွေကိုတော့ browser ကနေ မခေါ်ဘဲ ကိုယ့် backend ကနေ ခေါ်ပါ၊ browser code ထဲက key က လူတိုင်း မြင်နိုင်လို့ပါ။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. CORS ကို လုံခြုံရေး အဆင့်လို့ ယူဆတာ

"CORS ကို ကန့်သတ်ထားတယ်၊ ဒါဆို API က private ပါ" ဆိုတာ မှားပါတယ်။ curl၊ script၊ တခြား server တွေက CORS ကို ဂရုမစိုက်လို့ endpoint ကို ခေါ်နိုင်ဆဲပါ။ Private data အတွက် authentication နဲ့ authorization က မဖြစ်မနေ လိုပါတယ်။

2. Credentials နဲ့ * ရောတာ ဒါမှမဟုတ် Origin ကို reflect လုပ်တာ

Access-Control-Allow-Origin: * နဲ့ Allow-Credentials: true ကို အတူ ပို့ရင် browser က ပယ်ချပါတယ်။ ဒီအမှားကို ဖြေရှင်းဖို့ ဝင်လာတဲ့ Origin ကို အကုန် ပြန်ပေးလိုက်ရင် ပိုဆိုးပါတယ် — ဘယ် website မဆို သုံးစွဲသူရဲ့ session နဲ့ data ကို ဖတ်နိုင်သွားပါတယ်။ Allowlist နဲ့ တိုက်စစ်ပါ။

3. Auth middleware က OPTIONS ကို ပယ်ချတာ

Preflight request မှာ Authorization header မပါပါဘူး၊ browser က credentials မပို့ပါဘူး။ Route တိုင်းမှာ token လိုတဲ့ middleware က OPTIONS ကို 401 ပြန်ရင် preflight ကျပြီး အစစ်အမှန် request က ဘယ်တော့မှ မပို့ပါဘူး။ CORS ကို authentication ထက် ရှေ့မှာ ကိုင်ပါ။

4. Success response မှာပဲ CORS header ထည့်တာ

Error response (401, 429, 500) မှာ CORS header မပါရင် JavaScript က status နဲ့ body ကို မမြင်ရဘဲ ဘာကြောင့် ကျသလဲ မသိနိုင်ပါဘူး၊ Vary: Origin မေ့တာနဲ့ ပေါင်းရင် cache ကြောင့် တခါတလေပဲ ကျတဲ့ bug တွေလည်း ဖြစ်နိုင်ပါတယ်။ Response အားလုံးမှာ ထည့်ပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • ခွင့်ပြုတဲ့ origin, method နဲ့ header တွေကို လိုအပ်တာအတိုင်းပဲ ကန့်သတ်ပါ၊ ကျယ်ကျယ် ဖွင့်မထားပါနဲ့။
  • Retry-After လို client က ဖတ်ရမယ့် response header တွေကို Access-Control-Expose-Headers နဲ့ ဖော်ပြပါ။
  • ဖြစ်နိုင်ရင် frontend နဲ့ API ကို same-origin proxy နောက်မှာ ထားပြီး CORS ကို လုံးဝ မလိုအောင် လုပ်ပါ။

Mini challenge

Mini challenge: browser ရဲ့ preflight စစ်ဆေးမှု

သင်ကိုယ်တိုင် browser ဖြစ်ပြီး preflight response က အစစ်အမှန် request ကို ပို့ခွင့်ပေးမပေး ဆုံးဖြတ်တဲ့ preflightVerdict(origin, request, response) function တစ်ခု ရေးပါ။ ပြီးတော့ အခြေအနေ ခြောက်ခုကို စစ်ပြီး ရလဒ်တွေ print လုပ်ပါ။ ဒါက Fetch standard ကို ရိုးရှင်းအောင် ကူးထားတဲ့ model ပါ။

  • Preflight status က 2xx မဟုတ်ရင် "blocked" လို့ ပြန်ရမယ်
  • Access-Control-Allow-Origin မရှိရင်၊ ရှိပေမယ့် * မဟုတ်ဘဲ page origin နဲ့ မတူရင် block ရမယ်
  • Credentials ပါရင် * ကို ပယ်ပြီး Allow-Credentials: true လိုရမယ်
  • Request method က Allow-Methods ထဲမှာ ပါရမယ်၊ request header တစ်ခုချင်းစီက Allow-Headers ထဲမှာ ပါရမယ်
  • ရလဒ်က "allowed" ဒါမှမဟုတ် "blocked: <အကြောင်းရင်း>" ဖြစ်ရမယ်
preflight-verdict.mjs
// You play the browser: does this preflight response let the real request go out?
// request:  { method, headers: ["Authorization", ...], credentials: true or false }
// response: { status, headers: { "access-control-allow-origin": "...", ... } }

function preflightVerdict(origin, request, response) {
  // TODO 1: the preflight status must be 2xx
  // TODO 2: Access-Control-Allow-Origin must be present
  // TODO 3: with credentials, "*" is invalid and Allow-Credentials must be "true"
  // TODO 4: the allowed origin must be "*" or exactly the page origin
  // TODO 5: the method must be listed in Access-Control-Allow-Methods
  // TODO 6: every request header must be listed in Access-Control-Allow-Headers
  // return "allowed" or "blocked: <reason>"
}

// TODO: build six scenarios (good, 401 on OPTIONS, wrong origin, missing PUT,
// missing Authorization, "*" with credentials) and print one line for each

ရလဒ်: ရလဒ်ခြောက်ကြောင်း print ထွက်ရပါမယ်: full allowlist allowed auth blocks OPTIONS blocked: preflight returned 401 wrong origin blocked: origin https://app.example.com not allowed no PUT blocked: method PUT not allowed Authorization missing blocked: header Authorization not allowed * with cookies blocked: wildcard origin with credentials

အရိပ်အမြွက် ကြည့်ရန်

Allow-Methods နဲ့ Allow-Headers တန်ဖိုးတွေကို "," နဲ့ ခွဲပြီး trim + lowercase လုပ်ထားတဲ့ array အဖြစ် ပြောင်းပါ။ စစ်ဆေးမှုတွေကို ပေးထားတဲ့ အစဉ်အတိုင်း return နဲ့ ဆက်စစ်ရင် ပထမဆုံး မကိုက်တာက အကြောင်းရင်း ဖြစ်ပါမယ်။

အဖြေ ကြည့်ရန်
preflight-verdict.mjs
function preflightVerdict(origin, request, response) {
  const h = response.headers;
  const list = (value) =>
    (value ?? "").split(",").map((item) => item.trim().toLowerCase());

  if (response.status < 200 || response.status > 299) {
    return "blocked: preflight returned " + response.status;
  }
  const allowOrigin = h["access-control-allow-origin"];
  if (!allowOrigin) return "blocked: no Access-Control-Allow-Origin";
  if (request.credentials) {
    if (allowOrigin === "*") return "blocked: wildcard origin with credentials";
    if (h["access-control-allow-credentials"] !== "true") {
      return "blocked: credentials not allowed";
    }
  }
  if (allowOrigin !== "*" && allowOrigin !== origin) {
    return "blocked: origin " + origin + " not allowed";
  }
  if (!list(h["access-control-allow-methods"]).includes(request.method.toLowerCase())) {
    return "blocked: method " + request.method + " not allowed";
  }
  const allowedHeaders = list(h["access-control-allow-headers"]);
  const missing = request.headers.find(
    (name) => !allowedHeaders.includes(name.toLowerCase()),
  );
  if (missing) return "blocked: header " + missing + " not allowed";
  return "allowed";
}

const page = "https://app.example.com";
const headers = ["Authorization", "Content-Type"];
const put = { method: "PUT", headers, credentials: false };
const good = {
  "access-control-allow-origin": page,
  "access-control-allow-methods": "GET, PUT",
  "access-control-allow-headers": "Authorization, Content-Type",
};
const withChange = (change) => ({ status: 204, headers: { ...good, ...change } });

const other = withChange({ "access-control-allow-origin": "https://other.example" });
const noPut = withChange({ "access-control-allow-methods": "GET, POST" });
const noAuth = withChange({ "access-control-allow-headers": "Content-Type" });
const star = withChange({
  "access-control-allow-origin": "*",
  "access-control-allow-credentials": "true",
});

const scenarios = [
  ["full allowlist", put, withChange({})],
  ["auth blocks OPTIONS", put, { status: 401, headers: {} }],
  ["wrong origin", put, other],
  ["no PUT", put, noPut],
  ["Authorization missing", put, noAuth],
  ["* with cookies", { ...put, credentials: true }, star],
];
for (const [label, request, response] of scenarios) {
  console.log(label.padEnd(22) + preflightVerdict(page, request, response));
}

Quick Quiz 1 / 3

https://app.example.com ကနေ fetch("https://api.example.com/items", { headers: { Authorization: "Bearer x" } }) ကို ခေါ်ပါတယ်။ API က CORS header လုံးဝ မပို့ပါဘူး။ Browser က ဘာလုပ်မလဲ။

Quick Quiz 2 / 3

API က https://app.example.com ကနေပဲ cookie ပါတဲ့ request ကို လက်ခံရမယ်။ ဘယ် response header တွေက မှန်လဲ။

Quick Quiz 3 / 3

curl နဲ့ API ကို ခေါ်ရင် ရပေမယ့် browser မှာ CORS error ပေါ်ပါတယ်။ အဓိပ္ပာယ်က ဘာလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Origin က scheme + host + port ပါ။ CORS ကို server မဟုတ်ဘဲ browser က enforce လုပ်ပြီး response ကို ဖတ်တာကိုပဲ တားပါတယ်၊ server က request ကို run ပြီးသားပါ။
  • GET/HEAD/POST နဲ့ safelisted header သာ ပါရင် simple ဖြစ်ပြီး Authorization၊ Content-Type: application/json၊ PUT/DELETE တွေက preflight (OPTIONS) လိုပါတယ်။
  • Allow-Origin ကို allowlist စစ်ပြီးမှ echo လုပ်ပါ၊ Vary: Origin ထည့်ပါ၊ credentials ပါရင် * မသုံးရ၊ ဝင်လာတဲ့ Origin ကို မစစ်ဘဲ reflect မလုပ်ရ။
  • CORS က authentication မဟုတ်ပါဘူး၊ HTTPS ကလည်း ပို့လမ်းကြောင်းကိုပဲ လုံခြုံစေတာမို့ token စစ်ဆေးမှုကို ဆက်လုပ်ရပါမယ်။

RFC 9110 — HTTP Semantics — IETF

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

CORS & HTTPS | Thuta Learning