auth

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidCredentials = errors.New("invalid credentials")
	ErrUserNotFound       = errors.New("user not found")
	ErrInvalidToken       = errors.New("invalid token")
	ErrTokenExpired       = errors.New("token expired")
	ErrSessionNotFound    = errors.New("session not found")
	ErrSessionExpired     = errors.New("session expired")
	ErrProviderNotFound   = errors.New("provider not found")
	ErrUnauthorized       = errors.New("unauthorized")
	ErrForbidden          = errors.New("forbidden")
)

Common errors

Functions

func SetUserInContext

func SetUserInContext(c *gin.Context, user *User)

SetUserInContext sets the authenticated user in the request context

func ValidateOAuth2Config

func ValidateOAuth2Config(config OAuth2Config) error

ValidateConfig validates the OAuth2 provider configuration

Types

type Action

type Action struct {
	Type       string            `json:"type"`
	Resource   string            `json:"resource"`
	Attributes map[string]string `json:"attributes"`
}

Action represents an action being performed

type ApprovalWorkflow

type ApprovalWorkflow struct {
	Required         bool          `json:"required"`
	MinApprovers     int           `json:"min_approvers"`
	RequiredRoles    []string      `json:"required_roles"`
	TimeoutDuration  time.Duration `json:"timeout_duration"`
	EscalationRoles  []string      `json:"escalation_roles"`
	AutoApproveRoles []string      `json:"auto_approve_roles"`
}

ApprovalWorkflow defines approval requirements for policy actions

type AuditSettings

type AuditSettings struct {
	Enabled           bool          `json:"enabled"`
	LogAllEvaluations bool          `json:"log_all_evaluations"`
	RetentionPeriod   time.Duration `json:"retention_period"`
	ExportEnabled     bool          `json:"export_enabled"`
	ExportFormat      string        `json:"export_format"` // json, csv, siem
}

AuditSettings defines audit logging settings

type AuthConfig

type AuthConfig struct {
	DefaultProvider string                    `yaml:"default_provider" json:"default_provider"`
	Providers       map[string]ProviderConfig `yaml:"providers" json:"providers"`
	Session         SessionConfig             `yaml:"session" json:"session"`
}

AuthConfig holds authentication configuration

type AuthManager

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

AuthManager manages authentication and authorization

func NewAuthManager

func NewAuthManager(config AuthConfig, sessionManager SessionManager) *AuthManager

NewAuthManager creates a new authentication manager

func (*AuthManager) Authenticate

func (am *AuthManager) Authenticate(ctx context.Context, providerName, username, password string) (*User, error)

Authenticate authenticates a user using the specified provider

func (*AuthManager) CreateSession

func (am *AuthManager) CreateSession(ctx context.Context, user *User, ipAddress, userAgent string) (*Session, error)

CreateSession creates a new session for a user

func (*AuthManager) GetProvider

func (am *AuthManager) GetProvider(name string) (AuthProvider, error)

GetProvider returns a provider by name

func (*AuthManager) GetUser

func (am *AuthManager) GetUser(ctx context.Context, userID string) (*User, error)

GetUser retrieves user information

func (*AuthManager) Logout

func (am *AuthManager) Logout(ctx context.Context, token string) error

Logout logs out a user by invalidating their session

func (*AuthManager) RefreshSession

func (am *AuthManager) RefreshSession(ctx context.Context, token string) (*Session, error)

RefreshSession refreshes a session

func (*AuthManager) RegisterProvider

func (am *AuthManager) RegisterProvider(name string, provider AuthProvider)

RegisterProvider registers an authentication provider

func (*AuthManager) ValidateToken

func (am *AuthManager) ValidateToken(ctx context.Context, token string) (*User, error)

ValidateToken validates a token using the appropriate provider

type AuthProvider

type AuthProvider interface {
	// Authenticate authenticates a user with username/password
	Authenticate(ctx context.Context, username, password string) (*User, error)

	// ValidateToken validates an authentication token
	ValidateToken(ctx context.Context, token string) (*User, error)

	// GetUser retrieves user information by ID
	GetUser(ctx context.Context, userID string) (*User, error)

	// GetUserByUsername retrieves user information by username
	GetUserByUsername(ctx context.Context, username string) (*User, error)

	// RefreshToken refreshes an authentication token
	RefreshToken(ctx context.Context, token string) (string, error)

	// Logout invalidates a session
	Logout(ctx context.Context, token string) error

	// GetProviderType returns the provider type
	GetProviderType() string
}

AuthProvider defines the interface for authentication providers

type AuthorizationMiddleware

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

AuthorizationMiddleware provides RBAC-based authorization

func NewAuthorizationMiddleware

func NewAuthorizationMiddleware(rbac *RBACEngine, authManager *AuthManager, enabled bool) *AuthorizationMiddleware

NewAuthorizationMiddleware creates a new authorization middleware

func (*AuthorizationMiddleware) AdminOnlyMiddleware

func (am *AuthorizationMiddleware) AdminOnlyMiddleware() gin.HandlerFunc

AdminOnlyMiddleware restricts access to admin users only

func (*AuthorizationMiddleware) GetUserPermissions

func (am *AuthorizationMiddleware) GetUserPermissions(c *gin.Context) gin.HandlerFunc

GetUserPermissions returns all permissions for the current user

func (*AuthorizationMiddleware) RequireAction

func (am *AuthorizationMiddleware) RequireAction(actionType, resource string) gin.HandlerFunc

RequireAction creates a middleware that checks if user can perform a specific action

func (*AuthorizationMiddleware) RequireAnyRole

func (am *AuthorizationMiddleware) RequireAnyRole(roles ...string) gin.HandlerFunc

RequireAnyRole creates a middleware that requires any of the specified roles

func (*AuthorizationMiddleware) RequirePermission

func (am *AuthorizationMiddleware) RequirePermission(permission Permission) gin.HandlerFunc

RequirePermission creates a middleware that requires a specific permission

