🪢 Langfuse 图解教程Langfuse Visual Guide 第十部分 · 平台与运维Part 10 · Platform & Operations 49 / 55
第十部分 · 平台与运维Part 10 · Platform & Operations

RBAC · API key · SCIMRBAC, API keys & SCIM

🧭 读前Before you start
先读 第48课 的鉴权与 第10课 的多租户,本课讲 RBAC、API key 与 SCIM。
Read Lesson 48 (auth) and Lesson 10 (multi-tenancy); this lesson covers RBAC, API keys, and SCIM.

上一课解决了「你是谁」,这一课解决「你能干什么」——授权(authorization)。Langfuse 有两类「客人」要授权:人(在 UI 里点点点的用户)和机器(用 SDK 上报数据、调 API 的程序)。两类客人走两套授权机制:人靠 RBAC(基于角色的访问控制)——把细粒度的权限点(scope)打包成角色(OWNER/ADMIN/MEMBER/VIEWER),再看你在某项目里是什么角色;机器靠 API key——一对 pk-lf-…/sk-lf-… 密钥,背后藏着一个相当讲究的两层哈希设计(一层为了「查得快」,一层为了「存得安全」)。最后再看一眼 SCIM:让企业的身份系统能自动开通/注销 Langfuse 用户。 这一课你会反复看到两条安全信条:最小权限(默认只给够用的)与纵深防御(前端藏、后端拦,两道都做)。

📋 生活类比
还是那栋写字楼。上一课你已进了门、拿到访客牌,这一课讲这张牌能开哪些门。 对人,楼里用「岗位」管权限:前台、员工、主管、老板各是一个角色,每个角色预先配好「能进哪些房间」的一串钥匙(scope)。你不必逐人发钥匙,只要给人定个岗位,钥匙串就自动跟过来——这就是 RBAC。而且门禁做了两道:门上贴的指示牌会把你进不去的房间直接不显示(前端按角色隐藏按钮,体验好),但真正拦你的是门锁本身(后端强制校验,安全)——光把指示牌撕了可没用。 对机器(比如夜里自动来送货的机器人),楼里发的是一张门禁卡(API key)。卡片本体(密钥明文)只在发卡那一刻给你一次,之后楼里只留两份「指纹」:一份是快速比对用的卡号哈希(刷卡时一秒查到是谁),一份是慢而安全的加盐指纹(万一卡号库泄露也反推不出原卡)。

人的授权:角色 → 一串 scope

RBAC 的核心是一张映射表 projectRoleAccessRights: Record<Role, ProjectScope[]>:把每个角色映射到一串权限点(scope)。scope 是细粒度的「资源:动作」字符串,如 traces:delete、prompts:CUD、apiKeys:read、project:delete。角色从权大到权小是 OWNER → ADMIN → MEMBER → VIEWER → NONE:OWNER 拿到几乎全部 scope,VIEWER 只拿到一堆 *:read(只读),NONE 是空数组(什么都不能)。判权限时不直接问「你是不是 OWNER」,而是问「你的角色里有没有这个 scope」——这样加新功能只需给相关角色添一个 scope,不必到处改「if 角色==X」。

更关键的是同一个权限点要在两处校验,这是纵深防御:前端用 React hook useHasProjectAccess 决定「这个删除按钮要不要显示」(体验:没权限就别给看),后端在每个 tRPC resolver 里用 throwIfNoProjectAccess 强制拦截(安全:没权限就抛 FORBIDDEN)。前端的隐藏只是体面,真正挡住越权的是后端那道——因为前端代码在用户机器上,可被绕过。

