บทที่ 13 · Part 3 — API & Mobile Security
API Security Foundations
OWASP API Security Top 10:2023, REST/GraphQL/gRPC contracts, authorization, resource limits, inventory, versioning และ third-party trust
API ที่ไม่ปรากฏใน mobile app รุ่นปัจจุบันอาจยังเปิดอยู่เพราะ client เก่าใช้งาน หรือ GraphQL endpoint เดียวอาจเข้าถึง object/function จำนวนมากจน route inventory แบบ REST มองไม่เห็น API Security จึงเริ่มจาก contract, identity, resource และ lifecycle ไม่ใช่ติด rate limiter หน้า endpoint
Learning Outcomes
- ใช้ OWASP API Security Top 10:2023 เป็น risk vocabulary โดยไม่ตีความเป็น prevalence ได้
- เปรียบเทียบ security surface ของ REST, GraphQL และ gRPC ได้
- ออกแบบ contract/schema, authorization, limits และ error semantics ได้
- สร้าง API inventory พร้อม owner, exposure, version และ deprecation lifecycle ได้
- ปฏิบัติต่อ third-party API response เป็น untrusted input ได้
OWASP API Security Top 10:2023
| ID | Risk |
|---|---|
| API1 | Broken Object Level Authorization |
| API2 | Broken Authentication |
| API3 | Broken Object Property Level Authorization |
| API4 | Unrestricted Resource Consumption |
| API5 | Broken Function Level Authorization |
| API6 | Unrestricted Access to Sensitive Business Flows |
| API7 | Server Side Request Forgery |
| API8 | Security Misconfiguration |
| API9 | Improper Inventory Management |
| API10 | Unsafe Consumption of APIs |
รายการนี้เป็น awareness document ที่คัด risk เฉพาะ API ไม่ได้หมายความว่า Injection, XSS, software supply chain หรือ cryptographic failure ไม่มีผล และข้อมูลอันดับปี 2023 ไม่ควรถูกอ้างว่า เป็น measured prevalence สากล
API Contract คือ Security Boundary
contract ที่ดีระบุ:
- method/operation และ side-effect semantics
- request/response schema, required/unknown fields
- identity/authentication scheme
- subject-action-resource authorization
- idempotency/concurrency behavior
- timeout, retry และ error model
- request/response/resource limits
- sensitive field classification และ logging policy
- version/deprecation/owner
ตัวอย่าง schema intent แบบย่อ:
{
"source_account_id": "acc_opaque",
"beneficiary_id": "ben_opaque",
"amount_satang": 250000,
"currency": "THB",
"client_reference": "client_unique_reference"
}
backend ต้อง reject unknown privileged fields เช่น status, approved_by, fee_satang
และคำนวณ authoritative value ฝั่ง server
REST, GraphQL และ gRPC มี Surface ต่างกัน
| Style | Surface เด่น | Controls ที่ต้องเน้น |
|---|---|---|
| REST | path/method/resource/version | object ownership, method/function auth, pagination, content type |
| GraphQL | query graph, resolver, introspection, batching | resolver auth, depth/breadth/cost, field exposure, batching abuse |
| gRPC | protobuf service/method, streaming, metadata | interceptor auth, message/stream limit, deadline, reflection exposure |
protocol ไม่สร้าง authorization ให้อัตโนมัติ GraphQL schema และ protobuf type ช่วย validation แต่ resolver/handler ยังต้องตรวจ resource/state และ downstream call
Object, Function และ Property Authorization
API authorization อย่างน้อย 3 ชั้น:
- Object — subject เข้าถึง account/order/document ชิ้นนี้ได้หรือไม่
- Function — subject เรียก approve/export/admin operation ได้หรือไม่
- Property — subject อ่าน/เขียน field ใดได้หรือไม่
PATCH /accounts/acc_02 HTTP/1.1
Authorization: Bearer <token>
Content-Type: application/json
{"display_name":"Payroll","tenant_id":"other","status":"privileged"}
แม้ account acc_02 เป็นของ subject ระบบต้อง allowlist writable fields และไม่รับ tenant/status
จาก generic domain model ดูหลัก authorization เต็มในบทที่ 8
Schema Validation ยังไม่ใช่ Business Validation
schema อาจบอกว่า amount_satang เป็น positive integer แต่ยังต้องตรวจ:
- currency/account รองรับกัน
- beneficiary active และผูกกับ tenant ถูก
- limit/available funds/state version
- fee/FX rate มาจาก authoritative source
- operation ซ้ำหรือแข่งกันหรือไม่
- actor มี current authorization/assurance
validate request ก่อนงานแพงและ recheck invariant ใน transaction/state boundary
Resource Consumption ต้องคิดเป็น Cost
จำกัดมากกว่า request ต่อวินาที:
| Resource | ตัวอย่าง Limit |
|---|---|
| Request | bytes, fields, nesting, decompression |
| Compute | timeout/deadline, query cost, regex/parser work |
| Memory | result count, buffered stream, upload dimensions |
| Database | rows scanned, page size, concurrent query |
| Downstream | per-provider concurrency, response size, redirect |
| Money | OTP/SMS, KYC/vendor call, promotion/refund budget |
GraphQL query หนึ่งอาจเรียก resolver หลายพันครั้ง; gRPC stream อาจค้าง connection/worker slot; REST export อาจ scan table ทั้งหมด Rate limit แบบ count เดียวจึงไม่พอ
Pagination ต้องมีขอบเขต
- cap page size ฝั่ง server
- cursor opaque และ integrity-protected ตาม design
- authorize filter/sort fields
- stable ordering ป้องกัน skip/duplicate ตาม consistency need
- อย่า leak total count ของ resource ที่ subject ไม่ควรรู้
- export ขนาดใหญ่ใช้ async job + authorization ตอนสร้างและตอน download
API6: Sensitive Business Flow Abuse
API อาจทำงานตรง spec แต่ถูก automation ใช้ใน scale ที่ธุรกิจไม่ตั้งใจ:
- signup/promotion farming
- OTP/card testing
- scraping price/rate หรือ enumeration
- reserve inventory/beneficiary แล้วไม่ complete
- refund/transfer splitting เพื่อหลบ threshold
ต้องใช้ business limit, velocity, cost control, device/behavior/fraud signals และ human-owned policy ร่วมกับ technical rate limiting
API7: SSRF อยู่ใน API Top 10
endpoint ที่รับ URL สำหรับ webhook preview, document fetch หรือ image import อาจถูกใช้เรียก internal/control-plane endpoint Validation URL อย่างเดียวไม่พอ ต้องมี destination policy, DNS/IP resolution checks, redirect policy, isolated fetcher, egress controls และ response/time limits รายละเอียด advanced อยู่ในบทที่ 26
API Inventory ที่ใช้งานได้จริง
inventory ต่อ API/version ควรมี:
| Field | ตัวอย่าง |
|---|---|
| Host/environment | public, partner, internal, sandbox |
| Protocol/version | REST v2, GraphQL schema revision, gRPC service |
| Owner/on-call | ทีมและ escalation path |
| Exposure | Internet, private link, cluster-only |
| Auth scheme | cookie, OAuth audience/scope, mTLS identity |
| Data/actions | classification และ side effects |
| Dependencies | DB, queue, partner, callback |
| Lifecycle | active, deprecated, removal date |
| Evidence | spec, threat model, tests, telemetry |
หา shadow API จาก DNS/gateway/load balancer/service mesh/cloud inventory, code, mobile binary, logs และ certificate ไม่พึ่ง spreadsheet ที่กรอกมือเพียงแหล่งเดียว
Versioning และ Deprecation
version เก่ามักมี control เก่าและถูก monitor น้อย การ deprecate ต้องมี:
- owner และ usage telemetry แยก client/tenant
- published migration contract
- block new adoption
- security patch policy ระหว่าง sunset
- staged warning/deny และ exception ที่หมดอายุ
- removal ที่ gateway, DNS, route, function และ backend จริง
- test ว่า legacy hostname/path ใช้ไม่ได้
อย่าเพียงซ่อน endpoint จาก documentation เพราะ attacker ดู mobile binary/log/history ได้
Error Semantics ที่ไม่เปิด Internal Detail
public error ควร stable, machine-readable และไม่บอก query/stack/path/secret:
{
"code": "TRANSFER_NOT_ALLOWED",
"message": "ไม่สามารถดำเนินรายการได้",
"correlation_id": "req_opaque"
}
อย่าแยกเหตุผล authorization ละเอียดจน enumeration ได้ ภายในบันทึก reason/evidence ที่ restricted และกำหนด retryable/non-retryable ให้ client ไม่สร้าง retry storm หรือ duplicate side effect
Third-Party API คือ Untrusted Boundary
API10 เตือนว่าการเชื่อ response จาก partner มากเกินไปสร้างช่องโหว่:
- enforce TLS/peer identity และ redirect destination
- validate response schema/type/range/size
- จำกัด timeout, retry, concurrency และ response bytes
- ไม่ forward credential/header ข้าม host
- sanitize data ก่อน sink/log/browser
- map external state เป็น internal state machine อย่าง explicit
- verify webhook signature + replay uniqueness + idempotency
- monitor contract drift และ malformed response
partner ที่ trusted ทางธุรกิจยังอาจถูก compromise หรือส่งข้อมูลผิดจาก bug
Observability โดยไม่รั่ว Payload
เก็บ operation, API version, subject/service reference, resource class, outcome, latency, rate-limit decision, authorization deny และ downstream status โดยไม่ log raw token, OTP, account details หรือ full request/response เป็น default
metrics ควรเห็น resource exhaustion, auth failure, 4xx/5xx shift, deprecated-version traffic, schema rejection, downstream timeout และ sensitive-flow velocity พร้อม owner/runbook
Testing Checklist
- API Top 10 ระบุปี 2023 และไม่ถูกใช้แทน Web Top 10/ASVS
- REST/GraphQL/gRPC มี contract, auth, limits และ error semantics
- object/function/property authorization มี negative tests
- schema แยกจาก business invariant/current state
- จำกัด bytes/depth/cost/concurrency/downstream และ monetary resources
- sensitive flow มี automation/velocity/cost controls
- inventory ครอบคลุม host/version/owner/exposure/data/deprecation
- legacy/shadow endpoint ถูก discover และ removal ถูก verify
- third-party response ถูก validate/limit และ credential ไม่ follow redirect
- telemetry ไม่เก็บ raw token หรือ sensitive payload
สรุป
API Security เริ่มจาก inventory และ contract ที่บอก identity, resource, state, cost และ lifecycle Protocol/schema ช่วยสร้าง boundary แต่ไม่แทน authorization, business invariant, abuse control, third-party validation และ evidence ใน production