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

API Key ဖြင့် ခွင့်ပြု

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

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

  • API key ကို query string အစား request header ထဲမှာ ပို့နိုင်ပြီး ခြားနားချက်ကို ရှင်းပြနိုင်ဖို့
  • Key ကို hash နဲ့ ရှာပြီး timingSafeEqual နဲ့ နှိုင်းယှဉ်တဲ့ server code ရေးနိုင်ဖို့
  • 401 နဲ့ 403 ကို ရွေးချယ်ပြီး key မရှိ ဒါမှမဟုတ် မှားတဲ့အခါ WWW-Authenticate challenge ထည့်ပေးနိုင်ဖို့
  • Scope, prefix နဲ့ rotation တွေက key ပေါက်ကြားသွားရင်တောင် ထိခိုက်မှု နည်းအောင် ဘယ်လိုကူညီလဲ ပြောပြနိုင်ဖို့

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

API key ကို ရိုးရိုးလေး ပြောရရင်

API key ဆိုတာ program တစ်ခုက API ကို ပြလိုက်တဲ့ လျှို့ဝှက် စာကြောင်းရှည်တစ်ခုပါ၊ ဒါမှ API က ဘယ် application ကနေ ခေါ်နေတာလဲဆိုတာ သိမှာပါ။ ရုံးတံခါးက ဝန်ထမ်းကတ်လေးကို စဉ်းစားကြည့်ပါ။ ကတ်က သင် ဘယ်သူလဲဆိုတာ မပြောပါဘူး၊ ဘယ်ကုမ္ပဏီက လာတာလဲ၊ ဘယ်တံခါးတွေ ဖွင့်ခွင့်ရှိလဲဆိုတာကိုပဲ ပြောတာပါ။ API ကလည်း request တစ်ခုချင်းစီမှာ ကတ်ကို ဖတ်ပြီး ရှာကြည့်ကာ ဝင်ခွင့်ပေးမလား၊ ပယ်ချမလား၊ ဒါမှမဟုတ် ဝင်ခွင့်ပေးပေမဲ့ အဲဒီတံခါးကိုတော့ မဖွင့်ပေးဘူးလား ဆုံးဖြတ်ပါတယ်။

Key က request header ထဲမှာ ပါသွားတာမို့ call တစ်ခုချင်းစီက identification တစ်ကြောင်း ပိုပါတဲ့ ရိုးရိုး HTTP request တစ်ခုပါပဲ။ Login page မလိုသလို ထိန်းထားရမယ့် session လည်း မရှိပါဘူး။ အဲဒါကြောင့် API key က API authentication အထဲမှာ အရိုးရှင်းဆုံး ဖြစ်သလို ပေါက်ကြားရလွယ်ဆုံးတွေထဲမှာလည်း ပါပါတယ်။

Problem → Why → Solution

ပြဿနာ: လူတိုင်း မြင်နေရတဲ့ key

Front-end script ထဲကို key ကို paste လုပ်ပြီး call ကို အလုပ်လုပ်စေဖို့ အမြန်ဆုံးနည်းဆိုပြီး URL ထဲမှာ ထည့်လိုက်ပါတယ်။ အလုပ်လုပ်ပါတယ်၊ ပြီးတော့ ကိုယ်မမျှော်လင့်ထားတဲ့ နေရာတွေမှာ key ပေါ်လာပါတယ် — server ရဲ့ access log၊ browser history၊ bug report ထဲက screenshot၊ နောက် site ကို ပို့တဲ့ Referer header၊ နောက်ဆုံး public repository။ ကူးယူသူတိုင်း ကိုယ့်နာမည်နဲ့ API ကို ခေါ်လို့ရသွားပြီး provider က ကိုယ့်ဆီကို ငွေတောင်းပါတယ်။

leaky-client.js
// Runs in the browser: every visitor can open DevTools and read this key.
const API_KEY = "demo_live_key_do_not_use";

const url = `https://api.example.com/v1/orders?api_key=${API_KEY}`;
const res = await fetch(url);
console.log(await res.json());

Key ပေါက်ကြားရင် ပြန်သိမ်းဖို့ ဘာကြောင့် ခက်လဲ

