NODE / BACKEND CORE · 105
Validation / Error Handling / Authentication / Authorization:Server 的 Trust Boundary
Browser 可以被修改、request 可以被手工偽造,所以 client validation 只是 UX。Server 必須把 method、params、body、identity 都當不可信 input,重新驗證。
Learning outcomes
- 能區分 validation、authentication、authorization。
- 能建立 consistent error model。
- 能解釋 client hidden button 為什麼不是 security。
- 能避免把 internal stack / secret 洩漏給 client。
1. Validation:資料是否合法
function parseCourseBody(
body
) {
const title =
body?.title;
if (
typeof title !== "string"
|| !title.trim()
) {
return {
ok: false,
error:
"invalid title"
};
}
return {
ok: true,
data: {
title:
title.trim()
}
};
}Validation boundary 應產生明確 typed/normalized data,而不是只檢查完又繼續用原始 body。
2. Authentication:你是誰?
async function requireUser(
req,
res,
next
) {
const credential =
readCredential(req);
const user =
await verifyCredential(
credential
);
if (!user) {
return res
.status(401)
.json({
error:
"unauthenticated"
});
}
req.user = user;
next();
}3. Authorization:你能做這件事嗎?
if (
course.ownerId
!== req.user.id
&& req.user.role
!== "admin"
) {
return res
.status(403)
.json({
error:
"forbidden"
});
}
401
沒有有效 identity / authentication。
403
知道你是誰,但你沒有這項 permission。
4. Error taxonomy
| 類型 | 例子 | 可能 status |
|---|---|---|
| Client input | title 缺失 | 400 |
| Unauthenticated | credential 無效 | 401 |
| Forbidden | 別人的 private resource | 403 |
| Not found | course id 不存在 | 404 |
| Conflict | unique constraint | 409 |
| Unexpected server | DB unavailable | 500 |
5. Central error boundary
function errorHandler(
error,
req,
res,
next
) {
console.error({
requestId: req.id,
error
});
res
.status(500)
.json({
error:
"internal_error",
requestId: req.id
});
}Production response 不應把 raw stack、DB credential、SQL query 全部回給 client。
Project checkpoint:Course API v5
POST /courses
↓ express.json
↓ requireUser
↓ validate body
↓ authorize create
↓ service
↓ response 201現在 route 已經有 trust boundary;下一課再把 business rule 與 database responsibility 分開。
Debug evidence:Browser 顯示 403
先確認:
- 401 還是 403?
- server verified user id 是誰?
- resource owner / policy 是什麼?
- 是 application authorization 還是 DB RLS 拒絕?
Knowledge check
- client-side required attribute 能不能當 server security?
- 401 與 403 的語意差異?
- 為何 validation 後最好產生 normalized data?
- 設計一個 consistent error response format。