← Node / Backend Course

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

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 inputtitle 缺失400
Unauthenticatedcredential 無效401
Forbidden別人的 private resource403
Not foundcourse id 不存在404
Conflictunique constraint409
Unexpected serverDB unavailable500

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

先確認:

  1. 401 還是 403?
  2. server verified user id 是誰?
  3. resource owner / policy 是什麼?
  4. 是 application authorization 還是 DB RLS 拒絕?

Knowledge check

  1. client-side required attribute 能不能當 server security?
  2. 401 與 403 的語意差異?
  3. 為何 validation 後最好產生 normalized data?
  4. 設計一個 consistent error response format。