API key က bearer secret တစ်မျိုးပါ။ အဲဒီ စာကြောင်းကို ကိုင်ထားသူတိုင်းကို application လို့ သတ်မှတ်ပေးတာမို့ server က မူရင်းနဲ့ ကူးယူထားတာကို ခွဲမသိနိုင်ပါဘူး။ Request ထဲမှာ ခေါ်သူက ကိုယ့် code အစစ်ဖြစ်ကြောင်း သက်သေပြတဲ့ အရာ ဘာမှ မပါပါဘူး။ ကိုယ့်မှာ ရှိတဲ့ ကာကွယ်နည်းက key ကို အသုံးပြုသူတွေ မဖတ်နိုင်တဲ့ နေရာမှာ ထားဖို့၊ log မှာ မမှတ်တဲ့ နေရာကနေ ပို့ဖို့၊ key တစ်ခုချင်းစီ လုပ်ခွင့်ရတာကို ကန့်သတ်ဖို့ပဲ ရှိပါတယ်။

Core concept: key က application ကို ဖော်ပြပြီး header က သယ်ပေးတယ်

API key က လူတစ်ယောက်ကို မဟုတ်ဘဲ application ဒါမှမဟုတ် project တစ်ခုကို ဖော်ပြတာပါ။ Key မှန်ရင် server က 'ဒါ reporting dashboard ပဲ' ဒါမှမဟုတ် 'ဒါ mobile app ပဲ' ဆိုတာ သိပြီး အဲဒီ identity နဲ့ ချိတ်ထားတဲ့ ကန့်သတ်ချက်တွေ — ဘယ် endpoint တွေ သုံးခွင့်ရှိလဲ၊ တစ်မိနစ်ကို request ဘယ်နှစ်ခု၊ ဘယ် environment ရဲ့ key လဲ — ကို သုံးနိုင်ပါတယ်။ လက်ရှိ ဘယ် user က လုပ်နေလဲ သိချင်ရင်တော့ နောက် lesson တွေမှာ ပါတဲ့ token လို user-level credential လိုပါတယ်။

Key ကို request header ထဲမှာ ထည့်ပါ။ API အများစုက X-API-Key ကို သုံးပြီး တချို့က Authorization ဒါမှမဟုတ် provider ကိုယ်ပိုင် နာမည်ရှိတဲ့ header ကနေ ဖတ်ပါတယ်၊ ဒါကြောင့် documentation ကို စစ်ပါ။ Query string (?api_key=...) ထဲမှာ ထည့်တာက browser မှာ စမ်းရလွယ်လို့ စိတ်ဝင်စားစရာ ကောင်းပေမဲ့ URL ဆိုတာ header ထက် ပိုကျယ်ကျယ်ပြန့်ပြန့် ကူးခံရပါတယ်။ Web server နဲ့ proxy တွေက log မှတ်ပါတယ်၊ browser က history ထဲ သိမ်းပါတယ်၊ page တစ်ခုက တခြား site ကို link ချိတ်ရင် Referer header ထဲမှာ လိုက်ပါသွားပါတယ်။ Header တွေကိုတော့ access log ထဲ ပုံမှန်အားဖြင့် မရေးပါဘူး။

Server ဘက်မှာ key တွေကို plain text နဲ့ မသိမ်းပါနဲ့။ Key တစ်ခုချင်းစီရဲ့ hash ကို သိမ်းပြီး ဝင်လာတဲ့ key ကိုလည်း hash လုပ်ကာ crypto.timingSafeEqual နဲ့ hash နှစ်ခုကို နှိုင်းယှဉ်ပါ။ ပထမ byte ကွာတာဖြစ်ဖြစ် နောက်ဆုံး byte ကွာတာဖြစ်ဖြစ် အချိန်တူတူပဲ ကြာတာပါ။ ရိုးရိုး === နဲ့ နှိုင်းယှဉ်ရင် ကွာတဲ့ ပထမ character မှာ ရပ်သွားနိုင်ပြီး အဲဒီ အချိန်ကွာခြားချက်လေးကို attacker က တိုင်းနိုင်ပါတယ်။ နှစ်ဖက်စလုံး hash လုပ်တာက အရှည်တူစေတဲ့အတွက် timingSafeEqual လိုအပ်တဲ့ အချက်ကိုလည်း ဖြည့်ပေးပါတယ်။

နောက်ဆုံးအနေနဲ့ ကျရှုံးမှုတွေကို တိတိကျကျ ပြန်ဖြေပါ။ Key မပါတာ ဒါမှမဟုတ် မသိတဲ့ key ကို 401 Unauthorized နဲ့ ဖြေပါ၊ server က ခေါ်သူကို authenticate မလုပ်နိုင်လို့ပါ။ HTTP အရ 401 response မှာ authenticate လုပ်ပုံကို ဖော်ပြတဲ့ WWW-Authenticate header ပါဖို့ မျှော်လင့်ပါတယ်။ Key မှန်ပေမဲ့ ဒီ action ကို လုပ်ခွင့်မရှိရင် 403 Forbidden ပါ — server က သင် ဘယ်သူလဲ သိပါတယ်၊ ဒါပေမဲ့ မလုပ်ပေးနိုင်ဘူးလို့ ပြောတာပါ။

