rbacconnect

package module
v0.0.0-...-3bf89ab Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2026 License: MIT Imports: 4 Imported by: 0

README

rbacconnect

A flexible, declarative Role-Based Access Control (RBAC) system for connect-go RPC services.

Features

  • 🎯 Declarative Policy Builder - Define authorization rules with a fluent, chainable API
  • 🔍 Multi-Level Selectors - Control access at procedure, service, package, or default levels
  • 👑 Super-Roles - Define roles that bypass all authorization rules
  • ✅ Allow/Deny Rules - Fine-grained control with deny precedence over allow
  • 🔄 Atomic Policy Updates - Thread-safe hot-reloading of policies without service restart
  • 🔌 Connect-go Integration - Drop-in interceptor for connect-go services
  • 🎨 Customizable - Pluggable role extraction, spec parsing, and error handling

AI Agent Skills

This repository includes AI agent skills with documentation and usage examples for all packages. Install them with the skills CLI:

go install github.com/sxwebdev/skills/cmd/skills@latest
skills init
skills repo add sxwebdev/rbacconnect

Installation

go get github.com/sxwebdev/rbacconnect@latest

Quick Start

1. Define Your Policy
package main

import (
    "github.com/sxwebdev/rbacconnect"
)

func createPolicy() *rbacconnect.Policy {
    return rbacconnect.NewPolicyBuilder().
        // Super-roles bypass all rules
        WithSuperRoles("root").

        // Default deny (fail-closed security)
        WithDefaultAllow(false).

        // Allow specific procedure
        When(rbacconnect.Proc("/api.UserService/GetUser")).
            Allow("admin", "user").

        // Allow entire service
        When(rbacconnect.Svc("api.AdminService")).
            Allow("admin").

        // Allow entire package
        When(rbacconnect.Pkg("api.public")).
            Allow("user", "guest").

        // Explicit deny (takes precedence)
        When(rbacconnect.Proc("/api.UserService/DeleteUser")).
            Deny("user").

        // Default rule for everything else
        When(rbacconnect.Any()).
            Allow("admin").

        Build()
}
2. Create Provider and Interceptor
package main

import (
    "github.com/sxwebdev/rbacconnect"
    "connectrpc.com/connect"
)

func main() {
    // Create policy
    policy := createPolicy()

    // Create provider (for atomic updates)
    provider := rbacconnect.NewProvider(policy)

    // Create interceptor
    interceptor := rbacconnect.NewInterceptor(provider, rbacconnect.Options{
        // Optional: custom role extractor
        RoleExtractor: rbacconnect.RoleExtractorFunc(func(ctx context.Context) ([]rbacconnect.Role, error) {
            // Extract roles from your auth context
            // Example: from JWT claims, session, etc.
            user := getUserFromContext(ctx)
            return user.Roles, nil
        }),
    })

    // Add interceptor to your connect-go server
    mux := http.NewServeMux()
    mux.Handle(greetv1connect.NewGreetServiceHandler(
        &greetServer{},
        connect.WithInterceptors(interceptor),
    ))
}
3. Add Roles to Context
// In your authentication middleware
func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Extract user and their roles
        user := authenticateUser(r)

        // Add roles to context
        ctx := rbacconnect.WithRoles(r.Context(), user.Roles...)

        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Rule Evaluation Order

Rules are evaluated in order of specificity, from most specific to least:

  1. Super-Roles - Always granted access
  2. Procedure - Exact procedure match (e.g., /api.UserService/GetUser)
  3. Service - Service-level match (e.g., api.UserService)
  4. Package - Package-level match (e.g., api)
  5. Default - Explicit default rule via When(rbacconnect.Any())
  6. Fallback - WithDefaultAllow(true/false)

Within each level, Deny takes precedence over Allow.

Examples

Example 1: Simple Service Authorization
policy := rbacconnect.NewPolicyBuilder().
    WithSuperRoles("admin").
    WithDefaultAllow(false).
    When(rbacconnect.Svc("api.UserService")).
        Allow("user", "moderator").
    Build()
Example 2: Public and Private APIs
policy := rbacconnect.NewPolicyBuilder().
    WithDefaultAllow(false).

    // Public APIs - anyone can access
    When(rbacconnect.Pkg("api.public")).
        Allow("guest", "user", "admin").

    // Private APIs - authenticated users only
    When(rbacconnect.Pkg("api.private")).
        Allow("user", "admin").

    // Admin APIs - admins only
    When(rbacconnect.Pkg("api.admin")).
        Allow("admin").

    Build()
