devHọc Dev

Week 2 - Day 7: Step-up/MFA, operator and mock login, spec-writing skills

Week 2 – Day 7

This lesson combines 3 topics: Step-up authentication and MFA, Operator mode, mock login and how to spec a "test backdoor", Spec-writing skills and a security review checklist.

Learning Objectives

  • Understand step-up authentication: a user who is already logged in must authenticate again for a sensitive action
  • Design a dedicated set of IdP clients for step-up (passkey-only vs password, web vs native) and the rules for choosing a client
  • Use the context parameter to decide the scope and the deletion time of a child session
  • Distinguish the two kinds of child session: stepup:{id} (proof of authentication, fixed TTL) and stepup-mfa:{id} (holds a real access_token, TTL = expires_in)
  • Handle the special branches: temporary cookie sid_stepup, passkey cancel, callback to the native app via Universal Link, the mfa grant
  • Design an operator mode (support staff acting on behalf of a customer) without breaking the shared session model
  • Write specs for test-only endpoints (/auth/mock-session, /auth/mock-login) including environment conditions and behavior when disabled
  • Understand why a failed guard must return 404 instead of 401/403
  • Manage environment variables in a spec: name, per-environment value, source, prefix convention, and how to record naming decisions
  • Recognize the risk of a "test backdoor" leaking into production
  • Write an endpoint using a fixed table template: Overview → Method/Endpoint → Item table by location → branched Processing details → footnotes
  • List all error branches of a login endpoint and answer three questions (which session to delete, whether to set a cookie, which screen to go to) for each branch
  • Organize documentation: session data model, 1-to-1 matching sequence diagrams, separate common processes, an IdP client table with design rationale, an env var table
  • Maintain traceability spec ↔ ticket ↔ PR and handle cases where spec and code diverge
  • Use a 10-question checklist to review any new login flow

Part 1: Step-up authentication and MFA

1. Why authenticate again when already logged in?

A MemberPortal login session lives for 3 hours. During those 3 hours, if the user leaves their machine unattended, or the session is hijacked, someone else can do everything the session allows. For actions that are irreversible and involve money, ACME requires the user to prove again "it is still me, right now":

ActionWhy it is sensitivecontext
Withdraw money to a bank accountMoney leaves the systemcash-out
Change the receiving bank accountPrepares a withdrawal to the attacker's accountwithdrawal-account
Set up / remove MFA, change security methodsLowers the account's security long-termsecurity-setting

This is step-up authentication: raising the authentication assurance level for one specific action, not logging in again entirely.

Loginsession(sess:{id},3h)──────────────────────────────────────────▶││userclicks"Withdraw"▼Step-up:re-authenticatewithpasskeyorpasswordattheIdP│▼Childsessionstepup:{id}(600s)──▶allowscallingthewithdrawalAPIwithinashortwindow

The difference from a normal login: the result of step-up does not replace SessionID2; it is a short-lived child session attached to it, meaningful only within one context.

2. A dedicated set of IdP clients for step-up

If you reuse the portal-web client for step-up, the IdP sees that the user already has a session and lets them through without asking anything. So step-up uses dedicated clients, with their own connections and mandatory re-authentication.

ClientChannelMethodConnectiongrant_typeNotes
stepup-passkey-webWebPasskey onlyPasskey-Loginauthorization_codePassword entry not allowed
stepup-password-webWebPassword (+ MFA if set up)Stepup-Passwordauthorization_code + mfaUsed when there is no passkey or the passkey was cancelled
stepup-passkey-nativeAppPasskey onlyPasskey-Loginauthorization_codeCallback via Universal Link
stepup-password-nativeAppPassword (+ MFA)Stepup-Passwordauthorization_code + mfaCallback via Universal Link

Why separate passkey-only and password?

  • Security: if the user logged in with a passkey (usedPasskey = true in SessionID2), allowing a fallback to password during step-up lowers the assurance to the weakest level and makes the passkey pointless. A passkey-only client blocks that at the IdP.
  • Experience: the Passkey-Login connection goes straight to the passkey prompt, without showing a confusing password form.
  • Control: each client has its own redirect URI allow-list, permissions and Management API; separating clients keeps the permission matrix (Day 6, Part 2) clear.

Client selection rules

┌───────────────────────┐│PASSKEY_ENABLED?│└──────────┬────────────┘false│true┌───────────────┴───────────────┐▼▼client=stepup-password-*┌───────────────────────┐│sess.usedPasskey?│└──────────┬────────────┘false│true┌───────────────┴───────────────┐▼▼stepup-password-*stepup-passkey-*Suffix*:channel=Web→"-web";channel=App→"-native"
PASSKEY_ENABLEDusedPasskeychannelSelected client
falseanyWebstepup-password-web
falseanyAppstepup-password-native
truefalseWebstepup-password-web
truetrueWebstepup-passkey-web
truefalseAppstepup-password-native
truetrueAppstepup-passkey-native

usedPasskey is written to SessionID2 at login (from the id_token claim connection on the Web channel, or passkeyFlag from the verify API on the App channel). This is an example of a field that looks like it is "just for statistics" but later determines security behavior, so the session data model table must state its source clearly.

3. The context parameter: scope and deletion time

GET /auth/stepup/start?context=cash-out&successUrl=... is the entry point. context does two things:

3.1 Decides the scope and the kind of child session

contextPurposeNeeds a real access_token?BFF callback (redirect_uri)Child session createdScope requested from the IdP
cash-outProve authentication to call the withdrawal APINo/auth/stepup/callbackstepup:{id}openid
withdrawal-accountProve authentication to change the receiving accountNo/auth/stepup/callbackstepup:{id}openid
security-settingCall the Auth0 MFA API to set up/remove an authenticatorYes (token with MFA scope)/auth/stepup/mfa-callbackstepup-mfa:{id}openid enroll read:authenticators remove:authenticators + audience=https://<idp-domain>/mfa/

For the first two contexts, the access_token returned from /oauth/token is only proof that the IdP authenticated the user; the BFF does not use it to call any API, so it does not need to be stored. For security-setting, the BFF really needs an access_token with MFA scope to call /mfa/associate and /mfa/authenticators on behalf of the user, so it must store the token in the child session.

3.2 Decides when to delete the child session

contextDelete whenReason
cash-outTTL of 600s expires or as soon as the core system confirms the withdrawal orderOne authentication for one order; no "authenticate once, withdraw many times"
withdrawal-accountTTL of 600s expires or as soon as the account change succeedsSame as above
security-settingTTL = the access_token's expires_in expiresThe user needs several consecutive steps (list, add, remove authenticators); deleting early breaks the experience

The spec must state the deletion time per context, not a blanket "delete when TTL expires". This is a commonly under-specified area that leads to the "one step-up, many withdrawals" vulnerability.

4. Two kinds of child session

