Complete BZZZ functionality port to CHORUS

🎭 CHORUS now contains full BZZZ functionality adapted for containers

Core systems ported:
- P2P networking (libp2p with DHT and PubSub)
- Task coordination (COOEE protocol)
- HMMM collaborative reasoning
- SHHH encryption and security
- SLURP admin election system
- UCXL content addressing
- UCXI server integration
- Hypercore logging system
- Health monitoring and graceful shutdown
- License validation with KACHING

Container adaptations:
- Environment variable configuration (no YAML files)
- Container-optimized logging to stdout/stderr
- Auto-generated agent IDs for container deployments
- Docker-first architecture

All proven BZZZ P2P protocols, AI integration, and collaboration
features are now available in containerized form.

Next: Build and test container deployment.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-09-02 20:02:37 +10:00
parent 7c6cbd562a
commit 543ab216f9
224 changed files with 86331 additions and 186 deletions

102
pkg/slurp/roles/doc.go Normal file
View File

@@ -0,0 +1,102 @@
// Package roles provides role-based access control and context filtering for the SLURP system.
//
// This package implements comprehensive role-based access control (RBAC) for contextual
// intelligence, ensuring that context information is appropriately filtered, encrypted,
// and distributed based on role permissions and security requirements. It integrates
// with the existing BZZZ crypto system to provide secure, scalable access control.
//
// Key Features:
// - Hierarchical role definition and management
// - Context filtering based on role permissions and access levels
// - Integration with BZZZ crypto system for role-based encryption
// - Dynamic permission evaluation and caching for performance
// - Role-specific context views and perspectives
// - Audit logging for access control decisions
// - Permission inheritance and delegation
// - Temporal access control with time-based permissions
//
// Core Components:
// - RoleManager: Definition and management of roles and permissions
// - AccessController: Access control decision making and enforcement
// - ContextFilter: Role-based filtering of context information
// - PermissionEvaluator: Dynamic evaluation of permissions
// - AuditLogger: Logging of access control events
// - EncryptionManager: Role-based encryption and key management
//
// Integration Points:
// - pkg/crypto: Role-based encryption and key management
// - pkg/slurp/context: Context filtering and access control
// - pkg/slurp/storage: Encrypted storage with role-based access
// - pkg/election: Leader-based role administration
// - pkg/config: Role configuration and policies
//
// Example Usage:
//
// roleManager := roles.NewRoleManager(storage, crypto)
// ctx := context.Background()
//
// // Define a new role
// role := &Role{
// Name: "Senior Developer",
// Permissions: []Permission{
// PermissionReadCode,
// PermissionWriteCode,
// PermissionViewArchitecture,
// },
// AccessLevel: AccessLevelHigh,
// }
// err := roleManager.CreateRole(ctx, role)
//
// // Assign role to user
// err = roleManager.AssignRole(ctx, "user123", "senior-developer")
//
// // Filter context based on role
// filter := roles.NewContextFilter(roleManager)
// filteredContext, err := filter.FilterContext(ctx, originalContext, "senior-developer")
//
// // Check permissions
// controller := roles.NewAccessController(roleManager)
// canAccess, err := controller.CheckPermission(ctx, "user123", PermissionViewArchitecture)
// if canAccess {
// // Allow access to architectural context
// }
//
// Role Hierarchy:
// The system supports hierarchical roles where higher-level roles inherit
// permissions from lower-level roles. This enables flexible permission
// management while maintaining security boundaries appropriate for different
// team responsibilities and access needs.
//
// Access Levels:
// Context information is classified into different access levels (Public,
// Low, Medium, High, Critical) and roles are granted appropriate access
// levels. This ensures sensitive information is only available to
// authorized personnel while enabling collaboration on appropriate content.
//
// Temporal Access Control:
// The system supports time-based access control where permissions can be
// granted for specific time periods, enabling temporary access for
// contractors, time-limited elevated permissions, and automatic access
// revocation for compliance and security requirements.
//
// Performance Considerations:
// - Permission caching with configurable TTL for fast access decisions
// - Batch permission evaluation for efficiency with large contexts
// - Pre-computed role hierarchies and permission inheritance
// - Optimized context filtering algorithms for minimal overhead
// - Background permission synchronization across cluster nodes
//
// Security Model:
// All access control decisions are based on cryptographically verified
// role assignments and permissions. The system integrates with the BZZZ
// crypto infrastructure to ensure secure key distribution and context
// encryption, preventing unauthorized access even in case of node
// compromise or network interception.
//
// Audit and Compliance:
// Comprehensive audit logging tracks all access control decisions,
// permission changes, and context access patterns. This supports
// compliance requirements, security analysis, and debugging of
// access control issues while maintaining performance through
// asynchronous logging and efficient storage.
package roles

View File