အခြေအနေStatusClient က ဘာလုပ်သင့်လဲ
X-API-Key header မပါ401Key ထည့်ပြီး ပြန်ကြိုးစား
Key မသိ ဒါမှမဟုတ် revoke လုပ်ပြီး401Key မှန်ရယူပါ၊ ထပ်ကြိုးစားလို့ အကျိုးမရှိ
Key မှန်ပေမဲ့ scope မရှိ403Scope မှန်တဲ့ key တောင်းပါ
Key မှန်ပေမဲ့ quota ကျော်429ခဏစောင့်ပြီးမှ ပြန်ကြိုးစား
တံခါးဝမှာ ကတ်စစ်သလို
  1. Client က header ထဲမှာ X-API-Key ပို့
  2. Server က key ကို hash လုပ်ပြီး နှိုင်းယှဉ်
  3. Key မရှိ/မသိ: 401 + challenge
  4. Key မှန် scope မရှိ: 403
  5. Key မှန် scope ရှိ: handler အလုပ်လုပ်

Key က ဘယ် application ခေါ်နေလဲ ပြောပြီး သူ့မှာ ချိတ်ထားတဲ့ scope တွေက အဲဒီ application ဘာလုပ်ခွင့်ရှိလဲ ပြောပါတယ်။

အထွေထွေ ပုံစံ

text
GET /resource HTTP/1.1
Host: api.example.com
X-API-Key: <secret key>

key = lookup(hash(request header X-API-Key))
no key or unknown key  -> 401 + WWW-Authenticate
key without the scope  -> 403
otherwise              -> 200 and the handler runs

Client ဘက်က header တစ်ကြောင်း ပိုထည့်ရုံပါပဲ။ Server ဘက်မှာတော့ ရလဒ် သုံးမျိုးကို ဒီအစီအစဉ်အတိုင်း စစ်ပါတယ်။

Worked example: key နဲ့ ကာကွယ်ထားတဲ့ orders API

အောက်က script က random free port တစ်ခုပေါ်မှာ သေးငယ်တဲ့ HTTP server တစ်ခု စတင်ပြီး fetch နဲ့ ငါးကြိမ် ခေါ်ပါတယ်: read-only key မှန်နဲ့၊ key မပါဘဲ၊ key မှားနဲ့၊ read-only key နဲ့ DELETE လုပ်ပြီး၊ admin key နဲ့ DELETE လုပ်ပြီး။ Server က key တွေရဲ့ SHA-256 hash ကိုပဲ သိမ်းပြီး timingSafeEqual နဲ့ နှိုင်းယှဉ်ပါတယ်။ Run ကြည့်ပြီး အခြေအနေတစ်ခုချင်းစီက ဘယ် status ထွက်လဲ ကြည့်ပါ။

ဒီ script ထဲက key အားလုံးက ဖန်တီးထားတဲ့ demo တန်ဖိုးတွေပါ။ Port 0 ဆိုတာ operating system က လွတ်နေတဲ့ port တစ်ခု ရွေးပေးတာမို့ output ထဲမှာ port နံပါတ် မပါပါဘူး။

api-key-server.mjs
import http from "node:http";
import crypto from "node:crypto";

const sha256 = (text) => crypto.createHash("sha256").update(text).digest();

// The server keeps only a hash of each key, never the key itself.
const keyStore = [
  { id: "key_reporting", hash: sha256("demo-read-key"), scopes: ["read"] },
  { id: "key_admin", hash: sha256("demo-admin-key"), scopes: ["read", "write"] },
];

function findKey(presented) {
  if (!presented) return null;
  const digest = sha256(presented); // always 32 bytes, so timingSafeEqual cannot throw
  return keyStore.find((k) => crypto.timingSafeEqual(k.hash, digest)) ?? null;
}

