Add MaxPermission constant (62) to make the valid bit range explicit in the API. Document in PermissionProvider that audit logging belongs in the application layer. API committed as stable: Identity, PermissionMask, context helpers, and PermissionProvider interface are unchanged from v0.9.0.
47 lines
1.6 KiB
Go
47 lines
1.6 KiB
Go
package rbac
|
||
|
||
// Permission is a named bit position (0–62) representing a single capability.
|
||
//
|
||
// Applications define their own constants using this type:
|
||
//
|
||
// const (
|
||
// Read rbac.Permission = 0
|
||
// Write rbac.Permission = 1
|
||
// Delete rbac.Permission = 2
|
||
// )
|
||
//
|
||
// The zero value (0) is a valid permission representing the first bit.
|
||
// Valid positions are 0 through [MaxPermission] (62); values outside that
|
||
// range are silently ignored by [PermissionMask.Has] and [PermissionMask.Grant].
|
||
type Permission int64
|
||
|
||
// MaxPermission is the highest valid bit position (62).
|
||
// Permission constants defined by the application must be in the range
|
||
// [0, MaxPermission]. Bit 63 is reserved for the sign bit of the underlying int64.
|
||
const MaxPermission Permission = 62
|
||
|
||
// PermissionMask is a resolved bit-mask for a user on a specific resource.
|
||
// It is returned by [PermissionProvider.ResolveMask] and checked with [PermissionMask.Has].
|
||
type PermissionMask int64
|
||
|
||
// Has reports whether the given permission bit is set in the mask.
|
||
// Returns false for out-of-range values (p < 0 or p >= 63).
|
||
func (m PermissionMask) Has(p Permission) bool {
|
||
if p < 0 || p >= 63 {
|
||
return false
|
||
}
|
||
return (int64(m) & (1 << uint(p))) != 0
|
||
}
|
||
|
||
// Grant returns a new mask with the bit for p set.
|
||
// The receiver is not modified.
|
||
// Useful for building masks in tests and in-memory [PermissionProvider] implementations:
|
||
//
|
||
// mask := rbac.PermissionMask(0).Grant(Read).Grant(Write)
|
||
func (m PermissionMask) Grant(p Permission) PermissionMask {
|
||
if p < 0 || p >= 63 {
|
||
return m
|
||
}
|
||
return PermissionMask(int64(m) | (1 << uint(p)))
|
||
}
|