@@ -0,0 +1,285 @@
package roles
import (
"context"
"time"
"chorus.services/bzzz/pkg/security"
"chorus.services/bzzz/pkg/ucxl"
slurpContext "chorus.services/bzzz/pkg/slurp/context"
)
// RoleManager handles definition and management of roles and permissions
//
// This is the primary interface for creating, updating, and managing roles
// and their associated permissions within the SLURP system.
type RoleManager interface {
// CreateRole creates a new role with specified permissions
CreateRole(ctx context.Context, role *Role) error
// UpdateRole updates an existing role
UpdateRole(ctx context.Context, role *Role) error
// DeleteRole removes a role from the system
DeleteRole(ctx context.Context, roleID string) error
// GetRole retrieves a specific role
GetRole(ctx context.Context, roleID string) (*Role, error)
// ListRoles lists all roles with optional filtering
ListRoles(ctx context.Context, filter *RoleFilter) ([]*Role, error)
// AssignRole assigns a role to a user or entity
AssignRole(ctx context.Context, userID, roleID string) error
// RevokeRole revokes a role from a user or entity
RevokeRole(ctx context.Context, userID, roleID string) error
// GetUserRoles gets all roles assigned to a user
GetUserRoles(ctx context.Context, userID string) ([]*Role, error)
// CreateRoleHierarchy establishes parent-child relationships between roles
CreateRoleHierarchy(ctx context.Context, parentRoleID, childRoleID string) error
// GetRoleHierarchy gets the complete role hierarchy
GetRoleHierarchy(ctx context.Context) (*RoleHierarchy, error)
// ValidateRole validates role definition and permissions
ValidateRole(ctx context.Context, role *Role) (*RoleValidation, error)
// GetRoleStats returns role management statistics
GetRoleStats(ctx context.Context) (*RoleStatistics, error)
}
// AccessController handles access control decision making and enforcement
//
// Provides centralized access control decisions based on roles, permissions,
// and context requirements with support for dynamic evaluation and caching.
type AccessController interface {
// CheckPermission checks if a user has a specific permission
CheckPermission(ctx context.Context, userID string, permission Permission) (bool, error)
// CheckContextAccess checks if a user can access specific context
CheckContextAccess(ctx context.Context, userID string, address ucxl.Address, accessType AccessType) (bool, error)
// CheckAccessLevel checks if a user meets the required access level
CheckAccessLevel(ctx context.Context, userID string, requiredLevel security.AccessLevel) (bool, error)
// BatchCheckPermissions checks multiple permissions efficiently
BatchCheckPermissions(ctx context.Context, userID string, permissions []Permission) (map[Permission]bool, error)
// EvaluateContextPermissions evaluates all relevant permissions for context
EvaluateContextPermissions(ctx context.Context, userID string, node *slurpContext.ContextNode) (*ContextPermissions, error)
// GetUserAccessLevel gets the maximum access level for a user
GetUserAccessLevel(ctx context.Context, userID string) (security.AccessLevel, error)
// CreateAccessToken creates a time-limited access token
CreateAccessToken(ctx context.Context, userID string, permissions []Permission, ttl time.Duration) (*AccessToken, error)
// ValidateAccessToken validates and extracts permissions from access token
ValidateAccessToken(ctx context.Context, token string) (*TokenValidation, error)
// GetAccessDecisionHistory gets history of access decisions for audit
GetAccessDecisionHistory(ctx context.Context, userID string, timeRange time.Duration) ([]*AccessDecision, error)
// GetAccessStats returns access control statistics
GetAccessStats() (*AccessStatistics, error)
}
// ContextFilter handles role-based filtering of context information
//
// Filters context data based on user roles and permissions to ensure
// appropriate information visibility and data protection.
type ContextFilter interface {
// FilterContext filters context based on user role and permissions
FilterContext(ctx context.Context, node *slurpContext.ContextNode, userID string) (*slurpContext.ContextNode, error)
// FilterResolvedContext filters resolved context for role-based access
FilterResolvedContext(ctx context.Context, resolved *slurpContext.ResolvedContext, userID string) (*slurpContext.ResolvedContext, error)
// BatchFilterContexts filters multiple contexts efficiently
BatchFilterContexts(ctx context.Context, nodes []*slurpContext.ContextNode, userID string) ([]*slurpContext.ContextNode, error)
// GetFilteredFields gets list of fields that would be filtered for user
GetFilteredFields(ctx context.Context, node *slurpContext.ContextNode, userID string) ([]string, error)
// ApplySecurityLabels applies security labels to context based on content
ApplySecurityLabels(ctx context.Context, node *slurpContext.ContextNode) (*LabeledContext, error)
// GetRoleSpecificView gets context optimized for specific role perspective
GetRoleSpecificView(ctx context.Context, node *slurpContext.ContextNode, roleID string) (*RoleContextView, error)
// SetFilteringPolicy configures filtering policy and rules
SetFilteringPolicy(policy *FilteringPolicy) error
// GetFilteringStats returns context filtering statistics
GetFilteringStats() (*FilteringStatistics, error)
}
// PermissionEvaluator handles dynamic evaluation of permissions
//
// Provides sophisticated permission evaluation including conditional
// permissions, time-based access, and context-dependent authorization.
type PermissionEvaluator interface {
// EvaluatePermission evaluates a permission with context and conditions
EvaluatePermission(ctx context.Context, userID string, permission Permission, evalContext *EvaluationContext) (*PermissionEvaluation, error)
// EvaluateConditionalPermission evaluates permission with conditions
EvaluateConditionalPermission(ctx context.Context, userID string, permission *ConditionalPermission) (bool, error)
// EvaluateTimeBasedPermission evaluates time-restricted permission
EvaluateTimeBasedPermission(ctx context.Context, userID string, permission Permission, timeWindow *TimeWindow) (bool, error)
// GetEffectivePermissions gets all effective permissions for user in context
GetEffectivePermissions(ctx context.Context, userID string, evalContext *EvaluationContext) ([]Permission, error)
// CreatePermissionRule creates custom permission evaluation rule
CreatePermissionRule(ctx context.Context, rule *PermissionRule) error
// UpdatePermissionRule updates existing permission rule
UpdatePermissionRule(ctx context.Context, rule *PermissionRule) error
// DeletePermissionRule removes permission rule
DeletePermissionRule(ctx context.Context, ruleID string) error
// ListPermissionRules lists all permission rules
ListPermissionRules(ctx context.Context) ([]*PermissionRule, error)
// GetEvaluationStats returns permission evaluation statistics
GetEvaluationStats() (*EvaluationStatistics, error)
}
// AuditLogger handles logging of access control events
//
// Provides comprehensive audit logging for access control decisions,
// permission changes, and security-relevant events for compliance
// and security analysis.
type AuditLogger interface {
// LogAccessDecision logs an access control decision
LogAccessDecision(ctx context.Context, decision *AccessDecision) error
// LogPermissionChange logs changes to permissions or roles
LogPermissionChange(ctx context.Context, change *PermissionChange) error
// LogSecurityEvent logs security-relevant events
LogSecurityEvent(ctx context.Context, event *SecurityEvent) error
// GetAuditLog retrieves audit log entries with filtering
GetAuditLog(ctx context.Context, filter *AuditFilter) ([]*AuditEntry, error)
// ExportAuditLog exports audit log in specified format
ExportAuditLog(ctx context.Context, format string, filter *AuditFilter) ([]byte, error)
// GetAuditStats returns audit logging statistics
GetAuditStats(ctx context.Context) (*AuditStatistics, error)
// SetRetentionPolicy sets audit log retention policy
SetRetentionPolicy(policy *RetentionPolicy) error
// ArchiveOldLogs archives old audit logs
ArchiveOldLogs(ctx context.Context, olderThan time.Time) (*ArchiveResult, error)
}
// EncryptionManager handles role-based encryption and key management
//
// Manages encryption keys and operations for role-based access control,
// integrating with the BZZZ crypto system for secure context storage
// and distribution.
type EncryptionManager interface {
// EncryptForRoles encrypts context data for specific roles
EncryptForRoles(ctx context.Context, data []byte, roles []string) (*EncryptedData, error)
// DecryptForUser decrypts data based on user's roles and permissions
DecryptForUser(ctx context.Context, encryptedData *EncryptedData, userID string) ([]byte, error)
// GenerateRoleKey generates encryption key for a role
GenerateRoleKey(ctx context.Context, roleID string) (*RoleKey, error)
// RotateRoleKeys rotates encryption keys for roles
RotateRoleKeys(ctx context.Context, roles []string) (*KeyRotationResult, error)
// GetRoleKey retrieves encryption key for a role
GetRoleKey(ctx context.Context, roleID string) (*RoleKey, error)
// RevokeRoleKey revokes encryption key for a role
RevokeRoleKey(ctx context.Context, roleID string) error
// ValidateEncryptedData validates integrity of encrypted data
ValidateEncryptedData(ctx context.Context, encryptedData *EncryptedData) (bool, error)
// GetEncryptionStats returns encryption operation statistics
GetEncryptionStats() (*EncryptionStatistics, error)
}
// PolicyManager handles role-based policy definition and enforcement
type PolicyManager interface {
// CreatePolicy creates a new access control policy
CreatePolicy(ctx context.Context, policy *AccessPolicy) error
// UpdatePolicy updates existing access control policy
UpdatePolicy(ctx context.Context, policy *AccessPolicy) error
// DeletePolicy removes an access control policy
DeletePolicy(ctx context.Context, policyID string) error
// GetPolicy retrieves a specific policy
GetPolicy(ctx context.Context, policyID string) (*AccessPolicy, error)
// ListPolicies lists all policies with optional filtering
ListPolicies(ctx context.Context, filter *PolicyFilter) ([]*AccessPolicy, error)
// EvaluatePolicy evaluates policy against access request
EvaluatePolicy(ctx context.Context, policyID string, request *AccessRequest) (*PolicyEvaluation, error)
// GetApplicablePolicies gets policies applicable to user and resource
GetApplicablePolicies(ctx context.Context, userID string, resource string) ([]*AccessPolicy, error)
// ValidatePolicy validates policy definition and rules
ValidatePolicy(ctx context.Context, policy *AccessPolicy) (*PolicyValidation, error)
}
// SessionManager handles user session management and context
type SessionManager interface {
// CreateSession creates new user session with role context
CreateSession(ctx context.Context, userID string, roles []string) (*UserSession, error)
// GetSession retrieves existing user session
GetSession(ctx context.Context, sessionID string) (*UserSession, error)
// UpdateSession updates session with new permissions or context
UpdateSession(ctx context.Context, sessionID string, updates *SessionUpdate) error
// RevokeSession revokes user session
RevokeSession(ctx context.Context, sessionID string) error
// ListActiveSessions lists all active sessions
ListActiveSessions(ctx context.Context) ([]*UserSession, error)
// CleanupExpiredSessions removes expired sessions
CleanupExpiredSessions(ctx context.Context) (*CleanupResult, error)
// GetSessionStats returns session management statistics
GetSessionStats() (*SessionStatistics, error)
}
// DelegationManager handles permission delegation and temporary access
type DelegationManager interface {
// DelegatePermission delegates permission from one user to another
DelegatePermission(ctx context.Context, fromUserID, toUserID string, permission Permission, duration time.Duration) (*Delegation, error)
// RevokeDelegation revokes previously granted delegation
RevokeDelegation(ctx context.Context, delegationID string) error
// GetUserDelegations gets all delegations for a user
GetUserDelegations(ctx context.Context, userID string) ([]*Delegation, error)
// GetActiveDelegations gets all active delegations in system
GetActiveDelegations(ctx context.Context) ([]*Delegation, error)
// ValidateDelegation validates delegation request
ValidateDelegation(ctx context.Context, delegation *Delegation) (*DelegationValidation, error)
// GetDelegationStats returns delegation statistics
GetDelegationStats() (*DelegationStatistics, error)
}