func (*AuthorizationMiddleware) RequireRole

func (am *AuthorizationMiddleware) RequireRole(role string) gin.HandlerFunc

RequireRole creates a middleware that requires a specific role

func (*AuthorizationMiddleware) ResourceOwnershipMiddleware

func (am *AuthorizationMiddleware) ResourceOwnershipMiddleware(resourceParam string) gin.HandlerFunc

ResourceOwnershipMiddleware checks if user owns the resource

func (*AuthorizationMiddleware) SecurityAnalystOrAdminMiddleware

func (am *AuthorizationMiddleware) SecurityAnalystOrAdminMiddleware() gin.HandlerFunc

SecurityAnalystOrAdminMiddleware allows security analysts and admins

type DatabaseSessionManager

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

DatabaseSessionManager implements SessionManager using a database

func NewDatabaseSessionManager

func NewDatabaseSessionManager(db *sql.DB, config SessionConfig) *DatabaseSessionManager

NewDatabaseSessionManager creates a new database session manager

func (*DatabaseSessionManager) CleanupExpiredSessions

func (sm *DatabaseSessionManager) CleanupExpiredSessions(ctx context.Context) error

CleanupExpiredSessions removes expired sessions

func (*DatabaseSessionManager) CreateSession

func (sm *DatabaseSessionManager) CreateSession(ctx context.Context, user *User, ipAddress, userAgent string) (*Session, error)

CreateSession creates a new session for a user

func (*DatabaseSessionManager) GetSession

func (sm *DatabaseSessionManager) GetSession(ctx context.Context, token string) (*Session, error)

GetSession retrieves a session by token

func (*DatabaseSessionManager) GetSessionStats

func (sm *DatabaseSessionManager) GetSessionStats(ctx context.Context) (*SessionStats, error)

GetSessionStats returns session statistics

func (*DatabaseSessionManager) GetUserSessions

func (sm *DatabaseSessionManager) GetUserSessions(ctx context.Context, userID string) ([]*Session, error)

GetUserSessions retrieves all active sessions for a user

func (*DatabaseSessionManager) InitializeSessionTables

func (sm *DatabaseSessionManager) InitializeSessionTables(ctx context.Context) error

InitializeSessionTables creates the necessary database tables for sessions

func (*DatabaseSessionManager) InvalidateSession

func (sm *DatabaseSessionManager) InvalidateSession(ctx context.Context, token string) error

InvalidateSession invalidates a session

func (*DatabaseSessionManager) InvalidateUserSessions

func (sm *DatabaseSessionManager) InvalidateUserSessions(ctx context.Context, userID string) error

InvalidateUserSessions invalidates all sessions for a user

func (*DatabaseSessionManager) RefreshSession

func (sm *DatabaseSessionManager) RefreshSession(ctx context.Context, token string) (*Session, error)

RefreshSession refreshes a session

type EnforcementResult

type EnforcementResult struct {
	Allowed         bool                      `json:"allowed"`
	Reason          string                    `json:"reason"`
	PolicyResults   []*PolicyEvaluationResult `json:"policy_results"`
	Violations      []PolicyViolation         `json:"violations"`
	RequiredActions []string                  `json:"required_actions"`
	ApprovalURL     string                    `json:"approval_url,omitempty"`
	EvaluatedAt     time.Time                 `json:"evaluated_at"`
	Metadata        map[string]interface{}    `json:"metadata"`
}

EnforcementResult represents the result of policy enforcement

type EnterprisePolicyManager

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

EnterprisePolicyManager manages enterprise-level security policies

func NewEnterprisePolicyManager

func NewEnterprisePolicyManager(policyEngine *PolicyEngine, rbacEngine *RBACEngine, logger Logger) *EnterprisePolicyManager

NewEnterprisePolicyManager creates a new enterprise policy manager

func (*EnterprisePolicyManager) AddPolicy

func (epm *EnterprisePolicyManager) AddPolicy(policy *SecurityPolicy)

func (*EnterprisePolicyManager) CreatePolicyFromTemplate

func (epm *EnterprisePolicyManager) CreatePolicyFromTemplate(templateID, policyID string, customizations map[string]interface{}) (*SecurityPolicy, error)

CreatePolicyFromTemplate creates a new policy from a template

func (*EnterprisePolicyManager) EvaluateAndEnforce

func (epm *EnterprisePolicyManager) EvaluateAndEnforce(ctx context.Context, evalCtx *PolicyEvaluationContext) (*EnforcementResult, error)

EvaluateAndEnforce evaluates policies and enforces them based on configuration

func (*EnterprisePolicyManager) GetEnforcementSettings

func (epm *EnterprisePolicyManager) GetEnforcementSettings() *PolicyEnforcement

GetEnforcementSettings returns current enforcement settings

func (*EnterprisePolicyManager) GetPolicy

func (epm *EnterprisePolicyManager) GetPolicy(policyID string) (*SecurityPolicy, error)

func (*EnterprisePolicyManager) GetPolicyTemplate

func (epm *EnterprisePolicyManager) GetPolicyTemplate(templateID string) (*SecurityPolicy, error)

GetPolicyTemplate retrieves a policy template by ID

func (*EnterprisePolicyManager) ListPolicies

func (epm *EnterprisePolicyManager) ListPolicies() []*SecurityPolicy

Policy management methods that delegate to the policy engine

func (*EnterprisePolicyManager) ListPolicyTemplates

func (epm *EnterprisePolicyManager) ListPolicyTemplates() []*SecurityPolicy

ListPolicyTemplates returns all available policy templates

func (*EnterprisePolicyManager) RemovePolicy

func (epm *EnterprisePolicyManager) RemovePolicy(policyID string)

func (*EnterprisePolicyManager) UpdateEnforcementSettings

func (epm *EnterprisePolicyManager) UpdateEnforcementSettings(settings *PolicyEnforcement) error

UpdateEnforcementSettings updates policy enforcement settings

type LDAPConfig