角色打包 scope;同一权限前后端两道校验 角色(由大到小) OWNER(几乎全部) ADMIN MEMBER VIEWER(仅 *:read) NONE(空 []) scope 权限点(细粒度)traces:delete · prompts:CUDapiKeys:read · project:deletedatasets:CUD · scores:CUD …projectRoleAccessRightsRecord<Role, Scope[]> ① 前端 useHasProjectAccess没权限就隐藏按钮(体验)React hook · 可被绕过,仅体面 ② 后端 throwIfNoProjectAccess没权限抛 TRPCError FORBIDDEN(安全)每个 tRPC resolver 强制·真正的闸 判权限问「角色里有没有这个 scope」,而非「是不是某角色」——加功能只需给角色添 scope 前端隐藏可被绕过(代码在用户机器上),真正挡越权的是后端那道——纵深防御
角色→scope + 双查:projectAccessRights.ts:91 projectRoleAccessRights: Record<Role, ProjectScope[]>(OWNER:92 / ADMIN:150 / MEMBER:207 / VIEWER:251 仅 read / NONE:271 空);checkProjectAccess.ts:28 throwIfNoProjectAccess(服务端,抛 TRPCError FORBIDDEN)+ :42 useHasProjectAccess(前端 hook,隐藏 UI)。
示例:项目角色 × 权限矩阵 行=权限 scope,列=角色;■=有,□=无 OWNER ADMIN MEMBER VIEWER NONE scope project:read ✓ ✓ ✓ ✓ ✗ prompts:read ✓ ✓ ✓ ✓ ✗ scores:CUD ✓ ✓ ✓ ✗ ✗ prompts:CUD ✓ ✓ ✓ ✗ ✗ playground:execute ✓ ✓ ✓ ✗ ✗ traces:delete ✓ ✓ ✗ ✗ ✗ apiKeys:CUD ✓ ✓ ✗ ✗ ✗ auditLogs:read ✓ ✓ ✗ ✗ ✗ project:delete ✓ ✗ ✗ ✗ ✗ 该角色 scope 总数 56 55 42 18 0 阶梯式收权:OWNER 全有 · ADMIN 缺 project:delete · MEMBER 缺管理类 · VIEWER 只读 · NONE 回落到组织角色
权限不是「开/关」,而是一张「角色 × scope」表(取自 rbac/constants/projectAccessRights.ts 的 projectRoleAccessRights: Record<Role, ProjectScope[]>,真实映射):每个 API/页面要求某个 scope(如 traces:delete),checkProjectAccess 查当前角色是否在该 scope 的授权集里。五个角色排成清晰阶梯:OWNER 全有 → ADMIN 少了 project:delete → MEMBER 没有 traces:delete/apiKeys:CUD/auditLogs:read 这些管理类 → VIEWER 只剩 :read → NONE 为空(回落组织角色)。这张表正是第 48 课 JWT 里 role 字段的判权依据。
web/src/features/rbac/constants/projectAccessRights.ts · utils/checkProjectAccess.ts角色→scope + 强制校验
// scope 是细粒度「资源:动作」串;角色 = 一串 scope 的打包
export const projectScopes = ["traces:delete", "prompts:CUD", "apiKeys:read",
                              "project:delete", "datasets:CUD", …] as const;

export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
  OWNER:  [ /* 几乎全部 scope */ ],
  ADMIN:  [ … ],   MEMBER: [ … ],
  VIEWER: [ "project:read", "prompts:read", … /* 只有 *:read */ ],
  NONE:   [],      // 什么都不能
};

// 后端:每个 tRPC resolver 调用,无权限即抛 FORBIDDEN(真正的闸)
export const throwIfNoProjectAccess = (p) => {
  if (!hasProjectAccess(p))
    throw new TRPCError({ code: "FORBIDDEN", message: "… no access …" });
};
// 前端:同款判断的 React hook,用来隐藏没权限的按钮(仅体验)
export const useHasProjectAccess = ({ projectId, scope }) => { … };

👑 OWNER / ADMIN

几乎全部 scope:建删项目、管成员与 API key、增删改一切资源。OWNER 是项目主人,ADMIN 略少(如不能删项目)。

✍️ MEMBER

日常干活的角色:能读、能增删改大多数业务资源(trace/prompt/dataset/score…),但管不了成员与项目设置这类治理类操作。

👁️ VIEWER / NONE

VIEWER 只拿一堆 *:read——看得见、改不了,适合审计/旁观者。NONE 是空数组,连看都不行——最小权限的下限。

机器的授权:API key 的两层哈希

