Day 16 我們學了 Observability。今天加入 Production System
的另一個核心能力:Security。
Security 的目的,是保護 System、Data 與
User,避免未經允許的人讀取、修改、破壞或濫用它們。
CIA Triad 不是美國情報機構,而是三個 Security 目標:
Confidentiality
Integrity
Availability
只有被允許的人可以看到資料。
例如 User A 的私人資料不應被 User B 看到。
資料不能被未經允許地修改,而且應維持正確。
例如 Bank Balance 不能被 Attacker 任意從 $1,000 改成 $1,000,000。
User 需要 Service 時,Service 應該可以使用。
所以 Security 不只是防止資料被偷。大量惡意 Traffic 讓 Service
完全不可用,也屬於 Security Problem。
Threat:
可能對 System 造成傷害的威脅。
例如 Attacker、Malware、Credential Theft、DDoS。
Vulnerability:
System 裡可以被利用的弱點。
例如:
Weak Password
Outdated Software
Admin API 沒有權限檢查
SQL 直接拼 User Input
Exploit:
利用 Vulnerability 達成攻擊目的的方法或行為。
生活類比:
Threat → 小偷
Vulnerability → 門沒鎖
Exploit → 利用沒鎖的門進入
Attack Surface:
Attacker 可能嘗試進入、操作或攻擊 System 的所有入口。
例如:
Login Page
Public API
Admin API
File Upload
Open Network Port
Third-party Integration
入口越多,通常需要保護的地方也越多。
Authentication 回答:
Who are you?
也就是:
確認你是誰。
例如:
Email: alvin@example.com
Password: ********
驗證成功後,System 確認這是某個 User Identity。
Identity:
System 裡代表某個 User 或 Service 身分的資訊。
例如:
userId = 123
email = alvin@example.com
Credential:
用來證明 Identity 的資訊或物品。
例如:
Password
One-Time Code
Security Key
Client Certificate
簡單類比:
Identity → 我說我是 Alvin
Credential → 我拿出能證明身分的東西
Authentication Factor 是一種類型的身分證據。
你知道的:
Password
PIN
你擁有的:
Phone
Security Key
Authenticator Device
你的生物特徵:
Fingerprint
Face
MFA = Multi-Factor Authentication
使用兩種或更多不同 Factor 驗證身分。
例如:
Password
+
Authenticator App Code
2FA = Two-Factor Authentication
使用兩種不同 Factor,是 MFA 的一種。
Authentication 成功後,還有另一個問題:
What are you allowed to do?
這就是 Authorization:
確認已登入的 Identity 有沒有權限執行某個 Action。
例如 Alvin 已登入,但呼叫:
DELETE /admin/users/999
System 還要檢查:
Alvin 是 Admin 嗎?
有 DELETE_USER Permission 嗎?
最簡單記:
Authentication
→ 你是誰?
Authorization
→ 你可以做什麼?
公司類比:
刷員工證確認你是 Alvin
→ Authentication
確認 Alvin 能不能進 Server Room
→ Authorization
成功登入不代表可以做任何事情。
Permission:
允許執行某個特定 Action 的權限。
例如:
READ_USER
CREATE_ORDER
DELETE_USER
EDIT_PRODUCT
Role:
一組常見 Permissions 的集合。
例如:
ADMIN
├── READ_USER
├── DELETE_USER
├── EDIT_PRODUCT
└── VIEW_REPORT
RBAC = Role-Based Access Control
根據 User 的 Role 決定他可以執行哪些 Action。
例如:
CUSTOMER → View own orders
EMPLOYEE → Support operations
ADMIN → Manage users
Access Control:
決定誰可以存取哪些 Resource,以及可以做哪些 Action。
Least Privilege:
只給 User 或 Service 完成工作真正需要的最少權限。
例如 Email Service 只需要:
Read Email Address
Send Email
就不要給:
Delete Users
Modify Payment
如果 Email Service 被攻擊,Attacker 可以利用的權限也比較少。
不要直接存:
password = "MyPassword123"
這叫 Plaintext Password。
Plaintext:
沒有經過保護,可以直接讀懂的原始內容。
Database Leak 時,所有 Password 都可能直接曝光。
Password 通常需要使用 Password Hashing。
Hash Function:
把 Input 轉換成某種固定形式 Output 的 Function。
概念:
"MyPassword123"
↓
Hash Function
↓
"a8f91c..."
Password Hashing 的重要特性之一:
不需要把 Hash 反向還原成原本 Password。
Register:
Password
↓
Password Hashing
↓
Store Result
Login:
Entered Password
↓
Verify against stored hash
↓
Match / Not Match
Input → Hash → Output
通常不是為了之後還原。
常見用途:
Password Verification
Data Integrity
Plaintext
↓
Encryption + Key
↓
Ciphertext
之後:
Ciphertext
↓
Decryption + Key
↓
Plaintext
Encryption 的資料之後可以由持有正確 Key 的一方還原。
簡單記:
Password
→ 通常 Hash
需要日後讀回的秘密資料
→ 可能 Encryption
Encryption:
使用 Cryptographic Algorithm 與
Key,把可讀資料轉成不容易直接讀懂的形式。
原始資料叫:
Plaintext
加密結果叫:
Ciphertext
Decryption:
使用正確 Key,把 Ciphertext 還原成 Plaintext。
Key:
控制 Encryption / Decryption 的密碼學資料。
可以先類比成鎖與鑰匙。
Password Hashing 常加入 Salt:
一段為 Password Hashing 加入的隨機資料。
兩個 User 都使用:
password123
如果沒有 Salt,可能得到相同 Hash。
加入不同 Salt:
User A:
password123 + SaltA → HashA
User B:
password123 + SaltB → HashB
即使 Password 相同,結果也不同。
Salt 通常不需要像 Password 或 Encryption Key
一樣保密。它的目的主要是讓相同 Password 不會直接產生相同 Password
Hash,並提高預先計算攻擊的成本。
Attacker 可以預先計算大量常見 Password 與 Hash 的對照資料。
這類預先計算的 Hash Lookup 技術常和 Rainbow Table 有關。
Salt 讓不同 User 的 Hashing Input
不同,因此降低同一份預先計算資料直接套用到所有 User 的效果。
Password Hashing 不應只追求速度。
如果一秒能計算非常多 Password Guess,Attacker 也能更快猜 Password。
常見專門的 Password Hashing / Key Derivation Algorithm:
Argon2
bcrypt
scrypt
PBKDF2
它們的重要目的之一:
讓大量 Password Guessing 的計算成本提高。
Brute Force Attack:
不斷嘗試大量 Password,直到猜中。
Credential Stuffing:
使用其他 Data Leak 中取得的 Email / Password,去其他 Service
嘗試登入。
差別:
Brute Force
→ 猜 Password
Credential Stuffing
→ 拿已洩漏 Credential 到其他網站嘗試
Day 12 的 Rate Limiter 也能幫助 Login Security。
例如:
POST /login
如果允許:
1,000,000 attempts/min
Password Guessing 會更容易。
可以限制:
Per IP
Per Account
Per Device
但不能只依賴 IP,因為多人可能共享 IP,而 Attacker 也可能使用大量不同
IP。
Login 成功後,User 不希望每個 Page 都重新輸入 Password。
Session:
Server 保存的一段 Login State,用來記住某個 User 已通過
Authentication。
例如:
Session ID = abc123
Server Session Store:
abc123
→ userId = 123
→ role = CUSTOMER
State:
System 在某個時間點保存的資訊。
Session State 可能包含:
User ID
Login Status
Expiration Time
Session ID:
用來找到某個 Server-side Session 的識別碼。
Client 不需要一直傳 Password,只要帶著有效 Session ID。
Cookie:
Website 要求 Browser 保存的一小段資料,之後對符合條件的 Request
可以自動帶回 Server。
Login 後:
Set-Cookie:
session_id=abc123
之後 Browser:
Cookie:
session_id=abc123
Server 再用 Session ID 找 Session。
Session
→ Server-side Login State
Cookie
→ Browser 保存並傳送的一小段資料
常見:
Browser Cookie
contains Session ID
↓
Server uses ID
to find Session
所以 Cookie 可以攜帶 Session ID,但 Cookie 本身不等於 Session。
Token:
Client 通過 Authentication 後取得的一段
Credential,之後可以帶著它呼叫受保護 API。
例如:
GET /profile
Authorization:
Bearer <token>
Bearer Token:
誰持有有效 Token,通常就可以用它代表相對應的身分 / 權限呼叫 API。
所以 Token 必須被妥善保護。
JWT = JSON Web Token
它是一種 Token Format。
常見外觀:
xxxxx.yyyyy.zzzzz
主要部分:
Header
Payload
Signature
Claim:
Token 裡描述資訊的欄位。
例如:
{
"sub": "123",
"role": "CUSTOMER",
"exp": 1790000000
}
可能代表:
sub → Subject
role → Role
exp → Expiration Time
非常重要:
一般 JWT Payload 不一定有 Encryption。
很多 JWT 是:
Encoded
+
Signed
而不是:
Encrypted
所以不要把 Password 等 Secret 直接放進一般 JWT Payload。
Encoding:
把資料轉換成另一種表示格式,方便儲存或傳輸。
知道規則通常就可以還原。
所以:
Encoding ≠ Encryption
Encryption 的目的包含保護 Confidentiality;Encoding 通常不是為了保密。
Digital Signature:
使用密碼學方法產生可驗證的簽章,幫助接收方確認資料來源與完整性。
JWT 如果有人把:
role = USER
偷偷改成:
role = ADMIN
正確的 Signature Verification 應該失敗。
Browser
↓ Session ID
Server
↓
Session Store
Client
↓ Token
API
↓
Verify Token
Token-based 不代表整個 System 完全不需要
State。Logout、Revocation、Refresh Token 等設計仍可能需要 Server-side
State。
Stateless:
處理某次 Request 時,不依賴同一台 Server 保存前一次 Request 的特定
Client Session State。
例如:
Request #1 → Backend A
Request #2 → Backend B
如果 Request 本身帶足夠 Authentication Information,Backend B 不需要
Backend A 的 Local Session Memory。
但 Stateless 不代表:
整個 System 完全沒有 Database / Cache / State
Expiration:
超過某個時間後,Token 不再有效。
Access Token:
Client 用來存取受保護 API 的 Token。
通常有效時間有限。
Refresh Token:
用來取得新的 Access Token,而不是直接拿來呼叫一般 Business API。
概念:
Login
↓
Access Token + Refresh Token
Access Token expires
↓
Use Refresh Token
↓
New Access Token
Refresh Token 通常需要更謹慎保護。
Revocation:
在 Credential 原本到期之前,主動讓它失效。
例如:
Phone stolen
↓
Revoke Refresh Token
這也是為什麼 Authentication Design 不只是「產生 JWT 就完成」。
HTTPS = HTTP Secure
可以簡單理解:
HTTP
+
TLS
=
HTTPS
TLS = Transport Layer Security
用來保護 Network Communication 的 Security Protocol。
TLS 主要幫助:
Confidentiality
→ 別人不容易直接看到內容
Integrity
→ 內容不應被偷偷修改而不被發現
Authentication
→ Client 可以驗證 Server Identity
Protocol:
兩個 System Communication 時共同遵守的一組規則。
例如:
HTTP
TCP
TLS
都是 Protocol。
Browser 連到:
https://example.com
需要確認自己真的連到 example.com。
TLS Certificate:
把 Domain / Identity 與 Public Key 等資訊建立可驗證關係的數位憑證。
CA = Certificate Authority
受信任、負責簽發或驗證 Digital Certificate 的機構。
簡化:
Trusted CA
↓
Certificate
↓
example.com
↓
Browser verifies
在 **Asymmetric Cryptography(非對稱密碼學)**中有:
Public Key
Private Key
Public Key:
可以公開。
Private Key:
必須保密。
它們可以用於不同 Cryptographic Operations,例如 Digital
Signature、Encryption 或 Key Exchange。
最重要先記:
Private Key 不應公開。
Symmetric Encryption:
Encryption 與 Decryption 使用同一個 Secret Key。
通常速度快,但雙方需要安全取得同一個 Secret。
Asymmetric Cryptography:
使用 Public Key 與 Private Key 這對不同但有數學關係的 Keys。
TLS 實際上會組合多種 Cryptographic Techniques,不是簡單只使用其中一種。
Encryption in Transit:
保護 Data 在 Network 傳輸中的內容。
例如:
Browser
↓ HTTPS/TLS
Server
Encryption at Rest:
保護 Data 儲存在 Storage 時的內容。
例如:
Database
Disk
Object Storage
Backup
簡單記:
In Transit → 傳輸中
At Rest → 儲存中
常縮寫:
MITM
Man-in-the-Middle Attack:
Attacker 位於 Client 與 Server Communication
中間,嘗試偷看、攔截或修改資料。
概念:
Client
↓
Attacker
↓
Server
TLS 的目的之一就是降低這類風險。
假設程式直接把 User Input 拼進 SQL。
Attacker 可能輸入特殊內容,讓原本應該只是 Data 的 Input 變成 SQL Command
的一部分。
這叫:
SQL Injection
Injection 就是「注入」。
避免 SQL Injection 的重要方法之一:
Parameterized Query
SQL Structure 和 User Data 分開。
例如:
SELECT *
FROM users
WHERE username = ?;
User Input 以 Parameter 傳入,而不是直接拼進 SQL String。
Input Validation:
檢查 User Input 是否符合預期格式、範圍與規則。
例如:
Age → 0 ~ 150
File → Allowed Type / Size
Email → Expected Format
但 Input Validation 不能取代 Parameterized Query。不同 Security Controls
解決不同問題。
XSS = Cross-Site Scripting
Attacker 想辦法讓惡意 Script 在其他 User 的 Browser 裡執行。
例如 Website 顯示 User Comment,如果不安全地把內容當 HTML / Script
執行,就可能產生 XSS Risk。
Output Encoding:
把不可信 Data 放進 HTML 等輸出環境時,正確處理特殊字元,讓它被當作
Data 顯示,而不是 Code 執行。
例如:
<script>
應該安全顯示成文字,而不是直接執行。
CSRF = Cross-Site Request Forgery
Forgery = 偽造。
假設 User 已登入 bank.com,Browser 有 Login Cookie。
User 打開惡意 Website,惡意頁面誘導 Browser 對:
bank.com/transfer
送 Request。
如果 Browser 自動附上 Cookie,而 Server 沒有足夠防護,就可能把它當成
User 的合法操作。
CSRF Token:
重要 Request 除了 Authentication Cookie 外,還需要一個其他 Site
不容易取得的 Token。
例如:
Transfer Request
↓
Session Cookie
+
CSRF Token
Server 驗證後再接受。
SameSite:
控制 Cross-Site Request 時 Cookie 是否被帶上,可降低某些 CSRF Risk。
常見設定有:
Strict
Lax
None
HttpOnly:
限制 Browser-side JavaScript 直接讀取 Cookie。
可以降低某些 XSS 情境直接偷 Session Cookie 的風險,但不是完整 XSS 解法。
Secure:
Browser 只應透過 HTTPS 傳送 Cookie。
Authentication Cookie 常會考慮:
Secure
HttpOnly
SameSite
CORS = Cross-Origin Resource Sharing
先理解 Origin:
Scheme + Host + Port
例如:
https://example.com:443
CORS:
Browser 用來控制某個 Origin 的 Web Page 是否能透過 Browser Script
讀取另一個 Origin 的 Response。
例如:
frontend.com
↓ JavaScript
api.example.com
API 可以透過 CORS Policy 告訴 Browser 哪些 Origins 可以讀 Response。
非常重要:
CORS ≠ Authentication
API 設定 CORS 不代表 API 已經安全。
非 Browser Client 也不一定受到 Browser CORS Enforcement。
真正 API Security 仍需要:
Authentication
Authorization
Input Validation
Rate Limiting
DDoS = Distributed Denial of Service
Distributed
→ 大量不同來源
Denial of Service
→ 讓正常 User 無法使用 Service
例如大量 Machines 同時送 Millions of Requests,消耗:
Bandwidth
CPU
Connections
Rate Limiting 可以控制某個:
User
IP
API Key
的 Request Rate。
但大型 DDoS 可能來自大量不同 IP 與巨大 Network Traffic。
所以:
Rate Limiting 是防護的一部分,但不是完整 DDoS Solution。
還可能使用:
CDN
WAF
DDoS Protection
Network-level Protection
WAF = Web Application Firewall
Firewall:
根據 Security Rules 決定哪些 Traffic 可以通過。
WAF:
放在 Web Application 前面,分析 HTTP / HTTPS
Requests,協助阻擋某些惡意 Traffic。
User
↓
CDN / WAF
↓
API Gateway
↓
Backend
WAF 也不是萬能,而是 Defense in Depth 的其中一層。
Secret:
必須保密的 Credential / Key。
例如:
Database Password
API Key
Private Key
Encryption Key
不要直接 Hard-code Secret 到 Source Code。
Secret Management:
安全保存、提供、更新與控制 Secret Access 的方法。
Security 裡的 Rotation:
定期或必要時更換 Credential / Key。
例如:
Old API Key
↓
Create New Key
↓
Update Services
↓
Disable Old Key
如果 Secret 曾洩漏,Rotation 可以讓舊 Secret 失效。
Audit Log:
專門記錄「誰在什麼時間做了什麼重要 Action」。
例如:
adminUser=123
action=DELETE_USER
targetUser=999
Accountability:
能夠追蹤某個重要 Action 是誰執行,讓行為可以被追查。
Audit Log 可以回答:
誰做的?
什麼時候?
對什麼資料做了什麼?
Defense in Depth:
不依賴單一 Security Control,而是建立多層防護。
例如 Login:
HTTPS
↓
Rate Limiter
↓
Password Verification
↓
MFA
↓
Session Security
↓
Authorization
↓
Audit Log
即使一層失敗,其他 Layer 仍可能提供保護。
Security Control:
用來降低 Security Risk 的技術、規則或流程。
例如:
MFA
Rate Limiting
Encryption
Authorization
Audit Logging
WAF
Least Privilege
Risk:
Threat 利用 Vulnerability 後造成 Damage 的可能性與影響。
簡化思考:
Risk ≈ Likelihood × Impact
Likelihood:
發生的可能性。
Impact:
發生後造成的影響程度。
所以 Security Design 不是每個地方都做到最複雜,而是根據 Risk 選擇合理
Controls。
Data Sensitivity:
Data 被未授權讀取或修改後,可能造成多大的 Security / Business Impact。
例如:
Public Product Name
和:
Password
Credit Card Data
Private Personal Data
Security Requirement 明顯不同。
User
↓
HTTPS / TLS
↓
CDN / WAF
↓
API Gateway
↓
Rate Limiter
↓
Authentication
↓
Authorization
↓
Load Balancer
/ \
↓ ↓
Backend #1 Backend #2
\ /
\ /
Database
↓
Encryption at Rest
另外:
Passwords
→ Password Hashing + Salt
Secrets
→ Secret Management
Important Actions
→ Audit Logs
Sensitive Login
→ MFA when appropriate
User
↓
HTTPS
↓
POST /login
↓
Rate Limiter
↓
Find User
↓
Verify Password Hash
↓
MFA if required
↓
Authentication Success
↓
Create Session / Issue Token
↓
Return Credential
之後:
GET /orders/123
↓
Authentication
「你是誰?」
↓
Authorization
「你可以看 Order 123 嗎?」
↓
Business Logic
↓
Response
可以回答:
Authentication
→ Verify Identity
→ 你是誰?
Authorization
→ Verify Permission
→ 你可以做什麼?
例如:
Login with Password
→ Authentication
Check /admin permission
→ Authorization
不要回答:
Encrypt Password and store it
更好的方向:
Password
↓
Password Hashing Algorithm
+
Unique Salt
↓
Store Password Hash
例如:
Argon2
bcrypt
scrypt
PBKDF2
Login 時 Verify Password,而不是解密 Password。
不是。
一般 JWT:
Header
Payload
Signature
Payload 常可以 Decode。
Signature 主要幫助驗證:
Integrity
Authenticity
不是用來隱藏 Payload。
所以:
JWT 不等於 Encryption。
Session
→ Server-side State
Cookie
→ Browser 保存的一小段資料
常見:
Cookie contains Session ID
↓
Server uses ID
↓
Find Session
可以從:
Parameterized Query
Input Validation
Least Privilege DB Account
Safe ORM / DB APIs
回答。
核心是不要直接:
SQL String + User Input
拼接。
可以分 Layer:
1. HTTPS
2. Authentication
3. Authorization
4. Input Validation
5. Rate Limiting
6. Secret Management
7. Logging / Audit
8. Least Privilege
敏感 Operation 如 Payment、Admin Action、Password Change,可能還需要
MFA、Re-authentication 或其他 Risk-based Controls。
Security Controls 也可能增加:
User Friction
Latency
Engineering Complexity
Infrastructure Cost
Operational Cost
例如每次點擊都要求 MFA:
Security ↑
User Experience ↓
所以仍然是:
Understand Risk
↓
Choose Appropriate Controls
↓
Understand Trade-off
1. Security 是什麼?
2. CIA Triad?
3. Confidentiality / Integrity / Availability?
4. Threat / Vulnerability / Exploit?
5. Attack Surface?
6. Authentication?
7. Identity / Credential?
8. Authentication Factor?
9. MFA / 2FA?
10. Authorization?
11. Authentication vs Authorization?
12. Permission / Role / RBAC?
13. Access Control?
14. Least Privilege?
15. Plaintext Password?
16. Hashing?
17. Hashing vs Encryption?
18. Encryption / Decryption / Key?
19. Salt?
20. Rainbow Table?
21. Password Hashing Algorithm?
22. Brute Force?
23. Credential Stuffing?
24. Rate Limiting 如何保護 Login?
25. Session / State / Session ID?
26. Cookie?
27. Cookie vs Session?
28. Token / Bearer Token?
29. JWT?
30. Claim?
31. JWT Payload 是否一定加密?
32. Encoding vs Encryption?
33. Digital Signature?
34. Session vs Token?
35. Stateless?
36. Token Expiration?
37. Access Token / Refresh Token?
38. Revocation?
39. HTTPS / TLS?
40. Protocol?
41. TLS Certificate?
42. CA?
43. Public Key / Private Key?
44. Symmetric vs Asymmetric Cryptography?
45. Encryption in Transit vs at Rest?
46. MITM?
47. SQL Injection?
48. Parameterized Query?
49. Input Validation?
50. XSS?
51. Output Encoding?
52. CSRF / CSRF Token?
53. SameSite / HttpOnly / Secure Cookie?
54. CORS?
55. CORS 為什麼不是 Authentication?
56. DDoS?
57. DDoS vs Rate Limiting?
58. WAF?
59. Secret / Secret Management?
60. Rotation?
61. Audit Log / Accountability?
62. Defense in Depth?
63. Security Control?
64. Risk / Likelihood / Impact?
65. Data Sensitivity?
66. Login Flow 怎麼設計?
67. API Security 要考慮哪些 Layer?
第一組:
Authentication
→ 你是誰?
Authorization
→ 你可以做什麼?
第二組:
Hashing
→ 通常不是為了還原
→ 常用於 Password Storage
Encryption
→ 使用 Key 保護 Data
→ 授權方之後可以 Decrypt
第三組:
Session
→ Server-side Login State
Cookie
→ Browser 保存並傳回的小資料
Token
→ Client 帶著呼叫受保護 API 的 Credential
Network:
HTTPS = HTTP over TLS
Application Security:
SQL Injection
XSS
CSRF
Credential Stuffing
Brute Force
都需要不同的 Security Controls。
真正的 Security Architecture 常使用:
Defense in Depth
Security 不是 System 做完後才加上的功能,而是從
Data、API、Identity、Network 到 Infrastructure 都需要一起考慮的 Design
Requirement。
現在 System 已經逐步具備:
Scalability
Reliability
Observability
Security
接下來進入 System Design Interview 時,不應一看到題目就開始畫:
Load Balancer
Redis
Kafka
Database
第一件事應該是:
先搞清楚到底要設計什麼。
下一篇:
Day 18|System Design Interview
Process:拿到題目後,到底應該先問什麼?
會從零解釋:
Requirement
Functional Requirement
Non-Functional Requirement
Constraint
Scope
Assumption
Capacity
Traffic
Read/Write Ratio
Latency Requirement
Availability Requirement
Consistency Requirement
API Design
Data Model
High-Level Design
Bottleneck
Trade-off
並用完整的小型 System Design Interview Example 把思考流程串起來。