答案:A。这是 Web 安全里最常见也最致命的误区之一。前端代码(包括权限判断)整个运行在用户的浏览器里,用户可以打开开发者工具改它、可以绕过 UI 直接对后端接口构造请求。所以前端的 useHasProjectAccess「隐藏按钮」只是体验优化(让你看不到点不了的功能、不吃无谓的报错),绝不构成安全边界。真正挡住越权的,是后端每个 tRPC resolver 里的 throwIfNoProjectAccess——它跑在你控制的服务器上、不可绕过。许多越权漏洞正源于「只在前端藏了按钮,后端却忘了校验」,以为按钮没了就进不去,实则接口裸奔。原则:前端隐藏是礼貌,后端强制才是安全,两者必须同时在。
💭 发散思考(没有标准答案,动手或动脑想想)
这一课把授权拆成两类对象(人走 RBAC、机器走 API key)外加 SCIM,背后是「最小权限 + 纵深防御」两条信条。请结合你做过的系统想一想:你的权限模型是「角色→scope」这种细粒度的,还是粗放的「管理员/普通用户」两档?两层哈希这种「为不同目的存同一秘密的多种派生物」的思路,在你别的场景里(如缓存、去重、索引)有没有类似的影子?如果要给一个新系统设计 API key 体系,你会怎么平衡安全、查询性能和可吊销性?
The previous lesson settled "who you are"; this one settles "what you can do" — authorization. Langfuse has two kinds of "guests" to authorize: humans (users clicking around the UI) and machines (programs reporting data via SDK, calling the API). The two take two authorization mechanisms: humans rely on RBAC (role-based access control) — packaging fine-grained permission points (scopes) into roles (OWNER/ADMIN/MEMBER/VIEWER), then checking your role in a given project; machines rely on API keys — a pk-lf-…/sk-lf-… key pair backed by a rather thoughtful two-tier hash design (one tier for "fast lookup," one for "secure storage"). Finally a glance at SCIM: letting an enterprise's identity system auto-provision/deprovision Langfuse users.
You'll repeatedly see two security creeds here: least privilege (grant only what's needed by default) and defense in depth (hide on the front end, block on the back end — do both).
📋 Analogy
Same office building. Last lesson you got in and received a visitor badge; this lesson is about which doors that badge opens.
For humans, the building manages access by "job role": front-desk, employee, supervisor, boss are each a role, and each role is pre-fitted with a string of keys (scopes) for "which rooms you may enter." You don't hand out keys person by person — just assign a person a job, and the key ring follows automatically — that's RBAC. And door access is done twice: the signpost on the door simply doesn't display rooms you can't enter (the front end hides buttons by role, nice UX), but what actually stops you is the lock itself (the back end enforces, security) — tearing off the signpost gets you nowhere.
For machines (say a delivery robot that comes at night), the building issues an access card (API key). The card itself (the secret in cleartext) is given to you only once at issuance; afterward the building keeps only two "fingerprints": one is a card-number hash for fast matching (instantly find who it is on swipe), the other a slow, salted fingerprint (even if the card-number store leaks, the original card can't be reverse-derived).
Authorizing humans: a role → a string of scopes
RBAC's core is one mapping table projectRoleAccessRights: Record<Role, ProjectScope[]>: mapping each role to a string of permission points (scopes). A scope is a fine-grained "resource:action" string, like traces:delete, prompts:CUD, apiKeys:read, project:delete. Roles run most-to-least powerful: OWNER → ADMIN → MEMBER → VIEWER → NONE: OWNER gets almost all scopes, VIEWER gets only a pile of *:read (read-only), NONE is an empty array (nothing). When checking permission you don't ask "are you OWNER" but "does your role contain this scope" — so adding a feature only means adding a scope to the relevant roles, not editing "if role==X" everywhere.
More crucially, the same permission point is checked in two places — this is defense in depth: the front end uses the React hook useHasProjectAccess to decide "should this delete button show" (UX: don't show what you can't do), the back end uses throwIfNoProjectAccess in every tRPC resolver to enforce (security: throw FORBIDDEN if no access). Front-end hiding is just courtesy; what actually blocks privilege escalation is the back end — because front-end code runs on the user's machine and can be bypassed.
Permissions aren't on/off but a "role × scope" table (from projectRoleAccessRights: Record<Role, ProjectScope[]> in rbac/constants/projectAccessRights.ts, real mapping): each API/page requires a scope (e.g. traces:delete), and checkProjectAccess checks whether the current role is in that scope's grant set. The five roles form a clean staircase: OWNER has all → ADMIN drops project:delete → MEMBER loses admin ops like traces:delete/apiKeys:CUD/auditLogs:read → VIEWER keeps only :read → NONE is empty (falls back to the org role). This table is exactly what the role field in Lesson 48's JWT is checked against.
// a scope is a fine-grained "resource:action" string; a role = a package of scopesexport const projectScopes = ["traces:delete", "prompts:CUD", "apiKeys:read",
"project:delete", "datasets:CUD", …] as const;
export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
OWNER: [ /* almost all scopes */ ],
ADMIN: [ … ], MEMBER: [ … ],
VIEWER: [ "project:read", "prompts:read", … /* only *:read */ ],
NONE: [], // nothing allowed
};
// back end: called in every tRPC resolver, throws FORBIDDEN on no access (the real gate)export constthrowIfNoProjectAccess = (p) => {
if (!hasProjectAccess(p))
throw newTRPCError({ code: "FORBIDDEN", message: "… no access …" });
};
// front end: same check as a React hook, to hide buttons without access (UX only)export constuseHasProjectAccess = ({ projectId, scope }) => { … };
👑 OWNER / ADMIN
Almost all scopes: create/delete projects, manage members and API keys, CRUD every resource. OWNER is the project owner; ADMIN is slightly less (e.g. can't delete the project).
✍️ MEMBER
The everyday working role: can read and CUD most business resources (trace/prompt/dataset/score…), but can't manage members or project settings — those governance operations.
👁️ VIEWER / NONE
VIEWER gets only a pile of *:read — can see, can't change, fit for audit/observers. NONE is an empty array — can't even see — the floor of least privilege.
Authorizing machines: the API key's two-tier hash
Programs authenticate with an API key: generateKeySet generates a pair pk-lf-{uuid} (public) / sk-lf-{uuid} (secret). The secret in cleartext is returned only once, at creation; afterward the DB stores only three derivatives: ① fastHashedSecretKey = createShaHash(sk, SALT) (sha256, deterministic, for "fast lookup"); ② hashedSecretKey = bcrypt hash (salted, slow, for "secure storage"); ③ displaySecretKey = a masked string (e.g. sk-lf-...abc, for UI display).
Why two hashes? Because "fast lookup" and "security" are a contradiction. bcrypt adds a random salt each time and is deliberately slow — secure, but you can't use it as a database lookup (the same key bcrypts to a different value each time, so you can only compare row by row, O(n)). sha256 is deterministic — the same key always computes the same value, so it can be used directly as an index/cache key for O(1) lookup, and since it hashes "the key itself + salt," a store leak can't reverse-derive the key. So when a request arrives: first createShaHash computes the fast hash, then look up Redis first, falling back to Postgres; a hit yields that key's scopes. Legacy-format keys (with only the bcrypt hash) are verified once with verifySecretKey, then conveniently "upgraded" by storing the fast hash. One more trick: a not-found key stores an API_KEY_NON_EXISTENT sentinel in Redis to stop someone hammering the database with piles of nonexistent keys.
Two-tier hash: apiKeys.ts:19generateKeySet (pk-lf/sk-lf); :41 createAndAddApiKeysToDb stores hashedSecretKey(bcrypt :13) / displaySecretKey / fastHashedSecretKey(createShaHash sha256 :31), salt env.SALT. Verify apiAuth.ts:75 verifyAuthHeaderAndReturnScope: :97 compute fast hash, Redis→PG lookup (:107 legacy key verifySecretKey + :141 upgrade with fastHash), nonexistent cached as API_KEY_NON_EXISTENT.
1
Request brings sk
Compute createShaHash(sk, env.SALT) for the deterministic fast hash — this key's "card number."
2
Look up Redis first, then PG
Using the fast hash as the key, ask the Redis cache first; on a miss, query Postgres indexed by fastHashedSecretKey. A hit yields this key's scopes.
3
Legacy key: bcrypt verify + upgrade
A legacy key with only a bcrypt hash is slow-verified once via verifySecretKey, then conveniently "upgraded" by adding the fast hash, taking the fast path next time.
4
Not found: cache a sentinel
A nonexistent key stores API_KEY_NON_EXISTENT in Redis, blocking "hammer the DB with piles of fake keys." Finally allow or deny by scope.
SCIM: letting the enterprise identity system auto-provision users
A large enterprise has thousands of employees, joining and leaving constantly. Relying on an admin to manually add people one by one in Langfuse and delete them on departure is slow and error-prone (a missed deletion = a departed employee still has access, a security hazard). SCIM (System for Cross-domain Identity Management) is a standard protocol letting an enterprise's identity hub (Okta, Azure AD) automatically sync "who should have an account": auto-provision on joining, auto-deprovision on leaving. Langfuse implements the standard SCIM endpoints in web/src/pages/api/public/scim/* — Users (create/delete/list users), ServiceProviderConfig/ResourceTypes/Schemas (self-describe to the IdP "which SCIM capabilities I support"). This is an enterprise (EE) capability, neatly leading into the next lesson's "open-core & entitlements."
Subject
Mechanism
How it's judged
Key design
Humans (UI users)
RBAC role→scope
does the role contain the scope
front-end hide + back-end enforce (defense in depth)
Machines (SDK/API)
API key (pk/sk)
sk's fast hash finds the key, read its scopes
two-tier hash: sha256 fast lookup + bcrypt secure
Enterprise bulk
SCIM protocol
IdP pushes user create/delete
auto-provision on join, auto-deprovision on leave (EE)
Read the three rows and you'll find authorization cleanly decomposed: different kinds of "guests" use different mechanisms, but all reduce to one question — "is this operation within your permission range?" RBAC gives humans a "role," API keys give machines a "scoped secret," SCIM lets that roster be auto-maintained by the enterprise. Each does its job, and all serve the least-privilege principle of "every subject gets only the privileges it needs."
🎯 Design trade-off
Why store both a "sha256 fast hash" and a "bcrypt slow hash" for an API key — why not just one? Because the two solve a pair of conflicting needs. bcrypt's security comes from adding a random salt each time and being deliberately slow — making brute force uneconomical, but with a side effect: the same key bcrypts to a different value each time, so you can't use it as a database lookup condition; you'd bcrypt-compare every row (O(n), scanning the whole table per auth, a disaster). And API auth is extremely high-frequency (every reported trace verifies a key once), so it must find the key in O(1). sha256(key, SALT) fills the gap exactly: it's deterministic — the same key always computes the same value, so it can be an index or a Redis cache key for a one-step lookup; and since it hashes "the secret itself" rather than something enumerable, plus salt, a store leak can't reverse the key. So the final design is a division of labor: sha256 handles "O(1) find which key it is among millions," bcrypt handles "salted slow verification for legacy keys." When "fast" and "secure" conflict, it's not either/or but two tools each owning a segment.
Why does RBAC check both front end and back end — isn't checking only the back end enough, isn't it duplicate? The two checks have fundamentally different purposes, both indispensable. The back-end check is the security gate: throwIfNoProjectAccess in tRPC resolvers is the truly un-bypassable enforcement — because it runs on the server. The front-end check is UX: useHasProjectAccess simply doesn't show the buttons you can't use, sparing you a red error after clicking. The key realization: a front-end permission check is only "politeness," never security — because front-end code runs entirely in the user's browser; the user can modify it or craft requests directly to bypass the UI. So "front-end hiding" must always have "back-end enforcement" behind it. Many privilege-escalation bugs come precisely from a developer hiding a button on the front end but forgetting to add the back-end check — thinking "no button means no entry," while the endpoint sits exposed.
🎯 Key points
Authorization = what you can do: two subjects — humans (UI users) take RBAC, machines (SDK/API) take API keys; plus SCIM for the enterprise identity system to auto-maintain users. Shared goal: least privilege.
RBAC role→scope: projectRoleAccessRights: Record<Role, Scope[]> maps OWNER/ADMIN/MEMBER/VIEWER/NONE each to a string of fine-grained scopes (traces:delete etc, VIEWER read-only, NONE empty). Check "does the role contain the scope"; adding a feature just adds a scope.
Defense in depth: dual check: front-end useHasProjectAccess hides buttons (UX), back-end throwIfNoProjectAccess throws FORBIDDEN (security). The front end is bypassable; the real gate is the back end — front-end hiding must always have back-end enforcement behind it.
API key two-tier hash: fastHashedSecretKey=sha256 (deterministic, for O(1) fast lookup, cacheable) + hashedSecretKey=bcrypt (salted slow, secure) + displaySecretKey (masked display). The sk cleartext is returned only at creation; verification computes the fast hash, looks up Redis→PG, legacy keys verified by bcrypt then upgraded, nonexistent keys cached as a sentinel to stop DB hammering.
SCIM enterprise automation: a standard protocol letting Okta/Azure AD auto-provision/deprovision Langfuse users (have on joining, gone on leaving), avoiding manual add/delete misses. An EE capability, leading into the next lesson's open-core & entitlements.
🧪 Self-test - think about the design
1. Langfuse's RBAC writes the permission check as 'does your role contain this scope' (e.g. traces:delete), rather than 'are you OWNER/ADMIN'. The main benefit of this 'role→scope' indirection is?
this eliminates the need for roles
decoupling and maintainability: feature code only asks 'has this scope', adding a feature just adds a scope to relevant roles in the role definition, no editing scattered 'if role==X' checks everywhere; the permission model is centralized in one Record table, clear and auditable
scope checks run faster than role checks
scope strings compress storage
Show answer & explanation click to expand
Answer: B. If you write 'if (role === OWNER || role === ADMIN)' everywhere, every new feature and every permission tweak means combing the code for these scattered checks—easy to miss or misconfigure. With the scope indirection: each feature cares about one fine-grained point (traces:delete), while 'which role has which scopes' is maintained centrally in the projectRoleAccessRights table. Add a feature = add a scope to a role; tweak permissions = edit the table; the check logic (hasProjectAccess) stays fully generic. A classic 'a layer of indirection for maintainability and auditability'—and it makes 'what exactly can this role do' obvious at a glance.
2. Langfuse stores two hashes per API key: fastHashedSecretKey (sha256) and hashedSecretKey (bcrypt). Why not just use bcrypt alone?
bcrypt is obsolete and must be paired with sha256
because bcrypt adds a random salt each time with a nondeterministic result, unusable as a DB lookup key (only row-by-row compare, O(n)), while API auth is extremely high-frequency and must find it in O(1); sha256 is deterministic, same key→constant value, usable directly as an index/cache key for one-step lookup, and it hashes the secret itself + salt so a leak can't reverse it — the two divide labor: sha for fast lookup, bcrypt for secure storage
two hashes double-encrypt for more security
sha256 for the public key, bcrypt for the secret key
Show answer & explanation click to expand
Answer: B. 'Fast lookup' and 'brute-force resistance' conflict. bcrypt is deliberately slow for brute-force resistance and salted differently each time, so a key's bcrypt value isn't fixed—you can't use it in a WHERE lookup, only a full-table row-by-row compare, and since API auth verifies a key per trace, an O(n) scan is a disaster. sha256(key,SALT) is deterministic: same key→same value, usable as an index or Redis cache key for an O(1) hit; and since it hashes 'the secret itself' (high-entropy, non-enumerable) plus salt, a store leak can't reverse the key. So they divide labor: sha256 quickly locates which key among millions, bcrypt does salted slow verification for legacy keys. Exactly 'when fast and secure conflict, use two tools each owning a segment'.
3. Langfuse checks the same permission point (e.g. 'delete trace') in both front end (useHasProjectAccess) and back end (throwIfNoProjectAccess). Which statement about these two checks is correct?
the back-end check is the truly un-bypassable security gate (runs on the server), the front-end check is only UX (hide buttons without access); a front-end check is never security because front-end code runs in the user's browser, can be modified, and requests can be crafted to bypass the UI — front-end hiding must always have back-end enforcement behind it
the front-end check is the security gate, the back end is auxiliary
once the front end hides the button, the endpoint is automatically secure
the two checks are fully redundant; drop the back-end one to save performance
Show answer & explanation click to expand
Answer: A. This is one of the most common and fatal misconceptions in web security. Front-end code (including permission checks) runs entirely in the user's browser; the user can open dev tools to modify it or bypass the UI to craft requests straight to the back end. So the front-end useHasProjectAccess 'hide button' is only UX (you don't see unusable features or eat pointless errors), never a security boundary. What truly blocks escalation is throwIfNoProjectAccess in every back-end tRPC resolver—it runs on your controlled server and is un-bypassable. Many escalation bugs come precisely from 'hiding a button on the front end but forgetting the back-end check', thinking no button means no entry while the endpoint runs naked. Principle: front-end hiding is politeness, back-end enforcement is security, both must be present.
💭 Open questions (no single right answer - just think or try)
This lesson splits authorization into two subjects (humans via RBAC, machines via API keys) plus SCIM, underpinned by 'least privilege + defense in depth'. Reflect on systems you've built: is your permission model fine-grained 'role→scope', or coarse 'admin/regular user' two-tier? Does the two-tier-hash idea of 'storing multiple derivatives of the same secret for different purposes' echo elsewhere in your work (caching, dedup, indexing)? If designing an API key system for a new product, how would you balance security, query performance, and revocability?