type LDAPConfig struct {
	Host                 string            `yaml:"host" json:"host"`
	Port                 int               `yaml:"port" json:"port"`
	UseTLS               bool              `yaml:"use_tls" json:"use_tls"`
	SkipTLSVerify        bool              `yaml:"skip_tls_verify" json:"skip_tls_verify"`
	BindDN               string            `yaml:"bind_dn" json:"bind_dn"`
	BindPassword         string            `yaml:"bind_password" json:"bind_password"`
	BaseDN               string            `yaml:"base_dn" json:"base_dn"`
	UserFilter           string            `yaml:"user_filter" json:"user_filter"`
	UserSearchBase       string            `yaml:"user_search_base" json:"user_search_base"`
	GroupFilter          string            `yaml:"group_filter" json:"group_filter"`
	GroupSearchBase      string            `yaml:"group_search_base" json:"group_search_base"`
	UsernameAttribute    string            `yaml:"username_attribute" json:"username_attribute"`
	EmailAttribute       string            `yaml:"email_attribute" json:"email_attribute"`
	DisplayNameAttribute string            `yaml:"display_name_attribute" json:"display_name_attribute"`
	GroupMemberAttribute string            `yaml:"group_member_attribute" json:"group_member_attribute"`
	RoleMapping          map[string]string `yaml:"role_mapping" json:"role_mapping"`
	ConnectionTimeout    time.Duration     `yaml:"connection_timeout" json:"connection_timeout"`
	RequestTimeout       time.Duration     `yaml:"request_timeout" json:"request_timeout"`
}

LDAPConfig holds LDAP configuration

type LDAPProvider

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

LDAPProvider implements LDAP authentication

func NewLDAPProvider

func NewLDAPProvider(config LDAPConfig) *LDAPProvider

NewLDAPProvider creates a new LDAP authentication provider

func (*LDAPProvider) Authenticate

func (p *LDAPProvider) Authenticate(ctx context.Context, username, password string) (*User, error)

Authenticate authenticates a user against LDAP

func (*LDAPProvider) GetProviderType

func (p *LDAPProvider) GetProviderType() string

GetProviderType returns the provider type

func (*LDAPProvider) GetUser

func (p *LDAPProvider) GetUser(ctx context.Context, userID string) (*User, error)

GetUser retrieves user information by ID

func (*LDAPProvider) GetUserByUsername

func (p *LDAPProvider) GetUserByUsername(ctx context.Context, username string) (*User, error)

GetUserByUsername retrieves user information by username

func (*LDAPProvider) Logout

func (p *LDAPProvider) Logout(ctx context.Context, token string) error

Logout logs out a user (no-op for LDAP)

func (*LDAPProvider) RefreshToken

func (p *LDAPProvider) RefreshToken(ctx context.Context, token string) (string, error)

RefreshToken refreshes a token (not implemented for LDAP)

func (*LDAPProvider) TestConnection

func (p *LDAPProvider) TestConnection() error

TestConnection tests the LDAP connection

func (*LDAPProvider) ValidateToken

func (p *LDAPProvider) ValidateToken(ctx context.Context, token string) (*User, error)

ValidateToken validates a token (not implemented for LDAP)

type Logger

type Logger interface {
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
	Debug(msg string, fields ...interface{})
}

Logger interface for policy engine logging

type NotificationChannel

type NotificationChannel struct {
	Type     string            `json:"type"` // email, slack, webhook, teams
	Enabled  bool              `json:"enabled"`
	Settings map[string]string `json:"settings"`
}

NotificationChannel represents a notification channel

type OAuth2Config

type OAuth2Config struct {
	ClientID     string   `json:"client_id" yaml:"client_id"`
	ClientSecret string   `json:"client_secret" yaml:"client_secret"`
	AuthorizeURL string   `json:"authorize_url" yaml:"authorize_url"`
	TokenURL     string   `json:"token_url" yaml:"token_url"`
	UserInfoURL  string   `json:"user_info_url" yaml:"user_info_url"`
	RedirectURL  string   `json:"redirect_url" yaml:"redirect_url"`
	Scopes       []string `json:"scopes" yaml:"scopes"`
}

OAuth2Config contains OAuth2 provider configuration

type OAuth2Provider

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

OAuth2Provider implements SSO authentication using OAuth2/OIDC

func CreateOAuth2ProviderFromConfig

func CreateOAuth2ProviderFromConfig(name string, providerConfig ProviderConfig, logger *logrus.Logger) (*OAuth2Provider, error)

CreateOAuth2ProviderFromConfig creates an OAuth2 provider from configuration

func NewOAuth2Provider

func NewOAuth2Provider(name string, config OAuth2Config, logger *logrus.Logger) *OAuth2Provider

NewOAuth2Provider creates a new OAuth2 provider

func (*OAuth2Provider) ExchangeCode

func (p *OAuth2Provider) ExchangeCode(code, state string) (*SSOToken, error)

ExchangeCode exchanges authorization code for access token

func (*OAuth2Provider) GetAuthURL

func (p *OAuth2Provider) GetAuthURL(state string) (string, error)

GetAuthURL generates the OAuth2 authorization URL

func (*OAuth2Provider) GetProviderName

func (p *OAuth2Provider) GetProviderName() string

GetProviderName returns the provider name

func (*OAuth2Provider) GetTokenInfo

func (p *OAuth2Provider) GetTokenInfo(token *SSOToken) map[string]interface{}

GetTokenInfo returns information about a token without making external calls

func (*OAuth2Provider) GetUserInfo

func (p *OAuth2Provider) GetUserInfo(token *SSOToken) (*SSOUser, error)

GetUserInfo retrieves user information using the access token

func (*OAuth2Provider) Logout

func (p *OAuth2Provider) Logout(token string) error

Logout performs logout (revokes token if supported)

func (*OAuth2Provider) RefreshToken

func (p *OAuth2Provider) RefreshToken(refreshToken string) (*SSOToken, error)