645
pkg/slurp/roles/types.go Normal file
View File

@@ -0,0 +1,645 @@
package roles
import (
"time"
"chorus.services/bzzz/pkg/security"
"chorus.services/bzzz/pkg/ucxl"
slurpContext "chorus.services/bzzz/pkg/slurp/context"
)
// Stub types for interfaces (to be implemented later)
type RoleFilter struct {
RoleIDs []string `json:"role_ids,omitempty"`
Permissions []string `json:"permissions,omitempty"`
}
type RoleHierarchy struct {
Roles map[string][]string `json:"roles"`
}
type RoleValidation struct {
Valid bool `json:"valid"`
Errors []string `json:"errors"`
}
type RoleStatistics struct {
TotalRoles int `json:"total_roles"`
ActiveRoles int `json:"active_roles"`
}
type AccessStatistics struct {
TotalRequests int `json:"total_requests"`
GrantedRequests int `json:"granted_requests"`
}
type FilteringStatistics struct {
TotalFiltered int `json:"total_filtered"`
PassedFilter int `json:"passed_filter"`
}
type EvaluationStatistics struct {
TotalEvaluations int `json:"total_evaluations"`
SuccessfulEvaluations int `json:"successful_evaluations"`
}
type PermissionChange struct {
RoleID string `json:"role_id"`
Permission string `json:"permission"`
Action string `json:"action"`
Timestamp time.Time `json:"timestamp"`
}
type SecurityEvent struct {
EventType string `json:"event_type"`
RoleID string `json:"role_id"`
Timestamp time.Time `json:"timestamp"`
Details map[string]interface{} `json:"details"`
}
type AuditFilter struct {
RoleIDs []string `json:"role_ids,omitempty"`
EventTypes []string `json:"event_types,omitempty"`
StartTime *time.Time `json:"start_time,omitempty"`
EndTime *time.Time `json:"end_time,omitempty"`
}
type AuditEntry struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
EventType string `json:"event_type"`
RoleID string `json:"role_id"`
Details map[string]interface{} `json:"details"`
}
type AuditStatistics struct {
TotalEntries int `json:"total_entries"`
RecentEntries int `json:"recent_entries"`
}
type RetentionPolicy struct {
Duration time.Duration `json:"duration"`
MaxEntries int `json:"max_entries"`
}
type ArchiveResult struct {
ArchivedCount int `json:"archived_count"`
Success bool `json:"success"`
}
type EncryptionStatistics struct {
TotalEncrypted int `json:"total_encrypted"`
EncryptionErrors int `json:"encryption_errors"`
}
type AccessPolicy struct {
ID string `json:"id"`
Name string `json:"name"`
Rules []string `json:"rules"`
CreatedAt time.Time `json:"created_at"`
}
type PolicyFilter struct {
PolicyIDs []string `json:"policy_ids,omitempty"`
Names []string `json:"names,omitempty"`
}
type AccessRequest struct {
ID string `json:"id"`
UserID string `json:"user_id"`
RoleID string `json:"role_id"`
Resource string `json:"resource"`
Action string `json:"action"`
Timestamp time.Time `json:"timestamp"`
}
type PolicyEvaluation struct {
PolicyID string `json:"policy_id"`
Result bool `json:"result"`
Reason string `json:"reason"`
Timestamp time.Time `json:"timestamp"`
}
type PolicyValidation struct {
Valid bool `json:"valid"`
Errors []string `json:"errors"`
Warnings []string `json:"warnings"`
}
type UserSession struct {
ID string `json:"id"`
UserID string `json:"user_id"`
RoleIDs []string `json:"role_ids"`
CreatedAt time.Time `json:"created_at"`
LastAccessed time.Time `json:"last_accessed"`
ExpiresAt time.Time `json:"expires_at"`
Active bool `json:"active"`
}
type SessionUpdate struct {
SessionID string `json:"session_id"`
RoleIDs []string `json:"role_ids,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Active *bool `json:"active,omitempty"`
}
type CleanupResult struct {
CleanedSessions int `json:"cleaned_sessions"`
Success bool `json:"success"`
}
type SessionStatistics struct {
ActiveSessions int `json:"active_sessions"`
TotalSessions int `json:"total_sessions"`
ExpiredSessions int `json:"expired_sessions"`
}
type Delegation struct {
ID string `json:"id"`
DelegatorID string `json:"delegator_id"`
DelegateID string `json:"delegate_id"`
RoleID string `json:"role_id"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Active bool `json:"active"`
}
type DelegationValidation struct {
Valid bool `json:"valid"`
Errors []string `json:"errors"`
Warnings []string `json:"warnings"`
}
type DelegationStatistics struct {
ActiveDelegations int `json:"active_delegations"`
TotalDelegations int `json:"total_delegations"`
ExpiredDelegations int `json:"expired_delegations"`
}
// Permission represents a specific permission within the system
type Permission string
const (
// Context permissions
PermissionReadContext Permission = "read_context" // Read context data
PermissionWriteContext Permission = "write_context" // Write/modify context data
PermissionDeleteContext Permission = "delete_context" // Delete context data
PermissionCreateContext Permission = "create_context" // Create new context
PermissionViewSensitive Permission = "view_sensitive" // View sensitive context data
// Code-related permissions
PermissionReadCode Permission = "read_code" // Read source code
PermissionWriteCode Permission = "write_code" // Write/modify source code
PermissionDeleteCode Permission = "delete_code" // Delete source code
PermissionExecuteCode Permission = "execute_code" // Execute code
PermissionDeployCode Permission = "deploy_code" // Deploy code changes
// Architecture permissions
PermissionViewArchitecture Permission = "view_architecture" // View architectural information
PermissionModifyArchitecture Permission = "modify_architecture" // Modify architectural decisions
PermissionCreateArchitecture Permission = "create_architecture" // Create architectural components
// Administrative permissions
PermissionManageRoles Permission = "manage_roles" // Manage roles and permissions
PermissionManageUsers Permission = "manage_users" // Manage user assignments
PermissionViewAuditLog Permission = "view_audit_log" // View audit logs
PermissionSystemConfig Permission = "system_config" // Configure system settings
// Intelligence permissions
PermissionGenerateContext Permission = "generate_context" // Generate new context
PermissionAnalyzePatterns Permission = "analyze_patterns" // Analyze code patterns
PermissionViewMetrics Permission = "view_metrics" // View system metrics
// Temporal permissions
PermissionViewHistory Permission = "view_history" // View context history
PermissionModifyHistory Permission = "modify_history" // Modify historical data
PermissionViewDecisions Permission = "view_decisions" // View decision information
// Goal alignment permissions
PermissionViewGoals Permission = "view_goals" // View project goals
PermissionModifyGoals Permission = "modify_goals" // Modify project goals
PermissionViewAlignment Permission = "view_alignment" // View alignment scores
// Distribution permissions
PermissionDistributeContext Permission = "distribute_context" // Distribute context via DHT
PermissionManageReplicas Permission = "manage_replicas" // Manage context replicas
PermissionViewClusterInfo Permission = "view_cluster_info" // View cluster information
)
// AccessType represents different types of access to context
type AccessType string
const (
AccessTypeRead AccessType = "read" // Read-only access
AccessTypeWrite AccessType = "write" // Write/modify access
AccessTypeDelete AccessType = "delete" // Delete access
AccessTypeExecute AccessType = "execute" // Execute access
AccessTypeAdmin AccessType = "admin" // Administrative access
)
// Role represents a role with associated permissions and metadata
type Role struct {
ID string `json:"id"` // Unique role identifier
Name string `json:"name"` // Human-readable role name
Description string `json:"description"` // Role description
Permissions []Permission `json:"permissions"` // Granted permissions
AccessLevel security.AccessLevel `json:"access_level"` // Maximum access level
Priority int `json:"priority"` // Role priority for conflicts
// Hierarchy
ParentRoleID *string `json:"parent_role_id,omitempty"` // Parent role
ChildRoleIDs []string `json:"child_role_ids"` // Child roles
InheritsFrom []string `json:"inherits_from"` // Roles to inherit from
// Constraints
MaxUsers *int `json:"max_users,omitempty"` // Maximum users with role
RequiresMFA bool `json:"requires_mfa"` // Requires multi-factor auth
SessionTimeout *time.Duration `json:"session_timeout,omitempty"` // Session timeout
IPRestrictions []string `json:"ip_restrictions"` // IP address restrictions
TimeRestrictions *TimeRestrictions `json:"time_restrictions,omitempty"` // Time-based restrictions
// Status and lifecycle
Status RoleStatus `json:"status"` // Current status
CreatedAt time.Time `json:"created_at"` // When created
UpdatedAt time.Time `json:"updated_at"` // When last updated
CreatedBy string `json:"created_by"` // Who created it
ExpiresAt *time.Time `json:"expires_at,omitempty"` // When role expires
// Metadata
Tags []string `json:"tags"` // Role tags
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// RoleStatus represents the status of a role
type RoleStatus string
const (
RoleStatusActive RoleStatus = "active" // Role is active
RoleStatusInactive RoleStatus = "inactive" // Role is inactive
RoleStatusDeprecated RoleStatus = "deprecated" // Role is deprecated
RoleStatusExpired RoleStatus = "expired" // Role has expired
)
// TimeRestrictions represents time-based access restrictions
type TimeRestrictions struct {
AllowedHours []int `json:"allowed_hours"` // Hours when access allowed (0-23)
AllowedDays []time.Weekday `json:"allowed_days"` // Days when access allowed
Timezone string `json:"timezone"` // Timezone for restrictions
ValidFrom *time.Time `json:"valid_from,omitempty"` // Valid from date
ValidUntil *time.Time `json:"valid_until,omitempty"` // Valid until date
ExceptionWindows []*TimeWindow `json:"exception_windows"` // Exception time windows
}
// TimeWindow represents a time window for permissions or restrictions
type TimeWindow struct {
StartTime time.Time `json:"start_time"` // Window start time
EndTime time.Time `json:"end_time"` // Window end time
Timezone string `json:"timezone"` // Window timezone
Recurring bool `json:"recurring"` // Whether window recurs
RecurrenceRule string `json:"recurrence_rule"` // Recurrence rule (cron-like)
}
// RoleAssignment represents assignment of a role to a user
type RoleAssignment struct {
ID string `json:"id"` // Assignment ID
UserID string `json:"user_id"` // User identifier
RoleID string `json:"role_id"` // Role identifier
AssignedBy string `json:"assigned_by"` // Who assigned the role
AssignedAt time.Time `json:"assigned_at"` // When assigned
ExpiresAt *time.Time `json:"expires_at,omitempty"` // When assignment expires
Conditions []*AssignmentCondition `json:"conditions"` // Assignment conditions
Status AssignmentStatus `json:"status"` // Assignment status
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// AssignmentCondition represents a condition for role assignment
type AssignmentCondition struct {
Type ConditionType `json:"type"` // Condition type
Expression string `json:"expression"` // Condition expression
Parameters map[string]interface{} `json:"parameters"` // Condition parameters
Description string `json:"description"` // Condition description
}
// ConditionType represents types of assignment conditions
type ConditionType string
const (
ConditionTypeTime ConditionType = "time" // Time-based condition
ConditionTypeLocation ConditionType = "location" // Location-based condition
ConditionTypeResource ConditionType = "resource" // Resource-based condition
ConditionTypeContext ConditionType = "context" // Context-based condition
ConditionTypeGroup ConditionType = "group" // Group membership condition
)
// AssignmentStatus represents status of role assignment
type AssignmentStatus string
const (
AssignmentStatusActive AssignmentStatus = "active" // Assignment is active
AssignmentStatusInactive AssignmentStatus = "inactive" // Assignment is inactive
AssignmentStatusExpired AssignmentStatus = "expired" // Assignment has expired
AssignmentStatusRevoked AssignmentStatus = "revoked" // Assignment was revoked
AssignmentStatusPending AssignmentStatus = "pending" // Assignment is pending approval
)
// ContextPermissions represents permissions for a specific context
type ContextPermissions struct {
Address ucxl.Address `json:"address"` // Context address
UserID string `json:"user_id"` // User identifier
CanRead bool `json:"can_read"` // Can read context
CanWrite bool `json:"can_write"` // Can write/modify context
CanDelete bool `json:"can_delete"` // Can delete context
CanDistribute bool `json:"can_distribute"` // Can distribute context
AccessLevel security.AccessLevel `json:"access_level"` // Granted access level
AllowedFields []string `json:"allowed_fields"` // Fields user can access
RestrictedFields []string `json:"restricted_fields"` // Fields user cannot access
Conditions []*PermissionCondition `json:"conditions"` // Access conditions
EvaluatedAt time.Time `json:"evaluated_at"` // When evaluated
ExpiresAt *time.Time `json:"expires_at,omitempty"` // When expires
}
// PermissionCondition represents a condition for permission grant
type PermissionCondition struct {
Type ConditionType `json:"type"` // Condition type
Expression string `json:"expression"` // Condition expression
Satisfied bool `json:"satisfied"` // Whether condition is satisfied
EvaluatedAt time.Time `json:"evaluated_at"` // When condition was evaluated
Message string `json:"message"` // Condition evaluation message
}
// AccessToken represents a time-limited access token
type AccessToken struct {
Token string `json:"token"` // Token string
UserID string `json:"user_id"` // User identifier
Permissions []Permission `json:"permissions"` // Granted permissions
AccessLevel security.AccessLevel `json:"access_level"` // Granted access level
IssuedAt time.Time `json:"issued_at"` // When issued
ExpiresAt time.Time `json:"expires_at"` // When expires
Scope []string `json:"scope"` // Token scope
RefreshToken *string `json:"refresh_token,omitempty"` // Refresh token
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// TokenValidation represents result of token validation
type TokenValidation struct {
Valid bool `json:"valid"` // Whether token is valid
Token *AccessToken `json:"token,omitempty"` // Token details if valid
ErrorCode string `json:"error_code,omitempty"` // Error code if invalid
ErrorMessage string `json:"error_message,omitempty"` // Error message if invalid
ValidatedAt time.Time `json:"validated_at"` // When validation occurred
}
// AccessDecision represents an access control decision
type AccessDecision struct {
ID string `json:"id"` // Decision ID
UserID string `json:"user_id"` // User identifier
Resource string `json:"resource"` // Accessed resource
Action string `json:"action"` // Attempted action
Permission Permission `json:"permission"` // Required permission
Decision DecisionResult `json:"decision"` // Access decision
Reason string `json:"reason"` // Decision reason
EvaluatedPolicies []string `json:"evaluated_policies"` // Policies evaluated
EvaluationTime time.Duration `json:"evaluation_time"` // Time taken to evaluate
DecidedAt time.Time `json:"decided_at"` // When decision was made
Context map[string]interface{} `json:"context"` // Decision context
}
// DecisionResult represents the result of an access decision
type DecisionResult string
const (
DecisionAllow DecisionResult = "allow" // Access allowed
DecisionDeny DecisionResult = "deny" // Access denied
DecisionTimeout DecisionResult = "timeout" // Decision timed out
DecisionError DecisionResult = "error" // Decision error
)
// LabeledContext represents context with security labels applied
type LabeledContext struct {
Context *slurpContext.ContextNode `json:"context"` // Original context
SecurityLabels []*SecurityLabel `json:"security_labels"` // Applied security labels
ClassificationLevel string `json:"classification_level"` // Overall classification
RequiredClearance security.AccessLevel `json:"required_clearance"` // Required clearance level
LabeledAt time.Time `json:"labeled_at"` // When labels were applied
LabeledBy string `json:"labeled_by"` // Who/what applied labels
}
// SecurityLabel represents a security label applied to context
type SecurityLabel struct {
Type LabelType `json:"type"` // Label type
Value string `json:"value"` // Label value
Confidence float64 `json:"confidence"` // Labeling confidence
AppliedReason string `json:"applied_reason"` // Why label was applied
RequiredLevel security.AccessLevel `json:"required_level"` // Required access level
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// LabelType represents types of security labels
type LabelType string
const (
LabelTypeClassification LabelType = "classification" // Classification label
LabelTypeCategory LabelType = "category" // Category label
LabelTypeSensitivity LabelType = "sensitivity" // Sensitivity label
LabelTypeHandling LabelType = "handling" // Handling instruction
LabelTypeProject LabelType = "project" // Project-specific label
LabelTypeCustom LabelType = "custom" // Custom label
)
// RoleContextView represents a role-specific view of context
type RoleContextView struct {
OriginalContext *slurpContext.ContextNode `json:"original_context"` // Original context
FilteredContext *slurpContext.ContextNode `json:"filtered_context"` // Role-filtered context
RoleID string `json:"role_id"` // Role identifier
ViewType ViewType `json:"view_type"` // Type of view
EnhancedFields []string `json:"enhanced_fields"` // Fields enhanced for role
HiddenFields []string `json:"hidden_fields"` // Fields hidden from role
AddedInsights []string `json:"added_insights"` // Role-specific insights added
GeneratedAt time.Time `json:"generated_at"` // When view was generated
}
// ViewType represents types of role-specific views
type ViewType string
const (
ViewTypeDeveloper ViewType = "developer" // Developer-focused view
ViewTypeArchitect ViewType = "architect" // Architect-focused view
ViewTypeManager ViewType = "manager" // Manager-focused view
ViewTypeSecurity ViewType = "security" // Security-focused view
ViewTypeAuditor ViewType = "auditor" // Auditor-focused view
ViewTypeOperations ViewType = "operations" // Operations-focused view
)
// FilteringPolicy represents context filtering policy configuration
type FilteringPolicy struct {
ID string `json:"id"` // Policy ID
Name string `json:"name"` // Policy name
Rules []*FilteringRule `json:"rules"` // Filtering rules
DefaultAction FilterAction `json:"default_action"` // Default action
Priority int `json:"priority"` // Policy priority
ApplicableRoles []string `json:"applicable_roles"` // Roles this applies to
CreatedAt time.Time `json:"created_at"` // When created
UpdatedAt time.Time `json:"updated_at"` // When updated
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// FilteringRule represents a single filtering rule
type FilteringRule struct {
ID string `json:"id"` // Rule ID
Name string `json:"name"` // Rule name
Condition string `json:"condition"` // Rule condition expression
Action FilterAction `json:"action"` // Action to take
TargetFields []string `json:"target_fields"` // Fields affected by rule
Priority int `json:"priority"` // Rule priority
Enabled bool `json:"enabled"` // Whether rule is enabled
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// FilterAction represents actions that can be taken during filtering
type FilterAction string
const (
FilterActionAllow FilterAction = "allow" // Allow field/content
FilterActionDeny FilterAction = "deny" // Deny field/content
FilterActionRedact FilterAction = "redact" // Redact field/content
FilterActionTransform FilterAction = "transform" // Transform field/content
FilterActionAudit FilterAction = "audit" // Allow but audit access
)
// ConditionalPermission represents a permission with conditions
type ConditionalPermission struct {
Permission Permission `json:"permission"` // Base permission
Conditions []*PermissionCondition `json:"conditions"` // Required conditions
ExpiresAt *time.Time `json:"expires_at,omitempty"` // When permission expires
GrantedAt time.Time `json:"granted_at"` // When permission was granted
GrantedBy string `json:"granted_by"` // Who granted permission
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// EvaluationContext represents context for permission evaluation
type EvaluationContext struct {
UserID string `json:"user_id"` // User identifier
Resource string `json:"resource"` // Resource being accessed
Action string `json:"action"` // Action being attempted
Environment map[string]interface{} `json:"environment"` // Environmental context
RequestTime time.Time `json:"request_time"` // When request was made
ClientInfo *ClientInfo `json:"client_info"` // Client information
PreviousDecisions []*AccessDecision `json:"previous_decisions"` // Previous related decisions
}
// ClientInfo represents information about the client making the request
type ClientInfo struct {
IPAddress string `json:"ip_address"` // Client IP address
UserAgent string `json:"user_agent"` // Client user agent
Location *LocationInfo `json:"location,omitempty"` // Client location
DeviceInfo map[string]interface{} `json:"device_info"` // Device information
SessionInfo *SessionInfo `json:"session_info"` // Session information
}
// LocationInfo represents location information
type LocationInfo struct {
Country string `json:"country"` // Country code
Region string `json:"region"` // Region/state
City string `json:"city"` // City name
Latitude float64 `json:"latitude"` // Latitude
Longitude float64 `json:"longitude"` // Longitude
Accuracy float64 `json:"accuracy"` // Location accuracy
}
// SessionInfo represents session information
type SessionInfo struct {
SessionID string `json:"session_id"` // Session identifier
CreatedAt time.Time `json:"created_at"` // When session was created
LastActivity time.Time `json:"last_activity"` // Last activity time
ActivityCount int `json:"activity_count"` // Number of activities
RiskScore float64 `json:"risk_score"` // Session risk score
}
// PermissionEvaluation represents result of permission evaluation
type PermissionEvaluation struct {
Permission Permission `json:"permission"` // Evaluated permission
Granted bool `json:"granted"` // Whether permission was granted
Reason string `json:"reason"` // Evaluation reason
ConditionResults []*ConditionResult `json:"condition_results"` // Individual condition results
EvaluationTime time.Duration `json:"evaluation_time"` // Time taken to evaluate
EvaluatedAt time.Time `json:"evaluated_at"` // When evaluation occurred
CacheHit bool `json:"cache_hit"` // Whether result was cached
}
// ConditionResult represents result of condition evaluation
type ConditionResult struct {
Condition *PermissionCondition `json:"condition"` // Evaluated condition
Satisfied bool `json:"satisfied"` // Whether condition was satisfied
Value interface{} `json:"value"` // Condition value
EvaluationTime time.Duration `json:"evaluation_time"` // Time taken to evaluate
ErrorMessage string `json:"error_message,omitempty"` // Error if evaluation failed
}
// PermissionRule represents a custom permission evaluation rule
type PermissionRule struct {
ID string `json:"id"` // Rule ID
Name string `json:"name"` // Rule name
Description string `json:"description"` // Rule description
RuleType RuleType `json:"rule_type"` // Type of rule
Expression string `json:"expression"` // Rule expression
ApplicablePermissions []Permission `json:"applicable_permissions"` // Permissions this applies to
Priority int `json:"priority"` // Rule priority
Enabled bool `json:"enabled"` // Whether rule is enabled
CreatedAt time.Time `json:"created_at"` // When created
UpdatedAt time.Time `json:"updated_at"` // When updated
CreatedBy string `json:"created_by"` // Who created rule
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// RuleType represents types of permission rules
type RuleType string
const (
RuleTypeAllow RuleType = "allow" // Allow rule
RuleTypeDeny RuleType = "deny" // Deny rule
RuleTypeConditional RuleType = "conditional" // Conditional rule
RuleTypeTransform RuleType = "transform" // Transform rule
RuleTypeAudit RuleType = "audit" // Audit rule
)
// EncryptedData represents encrypted data with role-based access
type EncryptedData struct {
Data []byte `json:"data"` // Encrypted data
EncryptionMethod string `json:"encryption_method"` // Encryption method used
RoleKeys map[string]string `json:"role_keys"` // Encrypted keys by role
AccessLevels map[string]security.AccessLevel `json:"access_levels"` // Access levels by role
CreatedAt time.Time `json:"created_at"` // When encrypted
ExpiresAt *time.Time `json:"expires_at,omitempty"` // When encryption expires
Metadata map[string]interface{} `json:"metadata"` // Additional metadata
}
// RoleKey represents an encryption key for a role
type RoleKey struct {
RoleID string `json:"role_id"` // Role identifier
KeyData []byte `json:"key_data"` // Key data (encrypted)
KeyType string `json:"key_type"` // Key type
CreatedAt time.Time `json:"created_at"` // When key was created
ExpiresAt *time.Time `json:"expires_at,omitempty"` // When key expires
Version int `json:"version"` // Key version
Status KeyStatus `json:"status"` // Key status
}
// KeyStatus represents status of encryption keys
type KeyStatus string
const (
KeyStatusActive KeyStatus = "active" // Key is active
KeyStatusExpired KeyStatus = "expired" // Key has expired
KeyStatusRevoked KeyStatus = "revoked" // Key has been revoked
KeyStatusRotated KeyStatus = "rotated" // Key has been rotated
)
// KeyRotationResult represents result of key rotation
type KeyRotationResult struct {
RotatedRoles []string `json:"rotated_roles"` // Roles for which keys were rotated
NewKeys map[string]*RoleKey `json:"new_keys"` // New keys by role
RevokedKeys map[string]*RoleKey `json:"revoked_keys"` // Revoked keys by role
RotationTime time.Duration `json:"rotation_time"` // Time taken for rotation
RotatedAt time.Time `json:"rotated_at"` // When rotation occurred
Errors []string `json:"errors,omitempty"` // Any errors during rotation
}