# Story 2.3: Role-Based Access Control (RBAC) System

## Metadata
- **Story ID**: 2.3
- **Title**: Role-Based Access Control (RBAC) System
- **Epic**: 2 - Authentication & Authorization
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 6-8 hours
- **Dependencies**: 1.2, 2.1

## Goal
Implement a complete RBAC system with permissions, role management, and authorization middleware.

## Description
This story implements the complete RBAC system including permission definitions, permission resolution, authorization checking, and middleware for protecting routes.

## Deliverables

### 1. Permission System (`pkg/perm/perm.go`)
- `Permission` type (string format: "module.resource.action")
- Core permission constants (system, user, role permissions)
- Permission validation utilities

### 2. Permission Resolver (`pkg/perm/resolver.go` & `internal/perm/in_memory_resolver.go`)
- `PermissionResolver` interface
- Implementation that loads user roles and permissions from database
- Permission checking with caching
- Permission inheritance via roles

### 3. Authorization System (`pkg/auth/authz.go` & `internal/auth/rbac_authorizer.go`)
- `Authorizer` interface
- RBAC authorizer implementation
- Extract user from context
- Check permissions
- Return authorization errors

### 4. Authorization Middleware
- `RequirePermission(perm Permission) gin.HandlerFunc` decorator
- Integration with route registration
- Proper error responses for unauthorized access

### 5. gRPC Server (Microservices)
- Expose gRPC server for authorization service
- gRPC service definition in `api/proto/authz.proto`
- gRPC server implementation in `internal/auth/grpc/authz_server.go`
- Service registration in service registry
- Uses `IdentityServiceClient` for user operations

## Acceptance Criteria
- [ ] Permissions are defined and can be checked
- [ ] Users inherit permissions through roles
- [ ] Authorization middleware protects routes
- [ ] Unauthorized requests return 403 errors
- [ ] Permission checks are cached for performance
- [ ] Permission system is extensible by modules

## Related ADRs
- [ADR-0019: Permission DSL Format](../../adr/0019-permission-dsl-format.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)

## Files to Create/Modify
- `pkg/perm/perm.go` - Permission types
- `pkg/perm/resolver.go` - Permission resolver interface
- `internal/perm/in_memory_resolver.go` - Permission resolver implementation
- `pkg/auth/authz.go` - Authorization interface
- `internal/auth/rbac_authorizer.go` - RBAC authorizer
- `internal/auth/middleware.go` - Add authorization middleware