const server = http.createServer((req, res) => {
  const send = (status, body, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(body));
  };
  const key = findKey(req.headers["x-api-key"]);
  if (!key) {
    const challenge = { "WWW-Authenticate": 'ApiKey realm="orders"' };
    return send(401, { error: "unauthorized" }, challenge);
  }
  const needed = req.method === "GET" ? "read" : "write";
  if (!key.scopes.includes(needed)) return send(403, { error: "forbidden" });
  send(200, { ok: true, key: key.id });
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function call(label, method, headers) {
  const res = await fetch(`${base}/v1/orders`, { method, headers });
  const challenge = res.headers.get("www-authenticate");
  const body = await res.text();
  const extra = challenge ? `  ${challenge}` : "";
  console.log(`${label.padEnd(18)} ${res.status} ${body}${extra}`);
}

await call("valid read key", "GET", { "X-API-Key": "demo-read-key" });
await call("no key", "GET", {});
await call("wrong key", "GET", { "X-API-Key": "demo-read-kez" });
await call("read key, DELETE", "DELETE", { "X-API-Key": "demo-read-key" });
await call("admin key, DELETE", "DELETE", { "X-API-Key": "demo-admin-key" });
server.close();

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

  1. Store hashes{ id: "key_reporting", hash: sha256("demo-read-key"), scopes: ["read"] },

    Record တစ်ခုချင်းစီမှာ id၊ key ရဲ့ hash နဲ့ ပေးထားတဲ့ scope တွေ ပါပါတယ်။ Key အစစ်က store ထဲမှာ မရှိတာမို့ database ပေါက်ကြားရင်တောင် သုံးလို့ရတဲ့ key တွေ မပါသွားပါဘူး။ (ဒီ demo မှာတော့ client ဘာပို့လဲ မြင်ရအောင် plain text ကို source ထဲ ရေးထားတာပါ။)

  2. Constant-time lookupreturn keyStore.find((k) => crypto.timingSafeEqual(k.hash, digest)) ?? null;

    ဝင်လာတဲ့ key ကို hash လုပ်ထားတဲ့ digest နဲ့ record တစ်ခုချင်းစီရဲ့ hash ကို timingSafeEqual နဲ့ နှိုင်းယှဉ်ပါတယ်။ digest နှစ်ခုစလုံး byte 32 လုံးမို့ length မကိုက်လို့ error မတက်ပါဘူး။ မတွေ့ရင် null ပြန်ပါတယ်။

  3. 401 with a challengeconst challenge = { "WWW-Authenticate": 'ApiKey realm="orders"' };

    Key မရှိတာ ဒါမှမဟုတ် မသိတာဆိုရင် 401 ပြန်ပြီး WWW-Authenticate header ကိုလည်း ထည့်ပေးပါတယ်။ ApiKey ဆိုတာ ကိုယ်ပိုင် scheme နာမည်ပါ၊ standard မဟုတ်လို့ client တွေက ဒီနာမည်ကို အားမကိုးသင့်ပါဘူး။

  4. 403 for a missing scopeif (!key.scopes.includes(needed)) return send(403, { error: "forbidden" });

    Key မှန်ပြီဆိုမှ method ကနေ လိုအပ်တဲ့ scope ကို ရွေးပါတယ် (GET ဆို read၊ ကျန်တာ write)။ Scope မပါရင် 403 ပါ၊ ဒီအချိန်မှာ ခေါ်သူကို ဘယ်သူလဲ သိပြီးသားမို့ 401 မဟုတ်ပါဘူး။

  5. Send the headerconst res = await fetch(`${base}/v1/orders`, { method, headers });

    Client ဘက်မှာ key ကို headers object ထဲက X-API-Key အနေနဲ့ ပို့ပါတယ်။ URL မှာ ဘာမှ မပါလို့ server log ထဲက request line မှာ key မပါပါဘူး။

You should see
valid read key     200 {"ok":true,"key":"key_reporting"}
no key             401 {"error":"unauthorized"}  ApiKey realm="orders"
wrong key          401 {"error":"unauthorized"}  ApiKey realm="orders"
read key, DELETE   403 {"error":"forbidden"}
admin key, DELETE  200 {"ok":true,"key":"key_admin"}
Request တစ်ခုချင်းစီအတွက် server ဆုံးဖြတ်ပုံ
  1. X-API-Key header ကို ဖတ်
  2. Hash လုပ်ပြီး store ထဲက ရှာ
  3. ဒီ method အတွက် scope ကို စစ်
  4. Handler ကို run

Key မရှိ ဒါမှမဟုတ် မသိ

401 Unauthorized + WWW-Authenticate

Key မှန်၊ scope မရှိ

403 Forbidden

Key မှန်၊ scope ရှိ

200 OK

Header လား query string လား

API တချို့က browser address bar မှာ စမ်းလို့ရအောင် key ကို URL ထဲမှာလည်း လက်ခံပါတယ်။ အဲဒီ အဆင်ပြေမှုမှာ ဈေးကြီးပါတယ်၊ URL က request ရဲ့ အကူးခံရဆုံး အပိုင်းမို့ပါ။ အောက်က script က local server ကို နှစ်ကြိမ် ခေါ်ပါတယ်၊ တစ်ကြိမ်က key ကို query string ထဲမှာ၊ နောက်တစ်ကြိမ်က header ထဲမှာပါ၊ ပြီးရင် ပုံမှန် access log က ဘာမှတ်လဲ print ထုတ်ပါတယ်။

access-log-leak.mjs
import http from "node:http";

const accessLog = [];
const server = http.createServer((req, res) => {
  accessLog.push(`${req.method} ${req.url}`); // roughly what an access log records
  res.end("ok");
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

const asQuery = await fetch(`${base}/v1/orders?api_key=demo-read-key`);
await asQuery.text();
const headers = { "X-API-Key": "demo-read-key" };
const asHeader = await fetch(`${base}/v1/orders`, { headers });
await asHeader.text();

console.log(accessLog.join("\n"));
server.close();

ပထမ log line မှာ သုံးလို့ရတဲ့ key ပါနေပြီး ဒုတိယ line မှာ လျှို့ဝှက်ချက် ဘာမှ မပါပါဘူး။ ဒါက server ကိုယ်တိုင်ရဲ့ log သက်သက်ပါ။ Corporate proxy၊ CDN၊ monitoring tool နဲ့ browser history တို့က URL ရဲ့ ကိုယ်ပိုင် copy တွေ သိမ်းထားပါတယ်။

Key သွားတဲ့ နေရာဘယ်သူတွေ မြင်နိုင်လဲ
Query string (?api_key=...)Access log၊ proxy၊ CDN၊ browser history၊ Referer header၊ share လုပ်တဲ့ link၊ screenshot
Request header (X-API-Key)TLS ကို အဆုံးသတ်တဲ့ server နဲ့ ကိုယ့် application code ပဲ၊ header ကို log မလုပ်ရင် မမြင်ရ

တချို့ key တွေက web page ထဲ ထည့်ထားတဲ့ map key လို အများမြင်ရအောင် ဒီဇိုင်းလုပ်ထားတာပါ။ အဲဒီ provider တွေက လျှို့ဝှက်ချက်အစား ကန့်သတ်ချက်တွေ (သုံးခွင့်ရတဲ့ domain ဒါမှမဟုတ် app၊ quota limit) နဲ့ ကာကွယ်ပါတယ်။ Provider ရဲ့ documentation က key ကို browser အတွက်လို့ ပြောထားရင် ပြောထားတဲ့အတိုင်း restrict လုပ်ပါ၊ မပြောထားရင်တော့ key ကို လျှို့ဝှက်ချက်အနေနဲ့ ဆက်ဆံပါ။

အချိန်ကို မပေါက်ကြားစေဘဲ key နှိုင်းယှဉ်ခြင်း

=== နဲ့ key စစ်တာ အန္တရာယ်မရှိသလိုပေမဲ့ string နှိုင်းယှဉ်မှုက ကွာတဲ့ character ကို တွေ့တာနဲ့ ချက်ချင်း return ပြန်နိုင်ပါတယ်။ Request အများကြီးနဲ့ attacker က အဲဒီ အလွန်သေးငယ်တဲ့ အချိန်ကွာခြားချက်တွေကို တိုင်းပြီး key ကို character တစ်လုံးချင်း ရှာဖွေနိုင်တာ သီအိုရီအရ ဖြစ်နိုင်ပါတယ်။ crypto.timingSafeEqual က အဲဒါကို ရှောင်ပေမဲ့ buffer နှစ်ခုရဲ့ အရှည်မတူရင် error တက်ပါတယ်၊ အဲဒါကိုယ်တိုင်က key အရှည်ကို ပြောပြသလို ဖြစ်ပါတယ်။ စံနည်းက တန်ဖိုးနှစ်ခုစလုံးကို အရင် hash လုပ်ပြီး byte 32 လုံးရှိတဲ့ digest နှစ်ခုကို နှိုင်းယှဉ်တာပါ။

timing-safe.mjs
import crypto from "node:crypto";

try {
  crypto.timingSafeEqual(Buffer.from("demo-read-key"), Buffer.from("demo-read"));
} catch (err) {
  console.log(err.code); // buffers of different lengths are rejected outright
}

const digest = (text) => crypto.createHash("sha256").update(text).digest();
console.log(crypto.timingSafeEqual(digest("demo-read-key"), digest("demo-read-key")));
console.log(crypto.timingSafeEqual(digest("demo-read-key"), digest("demo-read")));

ပထမ line က အရှည်မတူတဲ့အခါ Node ပြတဲ့ error code ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH ပါ။ နောက်နှစ်ကြောင်းက digest တွေ ကိုက်တာနဲ့ မကိုက်တာကို ပြပါတယ်။ လက်တွေ့မှာ network jitter ကြောင့် remote server ကို timing attack လုပ်ဖို့ ခက်ပေမဲ့ ပြင်ဆင်ချက်က တစ်ကြောင်းတည်းမို့ ကျော်သွားဖို့ အကြောင်းမရှိပါဘူး။

Key ရဲ့ lifecycle: prefix, scope, rotation

မြင်သာတဲ့ prefix ပေးပါ

sk_test_ ဒါမှမဟုတ် key_live_ လို prefix က log ဒါမှမဟုတ် commit ထဲမှာ key ကို လူနဲ့ secret scanner တွေ မှတ်မိစေပြီး test key လား production key လားလည်း ပြောပြပါတယ်။

အနည်းဆုံး scope ပေးပါ

အလုပ်တစ်ခုစီအတွက် key သီးခြားစီ ဖန်တီးပါ: dashboard အတွက် read-only key၊ importer အတွက် write key။ အဲဒါဆို read key ပေါက်ကြားရင်တောင် ဘာမှ ဖျက်လို့ မရပါဘူး။

Overlap နဲ့ rotate လုပ်ပါ

Key အသစ် ထုတ်၊ deploy လုပ်၊ ပြီးမှ key အဟောင်းကို revoke လုပ်ပါ။ ခဏတာ နှစ်ခုလုံးကို လက်ခံထားရင် rotation ကြောင့် service ပြတ်မသွားပါဘူး။

ချက်ချင်း revoke လုပ်နိုင်ပြီး လုံခြုံစွာ log မှတ်ပါ

Key တစ်ခုတည်းကို ချက်ချင်း ပိတ်နိုင်တဲ့ နည်းလမ်း ရှိထားပါ၊ log မှာ key တစ်ခုလုံး မဟုတ်ဘဲ id ဒါမှမဟုတ် နောက်ဆုံး character လေးလုံးပဲ မှတ်ပါ။

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

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

Payment၊ map၊ email၊ SMS၊ weather လို third-party service အများစုက သူတို့ API ကို API key နဲ့ ဖွင့်ပေးပါတယ်။ ကိုယ့် backend က အဲဒီ service တွေကို ခေါ်တဲ့အခါ key ကို environment variable ဒါမှမဟုတ် secret manager ထဲကနေ ဖတ်ပါတယ်၊ source code ထဲ မရေးပါဘူး။ ကိုယ်ပိုင် API ကို partner တွေကို ပေးမယ့်အခါလည်း API gateway ဒါမှမဟုတ် middleware တစ်ခုက အဲဒီ header ကို စစ်ပြီး partner တစ်ဦးချင်းစီရဲ့ quota နဲ့ usage ကို ခြေရာခံပါတယ်။

  • Environment တစ်ခုချင်းစီအတွက် key သီးခြားစီ: development, staging, production တို့ကို မရောပါနဲ့၊ test key က ပေါက်ကြားရင် production မထိခိုက်ပါဘူး။
  • CI/CD pipeline မှာ key ကို pipeline ရဲ့ secret store ထဲ ထည့်ပြီး build log ထဲ print မထွက်အောင် စစ်ပါ။
  • Repository ကို secret scanning နဲ့ စစ်ပါ၊ provider တချို့ကလည်း public repo ထဲ ပေါ်လာတဲ့ သူတို့ရဲ့ key format ကို ရှာပြီး သတိပေးတတ်ပါတယ်။
  • Provider dashboard ရဲ့ usage graph ကို ကြည့်ပါ၊ မမျှော်လင့်တဲ့ တက်လာမှုက key ပေါက်ကြားတယ်ဆိုတဲ့ အစောဆုံး လက္ခဏာဖြစ်လေ့ရှိပါတယ်။

အမှားများ

API key နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Key ကို URL ထဲ ထည့်ခြင်း

?api_key=... က curl နဲ့ browser မှာ အလွယ်ဆုံး ဖြစ်ပေမဲ့ log၊ history နဲ့ Referer ထဲ ကူးသွားပါတယ်။ Provider က header ကို လက်ခံရင် header ကိုပဲ သုံးပါ။

Front-end code ဒါမှမဟုတ် mobile app ထဲ key ထည့်ခြင်း

Browser JavaScript ဒါမှမဟုတ် mobile package ထဲက static key ကို အသုံးပြုသူတွေ ထုတ်ယူနိုင်ပါတယ်။ လျှို့ဝှက် key ရှိတဲ့ call တွေကို ကိုယ့် backend ကနေ ခေါ်ပြီး browser က backend ကိုပဲ ခေါ်ပါ။

Key ကို Git ထဲ commit လုပ်မိခြင်း

နောက် commit မှာ ဖျက်လိုက်လည်း history ထဲမှာ ကျန်နေပါတယ်။ Commit လုပ်မိရင် ဖျက်တာနဲ့ မပြီးပါဘူး၊ key ကို revoke လုပ်ပြီး အသစ် ထုတ်ရပါမယ်။ .env ကို .gitignore ထဲ အစကတည်းက ထည့်ထားပါ။

401 နဲ့ 403 ကို ရောပြန်ခြင်း

Key မပါတာကို 403 နဲ့ ဖြေရင် client က permission ပြဿနာလို့ ထင်ပြီး key ထည့်ဖို့ မေ့သွားနိုင်ပါတယ်။ Key မှန်ပေမဲ့ scope မရှိတာကို 401 နဲ့ ဖြေရင် ဘယ် key ကိုပဲ ပြောင်းပြောင်း ပြေလည်မယ်လို့ ထင်စေပါတယ်။ ဒါကြောင့် 401 က 'သင်ဘယ်သူလဲ မသိဘူး'၊ 403 က 'သိတယ်၊ ဒါပေမဲ့ မရဘူး' လို့ မှတ်ထားပါ။

Best Practices

Best practices

  • Key ကို header ထဲမှာပဲ ပို့ပါ၊ HTTPS ပေါ်မှာသာ ပို့ပါ။
  • Server မှာ hash ပဲ သိမ်းပါ၊ timingSafeEqual နဲ့ နှိုင်းယှဉ်ပါ။
  • Key တစ်ခုချင်းစီကို အနည်းဆုံး scope နဲ့ ထုတ်ပြီး ပုံမှန် rotate လုပ်ပါ။
  • Log ထဲမှာ key တစ်ခုလုံးကို မမှတ်ပါနဲ့၊ id ဒါမှမဟုတ် mask လုပ်ထားတဲ့ ပုံစံကိုပဲ မှတ်ပါ။

Mini challenge

Mini challenge: scope ပါတဲ့ key နဲ့ mask လုပ်ထားတဲ့ log

/reports endpoint တစ်ခုကို key သုံးမျိုးနဲ့ ကာကွယ်ပါ: ci-bot က ဖတ်ခွင့်ပဲရှိတယ်၊ analyst က ဖတ်ရေး နှစ်မျိုးလုံးရတယ်၊ old-bot ကိုတော့ revoke လုပ်ထားပြီး။ authenticate function တစ်ခုက 401၊ 403 ဒါမှမဟုတ် 200 ကို ဆုံးဖြတ်ပေးရမယ်၊ request တစ်ခုချင်းစီကို key နောက်ဆုံး character လေးလုံးပဲ မြင်ရတဲ့ log line အဖြစ် မှတ်ပါ။

  • Key တွေကို hash နဲ့ သိမ်းပြီး timingSafeEqual နဲ့ နှိုင်းယှဉ်ရမယ်
  • Key မပါတာနဲ့ revoke လုပ်ထားတာက 401၊ scope မရှိတာက 403 ပြန်ရမယ်
  • Log line က METHOD path key=****xxxx -> status ပုံစံ ဖြစ်ပြီး key တစ်ခုလုံး မပါရဘူး
  • Request ငါးခု ပို့ပြီး log ကို print ထုတ်ကာ server ကို ပိတ်ပါ
reports-keys.mjs
import http from "node:http";
import crypto from "node:crypto";

// TODO: records = [{ id, hash, scopes, revoked }], hashing each key with sha256

// TODO: mask(key) -> "****" plus the last 4 characters, or "(none)" when missing

// TODO: authenticate(presented, scope) -> { status, error?, id? }
//   no key -> 401 | unknown or revoked key -> 401 | scope missing -> 403 | else 200

// TODO: start a server on port 0 whose handler
//   - picks the scope from the method: GET -> reports:read, others -> reports:write
//   - pushes "METHOD path key=<masked> -> status" onto a log array
//   - answers with the status and a small JSON body (never echo the key)

// TODO: send five requests with fetch, print the log lines, close the server

ရလဒ်: Log line ငါးကြောင်း ထွက်ရမယ်: ci-bot GET က 200၊ ci-bot POST က 403၊ analyst POST က 200၊ old-bot GET က 401၊ key မပါတဲ့ GET က 401။

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

authenticate ကို function သီးခြားအဖြစ် ရေးပါ။ အစီအစဉ်က key မပါ → မသိ ဒါမှမဟုတ် revoke → scope စစ် → အောင်မြင်။ Revoke လုပ်ထားတဲ့ key နဲ့ မသိတဲ့ key ကို error တူတူ ပြန်ရင် ပိုကောင်းပါတယ်။

အဖြေ ကြည့်ရန်
reports-keys.mjs
import http from "node:http";
import crypto from "node:crypto";

const sha256 = (text) => crypto.createHash("sha256").update(text).digest();
const record = (id, key, scopes, revoked = false) => {
  return { id, hash: sha256(key), scopes, revoked };
};
const records = [
  record("ci-bot", "sk_test_ci_1111", ["reports:read"]),
  record("analyst", "sk_test_an_2222", ["reports:read", "reports:write"]),
  record("old-bot", "sk_test_ol_3333", ["reports:read"], true),
];

const mask = (key) => (key ? `****${key.slice(-4)}` : "(none)");

function authenticate(presented, scope) {
  if (!presented) return { status: 401, error: "missing_key" };
  const digest = sha256(presented);
  const record = records.find((r) => crypto.timingSafeEqual(r.hash, digest));
  if (!record || record.revoked) return { status: 401, error: "invalid_key" };
  if (!record.scopes.includes(scope)) return { status: 403, error: "insufficient_scope" };
  return { status: 200, id: record.id };
}

const log = [];
const server = http.createServer((req, res) => {
  const key = req.headers["x-api-key"];
  const scope = req.method === "GET" ? "reports:read" : "reports:write";
  const result = authenticate(key, scope);
  log.push(`${req.method} ${req.url} key=${mask(key)} -> ${result.status}`);
  res.writeHead(result.status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(result.status === 200 ? { ok: true } : { error: result.error }));
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function send(method, key) {
  const headers = key ? { "X-API-Key": key } : {};
  const res = await fetch(`${base}/reports`, { method, headers });
  await res.text();
}

await send("GET", "sk_test_ci_1111");
await send("POST", "sk_test_ci_1111");
await send("POST", "sk_test_an_2222");
await send("GET", "sk_test_ol_3333");
await send("GET", undefined);

console.log(log.join("\n"));
server.close();

Quick Quiz 1 / 3

ဘယ် request က API key ကို အလုံခြုံဆုံး နေရာမှာ ပို့ထားလဲ?

Quick Quiz 2 / 3

Server က DELETE /v1/orders/7 ကို read-only scope ပဲရှိတဲ့ မှန်ကန်တဲ့ key နဲ့ လက်ခံရရှိတယ်။ ဘယ် status က မှန်လဲ?

Quick Quiz 3 / 3

crypto.timingSafeEqual ကို မခေါ်ခင် တန်ဖိုးနှစ်ခုစလုံးကို hash လုပ်တာ ဘာကြောင့်လဲ?

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

  • API key က application ကို ဖော်ပြပါတယ်၊ user ကို မဟုတ်ပါဘူး၊ ဒါကြောင့် ပေါက်ကြားရင် ကူးယူသူတိုင်း အဲဒီ application အဖြစ် ဟန်ဆောင်နိုင်ပါတယ်။
  • Key ကို query string မဟုတ်ဘဲ request header ထဲမှာ ပို့ပါ၊ URL တွေက log, history နဲ့ Referer ထဲ ကူးသွားတတ်ပါတယ်။
  • Server မှာ key တွေကို hash နဲ့ သိမ်းပြီး timingSafeEqual နဲ့ နှိုင်းယှဉ်ပါ၊ နှစ်ဖက်စလုံး hash လုပ်ရင် length အမှား မတက်ပါဘူး။
  • 401 က key မရှိ/မှား၊ 403 က key မှန်ပေမဲ့ ခွင့်မရှိ ဖြစ်ပြီး 401 မှာ WWW-Authenticate ပါသင့်ပါတယ်။

RFC 6750 — Bearer Token Usage — IETF

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

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

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

API Key ဖြင့် ခွင့်ပြု | Thuta Learning