forked from Cap-go/capgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrbac.ts
More file actions
490 lines (451 loc) · 13.3 KB
/
rbac.ts
File metadata and controls
490 lines (451 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/**
* RBAC Permission System
*
* This module provides a unified permission checking system that routes between
* legacy role-based checks (check_min_rights) and the new RBAC permission system
* based on the org's feature flag.
*
* Usage:
* import { checkPermission } from './rbac.ts'
*
* // Check app-level permission
* const allowed = await checkPermission(c, 'app.upload_bundle', { appId: 'com.example.app' })
*
* // Check channel-level permission (appId and orgId are auto-derived)
* const allowed = await checkPermission(c, 'channel.promote_bundle', { channelId: 123 })
*
* // Check org-level permission
* const allowed = await checkPermission(c, 'org.invite_user', { orgId: 'uuid...' })
*/
import type { Context } from 'hono'
import type { MiddlewareKeyVariables } from './hono.ts'
import type { Database } from './supabase.types.ts'
import { sql } from 'drizzle-orm'
import { cloudlog, cloudlogErr } from './logging.ts'
import { closeClient, getDrizzleClient, getPgClient, logPgError } from './pg.ts'
// =============================================================================
// Types
// =============================================================================
/**
* All available RBAC permissions from the permissions table.
* These match exactly the keys in public.permissions.
*/
export type Permission
= | 'org.read'
| 'org.create_app'
| 'org.update_settings'
| 'org.delete'
| 'org.read_members'
| 'org.invite_user'
| 'org.update_user_roles'
| 'org.read_billing'
| 'org.update_billing'
| 'org.read_invoices'
| 'org.read_audit'
| 'org.read_billing_audit'
// App permissions
| 'app.read'
| 'app.update_settings'
| 'app.delete'
| 'app.read_bundles'
| 'app.upload_bundle'
| 'app.create_channel'
| 'app.read_channels'
| 'app.read_logs'
| 'app.manage_devices'
| 'app.read_devices'
| 'app.build_native'
| 'app.read_audit'
| 'app.update_user_roles'
// Bundle permissions
| 'bundle.delete'
// Channel permissions
| 'channel.read'
| 'channel.update_settings'
| 'channel.delete'
| 'channel.read_history'
| 'channel.promote_bundle'
| 'channel.rollback_bundle'
| 'channel.manage_forced_devices'
| 'channel.read_forced_devices'
| 'channel.read_audit'
/**
* Scope types for RBAC permissions
*/
export type ScopeType = 'org' | 'app' | 'channel'
/**
* Scope identifiers for permission checks.
* At least one must be provided. More specific scopes (channelId) will auto-derive
* parent scopes (appId, orgId) if not explicitly provided.
*/
export interface PermissionScope {
orgId?: string
appId?: string
channelId?: number
}
/**
* Extended context interface with RBAC information
*/
export interface RbacContextVariables {
rbacEnabled?: boolean
resolvedOrgId?: string
}
function deniesExplicitApiKeyScope(
c: Context<MiddlewareKeyVariables>,
scope: PermissionScope,
) {
const auth = c.get('auth')
if (auth?.authType !== 'apikey' || !auth.apikey)
return false
const limitedToApps = auth.apikey.limited_to_apps
if (scope.appId && Array.isArray(limitedToApps) && limitedToApps.length > 0 && !limitedToApps.includes(scope.appId)) {
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermission: explicit api key app scope denied',
appId: scope.appId,
keyId: auth.apikey.id,
})
return true
}
const limitedToOrgs = auth.apikey.limited_to_orgs
if (scope.orgId && Array.isArray(limitedToOrgs) && limitedToOrgs.length > 0 && !limitedToOrgs.includes(scope.orgId)) {
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermission: explicit api key org scope denied',
orgId: scope.orgId,
keyId: auth.apikey.id,
})
return true
}
return false
}
// =============================================================================
// Legacy Mapping
// =============================================================================
/**
* Maps RBAC permissions to legacy user_min_right values.
* Used for fallback when org doesn't have RBAC enabled.
*/
const PERMISSION_TO_LEGACY_RIGHT: Record<Permission, Database['public']['Enums']['user_min_right']> = {
// Org permissions
'org.read': 'read',
'org.create_app': 'admin',
'org.update_settings': 'admin',
'org.delete': 'super_admin',
'org.read_members': 'read',
'org.invite_user': 'admin',
'org.update_user_roles': 'super_admin',
'org.read_billing': 'admin',
'org.update_billing': 'super_admin',
'org.read_invoices': 'admin',
'org.read_audit': 'admin',
'org.read_billing_audit': 'super_admin',
// App permissions
'app.read': 'read',
'app.update_settings': 'write',
'app.delete': 'admin',
'app.read_bundles': 'read',
'app.upload_bundle': 'upload',
'app.create_channel': 'write',
'app.read_channels': 'read',
'app.read_logs': 'read',
'app.manage_devices': 'write',
'app.read_devices': 'read',
'app.build_native': 'write',
'app.read_audit': 'admin',
'app.update_user_roles': 'admin',
// Bundle permissions
'bundle.delete': 'admin',
// Channel permissions
'channel.read': 'read',
'channel.update_settings': 'write',
'channel.delete': 'admin',
'channel.read_history': 'read',
'channel.promote_bundle': 'write',
'channel.rollback_bundle': 'write',
'channel.manage_forced_devices': 'write',
'channel.read_forced_devices': 'read',
'channel.read_audit': 'admin',
}
// =============================================================================
// Core Functions
// =============================================================================
/**
* Check if RBAC is enabled for an organization.
* Caches the result in context to avoid repeated queries.
*/
export async function isRbacEnabledForOrg(
c: Context<MiddlewareKeyVariables>,
orgId: string | null,
): Promise<boolean> {
// Check cache first
const cached = c.get('rbacEnabled')
if (cached !== undefined) {
return cached
}
if (!orgId) {
return false
}
let pgClient
try {
pgClient = getPgClient(c)
const drizzleClient = getDrizzleClient(pgClient)
const result = await drizzleClient.execute(
sql`SELECT public.rbac_is_enabled_for_org(${orgId}::uuid) as enabled`,
)
const enabled = (result.rows[0] as any)?.enabled === true
// Cache the result
c.set('rbacEnabled', enabled)
return enabled
}
catch (e) {
logPgError(c, 'isRbacEnabledForOrg', e)
return false
}
finally {
if (pgClient) {
closeClient(c, pgClient)
}
}
}
/**
* Main permission check function.
*
* Uses the SQL function rbac_check_permission_direct which automatically
* routes between legacy (check_min_rights) and RBAC systems based on
* the org's feature flag.
*
* @param c - Hono context with auth info
* @param permission - The RBAC permission to check (e.g., 'app.upload_bundle')
* @param scope - Scope identifiers (orgId, appId, channelId). Parent scopes are auto-derived by SQL function.
* @returns true if the user has the permission, false otherwise
*
* @example
* // Check app-level permission
* if (await checkPermission(c, 'app.upload_bundle', { appId: 'com.example.app' })) {
* // User can upload bundles
* }
*
* @example
* // Check channel-level permission (appId and orgId are auto-derived)
* if (await checkPermission(c, 'channel.promote_bundle', { channelId: 123 })) {
* // User can promote bundles on this channel
* }
*
* @example
* // Check org-level permission
* if (await checkPermission(c, 'org.invite_user', { orgId: 'uuid...' })) {
* // User can invite members
* }
*/
export async function checkPermission(
c: Context<MiddlewareKeyVariables>,
permission: Permission,
scope: PermissionScope,
): Promise<boolean> {
const auth = c.get('auth')
if (!auth?.userId) {
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermission: no auth',
permission,
})
return false
}
const { userId, apikey } = auth
if (deniesExplicitApiKeyScope(c, scope))
return false
// For hashed keys, apikey.key is null, so we use capgkey from the request header
const apikeyString = apikey?.key ?? c.get('capgkey') ?? null
const { orgId = null, appId = null, channelId = null } = scope
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermission: checking',
permission,
scope,
userId,
hasApikey: !!apikeyString,
})
let pgClient
try {
pgClient = getPgClient(c)
const drizzleClient = getDrizzleClient(pgClient)
// Use the unified SQL function that handles legacy/RBAC routing
const result = await drizzleClient.execute(
sql`SELECT public.rbac_check_permission_direct(
${permission},
${userId}::uuid,
${orgId}::uuid,
${appId},
${channelId}::bigint,
${apikeyString}
) as allowed`,
)
const allowed = (result.rows[0] as any)?.allowed === true
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermission: result',
permission,
scope,
allowed,
})
return allowed
}
catch (e) {
cloudlogErr({
requestId: c.get('requestId'),
message: 'checkPermission error',
error: e,
permission,
scope,
})
return false
}
finally {
if (pgClient) {
closeClient(c, pgClient)
}
}
}
/**
* Require a permission, throwing an error if not allowed.
* Use this for endpoints that should return 403 if permission is denied.
*
* @throws HTTPException with status 403 if permission is denied
*/
export async function requirePermission(
c: Context<MiddlewareKeyVariables>,
permission: Permission,
scope: PermissionScope,
): Promise<void> {
const allowed = await checkPermission(c, permission, scope)
if (!allowed) {
const { quickError } = await import('./hono.ts')
quickError(403, 'permission_denied', `Permission denied: ${permission}`, {
permission,
scope,
})
}
}
/**
* Check multiple permissions at once.
* Returns true only if ALL permissions are granted.
*/
export async function checkPermissions(
c: Context<MiddlewareKeyVariables>,
permissions: Permission[],
scope: PermissionScope,
): Promise<boolean> {
for (const permission of permissions) {
if (!(await checkPermission(c, permission, scope))) {
return false
}
}
return true
}
/**
* Check if ANY of the given permissions is granted.
*/
export async function checkAnyPermission(
c: Context<MiddlewareKeyVariables>,
permissions: Permission[],
scope: PermissionScope,
): Promise<boolean> {
for (const permission of permissions) {
if (await checkPermission(c, permission, scope)) {
return true
}
}
return false
}
/**
* Check permission using an existing Drizzle client.
* Use this when you already have a connection open and want to avoid opening a new one.
*
* @param c - Hono context with auth info
* @param permission - The RBAC permission to check
* @param scope - Scope identifiers
* @param drizzleClient - An existing Drizzle client
* @param userId - User ID to check (required, as it may come from API key lookup)
* @param apikeyString - Optional API key string for additional validation
*/
export async function checkPermissionPg(
c: Context<MiddlewareKeyVariables>,
permission: Permission,
scope: PermissionScope,
drizzleClient: ReturnType<typeof getDrizzleClient>,
userId: string,
apikeyString?: string | null,
): Promise<boolean> {
if (!userId) {
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermissionPg: no userId',
permission,
})
return false
}
const { orgId = null, appId = null, channelId = null } = scope
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermissionPg: checking',
permission,
scope,
userId,
hasApikey: !!apikeyString,
})
try {
// Use the unified SQL function that handles legacy/RBAC routing
const result = await drizzleClient.execute(
sql`SELECT public.rbac_check_permission_direct(
${permission},
${userId}::uuid,
${orgId}::uuid,
${appId},
${channelId}::bigint,
${apikeyString ?? null}
) as allowed`,
)
const allowed = (result.rows[0] as any)?.allowed === true
cloudlog({
requestId: c.get('requestId'),
message: 'checkPermissionPg: result',
permission,
scope,
allowed,
})
return allowed
}
catch (e) {
cloudlogErr({
requestId: c.get('requestId'),
message: 'checkPermissionPg error',
error: e,
permission,
scope,
})
return false
}
}
// =============================================================================
// Utility Functions
// =============================================================================
/**
* Get the legacy right equivalent for a permission.
* Useful for compatibility layers.
*/
export function getLegacyRightForPermission(permission: Permission): Database['public']['Enums']['user_min_right'] {
return PERMISSION_TO_LEGACY_RIGHT[permission]
}
/**
* Infer the scope type from a permission key.
*/
export function getScopeTypeFromPermission(permission: Permission): ScopeType {
if (permission.startsWith('org.'))
return 'org'
if (permission.startsWith('app.') || permission.startsWith('bundle.'))
return 'app'
if (permission.startsWith('channel.'))
return 'channel'
return 'org' // Default fallback
}