RefreshToken refreshes an access token using the refresh token

func (*OAuth2Provider) SetHTTPClient

func (p *OAuth2Provider) SetHTTPClient(client *http.Client)

SetHTTPClient allows setting a custom HTTP client

func (*OAuth2Provider) ValidateToken

func (p *OAuth2Provider) ValidateToken(tokenString string) (*SSOUser, error)

ValidateToken validates an access token

type OAuth2TokenResponse

type OAuth2TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token,omitempty"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int64  `json:"expires_in"`
	Scope        string `json:"scope,omitempty"`
	IDToken      string `json:"id_token,omitempty"`
}

OAuth2TokenResponse represents the OAuth2 token response

type OAuth2UserInfo

type OAuth2UserInfo struct {
	Sub               string   `json:"sub"`
	Email             string   `json:"email"`
	EmailVerified     bool     `json:"email_verified"`
	Name              string   `json:"name"`
	GivenName         string   `json:"given_name"`
	FamilyName        string   `json:"family_name"`
	Picture           string   `json:"picture"`
	Locale            string   `json:"locale"`
	PreferredUsername string   `json:"preferred_username"`
	Groups            []string `json:"groups,omitempty"`
	Roles             []string `json:"roles,omitempty"`
}

OAuth2UserInfo represents user information from OAuth2 provider

type Permission

type Permission string

Permission represents a specific permission

const (
	PermissionScanAll         Permission = "scan:all"
	PermissionScanRead        Permission = "scan:read"
	PermissionScanExecute     Permission = "scan:execute"
	PermissionScanOwnRepos    Permission = "scan:own_repos"
	PermissionReportsAll      Permission = "reports:all"
	PermissionReportsRead     Permission = "reports:read"
	PermissionReportsOwnRepos Permission = "reports:own_repos"
	PermissionConfigWrite     Permission = "config:write"
	PermissionConfigRead      Permission = "config:read"
	PermissionUsersManage     Permission = "users:manage"
	PermissionUsersRead       Permission = "users:read"
	PermissionPoliciesManage  Permission = "policies:manage"
	PermissionPoliciesRead    Permission = "policies:read"
)

Common permissions

type Policy

type Policy struct {
	Name       string            `json:"name"`
	Effect     string            `json:"effect"` // "allow" or "deny"
	Actions    []string          `json:"actions"`
	Resources  []string          `json:"resources"`
	Conditions map[string]string `json:"conditions"`
}

Policy represents an authorization policy

type PolicyAction

type PolicyAction string

PolicyAction represents an action to take when a policy is triggered

const (
	PolicyActionAllow           PolicyAction = "allow"
	PolicyActionDeny            PolicyAction = "deny"
	PolicyActionBlock           PolicyAction = "block_deployment"
	PolicyActionRequireApproval PolicyAction = "require_approval"
	PolicyActionGenerateSPDX    PolicyAction = "generate_spdx"
	PolicyActionNotify          PolicyAction = "notify"
	PolicyActionQuarantine      PolicyAction = "quarantine"
	PolicyActionLog             PolicyAction = "log"
)

type PolicyApproval

type PolicyApproval struct {
	ID         string     `json:"id"`
	ApproverID string     `json:"approver_id"`
	Approver   string     `json:"approver"`
	Decision   string     `json:"decision"` // approved, rejected
	Reason     string     `json:"reason"`
	ApprovedAt time.Time  `json:"approved_at"`
	ExpiresAt  *time.Time `json:"expires_at"`
}

PolicyApproval represents an approval for a policy violation

type PolicyCondition

type PolicyCondition struct {
	Field    string      `json:"field"`    // e.g., "threat.severity", "package.downloads"
	Operator string      `json:"operator"` // e.g., "==", ">", "<", "contains", "matches"
	Value    interface{} `json:"value"`    // The value to compare against
}

PolicyCondition represents a condition that must be met for a policy to trigger

type PolicyEnforcement

type PolicyEnforcement struct {
	Enabled              bool                        `json:"enabled"`
	StrictMode           bool                        `json:"strict_mode"`  // Block on any policy violation
	GracePeriod          time.Duration               `json:"grace_period"` // Grace period for new policies
	NotificationChannels []NotificationChannel       `json:"notification_channels"`
	ApprovalWorkflows    map[string]ApprovalWorkflow `json:"approval_workflows"`
	AuditSettings        AuditSettings               `json:"audit_settings"`
}

PolicyEnforcement manages policy enforcement settings

type PolicyEngine

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

PolicyEngine manages and evaluates security policies

func NewPolicyEngine

func NewPolicyEngine(logger Logger) *PolicyEngine

NewPolicyEngine creates a new policy engine

func (*PolicyEngine) AddPolicy

func (pe *PolicyEngine) AddPolicy(policy *SecurityPolicy) error

AddPolicy adds a new policy to the engine

func (*PolicyEngine) EvaluatePolicies

func (pe *PolicyEngine) EvaluatePolicies(ctx context.Context, evalCtx *PolicyEvaluationContext) ([]*PolicyEvaluationResult, error)

EvaluatePolicies evaluates all policies against the given context

func (*PolicyEngine) GetPolicy

func (pe *PolicyEngine) GetPolicy(policyID string) (*SecurityPolicy, error)

GetPolicy retrieves a policy by ID

func (*PolicyEngine) ListPolicies

func (pe *PolicyEngine) ListPolicies() []*SecurityPolicy

ListPolicies returns all policies

func (*PolicyEngine) RemovePolicy

func (pe *PolicyEngine) RemovePolicy(policyID string) error

RemovePolicy removes a policy from the engine

type PolicyEvaluationContext

type PolicyEvaluationContext struct {
	ScanResult  *types.ScanResult      `json:"scan_result"`
	Package     *types.Package         `json:"package"`
	Repository  *RepositoryInfo        `json:"repository"`
	User        *User                  `json:"user"`
	Environment string                 `json:"environment"` // e.g., "production", "staging", "development"
	Metadata    map[string]interface{} `json:"metadata"`
}