程序用 API key 认证:generateKeySet 生成一对 pk-lf-{uuid}(public)/sk-lf-{uuid}(secret)。secret 明文只在创建那一刻返回一次,之后库里只存它的三种衍生物:① fastHashedSecretKey= createShaHash(sk, SALT)(sha256,确定性,给「查得快」用);② hashedSecretKey= bcrypt 哈希(加盐慢,给「存得安全」用);③ displaySecretKey= 打码串(如 sk-lf-...abc,给 UI 显示)。

为什么要两种哈希?因为「快查」和「安全」是一对矛盾。bcrypt 每次加随机盐、故意很慢——安全,但没法拿它做数据库查找(同一个 key 每次 bcrypt 结果都不同,你只能一行行比对,O(n))。sha256 是确定性的——同一个 key 永远算出同一个值,能直接当索引/缓存键 O(1) 查到,且因为算的是「key 本身 + 盐」,库泄露也反推不出原 key。于是请求来时:先 createShaHash 算出快哈希,先查 Redis、没有再查 Postgres;命中即拿到这把 key 的 scope。老格式的 key(只有 bcrypt 哈希)会用 verifySecretKey 验一次、然后顺手补上快哈希「升级」。还有个小心机:查不到的 key 在 Redis 里存一个 API_KEY_NON_EXISTENT 哨兵,防止有人拿一堆不存在的 key 反复砸数据库。

一层为「查得快」,一层为「存得安全」 创建时(generateKeySet)pk-lf-{uuid} / sk-lf-{uuid}sk 明文只返回这一次! ① fastHashedSecretKeysha256(sk,SALT) 确定性·快查 ② hashedSecretKeybcrypt 加盐慢·安全 ③ displaySecretKeysk-lf-...abc 打码显示 请求带 sk 来createShaHash(sk,SALT) 先查 Redis命中即拿 scope(O(1)) 没有→查 Postgres按 fastHashedSecretKey 索引 老格式 key(仅 bcrypt)verifySecretKey 验一次 → 补 fastHash「升级」 查不到 → 缓存哨兵API_KEY_NON_EXISTENT 防刷库 拿到 scope → 放行/拒绝机器也有自己的权限范围
两层哈希:apiKeys.ts:19 generateKeySet(pk-lf/sk-lf);:41 createAndAddApiKeysToDb 存 hashedSecretKey(bcrypt :13) / displaySecretKey / fastHashedSecretKey(createShaHash sha256 :31),盐 env.SALT。验证 apiAuth.ts:75 verifyAuthHeaderAndReturnScope::97 算快哈希、Redis→PG 查(:107 老 key verifySecretKey + :141 升级补 fastHash),不存在缓存 API_KEY_NON_EXISTENT。
1

请求带 sk 来

算 createShaHash(sk, env.SALT) 得到确定性的快哈希——这把 key 的「卡号」。

2

先查 Redis,没有再查 PG

用快哈希当键,先问 Redis 缓存;未命中再按 fastHashedSecretKey 索引查 Postgres。命中即拿到这把 key 的 scope。

3

老格式 key:bcrypt 验 + 升级

只有 bcrypt 哈希的旧 key,用 verifySecretKey 慢验一次,然后顺手补上快哈希「升级」,下次就走快路。

4

查不到:缓存哨兵

不存在的 key 在 Redis 存 API_KEY_NON_EXISTENT,挡住「拿一堆假 key 反复砸数据库」的攻击。最后据 scope 放行或拒绝。

SCIM:让企业身份系统自动开通用户

