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
contextparameter 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) andstepup-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, themfagrant - 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":
| Action | Why it is sensitive | context |
|---|---|---|
| Withdraw money to a bank account | Money leaves the system | cash-out |
| Change the receiving bank account | Prepares a withdrawal to the attacker's account | withdrawal-account |
| Set up / remove MFA, change security methods | Lowers the account's security long-term | security-setting |
This is step-up authentication: raising the authentication assurance level for one specific action, not logging in again entirely.
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.
| Client | Channel | Method | Connection | grant_type | Notes |
|---|---|---|---|---|---|
stepup-passkey-web | Web | Passkey only | Passkey-Login | authorization_code | Password entry not allowed |
stepup-password-web | Web | Password (+ MFA if set up) | Stepup-Password | authorization_code + mfa | Used when there is no passkey or the passkey was cancelled |
stepup-passkey-native | App | Passkey only | Passkey-Login | authorization_code | Callback via Universal Link |
stepup-password-native | App | Password (+ MFA) | Stepup-Password | authorization_code + mfa | Callback via Universal Link |
Why separate passkey-only and password?
- Security: if the user logged in with a passkey (
usedPasskey = truein 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-Loginconnection 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 | usedPasskey | channel | Selected client |
|---|---|---|---|
| false | any | Web | stepup-password-web |
| false | any | App | stepup-password-native |
| true | false | Web | stepup-password-web |
| true | true | Web | stepup-passkey-web |
| true | false | App | stepup-password-native |
| true | true | App | stepup-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
context | Purpose | Needs a real access_token? | BFF callback (redirect_uri) | Child session created | Scope requested from the IdP |
|---|---|---|---|---|---|
cash-out | Prove authentication to call the withdrawal API | No | /auth/stepup/callback | stepup:{id} | openid |
withdrawal-account | Prove authentication to change the receiving account | No | /auth/stepup/callback | stepup:{id} | openid |
security-setting | Call the Auth0 MFA API to set up/remove an authenticator | Yes (token with MFA scope) | /auth/stepup/mfa-callback | stepup-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
context | Delete when | Reason |
|---|---|---|
cash-out | TTL of 600s expires or as soon as the core system confirms the withdrawal order | One authentication for one order; no "authenticate once, withdraw many times" |
withdrawal-account | TTL of 600s expires or as soon as the account change succeeds | Same as above |
security-setting | TTL = the access_token's expires_in expires | The 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
| Criterion | stepup:{id} | stepup-mfa:{id} |
|---|---|---|
| Role | Proof of "re-authenticated for context X" | Holds the access_token so the BFF can call the MFA API |
| Contents | accountNo, context, verifiedAt, parentSessionId | accountNo, access_token, parentSessionId |
| TTL | Fixed STEPUP_SESSION_TTL = 600s | = the access_token's expires_in (usually shorter than 600s) |
| Why this TTL | No token is bound to it; 600s is a window long enough to complete one order | Once the token expires the session is meaningless; keeping it longer only keeps a dead token |
| Deleted early when | The business action completes (withdrawal OK, account change OK) | Not deleted early (multiple steps) |
| Used where | Middleware checking before the withdrawal / account-change API | The BFF's /auth/stepup/mfa/* endpoints |
| Does the token leave the server? | No token | access_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.
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:
prompt=login&max_age=600forces the IdP to re-authenticate even when an IdP session exists.max_ageis what makes the IdP required to return theauth_timeclaim (OIDC Core:auth_timeis only REQUIRED whenmax_ageis present), so the verify step can checknow - 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.- Binding to the parent session:
account_noin the id_token must equal theaccountNoof 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. - The temporary cookie
sid_stepupis separate fromsidso 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). - Two separate callbacks, no branching on
contextinside one callback.redirect_uriis 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 MFAaudience) 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 "readscontextfrom 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.
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.
7. Native app: callback via Universal Link
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 APIPoints to settle in the spec:
- Native step-up only accepts sessions with
channel = App. AWebsession has no app to receive the Universal Link; reject early with 400. STEPUP_COMPLETE_URLis a per-environment env var, because the Universal Link domain differs between dev/stg/prod.- The Universal Link carries
stepupId, not a token.stepupIdis a handle tostepup:{id}in Redis, meaningful only together with the correctsidof 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/associategets 401 even with the right scope.audienceis 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:
| Term | What it is | Where 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-otp | An actual grant: call /oauth/token with mfa_token (received after an mfa_required error) and otp to complete MFA without a redirect | Only 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 audience | Permissions of the access_token to call the MFA API after authentication | stepup-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 endpoint | Auth0 call | Purpose |
|---|---|---|
GET /auth/stepup/mfa/authenticators | GET /mfa/authenticators | List enrolled authenticators |
POST /auth/stepup/mfa/associate | POST /mfa/associate | Start enrolling a new authenticator (OTP, push...) |
DELETE /auth/stepup/mfa/authenticators/:id | DELETE /mfa/authenticators/:id | Remove 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 via | client_credentials, client portal-management, at boot | authorization_code + mfa grant, step-up client, per user |
| Represents | The BFF application | The specific user who just re-authenticated |
| Used to | Look up/modify users with admin permissions | Set up/remove MFA for that same user |
| Why not use the Management API for MFA | Possible, but loses the binding "only the user who just authenticated may change their own MFA" |
9. Common mistakes when writing a step-up spec
| Mistake | Consequence |
|---|---|
Not checking id_token account_no == parent session accountNo | Step-up with the attacker's account, withdraw from the victim's account |
Not checking auth_time despite prompt=login | The IdP may return an old session, step-up is just a formality |
| Writing "delete when TTL expires" for every context | One step-up, multiple withdrawals within 10 minutes |
Storing the access_token in stepup:{id} for cash-out | Keeps an unnecessary token, increases the risk surface |
Setting a fixed 600s TTL for stepup-mfa | Keeps an expired token or cuts off while the token is still valid |
Forgetting the MFA audience when requesting a token for security-setting | Opaque token, every /mfa/* call returns 401, the bug only shows up in integration testing |
A single callback branching on context | A passkey-only client may receive an MFA token; the reviewer must prove every client × context combination |
| Universal Link carrying the access_token | Token leaks via the OS URL/logs |
Reusing the sid cookie for the step-up login sequence | Overwrites 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.
Design principles
| Principle | How it is expressed |
|---|---|
| Same session model | Still sess:{id} + cookies sid/xsrf; the /api/s/* middleware is unchanged |
| Different issuance and permissions | channel = Operator; money APIs (withdrawal, changing the receiving account, step-up) reject this channel |
| No wrong turns | When 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 body | operatorId comes from the verified operator_token; the body only carries the customer's accountNo |
| Traceability | The 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
| Item | Value |
|---|---|
| Overview | Issue a SessionID2 with channel Operator for support staff |
| Method / Endpoint | POST /auth/operator/login |
| Location | Item | Required | Value |
|---|---|---|---|
| header | Authorization | ✓ | Bearer <operator_token> — JWT issued to staff by the company's internal IdP |
| header | Content-Type | ✓ | application/json |
| body | accountNo | ✓ | 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,expnot expired → any check fails → 401. TakeoperatorIdfrom claimsub. - 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},xsrfTokenwith 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:
| Endpoint | Used for | Enabled when |
|---|---|---|
POST /auth/mock-session | Automated tests, Postman, backend stubs | STAGE ∈ {dev, stub, stg} and the body has a password matching MOCK_LOGIN_PASSWORD |
GET /auth/mock-login | Developers opening it quickly in a browser | STAGE = dev |
Three characteristics to note:
- Two independent conditions (stage and password). Stage alone is not enough, because the
stgenvironment may be reachable from outside networks for the test team; the password is the second barrier. - 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. - Fake sessions use a separate
mock:prefix but the same structure assess:. 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 fails | What 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:
| Section | Content | Example for /auth/mock-session |
|---|---|---|
| Enable conditions | Which stage, which variables must be set | STAGE ∈ {dev, stub, stg} and MOCK_LOGIN_PASSWORD is set |
| Behavior when disabled | Status code, whether it logs | 404, logged at debug level (no alert, to avoid noise) |
| Differences from the real flow | Which steps are skipped, where the fake data comes from | Does not call the IdP, does not call Login Status API; accountNo comes from the body |
| Cleanup and limits | TTL, prefix, which APIs reject mock sessions | mock:{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.
| Variable | Meaning | dev | stg | prod | Source | Secret? |
|---|---|---|---|---|---|---|
STAGE | Environment name | dev | stg | prod | Infra stack | No |
BFF_DOMAIN | BFF domain, used to validate successUrl | dev-portal.example.com | stg-portal.example.com | portal.example.com | Infra stack | No |
SESSION_TTL | SessionID2 TTL (seconds) | 10800 | 10800 | 10800 | Config | No |
SESSION_LOGIN_TTL | SessionID1 TTL (seconds) | 10800 | 10800 | 10800 | Config | No |
STEPUP_SESSION_TTL | stepup:{id} TTL (seconds) | 600 | 600 | 600 | Config | No |
MOCK_SESSION_TTL | mock:{id} TTL (seconds) | 3600 | 1800 | — (not used) | Config | No |
MOCK_LOGIN_PASSWORD | Mock guard password | (secret) | (secret) | not set | Secret store (SSM Parameter Store / Secrets Manager) | Yes |
ALT_IDP_ENABLED | Enable the backup IdP | false | true | true | Config | No |
AUTH_HEALTH_CACHE_SECONDS | Health check cache | 60 | 60 | 60 | Config | No |
PASSKEY_ENABLED | Enable passkeys | true | true | per release schedule | Config | No |
STEPUP_COMPLETE_URL | Native Universal Link callback | per environment | per environment | per environment | Infra stack | No |
IDP_CLIENT_ID | client_id of portal-web | (per tenant) | (per tenant) | (per tenant) | Config | No |
IDP_CLIENT_SECRET | client_secret of portal-web | <secret> | <secret> | <secret> | Secret store | Yes |
IDP_MGMT_CLIENT_ID | client_id of portal-management (Management API, Day 4, Part 1) | (per tenant) | (per tenant) | (per tenant) | Config | No |
IDP_MGMT_CLIENT_SECRET | client_secret of portal-management | <secret> | <secret> | <secret> | Secret store | Yes |
OPERATOR_IDP_JWKS_URL | Internal IdP JWKS for verifying operator_token | per environment | per environment | per environment | Infra stack | No |
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?
| Option | Pros | Cons |
|---|---|---|
Rename everything to PORTAL_ | Consistent, easy to find | Must 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 ones | Does not touch running infrastructure, clear origin | Two 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
| Mistake | Consequence |
|---|---|
Guard reads the stage from a client-sent X-Stage header | The client declares itself dev → mock login opens in production |
| Failed guard returns 401 | Reveals 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: prefix | Cannot tell real from fake during investigation, cannot block it on money APIs |
| Operator calling web login gets redirected to the IdP | Session in the wrong mode, staff log in with their personal account |
| Operator login writes Login History as the customer | The customer's login history is wrong, the customer gets confused |
| Env var table missing the "prod" column | Nobody knows whether test variables are disabled in production |
| Renaming variables without an ADR | Deployment 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:
| Characteristic | Consequence 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 consequences | Error 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
| Location | Item | Required | Value / constraints |
|---|---|---|---|
| cookie | SessionID1 cookie | ✓ | Points to login:{id}; missing or TTL expired → see branch 1 |
| query | state | ✓ | Must match login:{id}.state |
| query | code | ✓ (when there is no error) | Single-use authorization code |
| query | error | – | Present when the IdP refuses; see branch 3 |
| query | error_description | – | Used to classify IdP errors |
Processing details.
- Read
login:{id}by the SessionID1 cookie.- Missing / TTL expired → (delete nothing) / (no cookie set) / redirect to the "Login failed" screen.
- Compare
statewithlogin:{id}.state.- Mismatch or missing → delete
login:{id}/ no cookie set / "Login failed" screen.
- Mismatch or missing → delete
- If
erroris present:error_description=user is blocked→ deletelogin:{id}/ no cookie set / "Account login restricted" screen.error_description=connection is not enabledor starts withmaintenance::→ deletelogin:{id}/ no cookie set / "Login under maintenance" screen.error=access_deniedor other → deletelogin:{id}/ no cookie set / "Login failed" screen.
- Missing
code→ deletelogin:{id}/ no cookie set / "Login failed" screen. - 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.
- 5xx / timeout → retry at most 2 times → still failing → delete
- Verify the id_token with the 7 checks2 (signature via the idProvider's JWKS,
iss,aud,exp,nonce=login:{id}.nonce, claimconnection,auth_timeif the/authorizerequest hadmax_age).- Any check fails → delete
login:{id}/ no cookie set / "Login failed" screen.
- Any check fails → delete
- Take
accountNofrom claimhttps://claims.example.com/account_no,subfrom claimsub,usedPasskeyfrom claimconnection. - Generate SessionID2 and
xsrfTokenwith a CSPRNG3 (not stored yet). - 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.
- Error after 2 retries → delete
- Call Login Status API.
- Error after 2 retries → delete
login:{id}/ no cookie set / system error screen. isLoginAllowed = false→ deletelogin:{id}/ no cookie set / "Login failed" screen.
- Error after 2 retries → delete
- Store
sess:{id}(TTLSESSION_TTL) per the data model in section 3; deletelogin:{id}. - If
needsTradingInfoEntry = false→ call Login History API (usedPasskey); on error → log a warning, continue. - Set-Cookie
sid(Secure, HttpOnly, SameSite=Lax),xsrf,uid; delete the SessionID1 cookie → 302login:{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} | Field | Type | Source | Notes |
|---|---|---|---|---|
accountNo | string | id_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 | |
sub | string | id_token claim sub / verify API / operator:<operatorId> | ||
operatorId | string? | claim sub of the verified operator_token (Operator channel only) | NOT from the body; used for audit logs | |
xsrfToken | string | CSPRNG 32 bytes, base64url | Compared with the X-XSRF-TOKEN header | |
channel | enum | Constant per issuing endpoint: Web / App / Operator | Native step-up only accepts App | |
usedPasskey | boolean | claim connection (Web) / passkeyFlag (App) / false (Operator) | Determines the step-up client | |
idProvider | enum | login:{id}.idProvider | Needed for RP-initiated logout at the right IdP | |
| TTL | SESSION_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
end5. 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 process | Used 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 policy | Every callback, boot |
Determine usedPasskey from claim connection | Login 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":
| Client | Login callback | Logout callback | Connection | grant_type | Management API used | Purpose | Design rationale |
|---|---|---|---|---|---|---|---|
portal-web | /auth/web/login-callback | /auth/web/logout-callback | Username-Password, Passkey-Login | authorization_code | – | Web login | Confidential 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_credentials | read:users, update:users, read:users_app_metadata, update:users_app_metadata | Look up/modify users | Separate from portal-web to confine admin scope to a client that does not interact with users |
stepup-passkey-web | /auth/stepup/callback | – | Passkey-Login | authorization_code | – | Passkey step-up | Passkey-only so assurance is not lowered when the user has used a passkey |
stepup-password-web | /auth/stepup/callback, /auth/stepup/mfa-callback | – | Stepup-Password | authorization_code, MFA grant (mfa-otp/mfa-oob) | – | Password + MFA step-up | Two 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 above | as above | – | In-app step-up | Separate 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:
Rules when spec and code diverge:
- Do not fix either side right away.
- 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. - Read the ticket attached to that PR: is there a decision (ruling) explaining the divergence?
- If there is an earlier decision → the side that was not updated is wrong; fix that side and link the decision.
- 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.
| # | Question | If missing → vulnerability | Related lesson |
|---|---|---|---|
| 1 | Safe redirects: do successUrl, failureUrl, callbacks have a domain allow-list? Any open redirect? | Phishing via redirects from a trusted domain | Day 1, Part 2 |
| 2 | Binding: 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 APIs | Day 2, Part 2; Day 3, Part 2 |
| 3 | Tokens never leave the server: does any access_token / id_token / refresh_token reach the browser or the logs? | Session hijacking via leaked logs or XSS | Day 2, Part 1; Day 7, Part 1 |
| 4 | Session fixation: is SessionID2 newly created after authentication, not reusing SessionID1? | The attacker plants a session id and waits for the victim to log in | Day 2, Part 3 |
| 5 | Revocation: 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 logout | Day 2, Part 3; Day 6, Part 1; Day 7, Part 1 |
| 6 | Authorization 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 channel | Day 6, Part 2 |
| 7 | Timeout / 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 step | Day 3, Part 3; Day 4, Part 1; Day 6, Part 3 |
| 8 | Environment: 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 secrets | Day 7, Part 2 |
| 9 | Enumeration / 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 logs | Day 4, Part 2; Day 7, Part 2 |
| 10 | WebView / UA: is there anywhere that grants permissions based on UA? Are permissions based on token verification + account type? | UA spoofing to take a shortcut | Day 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
-
Why does step-up need a dedicated IdP client instead of reusing
portal-webwithprompt=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=loginis still used, but on the step-up client. Reusingportal-webwould let the IdP fall back to password and make the passkey pointless. -
Explain why
stepup:{id}has a fixed 600s TTL whilestepup-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 toexpires_in. Principle: a session's TTL must follow the lifetime of what it represents. -
An attacker has the victim's
sid+xsrfand 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_noin the id_token with theaccountNoof 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 hisaccount_no. The BFF sees it does not match the parent session → refuses to createstepup:{id}. In addition,parentSessionIdin the child session and thecontextcheck ensure child sessions cannot be used across sessions or contexts. -
Why must
contextdecide 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.
-
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,parentSessionIdare kept inlogin:{id1}. -
Why does operator mode still use
sess:{id}and thesidcookie like customers, yet needchannel = 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 = Operatoris 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". -
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.
-
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.
-
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 reachstgcan create a session for anyaccountNo. 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. -
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.
- 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.
- 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.
- 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.
- 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.
- 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:
- Design decision (1 page): which mechanism (an opaque token like App? OIDC with a new client? a combination?), a new
Desktopchannel or reuseApp, the reasons, and the impact on native step-up. - Endpoint tables for every new or modified endpoint (at minimum: the endpoint issuing the desktop session; changes to
/auth/stepup/startif needed). - Session data model: new/changed fields with Source and TTL columns.
- Mermaid sequence diagram matching the Processing details 1-to-1, syntax-checked.
- IdP client table (if a client is added) with a Design rationale column.
- New env var table with per-environment values, secrets as placeholders.
- Updated 401 handling in the UI and the list of cookies deleted/kept.
- 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
- OpenID Connect Core 1.0 —
prompt,max_age,auth_time - OpenID Connect Core 1.0 —
acr_valuesand step-up (Authentication Context Class) - OAuth 2.0 Step-up Authentication Challenge Protocol — RFC 9470
- Auth0 — MFA API
- Auth0 — Passkeys
- Apple — Supporting Universal Links
- Android — App Links
- OAuth 2.0 for Native Apps — RFC 8252
- OWASP Web Security Testing Guide — Test for Debug/Backdoor endpoints (Configuration and Deployment Management Testing)
- OWASP Secrets Management Cheat Sheet
- The Twelve-Factor App — Config
- Node.js —
crypto.timingSafeEqual - NestJS — Guards
- Architecture Decision Records (adr.github.io)
- OAuth 2.0 Security Best Current Practice — RFC 9700
- OAuth 2.0 for Browser-Based Apps (BFF pattern)
- OpenID Connect Core 1.0 — ID Token Validation
- OWASP Session Management Cheat Sheet
- OWASP Unvalidated Redirects and Forwards Cheat Sheet
- OWASP Logging Cheat Sheet
- Mermaid — Sequence diagrams and mermaid-cli
- Architecture Decision Records