Example 3: Mixed Allow/Deny Rules
policy := rbacconnect.NewPolicyBuilder().
    WithDefaultAllow(false).

    // Users can access most of UserService
    When(rbacconnect.Svc("api.UserService")).
        Allow("user").

    // But users cannot delete
    When(rbacconnect.Proc("/api.UserService/DeleteUser")).
        Deny("user").
        Allow("admin").

    Build()
Example 4: Hot-Reloading Policies
// Initial policy
policy := createPolicy()
provider := rbacconnect.NewProvider(policy)

// Later, update the policy without restarting
newPolicy := rbacconnect.NewPolicyBuilder().
    WithSuperRoles("root", "superadmin").
    WithDefaultAllow(false).
    When(rbacconnect.Any()).
        Allow("admin").
    Build()

// Atomic update - all new requests use the new policy
provider.Update(newPolicy)
Example 5: Custom Role Extractor from JWT
import "github.com/golang-jwt/jwt/v5"

type Claims struct {
    Roles []string `json:"roles"`
    jwt.RegisteredClaims
}

interceptor := rbacconnect.NewInterceptor(provider, rbacconnect.Options{
    RoleExtractor: rbacconnect.RoleExtractorFunc(func(ctx context.Context) ([]rbacconnect.Role, error) {
        // Extract JWT from context
        token := getTokenFromContext(ctx)
        if token == "" {
            return nil, errors.New("no token")
        }

        // Parse and validate JWT
        claims := &Claims{}
        _, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
            return []byte("your-secret-key"), nil
        })
        if err != nil {
            return nil, err
        }

        return claims.Roles, nil
    }),
})

API Reference

Types
  • Role - String type representing a user role
  • RoleSet - Set of roles for efficient lookup
  • Selector - Defines the scope of a rule (Procedure/Service/Package/Default)
  • Rule - Allow/Deny permissions for roles
  • Policy - Complete set of RBAC rules
  • Decision - Result of authorization check
Builder Methods
  • NewPolicyBuilder() - Create a new policy builder
  • WithSuperRoles(roles ...Role) - Add super-roles
  • WithDefaultAllow(bool) - Set default behavior
  • When(Selector) - Start a rule clause
  • Allow(roles ...Role) - Grant access to roles
  • Deny(roles ...Role) - Block access for roles
  • Build() - Finalize and return the policy
Selectors
  • Proc(procedure string) - Match specific procedure
  • Svc(service string) - Match all procedures in a service
  • Pkg(package string) - Match all procedures in a package
  • Any() - Match everything (default rule)
Provider
  • NewProvider(policy *Policy) - Create atomic policy provider
  • Get() - Get current policy
  • Update(newPolicy *Policy) - Atomically update policy
Interceptor
  • NewInterceptor(provider *Provider, opts Options) - Create RBAC interceptor
Context Helpers
  • WithRoles(ctx, roles ...Role) - Add roles to context
  • RolesFromContext(ctx) - Extract roles from context

Testing

func TestPolicy(t *testing.T) {
    policy := rbacconnect.NewPolicyBuilder().
        WithSuperRoles("root").
        WithDefaultAllow(false).
        When(rbacconnect.Proc("/api.UserService/GetUser")).
            Allow("user").
        Build()

    // Test super-role
    dec := policy.Evaluate("/api.UserService/GetUser", "api.UserService", "api", []string{"root"})
    assert.True(t, dec.Allowed)

    // Test allowed role
    dec = policy.Evaluate("/api.UserService/GetUser", "api.UserService", "api", []string{"user"})
    assert.True(t, dec.Allowed)

    // Test denied role
    dec = policy.Evaluate("/api.UserService/GetUser", "api.UserService", "api", []string{"guest"})
    assert.False(t, dec.Allowed)
}

Best Practices

  1. Fail Closed - Use WithDefaultAllow(false) for security
  2. Least Privilege - Grant minimum necessary permissions
  3. Explicit Deny - Use deny rules for critical restrictions
  4. Test Policies - Write unit tests for your authorization logic
  5. Audit Decisions - Log authorization decisions for security auditing
  6. Version Policies - Track policy changes in version control

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is part of the Sentinel project.

Support

For issues and questions, please open an issue on GitHub.

Documentation

Overview