大企业有几千名员工,进出职频繁。靠管理员手动在 Langfuse 里一个个加人、离职再删人,既慢又容易漏(漏删 = 离职员工还能访问,是安全隐患)。SCIM(System for Cross-domain Identity Management,跨域身份管理系统)是一套标准协议,让企业的身份中枢(如 Okta、Azure AD)能自动把「谁该有账号」同步过来:入职自动开通、离职自动注销。Langfuse 在 web/src/pages/api/public/scim/* 实现了 SCIM 的标准端点——Users(增删查用户)、ServiceProviderConfig/ResourceTypes/Schemas(向 IdP 自描述「我支持哪些 SCIM 能力」)。这属于企业级(EE)能力,正好引出下一课的「开源核与权益」。

SCIM:IdP 自动同步「谁该有账号」 企业身份中枢 Okta / Azure AD SCIM 标准端点(scim/*) Users(增删查用户) ServiceProviderConfig ResourceTypes / Schemas(自描述) Langfuse 用户生命周期 入职 → 自动开通 provision 离职 → 自动注销 deprovision 漏删=隐患,自动注销堵住 推送
授权对象机制怎么判关键设计
人(UI 用户)RBAC 角色→scope角色里有没有该 scope前端隐藏 + 后端强制(纵深防御)
机器(SDK/API)API key(pk/sk)sk 的快哈希查到 key、读其 scope两层哈希:sha256 快查 + bcrypt 安全
企业批量SCIM 协议由 IdP 推送增删用户入职自动开通、离职自动注销(EE)

把三行读完,你会发现授权这件事被拆得很清爽:不同类型的「客人」用不同的机制,但都落到同一个问题——「这次操作,在不在你的权限范围内」。RBAC 给人发「角色」、API key 给机器发「带 scope 的密钥」、SCIM 让这套人员名册能被企业自动维护。三者各司其职,又都服务于「每个主体只拿够用的权限」这条最小权限原则。

🎯 设计取舍
为什么 API key 要同时存「sha256 快哈希」和「bcrypt 慢哈希」两份,不能只留一份? 因为这两份分别解决一对互相打架的需求。bcrypt 的安全来自它每次都加随机盐、且故意算得很慢——这让暴力破解变得不划算,但也带来一个副作用:同一个 key 每次 bcrypt 出来的值都不同,所以你没法拿它当数据库查找条件,只能把库里每一行都 bcrypt-compare 一遍(O(n),每次认证扫全表,灾难)。而 API 认证是极高频的(每条上报的 trace 都要验一次 key),必须 O(1) 查到。sha256(key, SALT) 正好补上:它确定性——同一个 key 永远算出同一个值,于是能直接当索引、当 Redis 缓存键,一步查到;同时因为算的是「密钥本身」而非可枚举的东西,加上盐,库泄露也反推不出原 key。所以最终方案是分工:sha256 负责「在海量 key 里 O(1) 找到是哪一把」,bcrypt 负责「对老格式 key 做加盐慢验证」。当「快」和「安全」打架时,不是二选一,而是用两种工具各管一段。

RBAC 为什么前端、后端都要查一遍?只在后端查不够吗、岂不是重复? 两道查的目的根本不同,缺一不可。后端那道是安全闸:tRPC resolver 里的 throwIfNoProjectAccess 是真正不可绕过的强制——因为它跑在服务器上。前端那道是体验:useHasProjectAccess 把你没权限的按钮直接不显示,让你不会点了之后才吃一个红色报错。关键认知是:前端的权限判断只是「礼貌」,绝不能当作安全——因为前端代码整个跑在用户的浏览器里,用户可以改它、可以直接构造请求绕过 UI。所以「前端隐藏」必须始终有「后端强制」兜底。很多越权漏洞,恰恰来自开发者只在前端藏了按钮、却忘了在后端加校验——以为「按钮没了就进不去」,殊不知接口是裸的。
🎯 本课要点
  • 授权 = 你能干什么:两类对象——人(UI 用户)走 RBAC,机器(SDK/API)走 API key;外加 SCIM 让企业身份系统自动维护用户。共同目标:最小权限。
  • RBAC 角色→scope:projectRoleAccessRights: Record<Role, Scope[]> 把 OWNER/ADMIN/MEMBER/VIEWER/NONE 各映射到一串细粒度 scope(traces:delete 等,VIEWER 仅 read、NONE 空)。判权限问「角色含不含该 scope」,加功能只需添 scope。
  • 纵深防御:前后端双查:前端 useHasProjectAccess 隐藏按钮(体验),后端 throwIfNoProjectAccess 抛 FORBIDDEN(安全)。前端可被绕过,真正的闸是后端——前端隐藏永远要有后端强制兜底。
  • API key 两层哈希:fastHashedSecretKey=sha256(确定性,给 O(1) 快查、可缓存) + hashedSecretKey=bcrypt(加盐慢,安全) + displaySecretKey(打码显示)。sk 明文只在创建时返回一次;验证先算快哈希查 Redis→PG,老 key 用 bcrypt 验后升级,不存在的 key 缓存哨兵防刷库。
  • SCIM 企业自动化:标准协议让 Okta/Azure AD 等自动开通/注销 Langfuse 用户(入职即有、离职即无),避免手动加删的遗漏。属 EE 能力,引出下一课开源核与权益。

🧪 自测 · 想一想为什么这么设计

1. Langfuse 的 RBAC 把权限判断写成「你的角色里有没有这个 scope」(如 traces:delete),而不是「你是不是 OWNER/ADMIN」。这种「角色→scope」间接层的主要好处是?
  1. 这样可以不需要角色了
  2. 解耦与可维护:功能代码只问「有没有某 scope」,加新功能只需在角色定义里给相关角色添一个 scope,不必到处去改散落的「if 角色==X」判断;权限模型集中在一张 Record 表里,清晰可审计
  3. scope 比角色判断运行更快
  4. scope 字符串能压缩存储
看答案与解析 点击展开
答案:B。如果到处写「if (role === 'OWNER' || role === 'ADMIN')」,每加一个功能、每调一次权限,都要翻遍代码找这些散落的判断,极易漏改、错配。引入 scope 间接层后:每个功能只关心一个细粒度权限点(traces:delete),而「哪个角色拥有哪些 scope」集中在 projectRoleAccessRights 一张表里维护。加功能=给角色添 scope,调权限=改这张表,判断逻辑(hasProjectAccess)则完全通用。这是「用一层间接换取可维护性与可审计性」的经典做法——也让「这个角色到底能干什么」一目了然。
2. Langfuse 为每个 API key 存了两种哈希:fastHashedSecretKey(sha256)和 hashedSecretKey(bcrypt)。为什么不能只用 bcrypt 一种?
  1. bcrypt 已经过时,必须配 sha256
  2. 因为bcrypt每次加随机盐、结果不确定,没法当数据库查找键(只能逐行compare,O(n)),而API认证极高频必须O(1)查到;sha256确定性、同key恒定值,能直接当索引/缓存键一步查到,且哈希的是密钥本身+盐故泄露也反推不出——两者分工:sha查得快、bcrypt存得安全
  3. 两种哈希是为了双重加密更安全
  4. sha256 用于公钥、bcrypt 用于私钥
看答案与解析 点击展开
答案:B。「快查」和「抗暴破」是一对矛盾。bcrypt 为抗暴破刻意慢、且每次盐不同,导致同一 key 的 bcrypt 值不固定——你无法拿它做 WHERE 查找,只能扫全表逐行 compare,而 API 认证每条 trace 都要验一次 key,O(n) 扫表是灾难。sha256(key,SALT) 是确定性的:同一 key 永远同一值,能直接建索引、当 Redis 缓存键,O(1) 命中;又因为算的是「密钥本身」(高熵、不可枚举)加盐,库泄露也无法反推原 key。于是分工:sha256 负责「在海量 key 里快速定位是哪把」,bcrypt 负责老格式 key 的加盐慢验证。这正是「当快与安全冲突时,用两种工具各管一段」。
3. Langfuse 的同一个权限点(如「删除 trace」)在前端用 useHasProjectAccess、后端用 throwIfNoProjectAccess 各查一遍。关于这两道校验,哪种说法正确?
  1. 后端那道是真正不可绕过的安全闸(跑在服务器上),前端那道只是体验优化(隐藏没权限的按钮);前端校验绝不能当安全,因为前端代码在用户浏览器里可被改、可直接构造请求绕过UI——前端隐藏必须始终有后端强制兜底
  2. 前端那道是安全闸,后端只是辅助
  3. 只要前端隐藏了按钮,接口就自动安全了
  4. 两道校验完全重复,可以删掉后端那道省性能
看答案与解析 点击展开
答案: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.

Roles package scopes; same permission checked front + back roles (most→least) OWNER (almost all) ADMIN MEMBER VIEWER (only *:read) NONE (empty []) scope points (fine-grained)traces:delete · prompts:CUDapiKeys:read · project:deletedatasets:CUD · scores:CUD …projectRoleAccessRightsRecord<Role, Scope[]> ① front: useHasProjectAccesshide the button if no access (UX)React hook · bypassable, courtesy only ② back: throwIfNoProjectAccessthrow TRPCError FORBIDDEN if no access (security)enforced in every tRPC resolver · the real gate Ask "does the role contain this scope," not "is it some role" — adding a feature just adds a scope to a role Front-end hiding is bypassable (code runs on the user's machine); the real escalation block is the back end — defense in depth
Role→scope + dual check: projectAccessRights.ts:91 projectRoleAccessRights: Record<Role, ProjectScope[]> (OWNER:92 / ADMIN:150 / MEMBER:207 / VIEWER:251 read-only / NONE:271 empty); checkProjectAccess.ts:28 throwIfNoProjectAccess (server, throws TRPCError FORBIDDEN) + :42 useHasProjectAccess (front-end hook, hides UI).
Example: project role × permission matrix rows = scopes, cols = roles; ■ = granted, □ = denied OWNER ADMIN MEMBER VIEWER NONE scope project:read ✓ ✓ ✓ ✓ ✗ prompts:read ✓ ✓ ✓ ✓ ✗ scores:CUD ✓ ✓ ✓ ✗ ✗ prompts:CUD ✓ ✓ ✓ ✗ ✗ playground:execute ✓ ✓ ✓ ✗ ✗ traces:delete ✓ ✓ ✗ ✗ ✗ apiKeys:CUD ✓ ✓ ✗ ✗ ✗ auditLogs:read ✓ ✓ ✗ ✗ ✗ project:delete ✓ ✗ ✗ ✗ ✗ total scopes / role 56 55 42 18 0 a staircase: OWNER all · ADMIN lacks project:delete · MEMBER lacks admin ops · VIEWER read-only · NONE falls back to the org role
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.
web/src/features/rbac/constants/projectAccessRights.ts · utils/checkProjectAccess.tsrole→scope + enforced check
// a scope is a fine-grained "resource:action" string; a role = a package of scopes
export 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 const throwIfNoProjectAccess = (p) => {
  if (!hasProjectAccess(p))
    throw new TRPCError({ code: "FORBIDDEN", message: "… no access …" });
};
// front end: same check as a React hook, to hide buttons without access (UX only)
export const useHasProjectAccess = ({ 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.

One tier for "fast lookup," one for "secure storage" at creation (generateKeySet)pk-lf-{uuid} / sk-lf-{uuid}sk cleartext returned only once! ① fastHashedSecretKeysha256(sk,SALT) deterministic·fast ② hashedSecretKeybcrypt salted slow·secure ③ displaySecretKeysk-lf-...abc masked display request brings skcreateShaHash(sk,SALT) look up Redis firsthit → get scopes (O(1)) miss → query Postgresindexed by fastHashedSecretKey legacy key (bcrypt only)verifySecretKey once → add fastHash "upgrade" not found → cache a sentinelAPI_KEY_NON_EXISTENT, stop DB hammering get scopes → allow/denymachines also have their own scope range
Two-tier hash: apiKeys.ts:19 generateKeySet (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."

SCIM: the IdP auto-syncs "who should have an account" identity hub Okta / Azure AD SCIM standard endpoints (scim/*) Users (create/delete/list) ServiceProviderConfig ResourceTypes / Schemas (self-describe) Langfuse user lifecycle join → auto-provision leave → auto-deprovision missed deletion = hazard, closed push
SubjectMechanismHow it's judgedKey design
Humans (UI users)RBAC role→scopedoes the role contain the scopefront-end hide + back-end enforce (defense in depth)
Machines (SDK/API)API key (pk/sk)sk's fast hash finds the key, read its scopestwo-tier hash: sha256 fast lookup + bcrypt secure
Enterprise bulkSCIM protocolIdP pushes user create/deleteauto-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?
  1. this eliminates the need for roles
  2. 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
  3. scope checks run faster than role checks
  4. 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?
  1. bcrypt is obsolete and must be paired with sha256
  2. 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
  3. two hashes double-encrypt for more security
  4. 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?
  1. 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
  2. the front-end check is the security gate, the back end is auxiliary
  3. once the front end hides the button, the endpoint is automatically secure
  4. 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?