PolicyEvaluationContext contains context for policy evaluation

type PolicyEvaluationResult

type PolicyEvaluationResult struct {
	PolicyID      string                 `json:"policy_id"`
	PolicyName    string                 `json:"policy_name"`
	Triggered     bool                   `json:"triggered"`
	Action        PolicyAction           `json:"action"`
	Reason        string                 `json:"reason"`
	Parameters    map[string]string      `json:"parameters"`
	Notifications []string               `json:"notifications"`
	Approvers     []string               `json:"approvers"`
	Metadata      map[string]interface{} `json:"metadata"`
	EvaluatedAt   time.Time              `json:"evaluated_at"`
}

PolicyEvaluationResult represents the result of policy evaluation

type PolicyViolation

type PolicyViolation struct {
	ID               string                   `json:"id"`
	PolicyID         string                   `json:"policy_id"`
	PolicyName       string                   `json:"policy_name"`
	Severity         string                   `json:"severity"`
	Description      string                   `json:"description"`
	Context          *PolicyEvaluationContext `json:"context"`
	Result           *PolicyEvaluationResult  `json:"result"`
	Status           ViolationStatus          `json:"status"`
	ApprovalRequired bool                     `json:"approval_required"`
	Approvals        []PolicyApproval         `json:"approvals"`
	Remediation      *RemediationAction       `json:"remediation"`
	CreatedAt        time.Time                `json:"created_at"`
	ResolvedAt       *time.Time               `json:"resolved_at"`
	Metadata         map[string]interface{}   `json:"metadata"`
}

PolicyViolation represents a policy violation

type ProviderConfig

type ProviderConfig struct {
	Type     string                 `yaml:"type" json:"type"`
	Enabled  bool                   `yaml:"enabled" json:"enabled"`
	Settings map[string]interface{} `yaml:"settings" json:"settings"`
}

ProviderConfig holds provider-specific configuration

type RBACEngine

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

RBACEngine handles role-based access control

func NewRBACEngine

func NewRBACEngine(config *config.AuthzConfig) *RBACEngine

NewRBACEngine creates a new RBAC engine

func (*RBACEngine) AddPolicy

func (rbac *RBACEngine) AddPolicy(policy *Policy)

AddPolicy adds a new policy to the RBAC engine

func (*RBACEngine) AddRole

func (rbac *RBACEngine) AddRole(role *Role)

AddRole adds a new role to the RBAC engine

func (*RBACEngine) CheckAction

func (rbac *RBACEngine) CheckAction(ctx context.Context, user *User, action *Action) (bool, error)

CheckAction checks if a user can perform a specific action

func (*RBACEngine) CheckPermission

func (rbac *RBACEngine) CheckPermission(ctx context.Context, user *User, permission Permission) bool

CheckPermission checks if a user has a specific permission

func (*RBACEngine) GetPolicy

func (rbac *RBACEngine) GetPolicy(name string) (*Policy, bool)

GetPolicy retrieves a policy by name

func (*RBACEngine) GetRole

func (rbac *RBACEngine) GetRole(name string) (*Role, bool)

GetRole retrieves a role by name

func (*RBACEngine) GetUserPermissions

func (rbac *RBACEngine) GetUserPermissions(user *User) []Permission

GetUserPermissions returns all permissions for a user

func (*RBACEngine) ListPolicies

func (rbac *RBACEngine) ListPolicies() []*Policy

ListPolicies returns all available policies

func (*RBACEngine) ListRoles

func (rbac *RBACEngine) ListRoles() []*Role

ListRoles returns all available roles

func (*RBACEngine) ValidateRoleConfiguration

func (rbac *RBACEngine) ValidateRoleConfiguration() error

ValidateRoleConfiguration validates role configuration for circular dependencies

type RemediationAction

type RemediationAction struct {
	Type        string                 `json:"type"`   // block, quarantine, notify, manual
	Status      string                 `json:"status"` // pending, in_progress, completed, failed
	Description string                 `json:"description"`
	Actions     []string               `json:"actions"`
	AssignedTo  string                 `json:"assigned_to"`
	DueDate     *time.Time             `json:"due_date"`
	CompletedAt *time.Time             `json:"completed_at"`
	Metadata    map[string]interface{} `json:"metadata"`
}

RemediationAction represents an action to remediate a policy violation

type RepositoryInfo

type RepositoryInfo struct {
	Name         string            `json:"name"`
	Owner        string            `json:"owner"`
	URL          string            `json:"url"`
	Branch       string            `json:"branch"`
	IsProduction bool              `json:"is_production"`
	Tags         []string          `json:"tags"`
	Attributes   map[string]string `json:"attributes"`
}

RepositoryInfo contains repository information for policy evaluation

type Role

type Role struct {
	Name        string       `json:"name"`
	Description string       `json:"description"`
	Permissions []Permission `json:"permissions"`
	Inherits    []string     `json:"inherits"`
	// contains filtered or unexported fields
}

Role represents a role with permissions

type SAMLAssertion

type SAMLAssertion struct {
	XMLName            xml.Name               `xml:"urn:oasis:names:tc:SAML:2.0:assertion Assertion"`
	ID                 string                 `xml:"ID,attr"`
	Version            string                 `xml:"Version,attr"`
	IssueInstant       string                 `xml:"IssueInstant,attr"`
	Issuer             SAMLIssuer             `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
	Subject            SAMLSubject            `xml:"urn:oasis:names:tc:SAML:2.0:assertion Subject"`
	Conditions         SAMLConditions         `xml:"urn:oasis:names:tc:SAML:2.0:assertion Conditions"`
	AttributeStatement SAMLAttributeStatement `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeStatement"`
}

SAMLAssertion represents a SAML assertion

type SAMLAttribute