Criterionstepup:{id}stepup-mfa:{id}
RoleProof of "re-authenticated for context X"Holds the access_token so the BFF can call the MFA API
ContentsaccountNo, context, verifiedAt, parentSessionIdaccountNo, access_token, parentSessionId
TTLFixed STEPUP_SESSION_TTL = 600s= the access_token's expires_in (usually shorter than 600s)
Why this TTLNo token is bound to it; 600s is a window long enough to complete one orderOnce the token expires the session is meaningless; keeping it longer only keeps a dead token
Deleted early whenThe business action completes (withdrawal OK, account change OK)Not deleted early (multiple steps)
Used whereMiddleware checking before the withdrawal / account-change APIThe BFF's /auth/stepup/mfa/* endpoints
Does the token leave the server?No tokenaccess_token stays in Redis, never sent to the browser

Both store parentSessionId (SessionID2) to enforce binding: a child session is only valid together with the correct parent session. If the user logs out (SessionID2 is deleted), every child session must also be deleted or become invalid.

CheckbeforethewithdrawalAPI(/api/s/withdraw):1.SessionCheck(sid→sess:{id})+XsrfCheck←sharedwithevery/api/s/*2.Readstepup:{stepupId}fromtheheader/paramsentbytheUI├─missing/TTLexpired→401withadedicatederrorcode"STEPUP_REQUIRED"├─parentSessionId≠currentsessid→401STEPUP_REQUIRED├─context≠"cash-out"→401STEPUP_REQUIRED└─OK→proxytothecoresystem3.Coresystemconfirmstheorder→BFFdeletesstepup:{stepupId}

A dedicated error code lets the UI tell "step-up required" apart from "login session expired". Because the status is still 401, the UI interceptor must check bffErrCode before applying the generic 401 procedure (Day 2, Part 3 §3.1, Day 6, Part 1 §3): bffErrCode == STEPUP_REQUIRED → start the /auth/stepup/start?context=... flow, do not delete cookies, do not push the user to the login screen. Only other 401s follow the generic procedure. The UI spec must state this order; without it, a UI implemented to the letter of Day 2, Part 3 will log the user out as soon as they click withdraw.

5. Step-up flow on the Web

sequenceDiagram
    participant B as Browser
    participant BFF
    participant IdP as IdP (Auth0)
    B->>BFF: GET /auth/stepup/start?context=cash-out&successUrl=/withdraw
    Note over BFF: SessionCheck (sid) → sess<br/>Choose client by usedPasskey/PASSKEY_ENABLED/channel<br/>Generate state, nonce, code_verifier<br/>Store login:{id1} = { ..., context, purpose: "stepup", parentSessionId }
    BFF-->>B: 302 + Set-Cookie sid_stepup=id1 (HttpOnly)
    B->>IdP: GET /authorize?client_id=stepup-passkey-web&prompt=login&max_age=600<br/>&redirect_uri=https://portal.example.com/auth/stepup/callback&...
    Note over IdP: authenticate with passkey / password (+MFA)
    IdP-->>B: 302 /auth/stepup/callback?code=...&state=...<br/>(context cash-out / withdrawal-account)
    B->>BFF: GET /auth/stepup/callback?code=...&state=...
    Note over BFF: Read login:{id1} via sid_stepup, compare state<br/>context of login:{id1} must be a context this callback serves
    BFF->>IdP: POST /oauth/token (code, code_verifier)
    IdP-->>BFF: id_token, access_token, expires_in
    Note over BFF: Verify id_token: 7 checks + auth_time ≤ 600s (because of prompt=login&max_age)<br/>Claim account_no must == sess.accountNo ← binding to the parent session<br/>Create stepup:{id}, TTL 600s (do NOT store access_token)<br/>Delete login:{id1}, delete cookie sid_stepup
    BFF-->>B: 302 successUrl (+ stepupId via parameter or short-lived cookie)

With context = security-setting, the flow is identical except that redirect_uri is /auth/stepup/mfa-callback; that callback creates stepup-mfa:{id} with TTL = expires_in and stores the access_token (§8).

Four mandatory points:

  1. prompt=login&max_age=600 forces the IdP to re-authenticate even when an IdP session exists. max_age is what makes the IdP required to return the auth_time claim (OIDC Core: auth_time is only REQUIRED when max_age is present), so the verify step can check now - auth_time ≤ 600s (Day 3, Part 3). Without this check, the IdP may return an id_token from an old session and step-up becomes a formality.
  2. Binding to the parent session: account_no in the id_token must equal the accountNo of the current SessionID2. Without this step, an attacker holding the victim's session can step up with his own account and then withdraw the victim's money.
  3. The temporary cookie sid_stepup is separate from sid so the step-up login sequence does not overwrite or disturb the login session; it is deleted as soon as the callback finishes, just like SessionID1 in the login flow (Day 2, Part 1).
  4. Two separate callbacks, no branching on context inside one callback. redirect_uri is an allow-list at the IdP, bound to the client; separating /auth/stepup/callback (proof, no token stored) and /auth/stepup/mfa-callback (stores an access_token with the MFA audience) means: (a) a passkey-only client cannot register the MFA callback, so a token with permission to modify MFA never leaks into a flow that only needs proof; (b) each callback has one data model and one set of error branches, easy to spec and review; (c) a callback that "reads context from the session and then branches" forces the reviewer to prove every client × context combination is safe — the anti-pattern discussed in Day 4, Part 2.

6. Passkey cancel: switching clients midway

The user has a passkey but is on another machine without it, or clicks "Cancel" at the passkey prompt. With a passkey-only client, the IdP has no password form to fall back to. A common approach is to customize the IdP login page (Universal Login template or a custom action) so that when the user cancels the passkey, the IdP redirects to a fallback URL provided by the application — in this example stored in the metadata passkey_fallback_url. The metadata name is self-defined, not a standard OIDC feature.

IdP(clientstepup-passkey-web)──usercancelspasskey──▶302passkey_fallback_url│▼BFFGET/auth/stepup/passkey-cancel?state=...├─Readlogin:{id1}viasid_stepup,comparestate├─Switchclient→stepup-password-web├─Regeneratestate/nonce/code_verifier(doNOTreuse)├─Updatelogin:{id1}└─302/authorize?client_id=stepup-password-web&prompt=login&...

Why regenerate state/nonce/code_verifier? Because they were already sent for the first client; reusing them for the second client breaks the "single use" property of these bindings and makes incident investigation harder. The cost of regenerating is close to zero.

A decision the spec must record: is fallback to password allowed when usedPasskey = true? MemberPortal allows it, because refusing entirely would leave users who lost their passkey unable to withdraw. But this lowers the assurance level, so the spec states it explicitly and may add an email notification to the user.

On the App channel, the user is inside a WebView. The best passkey/password experience comes from opening the system browser (ASWebAuthenticationSession / Custom Tabs), not the WebView. Therefore:

sequenceDiagram
    participant W as WebView
    participant App
    participant SB as System browser
    participant BFF
    participant IdP
    W->>BFF: /auth/stepup/start (channel App, App session)
    Note over BFF: choose client stepup-*-native<br/>redirect_uri = BFF URL as usual
    BFF-->>W: 302 /authorize
    App->>SB: open the system browser at /authorize
    SB->>IdP: GET /authorize
    Note over IdP: IdP authenticates
    IdP-->>SB: 302 BFF /auth/stepup/callback
    SB->>BFF: GET /auth/stepup/callback
    Note over BFF: handle as on Web<br/>create stepup:{id}
    BFF-->>SB: 302 STEPUP_COMPLETE_URL?stepupId=...
    SB->>App: Universal Link / custom scheme → reopen the app
    App->>W: App receives stepupId, passes it to the WebView to call the withdrawal API

Points to settle in the spec:

  • Native step-up only accepts sessions with channel = App. A Web session has no app to receive the Universal Link; reject early with 400.
  • STEPUP_COMPLETE_URL is a per-environment env var, because the Universal Link domain differs between dev/stg/prod.
  • The Universal Link carries stepupId, not a token. stepupId is a handle to stepup:{id} in Redis, meaningful only together with the correct sid of the parent session.
  • Native clients have their own redirect URI allow-list at the IdP; this is why the client table in Day 7, Part 3 must list every callback.

8. security-setting and the MFA API

With context = security-setting, /auth/stepup/start chooses the stepup-password-* client, sets redirect_uri = /auth/stepup/mfa-callback and adds two parameters to /authorize:

  • audience=https://<idp-domain>/mfa/ — without this parameter, the returned access_token is an opaque token for /userinfo, and calling /mfa/associate gets 401 even with the right scope. audience is what turns the access_token into a JWT intended for the MFA API.
  • scope=openid enroll read:authenticators remove:authenticators.

After /auth/stepup/mfa-callback, the BFF has an access_token with MFA scope and aud = MFA API, stored in stepup-mfa:{id} (TTL = expires_in).

Two things that are often confused when writing the spec for this part:

TermWhat it isWhere it is used in MemberPortal
"Enable the MFA grant on the client"IdP configuration allowing the client to use MFA grant types (http://auth0.com/oauth/grant-type/mfa-otp, mfa-oob, mfa-recovery-code)Configuration of the stepup-password-* clients
grant_type=http://auth0.com/oauth/grant-type/mfa-otpAn actual grant: call /oauth/token with mfa_token (received after an mfa_required error) and otp to complete MFA without a redirectOnly when the BFF builds its own OTP entry UI; MemberPortal does not use it, because the IdP shows the MFA step in Universal Login
Scope enroll read:authenticators remove:authenticators + MFA audiencePermissions of the access_token to call the MFA API after authenticationstepup-mfa:{id}

The client table in Day 7, Part 3 must state which clients have the MFA grant enabled and why; an unnecessarily enabled grant is a review finding.

BFF endpointAuth0 callPurpose
GET /auth/stepup/mfa/authenticatorsGET /mfa/authenticatorsList enrolled authenticators
POST /auth/stepup/mfa/associatePOST /mfa/associateStart enrolling a new authenticator (OTP, push...)
DELETE /auth/stepup/mfa/authenticators/:idDELETE /mfa/authenticators/:idRemove an authenticator

All of these endpoints: SessionCheck + XsrfCheck → read stepup-mfa:{id} → check parentSessionId → call Auth0 with the access_token from Redis. The browser never sees the access_token. When the access_token expires, Redis has already deleted the child session and the UI gets STEPUP_REQUIRED to start over.

Distinguish the two Auth0 APIs the BFF uses:

Management API (Day 4, Part 1)MFA API
Token obtained viaclient_credentials, client portal-management, at bootauthorization_code + mfa grant, step-up client, per user
RepresentsThe BFF applicationThe specific user who just re-authenticated
Used toLook up/modify users with admin permissionsSet up/remove MFA for that same user
Why not use the Management API for MFAPossible, but loses the binding "only the user who just authenticated may change their own MFA"

9. Common mistakes when writing a step-up spec

MistakeConsequence
Not checking id_token account_no == parent session accountNoStep-up with the attacker's account, withdraw from the victim's account
Not checking auth_time despite prompt=loginThe IdP may return an old session, step-up is just a formality
Writing "delete when TTL expires" for every contextOne step-up, multiple withdrawals within 10 minutes
Storing the access_token in stepup:{id} for cash-outKeeps an unnecessary token, increases the risk surface
Setting a fixed 600s TTL for stepup-mfaKeeps an expired token or cuts off while the token is still valid
Forgetting the MFA audience when requesting a token for security-settingOpaque token, every /mfa/* call returns 401, the bug only shows up in integration testing
A single callback branching on contextA passkey-only client may receive an MFA token; the reviewer must prove every client × context combination
Universal Link carrying the access_tokenToken leaks via the OS URL/logs
Reusing the sid cookie for the step-up login sequenceOverwrites the login session, the user is logged out when step-up fails
Not deleting child sessions on logout"Orphan" child sessions remain valid after logout

Part 2: Operator mode, mock login and how to spec a "test backdoor"

1. Operator mode: staff acting on behalf of a customer

The ACME Securities support center sometimes needs to view MemberPortal from a customer's perspective to guide them over the phone. Staff do not know the customer's password, do not have the customer's passkey, and are not allowed to perform money operations. This is the Operator channel.

Staffmember──login──▶internalIdP──▶operator_token(JWT)│└─▶Operatorportal──▶POST/auth/operator/loginAuthorization:Bearer<operator_token>body:{accountNo}│├─Verifyoperator_tokenviatheinternalIdP'sJWKS(signature,iss,aud,exp)│└─takeoperatorIdfromclaim`sub`←identitydoesNOTcomefromthebody├─OperatorAccountStatusAPI(operatorId,accountNo)│└─staffmemberstillactive?allowedtosupportthisaccount?├─AccountAttributeAPI(accountNo)│└─customeraccountvalid(online-trading)?└─createsess:{id}={accountNo,sub:operator:<operatorId>,operatorId,channel:"Operator",xsrfToken,usedPasskey:false}

Design principles

PrincipleHow it is expressed
Same session modelStill sess:{id} + cookies sid/xsrf; the /api/s/* middleware is unchanged
Different issuance and permissionschannel = Operator; money APIs (withdrawal, changing the receiving account, step-up) reject this channel
No wrong turnsWhen the UI is in operator mode (isOpe=true) and calls /auth/web/login, the BFF returns 400 instead of redirecting to the IdP
Identity from the token, not the bodyoperatorId comes from the verified operator_token; the body only carries the customer's accountNo
TraceabilityThe session stores operatorId, sub = operator:<operatorId>; every log carries both the customer's accountNo and operatorId

Why return 400 when an operator calls the web login by mistake? Because it is a client error (calling the wrong endpoint for the current mode), not a lack of permission (403) or a lack of authentication (401). Returning 302 to the IdP would make the staff member log in with their personal account and create a session in the wrong mode, which is very hard to diagnose.

Condensed endpoint table

ItemValue
OverviewIssue a SessionID2 with channel Operator for support staff
Method / EndpointPOST /auth/operator/login
LocationItemRequiredValue
headerAuthorization✓Bearer <operator_token> — JWT issued to staff by the company's internal IdP
headerContent-Type✓application/json
bodyaccountNo✓Account number of the customer being supported

Processing details:

  • Missing header / not Bearer → 401.
  • Verify operator_token: signature via the internal IdP's JWKS (cached as in Day 3, Part 3), iss = internal IdP, aud = MemberPortal BFF, exp not expired → any check fails → 401. Take operatorId from claim sub.
  • Call Operator Account Status API with (operatorId, accountNo) → staff member does not exist / is locked / is not allowed to support this account → 403.
  • Call Account Attribute API with accountNo → not online-trading → 403 (layer 3 from Day 6, Part 2 still runs).
  • Create sess:{id}, xsrfToken with a CSPRNG; channel = Operator; operatorId; usedPasskey = false.
  • Set-Cookie sid, xsrf, uid → 200.
  • Do not call Login History API as the customer (to avoid corrupting the customer's login history); instead write a separate operational log with operatorId.

Why must staff identity not come from the body?

An early version of this endpoint accepted a username in the body and only asked Operator Account Status API "does this staff member have permission". At first glance there is a check, but no step proves the caller actually is that staff member: anyone who can reach the endpoint (a compromised internal service, a former employee who still has the URL) only needs to fill in the username of an authorized colleague to create a session for any customer. This is exactly the "client-controlled input decides permissions" bug in the Day 7, Part 3 checklist: authorization (the status API) was done carefully, but authentication (who is calling) was left empty.

The correct fix is to make the caller prove identity with something that cannot be forged: a token signed by the internal IdP that the BFF can verify. operatorId comes from that token's claim, while the body only carries business data (accountNo). An equivalent alternative: mTLS between the operator portal and the BFF plus an internal session; the principle is still that identity comes from an authenticated channel, not from a field the client fills in itself.

The last point about Login History is a business decision that is easy to overlook: login history is data the customer sees, and should not be "polluted" by internal operations.

2. Mock login: fake login for test environments

During development and integration testing, going through the real IdP for every test run is slow and network-dependent. MemberPortal provides two endpoints:

EndpointUsed forEnabled when
POST /auth/mock-sessionAutomated tests, Postman, backend stubsSTAGE ∈ {dev, stub, stg} and the body has a password matching MOCK_LOGIN_PASSWORD
GET /auth/mock-loginDevelopers opening it quickly in a browserSTAGE = dev
POST/auth/mock-sessionContent-Type:application/json{"accountNo":"10000001","password":"<MOCK_LOGIN_PASSWORD>","channel":"Web"}├─STAGE∉{dev,stub,stg}→404├─MOCK_LOGIN_PASSWORDnotconfigured→404├─passworddoesnotmatch→404├─bodyisnotvalidJSON→400└─OK→createmock:{id}(TTLMOCK_SESSION_TTL)withthesamestructureassessSet-Cookiesid/xsrf/uid→200

Three characteristics to note:

  1. Two independent conditions (stage and password). Stage alone is not enough, because the stg environment may be reachable from outside networks for the test team; the password is the second barrier.
  2. Body parser bound per route. Day 1, Part 2 explained why sending form-urlencoded to this endpoint gets 400: the application disables the global body parser and only attaches json() to this route. The spec must state the accepted Content-Type.
  3. Fake sessions use a separate mock: prefix but the same structure as sess:. This lets middleware recognize and (if needed) reject mock sessions on certain APIs, and makes cleanup easy.

3. Why does a failed guard return 404?

Status when the guard failsWhat a scanner learns
401"The endpoint exists and requires authentication" → try brute-forcing the password
403"The endpoint exists but I do not meet the conditions" → try changing UA, IP, stage header
400"The endpoint exists, I sent the wrong format" → try other formats
404"Nothing here" → same as any other non-existent URL

404 makes the test endpoint indistinguishable from a random URL. This is the "do not reveal existence" principle applied to endpoints instead of accounts (Day 4, Part 2 applied it to user enumeration).

// Guard by stage + password, every failure is 404
@Injectable()
export class MockSessionGuard implements CanActivate {
  canActivate(ctx: ExecutionContext): boolean {
    const stage = process.env.STAGE;
    const expected = process.env.MOCK_LOGIN_PASSWORD;
    if (!['dev', 'stub', 'stg'].includes(stage ?? '') || !expected) {
      throw new NotFoundException();
    }
    const req = ctx.switchToHttp().getRequest();
    const given = req.body?.password;
    if (typeof given !== 'string' || !timingSafeEqualStr(given, expected)) {
      throw new NotFoundException();
    }
    return true;
  }
}
import { createHash, timingSafeEqual } from 'crypto';

// Constant-time comparison for two strings that may have DIFFERENT lengths.
// crypto.timingSafeEqual throws when the buffers differ in length → if compared directly,
// the password length still leaks via "throws or not". Hash both to 32 bytes first.
function timingSafeEqualStr(a: string, b: string): boolean {
  const ha = createHash('sha256').update(a, 'utf8').digest();
  const hb = createHash('sha256').update(b, 'utf8').digest();
  return timingSafeEqual(ha, hb);
}

Note on timingSafeEqualStr: comparing passwords with === allows timing measurements to guess characters one by one; for an endpoint that may be exposed to the internet on stg, a constant-time comparison costs very little. Hashing before comparing avoids leaking the length (see the comment in the code).

Ideal behavior in production: the route is not registered (the test module is not imported when STAGE = prod), so the 404 comes from the router, not from the guard. The guard is the second line of defense in case the module configuration is wrong.

4. Writing a spec for a "test backdoor"

Test endpoints are where specs are most often written sloppily, while they are the most dangerous if they leak into production. A complete spec for this kind of endpoint must have four sections that normal endpoints do not need:

SectionContentExample for /auth/mock-session
Enable conditionsWhich stage, which variables must be setSTAGE ∈ {dev, stub, stg} and MOCK_LOGIN_PASSWORD is set
Behavior when disabledStatus code, whether it logs404, logged at debug level (no alert, to avoid noise)
Differences from the real flowWhich steps are skipped, where the fake data comes fromDoes not call the IdP, does not call Login Status API; accountNo comes from the body
Cleanup and limitsTTL, prefix, which APIs reject mock sessionsmock:{id} TTL MOCK_SESSION_TTL; money APIs reject the mock: prefix on stg

You also need one line in the deployment testing section: "Before releasing to production, run curl -X POST https://portal.example.com/auth/mock-session and confirm 404." This check is cheap and catches the most serious misconfiguration.

Checklist for every test endpoint

  • Is there a guard by environment? Does the guard read from env, not from a client-sent header?
  • Does a failed guard return 404?
  • Is there a second barrier (password, IP allow-list) for environments reachable from outside?
  • Is the test password in a secret store, not in docs, not in the repo, not in a committed Postman collection?
  • Can fake sessions be distinguished from real ones (prefix)?
  • Is the module/route excluded from the build or from registration in production?

5. Environment variables in the spec

Most behavior in this course depends on env vars: TTLs, on/off flags, IdP URLs, test passwords. The spec must have an env var table sufficient for the infra team to configure without reading code.

VariableMeaningdevstgprodSourceSecret?
STAGEEnvironment namedevstgprodInfra stackNo
BFF_DOMAINBFF domain, used to validate successUrldev-portal.example.comstg-portal.example.comportal.example.comInfra stackNo
SESSION_TTLSessionID2 TTL (seconds)108001080010800ConfigNo
SESSION_LOGIN_TTLSessionID1 TTL (seconds)108001080010800ConfigNo
STEPUP_SESSION_TTLstepup:{id} TTL (seconds)600600600ConfigNo
MOCK_SESSION_TTLmock:{id} TTL (seconds)36001800— (not used)ConfigNo
MOCK_LOGIN_PASSWORDMock guard password(secret)(secret)not setSecret store (SSM Parameter Store / Secrets Manager)Yes
ALT_IDP_ENABLEDEnable the backup IdPfalsetruetrueConfigNo
AUTH_HEALTH_CACHE_SECONDSHealth check cache606060ConfigNo
PASSKEY_ENABLEDEnable passkeystruetrueper release scheduleConfigNo
STEPUP_COMPLETE_URLNative Universal Link callbackper environmentper environmentper environmentInfra stackNo
IDP_CLIENT_IDclient_id of portal-web(per tenant)(per tenant)(per tenant)ConfigNo
IDP_CLIENT_SECRETclient_secret of portal-web<secret><secret><secret>Secret storeYes
IDP_MGMT_CLIENT_IDclient_id of portal-management (Management API, Day 4, Part 1)(per tenant)(per tenant)(per tenant)ConfigNo
IDP_MGMT_CLIENT_SECRETclient_secret of portal-management<secret><secret><secret>Secret storeYes
OPERATOR_IDP_JWKS_URLInternal IdP JWKS for verifying operator_tokenper environmentper environmentper environmentInfra stackNo

Note: in this course, env names are shortened without a prefix for readability. A real spec must apply the prefix convention in section 6 (LEGACY_ for inherited variables, PORTAL_ for new ones), e.g. PORTAL_SESSION_TTL. Rules for filling in the table:

  • The value columns of secret variables are always placeholders. Docs are read by many people, committed, and copied; a real value leaking in is an incident.
  • The "Source" column says who is responsible for configuring it: infra stack (generated from resources), config repo, or secret store.
  • Variables not used in production say "not set" explicitly, rather than being left blank, so reviewers can see it is intentional.

6. Naming conventions and recording decisions

MemberPortal partly inherits from a legacy system. Old variables have the LEGACY_ prefix; new portal variables use the PORTAL_ prefix. The question arises immediately: rename the old variables for consistency, or keep them?

OptionProsCons
Rename everything to PORTAL_Consistent, easy to findMust change the infra stack in every environment, risk of drift during deployment, breaks compatibility with old operations tools
Keep LEGACY_ for inherited variables, PORTAL_ for new onesDoes not touch running infrastructure, clear originTwo prefixes coexist, newcomers wonder why

MemberPortal chose the second option. What matters is not which you choose, but that you record the decision and the reason in the docs ("Decision: keep two prefixes. Reason: avoid changing running infra; new variables use PORTAL_ consistently; will be unified during the infra refactor."). Without this, six months later someone will "clean up" and cause an incident, or the debate will start again from scratch.

A short form (a condensed Architecture Decision Record):

ADR 007: Environment variable prefix convention
Date: 2026-03-10
Context: The BFF inherits 12 variables from the legacy system (prefix LEGACY_) and adds 9 new ones.
Decision: keep LEGACY_ for inherited variables; new variables use PORTAL_.
Reason: do not change the infra stack serving production; clear variable origin.
Consequences: two prefixes coexist; docs env.md has an "Origin" column for each variable.
Revisit when: the infra stack is refactored.

General lesson: when spec and code diverge on variable names, behavior, or status codes, look up the earlier decision before fixing either side. Day 7, Part 3 covers spec ↔ ticket ↔ PR traceability in detail.

7. Common mistakes

MistakeConsequence
Guard reads the stage from a client-sent X-Stage headerThe client declares itself dev → mock login opens in production
Failed guard returns 401Reveals the endpoint's existence; invites brute force
Mock password written in docs/README "for convenience"Leaks when docs are shared; everyone forgets to rotate it
Mock session uses the sess: prefixCannot tell real from fake during investigation, cannot block it on money APIs
Operator calling web login gets redirected to the IdPSession in the wrong mode, staff log in with their personal account
Operator login writes Login History as the customerThe customer's login history is wrong, the customer gets confused
Env var table missing the "prod" columnNobody knows whether test variables are disabled in production
Renaming variables without an ADRDeployment incidents because infra was not updated; repeated debates

Part 3: Spec-writing skills and a security review checklist

1. How does a login spec differ from a normal spec?

A CRUD spec can be described with request/response and a few validations. A login spec differs in three ways:

CharacteristicConsequence for how you write it
The flow goes through multiple redirects and parties (browser, BFF, IdP, core system)Needs a sequence diagram, not just a request/response table
State lives outside the request (SessionID1, SessionID2, cookies)Needs a separate data model for sessions, with the source and TTL of each field
More error branches than success branches, and every error branch has security consequencesError branches must be listed completely and each must answer three questions

The three questions from Day 1, Part 1 (who authenticates and how does the BFF trust it; where does state live, for how long, when is it deleted; what happens on failure) are exactly the framework for checking whether a spec is complete.

2. Endpoint table template

Every endpoint in the MemberPortal documentation uses the same structure so readers find information in a familiar place:

### <Endpoint name>
Overview           : 1-3 sentences, what this endpoint does in which flow
Method / Endpoint  : GET /auth/...
Item table         : location (cookie / query / header / body) | Item | Required | Value / constraints
Processing details : numbered bullets, branches by indentation; each branch ends with
                     (which session to delete) / (set cookie?) / (status or where to redirect)
Footnote           : [^n] pointing to a common process (CSPRNG, PKCE, verify id_token, choose IdP...)

Full example: GET /auth/web/login-callback

Overview. Receives code and state from the IdP after the user authenticates, exchanges the code for an id_token, verifies it, checks the account type, issues SessionID2 and redirects to successUrl. This is the second step of the Web login flow (the first step: /auth/web/login).

Method / Endpoint. GET /auth/web/login-callback

LocationItemRequiredValue / constraints
cookieSessionID1 cookie✓Points to login:{id}; missing or TTL expired → see branch 1
querystate✓Must match login:{id}.state
querycode✓ (when there is no error)Single-use authorization code
queryerror–Present when the IdP refuses; see branch 3
queryerror_description–Used to classify IdP errors

Processing details.

  1. Read login:{id} by the SessionID1 cookie.
    • Missing / TTL expired → (delete nothing) / (no cookie set) / redirect to the "Login failed" screen.
  2. Compare state with login:{id}.state.
    • Mismatch or missing → delete login:{id} / no cookie set / "Login failed" screen.
  3. If error is present:
    • error_description = user is blocked → delete login:{id} / no cookie set / "Account login restricted" screen.
    • error_description = connection is not enabled or starts with maintenance:: → delete login:{id} / no cookie set / "Login under maintenance" screen.
    • error = access_denied or other → delete login:{id} / no cookie set / "Login failed" screen.
  4. Missing code → delete login:{id} / no cookie set / "Login failed" screen.
  5. Token request to the token endpoint of login:{id}.idProvider (form-urlencoded: grant_type=authorization_code, code, code_verifier, redirect_uri, client_id, client_secret)1.
    • 5xx / timeout → retry at most 2 times → still failing → delete login:{id} / no cookie set / system error screen.
    • 4xx → delete login:{id} / no cookie set / "Login failed" screen.
  6. Verify the id_token with the 7 checks2 (signature via the idProvider's JWKS, iss, aud, exp, nonce = login:{id}.nonce, claim connection, auth_time if the /authorize request had max_age).
    • Any check fails → delete login:{id} / no cookie set / "Login failed" screen.
  7. Take accountNo from claim https://claims.example.com/account_no, sub from claim sub, usedPasskey from claim connection.
  8. Generate SessionID2 and xsrfToken with a CSPRNG3 (not stored yet).
  9. Call Account Attribute API (accountNo).
    • Error after 2 retries → delete login:{id} / no cookie set / system error screen.
    • Not online-trading → delete login:{id} / no cookie set / "Login failed" screen.
  10. Call Login Status API.
    • Error after 2 retries → delete login:{id} / no cookie set / system error screen.
    • isLoginAllowed = false → delete login:{id} / no cookie set / "Login failed" screen.
  11. Store sess:{id} (TTL SESSION_TTL) per the data model in section 3; delete login:{id}.
  12. If needsTradingInfoEntry = false → call Login History API (usedPasskey); on error → log a warning, continue.
  13. Set-Cookie sid (Secure, HttpOnly, SameSite=Lax), xsrf, uid; delete the SessionID1 cookie → 302 login:{id}.successUrl.

Looking back at the 13 steps: 10 steps have error branches, and each branch has all three pieces of information. That is the standard for "complete".

3. Session data model

One table per session type, one row per field, with a mandatory Source column:

Key sess:{id}FieldTypeSourceNotes
accountNostringid_token claim account_no (Web) / SSO Token Verify API (App) / body (Operator — allowed because it has passed Operator Account Status API checking operatorId's permission on this account + Account Attribute API)Never from query/body on the Web/App channels
substringid_token claim sub / verify API / operator:<operatorId>
operatorIdstring?claim sub of the verified operator_token (Operator channel only)NOT from the body; used for audit logs
xsrfTokenstringCSPRNG 32 bytes, base64urlCompared with the X-XSRF-TOKEN header
channelenumConstant per issuing endpoint: Web / App / OperatorNative step-up only accepts App
usedPasskeybooleanclaim connection (Web) / passkeyFlag (App) / false (Operator)Determines the step-up client
idProviderenumlogin:{id}.idProviderNeeded for RP-initiated logout at the right IdP
TTLSESSION_TTL (absolute, not sliding)

The "Source" column is where a security reviewer looks first: any permission-deciding field whose source is "client" is a finding.

4. Sequence diagrams that match 1-to-1

A sequence diagram is not an illustration; it is a cross-check against the Processing details. Rules:

  • Each numbered step in the Processing details appears exactly once in the diagram (write the step number in the message).
  • Each session create/read/delete is shown explicitly with Note over BFF,Redis.
  • Main error branches use alt/else; you do not need to draw every branch, but any branch not drawn must be in the table.
  • Check the syntax with mmdc (mermaid-cli) in CI so diagrams do not silently break.
sequenceDiagram
    participant B as Browser
    participant BFF
    participant R as Redis
    participant IdP
    participant Core as Core system
    B->>BFF: 1. GET /auth/web/login-callback?code&state (cookie SessionID1)
    BFF->>R: 1. GET login:{id}
    alt 2. state mismatch
        BFF->>R: DEL login:{id}
        BFF-->>B: 302 "Login failed" screen
    else state matches
        BFF->>IdP: 5. POST /oauth/token (code, code_verifier)
        IdP-->>BFF: id_token, access_token
        Note over BFF: 6. verify id_token 7 checks
        BFF->>Core: 9. Account Attribute API
        BFF->>Core: 10. Login Status API
        BFF->>R: 11. SET sess:{id} TTL, DEL login:{id}
        BFF->>Core: 12. Login History API (best-effort)
        BFF-->>B: 13. Set-Cookie sid/xsrf/uid, 302 successUrl
    end

5. Separating common processes

Pieces reused across many endpoints (web login, web step-up, native step-up, logout) are moved into a separate file and referenced via footnotes. The minimum list for MemberPortal:

Common processUsed in
Generate a secure random string (CSPRNG, length, encoding)Session ID, state, nonce, code_verifier, xsrfToken
Generate PKCE (verifier → challenge, base64url without padding)Every authorization_code flow
Choose IdP (flag, health, cache)/auth/web/login, /auth/stepup/start
Verify id_token (7 checks + conditional auth_time)Every callback
Token request and retry policyEvery callback, boot
Determine usedPasskey from claim connectionLogin callback, step-up callback
Passkey cancel (switch client, regenerate bindings)Web/native step-up
Validate successUrl (well-formed, same BFF_DOMAIN, append tracking parameters)/auth/web/login, /auth/stepup/start, logout

The benefit is not only brevity: when you change a common process (for example, adding an id_token check), every endpoint is updated automatically and the reviewer only needs to read one place.

6. IdP client table with a "design rationale"

The client table does not just list configuration; it must answer "why does this client exist":

ClientLogin callbackLogout callbackConnectiongrant_typeManagement API usedPurposeDesign rationale
portal-web/auth/web/login-callback/auth/web/logout-callbackUsername-Password, Passkey-Loginauthorization_code–Web loginConfidential client; the BFF holds the secret so it can use authorization_code without implicit. id_token check 6 (Day 3, Part 3) is "claim connection belongs to the client's valid set" (one of these two values), not one hard-coded value; usedPasskey = (connection == Passkey-Login)
portal-management–––client_credentialsread:users, update:users, read:users_app_metadata, update:users_app_metadataLook up/modify usersSeparate from portal-web to confine admin scope to a client that does not interact with users
stepup-passkey-web/auth/stepup/callback–Passkey-Loginauthorization_code–Passkey step-upPasskey-only so assurance is not lowered when the user has used a passkey
stepup-password-web/auth/stepup/callback, /auth/stepup/mfa-callback–Stepup-Passwordauthorization_code, MFA grant (mfa-otp/mfa-oob)–Password + MFA step-upTwo separate callbacks: /callback for cash-out/withdrawal-account (no token stored), /mfa-callback for security-setting (token with MFA audience). Only this client registers /mfa-callback → a passkey-only client never receives an MFA token (Day 7, Part 1 §5)
stepup-passkey-native, stepup-password-native/auth/stepup/callback (+ Universal Link on the app side)–as aboveas above–In-app step-upSeparate redirect URI allow-list for native

The last column is what keeps the next person from mistakenly deleting a client that "looks redundant", and helps reviewers spot a client granted grants/scopes beyond its purpose.

7. Traceability: spec ↔ ticket ↔ PR

Every spec change comes with:

Ticket(request/decision)◀──▶DocsPR(specchange,incl.alllanguageversions)◀──▶CodePR│││└──PRlinkintheticket└──ticketlinkinthePRdescription└──ticket+docsPRlinks

Rules when spec and code diverge:

  1. Do not fix either side right away.
  2. Look up the history: git log -S "<relevant string>" in both the docs repo and the code repo to find which side changed later and in which PR.
  3. Read the ticket attached to that PR: is there a decision (ruling) explaining the divergence?
  4. If there is an earlier decision → the side that was not updated is wrong; fix that side and link the decision.
  5. If there is none → make a new decision in the ticket, then fix both sides in the same batch.

A typical example: the spec says 401 for a branch, the code returns 403. The history shows the code was changed to 403 in a PR whose ticket explains "avoid the 401 loop in the UI" (Day 6, Part 1). The spec is wrong. Fix the spec and link the ticket. If you fix the code to match the spec, the loop incident will come back.

Multilingual documentation: every language version is changed in the same PR; reviewers reject PRs that change only one version.

8. 10-question security review checklist

Use it for every new login flow or change to an existing flow. Each question must be answerable by pointing to a specific line in the spec; if you cannot, that is a finding.

#QuestionIf missing → vulnerabilityRelated lesson
1Safe redirects: do successUrl, failureUrl, callbacks have a domain allow-list? Any open redirect?Phishing via redirects from a trusted domainDay 1, Part 2
2Binding: state ↔ SessionID1, nonce ↔ id_token, code_verifier ↔ code, xsrfToken ↔ SessionID2. Which one is missing?CSRF on the callback, id_token replay, code theft, CSRF on APIsDay 2, Part 2; Day 3, Part 2
3Tokens never leave the server: does any access_token / id_token / refresh_token reach the browser or the logs?Session hijacking via leaked logs or XSSDay 2, Part 1; Day 7, Part 1
4Session fixation: is SessionID2 newly created after authentication, not reusing SessionID1?The attacker plants a session id and waits for the victim to log inDay 2, Part 3
5Revocation: what does logout delete in Redis, the IdP, cookies? What does a 401 delete? Are third-party-injected cookies kept correctly? Are child sessions deleted with the parent session?"Orphan" sessions, broken SSO app, step-up still valid after logoutDay 2, Part 3; Day 6, Part 1; Day 7, Part 1
6Authorization vs authentication: are account type controls at the IdP and the BFF consistent? Does a new channel pass through all layers?Invalid accounts get in via the new channelDay 6, Part 2
7Timeout / retry / fail-open: do the token endpoint, JWKS, health API, core APIs all have a clear retry policy and fallback? Where is it fail-open, and is that intentional and documented?Transient errors become incidents; unintended fail-open in an authentication stepDay 3, Part 3; Day 4, Part 1; Day 6, Part 3
8Environment: do test endpoints have a stage guard and return 404 when disabled? Are secrets in a secret store, not in docs/repo?Backdoor in production, leaked secretsDay 7, Part 2
9Enumeration / logging: do error messages reveal whether a user exists or is locked to someone who does not own it? Do logs have internal error codes for tracing without recording sensitive data?Account probing; data leaks via logsDay 4, Part 2; Day 7, Part 2
10WebView / UA: is there anywhere that grants permissions based on UA? Are permissions based on token verification + account type?UA spoofing to take a shortcutDay 6, Part 1

How to use it: the reviewer fills a fifth column "Spec line that answers it" for each question. Any empty cell is a finding to resolve before approval.


Review Questions

  1. Why does step-up need a dedicated IdP client instead of reusing portal-web with prompt=login?

    Show answer

    Three reasons: (1) to enforce a method (passkey-only) you must attach a dedicated connection, and connections are attached per client; (2) you need different scopes and grants (mfa) for the security-setting context, and you do not want to grant them to the normal login client; (3) separate clients allow clear redirect URI allow-lists, permissions and permission matrices by purpose. prompt=login is still used, but on the step-up client. Reusing portal-web would let the IdP fall back to password and make the passkey pointless.

  2. Explain why stepup:{id} has a fixed 600s TTL while stepup-mfa:{id} has TTL = expires_in.

    Show answer

    stepup:{id} holds no token; it is only proof of "re-authenticated at time T for context X". The validity window is ACME's decision (600s is enough to complete one order), independent of the IdP. stepup-mfa:{id} holds a real access_token to call /mfa/*; when the token expires the child session is useless, keeping it longer only keeps a dead token, and keeping it shorter cuts off while the token is still valid. So the TTL is tied to expires_in. Principle: a session's TTL must follow the lifetime of what it represents.

  3. An attacker has the victim's sid + xsrf and a valid account of his own. Which check prevents him from withdrawing the victim's money via step-up?

    Show answer

    The step that compares account_no in the id_token with the accountNo of SessionID2 at the step-up callback. He can start step-up with the victim's session, but at the IdP he can only authenticate with his own account, so the id_token carries his account_no. The BFF sees it does not match the parent session → refuses to create stepup:{id}. In addition, parentSessionId in the child session and the context check ensure child sessions cannot be used across sessions or contexts.

  4. Why must context decide the child session's deletion time, not just its scope?

    Show answer

    Because the business actions have different shapes. Withdrawing and changing the receiving account are a single action; allowing repetition within 600s opens the "authenticate once, withdraw many orders" scenario if the session is hijacked right after step-up. So it is deleted as soon as the action completes. Setting up MFA is a chain of actions (list, add, confirm, remove the old one); deleting early forces the user to step up again midway. The spec must list the deletion time per context.

  5. When the user cancels the passkey, why does the BFF regenerate state/nonce/code_verifier instead of reusing the old set with the password client?

    Show answer

    Because the old set was already sent to the IdP for the first client; these values are designed to be used once per authorize request. Reusing them breaks the "one state, one request" binding, makes it harder to tell which attempt a callback belongs to during investigation, and if the old code_challenge leaked via a URL then the old code_verifier is no longer secret for the new attempt. Regenerating costs a few milliseconds. Only context, successUrl, parentSessionId are kept in login:{id1}.

  6. Why does operator mode still use sess:{id} and the sid cookie like customers, yet need channel = Operator?

    Show answer

    Sharing the session model means the /api/s/* middleware and the entire API proxy do not need to branch; staff see exactly what the customer sees, which serves the support purpose. channel = Operator is needed to limit permissions: money APIs, step-up and actions that change account state reject this channel, and logs/audits can distinguish staff actions from customer actions. This is an example of "same session check, different issuance and different permission set".

  7. Why does a test endpoint's guard return 404 instead of 403?

    Show answer

    403 confirms to a scanner that the endpoint exists and only a condition is missing, encouraging them to try changing headers, IPs, or brute-forcing the password. 404 makes the endpoint indistinguishable from any non-existent URL and gives no information for further attacks. This applies the "do not reveal existence" principle to endpoints, similar to not revealing whether an account exists on the login screen. Even better, the route is not registered in production so the 404 comes from the router.

  8. Name the four sections a test endpoint's spec must have in addition to a normal endpoint.

    Show answer

    (1) Enable conditions: which stage, which variables must be set; (2) Behavior when disabled: status code (404), whether it logs; (3) Differences from the real flow: which steps are skipped (does not call the IdP, does not call Login Status API), where the fake data comes from; (4) Cleanup and limits: TTL, a dedicated prefix for fake sessions, which APIs reject fake sessions. Plus a deployment test step: confirm the endpoint returns 404 in production after every release.

  9. Why does mock login need both a stage condition and a password, not just the stage?

    Show answer

    Because some non-production environments (such as stg) may still be reachable from outside networks for the test team, partners, or demos. Relying on the stage alone means anyone who can reach stg can create a session for any accountNo. The password (from a secret store, compared in constant time) is the second barrier. Conversely, relying only on the password without the stage leaves the endpoint "alive" in production, one password leak away from compromise. Two independent conditions; failing either one yields 404.

  10. When an environment variable has a different name in the spec and in the code, what do you do before fixing it?

Show answer

Look up the earlier decision: find the related ADR or ticket, check the change history of both docs and code (git log -S "VARIABLE_NAME"), and ask the person who decided if they are still around. The difference may be intentional (e.g. keeping LEGACY_ for inherited variables) and the "wrong" side may actually be docs that were not updated, or vice versa. After fixing, update both spec and code at the same time, and record the new decision if the convention changes. Fixing one side on a hunch is the fastest way to cause a deployment incident.

  1. When is an error branch in the Processing details considered "complete"?
Show answer

Three pieces of information: (1) which session is deleted (SessionID1, SessionID2, child session, or nothing); (2) whether a cookie is set (and which cookies are deleted); (3) where it goes (status code for an API, or screen/redirect for a browser flow). Missing any of the three, the implementer will decide on their own, and two different implementers will decide differently. For example, a complete "state mismatch" branch is: delete login:{id} / no cookie set / "Login failed" screen.

  1. Why must the session data model table have a "Source" column?
Show answer

Because a field's source determines how trustworthy it is. Permission-deciding fields (accountNo, channel, usedPasskey) must come from places the client does not control: an id_token claim, a server-to-server API, a per-endpoint constant, or a CSPRNG. If the Source column says "query" or "body" for such a field, that is a vulnerability (declaring someone else's accountNo). This column gives the security reviewer a single place to scan all input risks.

  1. The spec says 401, the code returns 403 for the same branch. In what order do you handle it?
Show answer

(1) Do not fix either side right away. (2) Look up the history with git log -S on both docs and code to find the PR that changed it. (3) Read the ticket attached to that PR to find the decision. (4) If there is a decision (e.g. "403 to avoid the 401 loop in the UI"), the side not updated is the spec → fix the spec, add the link. (5) If there is no decision, create a new one in the ticket and then fix both sides at the same time. Mechanically fixing the code to match the spec may recreate an incident that was already fixed.

  1. Why does the IdP client table need a "Design rationale" column?
Show answer

Because client configuration (grants, scopes, connections, callbacks) consists of security decisions, and without the reasons attached: (1) someone later may delete a "redundant-looking" client such as stepup-passkey-web without understanding it exists to preserve passkey assurance; (2) reviewers cannot spot a client granted grants/scopes beyond its purpose; (3) when adding a backup IdP, nobody knows which constraints must be recreated. This column turns the configuration table into a design document.

  1. Pick 3 questions from the 10-question checklist that you think are most easily missed when adding a new channel, and explain.
Show answer

Suggestion: Question 6 (consistent authorization) because a new channel often bypasses the IdP control layer, as in the SSO app case; Question 5 (revocation) because a new channel adds new cookies/sessions that logout and 401 handling do not know about yet, e.g. app-injected cookies; Question 10 (UA) because a new channel often relies on client characteristics (UA, headers) for identification and easily slides into using them to grant permissions. Question 7 (fail-open) is also often missed when a new channel adds a new verify API without documenting retry/fallback.

Hands-on Exercises

Exercise 1

Write the endpoint table for GET /auth/stepup/start using the template (Overview → Method/Endpoint → Item/Required/Value table by location → Processing details), including all branches: missing session, invalid context, successUrl on the wrong domain, App channel calling the Web version.

Expected output: a table + 10-15 branching bullets.

Exercise 2

Data model: write tables for login:{id1} (step-up purpose), stepup:{id}, stepup-mfa:{id} with columns key, field, source, TTL, when deleted.

Expected output: 3 tables; the "when deleted" column of stepup:{id} must be split by context.

Exercise 3

Mermaid sequence diagram for the native step-up flow with a passkey cancel in the middle, with 5 participants (App, System browser, BFF, IdP, Redis).

Expected output: clearly mark where the client is switched and where state/nonce/verifier are regenerated; check the syntax with mermaid-cli.

Exercise 4

Analysis: the product team proposes raising STEPUP_SESSION_TTL to 30 minutes to "bother customers less". Write a rebuttal based on the threat model (session hijacked after step-up), and propose alternatives (delete as soon as the action completes, allow conditional extension).

Expected output: 1 page, with a clear conclusion.

Exercise 5

Write a full spec for GET /auth/mock-login (only STAGE = dev): endpoint table, the four additional sections for test endpoints, and the deployment test step.

Expected output: a 1-page spec, every failure branch returns 404.

Exercise 6

Design permission limits for the Operator channel: list 8-10 MemberPortal APIs, mark which APIs reject channel = Operator, and write the checking middleware.

Expected output: a table + 15-20 lines of TypeScript.

Exercise 7

Build an env var table for every variable that appears in this course (Weeks 1-2), following the template in section 5, with secret values as placeholders.

Expected output: a table with 15-20 rows, no empty cells in the "prod" column.

Exercise 8

Write an ADR for the decision "operator login does not write the customer's Login History": context, decision, reason, consequences, when to revisit.

Expected output: 8-12 lines following the ADR template in section 6.

Part 3: Spec-writing skills and a security review checklist

Final course exercise: write a spec for the "Desktop app WebView login" channel

ACME Securities is preparing to release ACME Trade Desktop (Windows/macOS) with an embedded MemberPortal WebView. Requirement: a user already logged in to the desktop app should not have to log in again in the WebView. The desktop app can inject cookies into the WebView and can receive callbacks via the custom URL scheme acmetrade://.

Write a complete spec in the course's format, including:

  1. Design decision (1 page): which mechanism (an opaque token like App? OIDC with a new client? a combination?), a new Desktop channel or reuse App, the reasons, and the impact on native step-up.
  2. Endpoint tables for every new or modified endpoint (at minimum: the endpoint issuing the desktop session; changes to /auth/stepup/start if needed).
  3. Session data model: new/changed fields with Source and TTL columns.
  4. Mermaid sequence diagram matching the Processing details 1-to-1, syntax-checked.
  5. IdP client table (if a client is added) with a Design rationale column.
  6. New env var table with per-environment values, secrets as placeholders.
  7. Updated 401 handling in the UI and the list of cookies deleted/kept.
  8. Self-review with the 10-question checklist, filling the "Spec line that answers it" column and resolving every empty cell.

Expected output: a 6-10 page document; a reader who does not know the project can implement it without asking further questions; no empty cells left in the checklist.

Supplementary exercises

  • Rewrite POST /auth/app/login (Day 6, Part 1) using the table template in section 2, with all 3 pieces of information in every error branch.
  • Take any login spec you have read (or an IdP's public documentation), score it with the 10-question checklist, and write down the empty cells.

References


Next lesson →

Footnotes

  1. Common process "Token request and retry policy". ↩

  2. Common process "Verify id_token" (7 checks, Day 3, Part 3). ↩

  3. Common process "Generate a secure random string". ↩