Package rbacconnect provides a flexible, declarative Role-Based Access Control (RBAC) system for connect-go RPC services.

Overview

rbacconnect enables fine-grained authorization for connect-go services through a declarative policy builder. It supports multiple levels of selectors (procedure, service, package, default), super-roles, allow/deny rules, and atomic policy updates.

Quick Start

Define a policy:

policy := rbacconnect.NewPolicyBuilder().
    WithSuperRoles("root").
    WithDefaultAllow(false).
    When(rbacconnect.Proc("/api.UserService/GetUser")).
        Allow("admin", "user").
    When(rbacconnect.Svc("api.AdminService")).
        Allow("admin").
    Build()

Create an interceptor:

provider := rbacconnect.NewProvider(policy)
interceptor := rbacconnect.NewInterceptor(provider, rbacconnect.Options{})

Add to your connect-go server:

mux.Handle(yourservice.NewHandler(
    &yourServer{},
    connect.WithInterceptors(interceptor),
))

Policy Structure

Policies are built using a fluent API with the following components:

  • Super-Roles: Roles that bypass all rules (e.g., "root", "superadmin")
  • Selectors: Define the scope of rules (Procedure, Service, Package, or Default)
  • Rules: Allow or Deny specific roles (Deny takes precedence)
  • Default Behavior: What happens when no rules match

Rule Evaluation Order

Rules are evaluated in order of specificity:

  1. Super-Roles (always allowed)
  2. Procedure-level rules (most specific)
  3. Service-level rules
  4. Package-level rules
  5. Default rule
  6. Fallback to WithDefaultAllow setting

Within each level, Deny takes precedence over Allow.

Selectors

Four types of selectors are available:

  • Proc(procedure): Match exact procedure like "/api.UserService/GetUser"
  • Svc(service): Match all procedures in a service like "api.UserService"
  • Pkg(package): Match all procedures in a package like "api"
  • Any(): Match everything (default rule)

Hot Reloading

Policies can be updated atomically without service restart:

newPolicy := rbacconnect.NewPolicyBuilder().
    WithSuperRoles("root", "admin").
    Build()
provider.Update(newPolicy)

Custom Role Extraction

Implement RoleExtractor to customize how roles are extracted from context:

interceptor := rbacconnect.NewInterceptor(provider, rbacconnect.Options{
    RoleExtractor: rbacconnect.RoleExtractorFunc(func(ctx context.Context) ([]rbacconnect.Role, error) {
        // Extract roles from JWT, session, etc.
        return extractRolesFromJWT(ctx)
    }),
})

Thread Safety

All components are thread-safe. The Provider uses atomic operations for policy updates, ensuring no race conditions during hot-reloads.

Best Practices

  • Use WithDefaultAllow(false) for fail-closed security
  • Grant minimum necessary permissions (principle of least privilege)
  • Use explicit Deny for critical restrictions
  • Test policies thoroughly with unit tests
  • Log authorization decisions for security auditing
  • Version control your policies

File Organization

The package is organized into logical files:

  • rbacconnect.go: Core types (Role, Selector, Rule, Policy)
  • builder.go: PolicyBuilder and fluent API
  • interceptor.go: Connect-go integration
  • context.go: Context helpers and role extraction
  • provider.go: Atomic policy provider
  • helpers.go: Utility functions for common patterns
  • utils.go: Internal utilities

For more examples and detailed documentation, see the README.md file.

Package rbacconnect provides a flexible, declarative Role-Based Access Control (RBAC) system for connect-go RPC services. It allows you to define fine-grained authorization rules based on procedures, services, packages, or default policies, with support for super-roles and dynamic policy updates.

Key Features:

  • Declarative policy builder with fluent API
  • Multiple selector levels: Procedure > Service > Package > Default
  • Super-roles that bypass all rules
  • Allow/Deny rules with deny precedence
  • Thread-safe atomic policy updates
  • Connect-go interceptor integration

Example usage:

policy := rbacconnect.NewPolicyBuilder().
    WithSuperRoles("root").
    WithDefaultAllow(false).
    When(rbacconnect.Proc("/api.UserService/GetUser")).
        Allow("admin", "user").
    When(rbacconnect.Svc("api.AdminService")).
        Allow("admin").
    When(rbacconnect.Pkg("api")).
        Deny("guest").
    Build()

provider := rbacconnect.NewProvider(policy)
interceptor := rbacconnect.NewInterceptor(provider, rbacconnect.Options{})

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllowPackages

func AllowPackages(b *PolicyBuilder, role Role, packages ...string)

AllowPackages adds allow rules for all procedures of the specified packages and role.

func AllowProcs

func AllowProcs(b *PolicyBuilder, role Role, procs ...string)

AllowProcs adds allow rules for the specified procedures and role.

func AllowServices

func AllowServices(b *PolicyBuilder, role Role, services ...string)

AllowServices adds allow rules for all procedures of the specified services and role.

func DenyPackages

func DenyPackages(b *PolicyBuilder, role Role, packages ...string)

DenyPackages adds deny rules for all procedures of the specified packages and role.

func DenyProcs

func DenyProcs(b *PolicyBuilder, role Role, procs ...string)

DenyProcs adds deny rules for the specified procedures and role.

func DenyServices

func DenyServices(b *PolicyBuilder, role Role, services ...string)

DenyServices adds deny rules for all procedures of the specified services and role.

func SplitProc

func SplitProc(proc string) (svc string, pkg string)

func WithRoles

func WithRoles(ctx context.Context, roles ...Role) context.Context

WithRoles adds roles to the context.

Example

Example 6: Using context helpers

ctx := context.Background()

// Add roles to context
ctx = WithRoles(ctx, "admin", "user")

// Extract roles from context
roles, ok := RolesFromContext(ctx)
if ok {
	println("Roles:", roles) // ["admin", "user"]
}

Types

type Decision

type Decision struct {
	Allowed  bool
	Selector string // which level matched: "procedure"|"service"|"package"|"default"|"none"
	Matched  string // which name matched
	Reason   string // description for logging
}

Decision represents the result of an authorization check.

type Err

type Err string

Err is a simple error type for string errors.

func (Err) Error

func (e Err) Error() string

Error implements the error interface.

type Interceptor

type Interceptor struct {
	// contains filtered or unexported fields
}

Interceptor is a connect-go interceptor that enforces RBAC policies.

Example (WithConnectService)

Example 8: Integration with connect-go service

// Create policy
policy := NewPolicyBuilder().
	WithSuperRoles("root").
	WithDefaultAllow(false).
	When(Pkg("greet.v1")).
	Allow("user").
	Build()

provider := NewProvider(policy)
_ = NewInterceptor(provider, Options{})

// Create HTTP handler with interceptor
mux := http.NewServeMux()

// In real code, use your actual service handler:
// mux.Handle(greetv1connect.NewGreetServiceHandler(
//     &greetServer{},
//     connect.WithInterceptors(interceptor),
// ))

// Start server
_ = httptest.NewServer(mux)

func NewInterceptor

func NewInterceptor(provider *Provider, opts Options) *Interceptor

NewInterceptor creates a new RBAC interceptor with the given provider and options. If options are not provided, sensible defaults are used.

Example (CustomErrorFactory)

Example 10: Custom error factory

policy := NewPolicyBuilder().
	WithDefaultAllow(false).
	Build()

provider := NewProvider(policy)

interceptor := NewInterceptor(provider, Options{
	ErrorFactory: func(code connect.Code, msg string) error {
		// Custom error with additional context
		return connect.NewError(code, errors.New(msg+" - contact support"))
	},
})

_ = interceptor
Example (CustomRoleExtractor)

Example 5: Custom role extractor

policy := NewPolicyBuilder().
	WithDefaultAllow(false).
	When(Any()).
	Allow("admin").
	Build()

provider := NewProvider(policy)

// Custom role extractor from HTTP headers
extractorFromHeader := RoleExtractorFunc(func(ctx context.Context) ([]Role, error) {
	// In real scenario, extract from actual context
	header := ctx.Value("X-User-Roles")
	if header == nil {
		return nil, errors.New("no roles header")
	}
	// Parse roles from header
	rolesStr, ok := header.(string)
	if !ok {
		return nil, errors.New("invalid roles")
	}
	return []string{rolesStr}, nil
})

_ = NewInterceptor(provider, Options{
	RoleExtractor: extractorFromHeader,
})

func (*Interceptor) WrapStreamingClient