type SAMLAttribute struct {
	XMLName        xml.Name           `xml:"urn:oasis:names:tc:SAML:2.0:assertion Attribute"`
	Name           string             `xml:"Name,attr"`
	NameFormat     string             `xml:"NameFormat,attr"`
	AttributeValue SAMLAttributeValue `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeValue"`
}

SAMLAttribute represents a SAML attribute

type SAMLAttributeStatement

type SAMLAttributeStatement struct {
	XMLName    xml.Name        `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeStatement"`
	Attributes []SAMLAttribute `xml:"urn:oasis:names:tc:SAML:2.0:assertion Attribute"`
}

SAMLAttributeStatement represents SAML attribute statement

type SAMLAttributeValue

type SAMLAttributeValue struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion AttributeValue"`
	Type    string   `xml:"http://www.w3.org/2001/XMLSchema-instance type,attr"`
	Value   string   `xml:",chardata"`
}

SAMLAttributeValue represents a SAML attribute value

type SAMLAudience

type SAMLAudience struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion Audience"`
	Value   string   `xml:",chardata"`
}

SAMLAudience represents SAML audience

type SAMLAudienceRestriction

type SAMLAudienceRestriction struct {
	XMLName  xml.Name     `xml:"urn:oasis:names:tc:SAML:2.0:assertion AudienceRestriction"`
	Audience SAMLAudience `xml:"urn:oasis:names:tc:SAML:2.0:assertion Audience"`
}

SAMLAudienceRestriction represents SAML audience restriction

type SAMLConditions

type SAMLConditions struct {
	XMLName             xml.Name                `xml:"urn:oasis:names:tc:SAML:2.0:assertion Conditions"`
	NotBefore           string                  `xml:"NotBefore,attr"`
	NotOnOrAfter        string                  `xml:"NotOnOrAfter,attr"`
	AudienceRestriction SAMLAudienceRestriction `xml:"urn:oasis:names:tc:SAML:2.0:assertion AudienceRestriction"`
}

SAMLConditions represents SAML conditions

type SAMLConfig

type SAMLConfig struct {
	EntityID                  string            `json:"entity_id"`
	SSOURL                    string            `json:"sso_url"`
	SLOURL                    string            `json:"slo_url"`
	Certificate               string            `json:"certificate"`
	PrivateKey                string            `json:"private_key"`
	IDPMetadataURL            string            `json:"idp_metadata_url"`
	IDPEntityID               string            `json:"idp_entity_id"`
	IDPSSOURL                 string            `json:"idp_sso_url"`
	IDPSLOURL                 string            `json:"idp_slo_url"`
	IDPCertificate            string            `json:"idp_certificate"`
	NameIDFormat              string            `json:"name_id_format"`
	SignRequests              bool              `json:"sign_requests"`
	WantAssertionsSigned      bool              `json:"want_assertions_signed"`
	WantResponseSigned        bool              `json:"want_response_signed"`
	AllowUnencryptedAssertion bool              `json:"allow_unencrypted_assertion"`
	AttributeMapping          map[string]string `json:"attribute_mapping"`
}

SAMLConfig holds SAML provider configuration

func (*SAMLConfig) Validate

func (c *SAMLConfig) Validate() error

Validate validates the SAML configuration

type SAMLIssuer

type SAMLIssuer struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
	Value   string   `xml:",chardata"`
}

SAMLIssuer represents the SAML issuer

type SAMLNameID

type SAMLNameID struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion NameID"`
	Format  string   `xml:"Format,attr"`
	Value   string   `xml:",chardata"`
}

SAMLNameID represents the SAML NameID

type SAMLProvider

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

SAMLProvider implements SAML 2.0 authentication

func CreateSAMLProviderFromConfig

func CreateSAMLProviderFromConfig(providerConfig *ProviderConfig) (*SAMLProvider, error)

CreateSAMLProviderFromConfig creates a SAML provider from ProviderConfig

func NewSAMLProvider

func NewSAMLProvider(config *SAMLConfig) *SAMLProvider

NewSAMLProvider creates a new SAML provider

func (*SAMLProvider) Authenticate

func (sp *SAMLProvider) Authenticate(ctx context.Context, request *http.Request) (*SSOToken, error)

Authenticate implements the SSOProvider interface

func (*SAMLProvider) GetAuthorizationURL

func (sp *SAMLProvider) GetAuthorizationURL(state string, redirectURI string) (string, error)

GetAuthorizationURL generates a SAML authentication request URL

func (*SAMLProvider) GetUser

func (sp *SAMLProvider) GetUser(ctx context.Context, token *SSOToken) (*SSOUser, error)

GetUser implements the SSOProvider interface

func (*SAMLProvider) RefreshToken

func (sp *SAMLProvider) RefreshToken(ctx context.Context, refreshToken string) (*SSOToken, error)

RefreshToken implements the SSOProvider interface

func (*SAMLProvider) ValidateToken

func (sp *SAMLProvider) ValidateToken(ctx context.Context, token *SSOToken) error

ValidateToken implements the SSOProvider interface

type SAMLResponse

type SAMLResponse struct {
	XMLName      xml.Name      `xml:"urn:oasis:names:tc:SAML:2.0:protocol Response"`
	ID           string        `xml:"ID,attr"`
	Version      string        `xml:"Version,attr"`
	IssueInstant string        `xml:"IssueInstant,attr"`
	Destination  string        `xml:"Destination,attr"`
	Issuer       SAMLIssuer    `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
	Status       SAMLStatus    `xml:"urn:oasis:names:tc:SAML:2.0:protocol Status"`
	Assertion    SAMLAssertion `xml:"urn:oasis:names:tc:SAML:2.0:assertion Assertion"`
}

SAMLResponse represents a SAML response

type SAMLStatus

type SAMLStatus struct {
	XMLName    xml.Name       `xml:"urn:oasis:names:tc:SAML:2.0:protocol Status"`
	StatusCode SAMLStatusCode `xml:"urn:oasis:names:tc:SAML:2.0:protocol StatusCode"`
}

SAMLStatus represents the SAML status

type SAMLStatusCode

type SAMLStatusCode struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol StatusCode"`
	Value   string   `xml:"Value,attr"`
}

SAMLStatusCode represents the SAML status code

type SAMLSubject

type SAMLSubject struct {
	XMLName             xml.Name                `xml:"urn:oasis:names:tc:SAML:2.0:assertion Subject"`
	NameID              SAMLNameID              `xml:"urn:oasis:names:tc:SAML:2.0:assertion NameID"`
	SubjectConfirmation SAMLSubjectConfirmation `xml:"urn:oasis:names:tc:SAML:2.0:assertion SubjectConfirmation"`
}

SAMLSubject represents the SAML subject

type SAMLSubjectConfirmation

type SAMLSubjectConfirmation struct {
	XMLName                 xml.Name                    `xml:"urn:oasis:names:tc:SAML:2.0:assertion SubjectConfirmation"`
	Method                  string                      `xml:"Method,attr"`
	SubjectConfirmationData SAMLSubjectConfirmationData `xml:"urn:oasis:names:tc:SAML:2.0:assertion SubjectConfirmationData"`
}

SAMLSubjectConfirmation represents SAML subject confirmation

type SAMLSubjectConfirmationData

type SAMLSubjectConfirmationData struct {
	XMLName      xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion SubjectConfirmationData"`
	NotOnOrAfter string   `xml:"NotOnOrAfter,attr"`
	Recipient    string   `xml:"Recipient,attr"`
}

SAMLSubjectConfirmationData represents SAML subject confirmation data

type SSOConfig

type SSOConfig struct {
	Enabled   bool                      `json:"enabled" yaml:"enabled"`
	Providers map[string]ProviderConfig `json:"providers" yaml:"providers"`
	Session   SSOSessionConfig          `json:"session" yaml:"session"`
	Security  SSOSecurityConfig         `json:"security" yaml:"security"`
}

SSOConfig contains SSO configuration

type SSOManager

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

SSOManager manages multiple SSO providers

func NewSSOManager

func NewSSOManager(config *SSOConfig, logger *logrus.Logger) *SSOManager

NewSSOManager creates a new SSO manager

func (*SSOManager) CleanupExpiredSessions

func (sm *SSOManager) CleanupExpiredSessions()

CleanupExpiredSessions removes expired sessions

func (*SSOManager) ExportSession

func (sm *SSOManager) ExportSession(sessionID string) ([]byte, error)

ExportSession exports session data for external storage

func (*SSOManager) GetAuthURL

func (sm *SSOManager) GetAuthURL(providerName string) (string, string, error)

GetAuthURL generates an authentication URL for the specified provider

func (*SSOManager) GetProvider

func (sm *SSOManager) GetProvider(name string) (SSOProvider, error)

GetProvider returns an SSO provider by name

func (*SSOManager) GetSessionStats

func (sm *SSOManager) GetSessionStats() map[string]interface{}

GetSessionStats returns statistics about active sessions

func (*SSOManager) GetUserFromSession

func (sm *SSOManager) GetUserFromSession(sessionID string) (*SSOUser, error)

GetUserFromSession returns user information from session

func (*SSOManager) HandleCallback

func (sm *SSOManager) HandleCallback(providerName, code, state string, r *http.Request) (*SSOSession, error)

HandleCallback handles the SSO callback

func (*SSOManager) ImportSession

func (sm *SSOManager) ImportSession(data []byte) error

ImportSession imports session data from external storage

func (*SSOManager) ListActiveSessions

func (sm *SSOManager) ListActiveSessions() []*SSOSession

ListActiveSessions returns all active sessions

func (*SSOManager) LogoutSession

func (sm *SSOManager) LogoutSession(sessionID string) error

LogoutSession logs out an SSO session

func (*SSOManager) RefreshSession

func (sm *SSOManager) RefreshSession(sessionID string) error

RefreshSession refreshes an SSO session token

func (*SSOManager) RegisterProvider

func (sm *SSOManager) RegisterProvider(name string, provider SSOProvider) error

RegisterProvider registers an SSO provider

func (*SSOManager) StartCleanupRoutine

func (sm *SSOManager) StartCleanupRoutine(ctx context.Context)

StartCleanupRoutine starts a background routine to clean up expired sessions

func (*SSOManager) ValidateSession

func (sm *SSOManager) ValidateSession(sessionID string) (*SSOSession, error)

ValidateSession validates an SSO session

type SSOProvider

type SSOProvider interface {
	GetAuthURL(state string) (string, error)
	ExchangeCode(code, state string) (*SSOToken, error)
	GetUserInfo(token *SSOToken) (*SSOUser, error)
	ValidateToken(token string) (*SSOUser, error)
	RefreshToken(refreshToken string) (*SSOToken, error)
	Logout(token string) error
	GetProviderName() string
}

SSOProvider defines the interface for SSO authentication providers

type SSOSecurityConfig

type SSOSecurityConfig struct {
	StateTimeout   time.Duration `json:"state_timeout" yaml:"state_timeout"`
	CSRFProtection bool          `json:"csrf_protection" yaml:"csrf_protection"`
	AllowedDomains []string      `json:"allowed_domains" yaml:"allowed_domains"`
	RequireHTTPS   bool          `json:"require_https" yaml:"require_https"`
	TrustedProxies []string      `json:"trusted_proxies" yaml:"trusted_proxies"`
}

SSOSecurityConfig configures SSO security settings

type SSOSession

type SSOSession struct {
	ID         string    `json:"id"`
	UserID     string    `json:"user_id"`
	Provider   string    `json:"provider"`
	Token      *SSOToken `json:"token"`
	User       *SSOUser  `json:"user"`
	CreatedAt  time.Time `json:"created_at"`
	LastAccess time.Time `json:"last_access"`
	ExpiresAt  time.Time `json:"expires_at"`
	IPAddress  string    `json:"ip_address"`
	UserAgent  string    `json:"user_agent"`
}

SSOSession represents an active SSO session

type SSOSessionConfig

type SSOSessionConfig struct {
	Timeout         time.Duration `json:"timeout" yaml:"timeout"`
	RefreshWindow   time.Duration `json:"refresh_window" yaml:"refresh_window"`
	CleanupInterval time.Duration `json:"cleanup_interval" yaml:"cleanup_interval"`
	SecureCookies   bool          `json:"secure_cookies" yaml:"secure_cookies"`
	SameSite        string        `json:"same_site" yaml:"same_site"`
}

SSOSessionConfig configures SSO sessions

type SSOToken

type SSOToken struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	TokenType    string    `json:"token_type"`
	ExpiresIn    int64     `json:"expires_in"`
	ExpiresAt    time.Time `json:"expires_at"`
	Scope        string    `json:"scope,omitempty"`
	IDToken      string    `json:"id_token,omitempty"`
}

SSOToken represents an SSO authentication token

type SSOUser

type SSOUser struct {
	ID          string            `json:"id"`
	Email       string            `json:"email"`
	Name        string            `json:"name"`
	FirstName   string            `json:"first_name,omitempty"`
	LastName    string            `json:"last_name,omitempty"`
	Username    string            `json:"username,omitempty"`
	Picture     string            `json:"picture,omitempty"`
	Provider    string            `json:"provider"`
	Roles       []string          `json:"roles,omitempty"`
	Groups      []string          `json:"groups,omitempty"`
	Attributes  map[string]string `json:"attributes,omitempty"`
	Verified    bool              `json:"verified"`
	LastLoginAt time.Time         `json:"last_login_at"`
}

SSOUser represents a user from SSO provider

type SecurityPolicy

type SecurityPolicy struct {
	ID            string            `json:"id"`
	Name          string            `json:"name"`
	Description   string            `json:"description"`
	Enabled       bool              `json:"enabled"`
	Priority      int               `json:"priority"` // Higher number = higher priority
	Conditions    []PolicyCondition `json:"conditions"`
	Action        PolicyAction      `json:"action"`
	Parameters    map[string]string `json:"parameters"`    // Additional parameters for the action
	Notifications []string          `json:"notifications"` // Email addresses or webhook URLs
	Approvers     []string          `json:"approvers"`     // Users who can approve
	Schedule      string            `json:"schedule"`      // Cron expression for scheduled actions
	CreatedAt     time.Time         `json:"created_at"`
	UpdatedAt     time.Time         `json:"updated_at"`
	CreatedBy     string            `json:"created_by"`
}

SecurityPolicy represents a security policy

type Session

type Session struct {
	ID        string    `json:"id"`
	UserID    string    `json:"user_id"`
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
	IPAddress string    `json:"ip_address"`
	UserAgent string    `json:"user_agent"`
}

Session represents an authenticated session

type SessionConfig

type SessionConfig struct {
	Timeout        time.Duration `yaml:"timeout" json:"timeout"`
	RefreshTimeout time.Duration `yaml:"refresh_timeout" json:"refresh_timeout"`
	SecretKey      string        `yaml:"secret_key" json:"secret_key"`
	Secure         bool          `yaml:"secure" json:"secure"`
	SameSite       string        `yaml:"same_site" json:"same_site"`
}

SessionConfig holds session configuration

type SessionManager

type SessionManager interface {
	// CreateSession creates a new session for a user
	CreateSession(ctx context.Context, user *User, ipAddress, userAgent string) (*Session, error)

	// GetSession retrieves a session by token
	GetSession(ctx context.Context, token string) (*Session, error)

	// RefreshSession refreshes a session
	RefreshSession(ctx context.Context, token string) (*Session, error)

	// InvalidateSession invalidates a session
	InvalidateSession(ctx context.Context, token string) error

	// CleanupExpiredSessions removes expired sessions
	CleanupExpiredSessions(ctx context.Context) error
}

SessionManager manages user sessions

type SessionStats

type SessionStats struct {
	TotalSessions   int `json:"total_sessions"`
	ActiveSessions  int `json:"active_sessions"`
	ExpiredSessions int `json:"expired_sessions"`
	UniqueUsers     int `json:"unique_users"`
}

SessionStats represents session statistics

type User

type User struct {
	ID          string            `json:"id"`
	Username    string            `json:"username"`
	Email       string            `json:"email"`
	DisplayName string            `json:"display_name"`
	Roles       []string          `json:"roles"`
	Groups      []string          `json:"groups"`
	Attributes  map[string]string `json:"attributes"`
	CreatedAt   time.Time         `json:"created_at"`
	LastLoginAt *time.Time        `json:"last_login_at"`
	IsActive    bool              `json:"is_active"`
}

User represents an authenticated user

func GetUserFromContext

func GetUserFromContext(c *gin.Context) (*User, bool)

GetUserFromContext retrieves the user from the request context

func (*User) HasAnyRole

func (u *User) HasAnyRole(roles ...string) bool

HasAnyRole checks if a user has any of the specified roles

func (*User) HasRole

func (u *User) HasRole(role string) bool

HasRole checks if a user has a specific role

func (*User) InAnyGroup

func (u *User) InAnyGroup(groups ...string) bool

InAnyGroup checks if a user is in any of the specified groups

func (*User) InGroup

func (u *User) InGroup(group string) bool

InGroup checks if a user is in a specific group

type ViolationStatus

type ViolationStatus string

ViolationStatus represents the status of a policy violation

const (
	ViolationStatusOpen       ViolationStatus = "open"
	ViolationStatusPending    ViolationStatus = "pending_approval"
	ViolationStatusApproved   ViolationStatus = "approved"
	ViolationStatusRejected   ViolationStatus = "rejected"
	ViolationStatusRemediated ViolationStatus = "remediated"
	ViolationStatusIgnored    ViolationStatus = "ignored"
)

Jump to

Keyboard shortcuts

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