enforce-reauth-on-login: request max_age=0 and reject logins whose auth_time predates the login click
CI / build (push) Successful in 4m43s
CI / build (push) Successful in 4m43s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d546f1c31f
commit
c8a67fa7ec
@@ -44,7 +44,11 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
|
||||
|
||||
## Authentication & authorization
|
||||
|
||||
- Login is company Authentik OIDC only (`AUTH_MODE=oidc`, default), with `prompt=login` (always re-enter credentials) and local-only logout (doesn't sign out of other company systems) — both user decisions. The vibe platform injects `OIDC_ISSUER` / `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` (reserved names — never put them in the repo); `APP_URL` builds the redirect URI `${APP_URL}/api/auth/callback/authentik`. No passwords anywhere.
|
||||
- Login is company Authentik OIDC only (`AUTH_MODE=oidc`, default), with forced re-authentication (always re-enter credentials) and local-only logout (doesn't sign out of other company systems) — both user decisions.
|
||||
- Re-authentication is guaranteed by three things together: `prompt=login` + `max_age=0` on the authorization request, and the callback checking the ID token's `auth_time`.
|
||||
- `auth_time` must not be earlier than the moment the user clicked login (`issuedAt` in the login transaction cookie), with `REAUTH_CLOCK_SKEW_MS` = 60 s allowed.
|
||||
- If it is missing or too early, the login is rejected as `reauth_required` (「未重新驗證」): no account, no session, no HR Sync.
|
||||
- Never send the user to Authentik `end_session`, because that would sign them out of every company system. The vibe platform injects `OIDC_ISSUER` / `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` (reserved names — never put them in the repo); `APP_URL` builds the redirect URI `${APP_URL}/api/auth/callback/authentik`. No passwords anywhere.
|
||||
- `AUTH_MODE=dev` enables `/login/dev` (log in by employee number) for local dev and e2e. Startup refuses `AUTH_MODE=dev` when `OIDC_ISSUER` is present; in `oidc` mode `/login/dev` and its action return 404. Never key behavior off `NODE_ENV` for this.
|
||||
- Accounts are created on first login by `provisionOnLogin` (`src/server/auth/provision.ts`): employee role, department pending until a sysadmin assigns one or a roster CSV pre-assigns it. `BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS` grants sysadmin on login.
|
||||
- **Every page** must start with `await requireRouteAccess("<route pattern>")` (`src/server/auth/current-user.ts`); the pattern must exist in `ROUTE_RULES` (`src/lib/access.ts`) — unlisted routes are denied, and the sidebar (`buildNavigation`) is generated from the same table. Don't rely on a shared layout for the check (layouts don't re-run on client navigation). `src/proxy.ts` only redirects requests without a session cookie.
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
## 1. 請求重新驗證
|
||||
|
||||
- [ ] 1.1 `startOidcLogin` 的授權網址在 `prompt=login` 之外加 `max_age=0`,更新註解;`oidc.test.ts` 斷言授權網址同時帶 `prompt=login` 與 `max_age=0`(`npx vitest run src/server/auth/oidc.test.ts`)
|
||||
- [x] 1.1 `startOidcLogin` 的授權網址在 `prompt=login` 之外加 `max_age=0`,更新註解;`oidc.test.ts` 斷言授權網址同時帶 `prompt=login` 與 `max_age=0`(`npx vitest run src/server/auth/oidc.test.ts`)
|
||||
|
||||
## 2. 驗證 auth_time
|
||||
|
||||
- [ ] 2.1 `startMockOidcProvider` 的 ID token 支援 `auth_time`(預設為簽發當下,可由測試覆寫或省略),既有 OIDC 測試維持通過
|
||||
- [ ] 2.2 `provision.ts` 新增拒絕原因 `reauth_required`(`LOGIN_REJECT_REASONS`:「未重新驗證」);登入頁 `ERROR_MESSAGES.reauth_required` 為「公司登入沒有重新要求帳號密碼,請再登入一次;持續發生請洽系統管理員。」
|
||||
- [ ] 2.3 `completeOidcLogin` 在 ID token 驗證成功後、HR Sync 與 `provisionOnLogin` 之前檢查 `auth_time`:缺少或 `auth_time * 1000 < issuedAt - 60 秒` 即回傳 `reauth_required`,記 `auth.login_rejected`(員工編號取自 ID token),不建帳號、不建 session、不呼叫 HR Sync;callback route 導向 `/login?error=reauth_required`。測試:缺少 `auth_time`、早於按下登入、剛好在 60 秒誤差內、正常四種情況,以及首次登入者被拒時沒有建立帳號
|
||||
- [ ] 2.4 更新 `src/app/api/auth/logout/route.ts` 註解與 CLAUDE.md〈Authentication & authorization〉:重新驗證由 `prompt=login` + `max_age=0` + `auth_time` 檢查保證,登出仍只結束本系統 session
|
||||
- [x] 2.1 `startMockOidcProvider` 的 ID token 支援 `auth_time`(預設為簽發當下,可由測試覆寫或省略),既有 OIDC 測試維持通過
|
||||
- [x] 2.2 `provision.ts` 新增拒絕原因 `reauth_required`(`LOGIN_REJECT_REASONS`:「未重新驗證」);登入頁 `ERROR_MESSAGES.reauth_required` 為「公司登入沒有重新要求帳號密碼,請再登入一次;持續發生請洽系統管理員。」
|
||||
- [x] 2.3 `completeOidcLogin` 在 ID token 驗證成功後、HR Sync 與 `provisionOnLogin` 之前檢查 `auth_time`:缺少或 `auth_time * 1000 < issuedAt - 60 秒` 即回傳 `reauth_required`,記 `auth.login_rejected`(員工編號取自 ID token),不建帳號、不建 session、不呼叫 HR Sync;callback route 導向 `/login?error=reauth_required`。測試:缺少 `auth_time`、早於按下登入、剛好在 60 秒誤差內、正常四種情況,以及首次登入者被拒時沒有建立帳號
|
||||
- [x] 2.4 更新 `src/app/api/auth/logout/route.ts` 註解與 CLAUDE.md〈Authentication & authorization〉:重新驗證由 `prompt=login` + `max_age=0` + `auth_time` 檢查保證,登出仍只結束本系統 session
|
||||
|
||||
## 3. 驗證與上線閘門
|
||||
|
||||
- [ ] 3.1 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `npm run test:e2e` 全過(開發登入不受影響)
|
||||
- [ ] 3.2 部署前手動確認(design 決策 4):由正式站 `/api/auth/login` 產生授權網址並加 `&max_age=0`,請使用者在已登入 Authentik 的瀏覽器開啟,回報是否出現帳密輸入。出現才繼續;沒出現則暫停本 change,回報並整理給平台組的說明
|
||||
- [x] 3.1 `npm run lint`、`npm run format:check`、`npm run typecheck`、`npm test` 全過;`npm run test:e2e:prepare` 後 `npm run test:e2e` 全過(開發登入不受影響)
|
||||
- [x] 3.2 部署前手動確認(design 決策 4):由正式站 `/api/auth/login` 產生授權網址並加 `&max_age=0`,請使用者在已登入 Authentik 的瀏覽器開啟,回報是否出現帳密輸入。出現才繼續;沒出現則暫停本 change,回報並整理給平台組的說明(2026-10-14 使用者實測:已登入狀態開帶 `max_age=0` 的授權網址,Authentik 要求輸入帳密,通過)
|
||||
- [ ] 3.3 使用者授權後 push 部署,查部署結果;使用者以公司帳號驗收:登入成功、登出後再登入要求輸入帳密、其他公司系統仍維持登入。失敗(例如所有人被擋為「未重新驗證」)立即 revert 重新部署
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
@@ -7,7 +7,8 @@ import { getEnv } from "@/server/env";
|
||||
|
||||
/**
|
||||
* 登出:只結束本系統的 session,不登出 Authentik(使用者決定)。
|
||||
* 因為每次登入都帶 prompt=login,下次按登入仍須重新輸入帳密。
|
||||
* 下次按登入仍須重新輸入帳密:授權請求帶 prompt=login 與 max_age=0,callback 再以 ID token 的
|
||||
* auth_time 確認真的重新驗證過(沒有就拒絕登入)。
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const env = getEnv();
|
||||
|
||||
@@ -9,6 +9,7 @@ const ERROR_MESSAGES: Record<string, string> = {
|
||||
failed: "登入失敗,請重新登入。",
|
||||
missing_employee_number: "無法取得員工編號,請洽系統管理員。",
|
||||
inactive: "帳號已停用,請洽人資。",
|
||||
reauth_required: "公司登入沒有重新要求帳號密碼,請再登入一次;持續發生請洽系統管理員。",
|
||||
not_configured: "公司登入尚未設定,目前無法登入,請洽系統管理員。",
|
||||
};
|
||||
|
||||
|
||||
@@ -79,6 +79,36 @@ describe("公司登入(OIDC)", () => {
|
||||
expect(start.url.searchParams.get("redirect_uri")).toBe(redirectUri);
|
||||
// 每次登入都要求重新輸入帳密
|
||||
expect(start.url.searchParams.get("prompt")).toBe("login");
|
||||
expect(start.url.searchParams.get("max_age")).toBe("0");
|
||||
});
|
||||
|
||||
describe("確認重新驗證(auth_time)", () => {
|
||||
const seconds = (offsetMs: number) => Math.floor((Date.now() + offsetMs) / 1000);
|
||||
|
||||
it("ID token 沒有 auth_time:拒絕,不建立帳號,記錄「未重新驗證」", async () => {
|
||||
const { result } = await login({ employee_number: "E1234", auth_time: undefined });
|
||||
expect(result).toMatchObject({ ok: false, error: "reauth_required", employeeNo: "E1234" });
|
||||
expect(t.db.select().from(users).all()).toHaveLength(0);
|
||||
expect(expectAudit(t.db, "auth.login_rejected")).toMatchObject({
|
||||
comment: "未重新驗證",
|
||||
after: { employeeNo: "E1234", method: "oidc" },
|
||||
});
|
||||
});
|
||||
|
||||
it("驗證時間早於按下登入(Authentik 沿用先前的登入):拒絕", async () => {
|
||||
const { result } = await login({ employee_number: "E1234", auth_time: seconds(-120_000) });
|
||||
expect(result).toMatchObject({ ok: false, error: "reauth_required" });
|
||||
});
|
||||
|
||||
it("在 60 秒時鐘誤差內:通過", async () => {
|
||||
const { result } = await login({ employee_number: "E1234", auth_time: seconds(-55_000) });
|
||||
expect(result).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("按下登入之後才驗證:通過", async () => {
|
||||
const { result } = await login({ employee_number: "E1234", auth_time: seconds(5_000) });
|
||||
expect(result).toMatchObject({ ok: true, created: true });
|
||||
});
|
||||
});
|
||||
|
||||
it("成功登入:建立帳號與有效 session,導向原本要去的頁面", async () => {
|
||||
@@ -270,5 +300,15 @@ describe("公司登入(OIDC)", () => {
|
||||
expect(result).toMatchObject({ ok: false, error: "inactive" });
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("未重新驗證時不呼叫 HR Sync", async () => {
|
||||
const { result } = await login(
|
||||
{ employee_number: "E1234", auth_time: undefined },
|
||||
{},
|
||||
hrSync(designSnapshot),
|
||||
);
|
||||
expect(result).toMatchObject({ ok: false, error: "reauth_required" });
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,6 +23,8 @@ export const OIDC_CALLBACK_PATH = "/api/auth/callback/authentik";
|
||||
/** 登入進行中的暫存 cookie(state、nonce、PKCE、導向位置),10 分鐘內有效。 */
|
||||
export const OIDC_TX_COOKIE = "aisubsidy_oidc_tx";
|
||||
export const OIDC_TX_MAX_AGE_SECONDS = 600;
|
||||
/** `auth_time` 與按下登入時間(本系統與 Authentik 主機)的時鐘誤差容許值。 */
|
||||
export const REAUTH_CLOCK_SKEW_MS = 60_000;
|
||||
|
||||
interface OidcTransaction {
|
||||
state: string;
|
||||
@@ -85,7 +87,10 @@ export async function startOidcLogin(
|
||||
state: tx.state,
|
||||
nonce: tx.nonce,
|
||||
// 每次登入都要求在 Authentik 重新輸入帳密(使用者決定),不沿用公司其他系統的登入狀態。
|
||||
// prompt=login 單獨不可靠(2026-10-13 實測登出後再登入沒有要求帳密),再加 max_age=0;
|
||||
// 帶 max_age 時 ID token 必須含 auth_time,callback 以它確認真的重新驗證過。
|
||||
prompt: "login",
|
||||
max_age: "0",
|
||||
});
|
||||
return { url, txCookie: signValue(tx, secret) };
|
||||
}
|
||||
@@ -115,6 +120,8 @@ export interface HrSyncOnLogin {
|
||||
/**
|
||||
* 處理 callback:驗證暫存 cookie、state、nonce、PKCE 與 ID token(由 openid-client 負責),
|
||||
* 再以 ID token 的 claims 呼叫 `provisionOnLogin`。任何驗證失敗都回傳 `failed`,不建立帳號。
|
||||
* ID token 的 `auth_time` 缺少或早於按下登入的時間(Authentik 沿用了先前的登入)時回傳
|
||||
* `reauth_required`:不建立帳號與 session、不呼叫 HR Sync。
|
||||
*
|
||||
* 提供 `hrSync` 時,在建立帳號前(交易外)向 HR Sync 取得快照,帳號建立或更新後、建立 session 前
|
||||
* 於同一交易的 savepoint 內套用;HR 姓名優先於 ID token 的姓名。HR 同步的任何失敗都不影響登入,
|
||||
@@ -168,6 +175,10 @@ export async function completeOidcLogin(
|
||||
}
|
||||
|
||||
const employeeNo = stringClaim(claims?.employee_number)?.trim() || null;
|
||||
if (!reauthenticated(claims, tx.issuedAt)) {
|
||||
recordLoginRejected(db, { employeeNo, reason: "reauth_required", method: "oidc", ip, now });
|
||||
return { ok: false, error: "reauth_required", employeeNo };
|
||||
}
|
||||
const today = hrSync ? localDate(now, hrSync.timeZone) : "";
|
||||
// 員工編號一律取自已驗證的 ID token;停用帳號會被拒絕,不需要查 HR。
|
||||
const snapshot: HrSnapshot | undefined =
|
||||
@@ -216,6 +227,12 @@ export async function completeOidcLogin(
|
||||
};
|
||||
}
|
||||
|
||||
/** 是否在按下登入之後才在 Authentik 完成驗證(`auth_time` 為秒;容許少量時鐘誤差)。 */
|
||||
function reauthenticated(claims: client.IDToken | undefined, issuedAt: number): boolean {
|
||||
const authTime = claims?.auth_time;
|
||||
return typeof authTime === "number" && authTime * 1000 >= issuedAt - REAUTH_CLOCK_SKEW_MS;
|
||||
}
|
||||
|
||||
function isDeactivated(db: Db, employeeNo: string): boolean {
|
||||
return (
|
||||
db
|
||||
|
||||
@@ -12,17 +12,23 @@ export interface LoginClaims {
|
||||
email?: string | null;
|
||||
}
|
||||
|
||||
export type LoginRejectReason = "missing_employee_number" | "inactive" | "failed";
|
||||
export type LoginRejectReason =
|
||||
"missing_employee_number" | "inactive" | "failed" | "reauth_required";
|
||||
|
||||
export const LOGIN_REJECT_REASONS: Record<LoginRejectReason, string> = {
|
||||
missing_employee_number: "缺少員工編號",
|
||||
inactive: "帳號已停用",
|
||||
failed: "公司登入驗證失敗",
|
||||
reauth_required: "未重新驗證",
|
||||
};
|
||||
|
||||
export type ProvisionResult =
|
||||
| { ok: true; userId: number; created: boolean; sessionToken: string }
|
||||
| { ok: false; reason: Exclude<LoginRejectReason, "failed">; employeeNo: string | null };
|
||||
| {
|
||||
ok: false;
|
||||
reason: Exclude<LoginRejectReason, "failed" | "reauth_required">;
|
||||
employeeNo: string | null;
|
||||
};
|
||||
|
||||
export interface ProvisionOptions {
|
||||
/** 登入時自動授予系統管理員角色的員工編號(BOOTSTRAP_SYSADMIN_EMPLOYEE_NOS)。 */
|
||||
|
||||
@@ -72,6 +72,8 @@ export async function startMockOidcProvider(clientId: string) {
|
||||
iat: now,
|
||||
exp: now + 300,
|
||||
nonce: pending.nonce,
|
||||
// 實際驗證時間:預設為簽發當下;測試可覆寫,或給 undefined 省略。
|
||||
auth_time: now,
|
||||
...pending.claims,
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user