func (i *Interceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc

WrapStreamingClient wraps client-side streaming calls. By default, client streams are not restricted.

func (*Interceptor) WrapStreamingHandler

WrapStreamingHandler wraps server-side streaming calls with RBAC authorization.

func (*Interceptor) WrapUnary

func (i *Interceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc

WrapUnary wraps unary RPC calls with RBAC authorization.

type Options

type Options struct {
	// RoleExtractor extracts roles from the request context.
	RoleExtractor RoleExtractor
	// SpecSplitter parses connect.Spec into (proc, svc, pkg).
	// Default implementation parses "/pkg.Service/Method" format.
	SpecSplitter func(spec connect.Spec) (proc string, svc string, pkg string)
	// ErrorFactory creates custom errors (PermissionDenied/Unauthenticated).
	ErrorFactory func(code connect.Code, msg string) error
}

Options configures the Interceptor behavior.

type Policy

type Policy struct {
	// contains filtered or unexported fields
}

Policy is a set of RBAC rules. Can be updated atomically.

func (*Policy) Evaluate

func (p *Policy) Evaluate(procFull string, svc string, pkg string, roles []Role) Decision

Evaluate is a pure function that makes an authorization decision. It checks the given procedure, service, and package against the policy rules for the provided roles, returning a Decision.

type PolicyBuilder

type PolicyBuilder struct {
	// contains filtered or unexported fields
}

PolicyBuilder is a convenient builder for declarative policies.

Example (Basic)

Example 1: Basic policy with super-roles

policy := NewPolicyBuilder().
	WithSuperRoles("root").
	WithDefaultAllow(false).
	When(Proc("/api.UserService/GetUser")).
	Allow("admin", "user").
	Build()

// Evaluate for admin role
decision := policy.Evaluate("/api.UserService/GetUser", "api.UserService", "api", []string{"admin"})
println(decision.Allowed) // true
Example (DenyRules)

Example 3: Package-level with deny rules

policy := NewPolicyBuilder().
	WithDefaultAllow(false).
	// Allow users to access the package
	When(Pkg("api")).
	Allow("user", "admin").
	// But deny users from specific dangerous operations
	When(Proc("/api.UserService/DeleteUser")).
	Deny("user").
	Build()

// User can read
decision := policy.Evaluate("/api.UserService/GetUser", "api.UserService", "api", []string{"user"})
println(decision.Allowed) // true

// User cannot delete (deny takes precedence)
decision = policy.Evaluate("/api.UserService/DeleteUser", "api.UserService", "api", []string{"user"})
println(decision.Allowed) // false
Example (MultiLevel)

Example 9: Multi-level authorization

policy := NewPolicyBuilder().
	WithDefaultAllow(false).
	// Package level - all users can access public APIs
	When(Pkg("api.public")).
	Allow("guest", "user", "admin").
	// Service level - only registered users for private APIs
	When(Svc("api.private.UserService")).
	Allow("user", "admin").
	// Procedure level - only admins for dangerous operations
	When(Proc("/api.private.UserService/DeleteAll")).
	Allow("admin").
	// Default - admins get everything else
	When(Any()).
	Allow("admin").
	Build()

// Guest can access public
d := policy.Evaluate("/api.public.InfoService/GetInfo", "api.public.InfoService", "api.public", []string{"guest"})
println("Guest public:", d.Allowed) // true

// Guest cannot access private
d = policy.Evaluate("/api.private.UserService/GetProfile", "api.private.UserService", "api.private", []string{"guest"})
println("Guest private:", d.Allowed) // false

// User can access private
d = policy.Evaluate("/api.private.UserService/GetProfile", "api.private.UserService", "api.private", []string{"user"})
println("User private:", d.Allowed) // true

// User cannot delete all
d = policy.Evaluate("/api.private.UserService/DeleteAll", "api.private.UserService", "api.private", []string{"user"})
println("User delete:", d.Allowed) // false

// Admin can delete all
d = policy.Evaluate("/api.private.UserService/DeleteAll", "api.private.UserService", "api.private", []string{"admin"})
println("Admin delete:", d.Allowed) // true
Example (Service)

Example 2: Service-level authorization

policy := NewPolicyBuilder().
	WithDefaultAllow(false).
	When(Svc("api.UserService")).
	Allow("user").
	When(Svc("api.AdminService")).
	Allow("admin").
	Build()

// User can access UserService
decision := policy.Evaluate("/api.UserService/GetUser", "api.UserService", "api", []string{"user"})
println(decision.Allowed) // true

// User cannot access AdminService
decision = policy.Evaluate("/api.AdminService/DeleteUser", "api.AdminService", "api", []string{"user"})
println(decision.Allowed) // false

func NewPolicyBuilder

func NewPolicyBuilder() *PolicyBuilder

NewPolicyBuilder creates a new policy builder with empty rules.

func (*PolicyBuilder) Build

func (b *PolicyBuilder) Build() *Policy

Build finalizes the policy construction and returns the immutable Policy.

func (*PolicyBuilder) When

func (b *PolicyBuilder) When(s Selector) *clause

When starts a new rule clause for the given selector. Returns a clause that can be chained with Allow() and Deny() calls.

func (*PolicyBuilder) WithDefaultAllow

func (b *PolicyBuilder) WithDefaultAllow(v bool) *PolicyBuilder

WithDefaultAllow sets the default behavior when no rules match. If true, access is allowed by default. If false, access is denied by default.

func (*PolicyBuilder) WithSuperRoles

func (b *PolicyBuilder) WithSuperRoles(roles ...Role) *PolicyBuilder

WithSuperRoles adds super-roles that bypass all authorization rules. Super-roles are always granted access regardless of any rules.

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider is a thread-safe atomic policy provider for "hot" updates. It allows updating the policy without restarting the service.

Example (Update)

Example 4: Hot-reloading policies

// Initial policy
initialPolicy := NewPolicyBuilder().
	WithDefaultAllow(false).
	When(Any()).
	Allow("admin").
	Build()

provider := NewProvider(initialPolicy)

// Check with initial policy
policy := provider.Get()
decision := policy.Evaluate("/any/Procedure", "any.Service", "any", []string{"user"})
println(decision.Allowed) // false

// Update policy
newPolicy := NewPolicyBuilder().
	WithDefaultAllow(false).
	When(Any()).
	Allow("admin", "user"). // now users are allowed
	Build()

provider.Update(newPolicy)

// Check with new policy
policy = provider.Get()
decision = policy.Evaluate("/any/Procedure", "any.Service", "any", []string{"user"})
println(decision.Allowed) // true

func NewProvider

func NewProvider(p *Policy) *Provider

NewProvider creates a new Provider with the given initial policy.

func (*Provider) Get

func (p *Provider) Get() *Policy

Get returns the current policy.

func (*Provider) Update

func (p *Provider) Update(newP *Policy)

Update atomically replaces the current policy with a new one.

type Role

type Role = string

Role represents a user role as a string. Roles are used to determine access permissions in the RBAC system.

func RolesFromContext

func RolesFromContext(ctx context.Context) ([]Role, bool)

RolesFromContext retrieves roles from the context.

type RoleExtractor

type RoleExtractor interface {
	ExtractRoles(ctx context.Context) ([]Role, error)
}

RoleExtractor defines how to extract roles from a context. Users can provide their own implementation.

type RoleExtractorFunc

type RoleExtractorFunc func(ctx context.Context) ([]Role, error)

RoleExtractorFunc is a function adapter for RoleExtractor interface.

func (RoleExtractorFunc) ExtractRoles

func (f RoleExtractorFunc) ExtractRoles(ctx context.Context) ([]Role, error)

ExtractRoles implements the RoleExtractor interface.

type RoleSet

type RoleSet map[Role]struct{}

RoleSet is a set of roles implemented as a map for efficient lookup.

func NewRoleSet

func NewRoleSet(roles ...Role) RoleSet

NewRoleSet creates a new RoleSet from the provided roles.

func (RoleSet) Has

func (rs RoleSet) Has(r Role) bool

Has checks if the role exists in the set.

type Rule

type Rule struct {
	Allow RoleSet
	Deny  RoleSet
}

Rule represents allow/deny permissions for roles. If a role is in Deny, it takes precedence over Allow.

type Selector

type Selector struct {
	// Procedure is the full procedure name like "/pkg.Service/Method".
	Procedure string
	// Service is the service name like "pkg.Service".
	Service string
	// Package is the package name like "pkg".
	Package string
	// Default indicates a default rule (when nothing else matches).
	Default bool
}

Selector defines the scope of a rule application. Specificity order: Procedure > Service > Package > Default.

func Any

func Any() Selector

Any creates a default selector that matches everything.

func Pkg

func Pkg(pkg string) Selector

Pkg creates a selector for all procedures in a package. Example: Pkg("api")

func Proc

func Proc(procedure string) Selector

Proc creates a selector for a specific procedure. Example: Proc("/api.UserService/GetUser")

func Svc

func Svc(service string) Selector

Svc creates a selector for all procedures in a service. Example: Svc("api.UserService")

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL