security

package
v0.0.0-...-a1393ee Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package security provides comprehensive security utilities for authentication and authorization.

This module implements security controls required for SOC2 and ISO27001 compliance, including:

SECURITY FEATURES: - Rate limiting and account lockout protection - Password strength validation and complexity requirements - Input validation and sanitization - Cryptographic utilities for secure token generation - Security event logging and audit trails - Session management and concurrent session limits - Timing-safe operations to prevent timing attacks

COMPLIANCE STANDARDS: - SOC2 Type II (CC6.1, CC6.3, CC7.2) - ISO27001 (A.9.4.2, A.9.4.3, A.12.4.1, A.13.1.1, A.14.2.1)

USAGE: This utility module is designed to be used across all services in the authentication system to ensure consistent security policies and compliance requirements.

Example:

// Rate limiting
if err := util.CheckRateLimit(username); err != nil {
	return err
}

// Password validation
if err := util.ValidatePasswordStrength(password); err != nil {
	return err
}

// Security logging
util.LogSecurityEvent(util.SecurityEvent{
	EventType: "login_success",
	UserID:    userID,
	Timestamp: time.Now(),
})

Index

Constants

View Source
const (
	MaxLoginAttempts   = 5                // Maximum failed attempts before lockout
	LoginAttemptWindow = 15 * time.Minute // Time window for counting attempts
	AccountLockoutTime = 30 * time.Minute // Account lockout duration
)

Rate Limiting Constants (SOC2 CC6.1 - Logical Access Controls)

View Source
const (
	MaxConcurrentSessions = 5 // Maximum concurrent sessions per user
)

Session Security Constants (SOC2 CC6.3 - Logical Access Controls)

Variables

View Source
var HashPassword = func(password []byte) ([]byte, error) {
	_, span := otel.Tracer("security").Start(context.Background(), "security.hash_password")
	defer span.End()

	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		span.RecordError(err)
		span.SetStatus(codes.Error, "hash password failed")
		return nil, err
	}
	span.SetStatus(codes.Ok, "")
	return hash, nil
}

HashPassword hashes a password using bcrypt with the default cost. Exposed as a function variable so tests can inject errors.

Functions

func CheckRateLimit

func CheckRateLimit(identifier string) error

CheckRateLimit returns an error if the identifier is currently locked out. Complies with SOC2 CC6.1 and ISO27001 A.9.4.2

func GenerateCSRFToken

func GenerateCSRFToken() (string, error)

GenerateCSRFToken generates a cryptographically secure CSRF token. Returns an error if the system's random source fails. Complies with SOC2 CC6.1 and ISO27001 A.13.2.1

func GetDummyBcryptHash

func GetDummyBcryptHash() []byte

GetDummyBcryptHash returns the pre-computed dummy bcrypt hash for timing-safe operations.

func InitRateLimiter

func InitRateLimiter(rdb *redis.Client)

InitRateLimiter wires the Redis client for rate limiting. Must be called before CheckRateLimit / RecordFailedAttempt / ResetFailedAttempts.

func LogSecurityEvent

func LogSecurityEvent(event SecurityEvent)

LogSecurityEvent logs security events for compliance monitoring Complies with SOC2 CC7.2 (System Monitoring) and ISO27001 A.12.4.1

func RateLimitKey

func RateLimitKey(identifier, action string) string

RateLimitKey generates a consistent key for rate limiting Complies with SOC2 CC6.1 and ISO27001 A.9.4.2

func RecordFailedAttempt

func RecordFailedAttempt(identifier string)

RecordFailedAttempt increments the failure counter in Redis with a sliding window TTL.

func ResetFailedAttempts

func ResetFailedAttempts(identifier string)

ResetFailedAttempts clears all rate-limit state after a successful login.

func SanitizeInput

func SanitizeInput(input string) string

SanitizeInput sanitizes user input to prevent injection attacks Complies with SOC2 CC6.1 and ISO27001 A.14.2.1

func ValidateIPAddress

func ValidateIPAddress(ipStr string) error

ValidateIPAddress validates if an IP address is valid and not from restricted ranges Complies with SOC2 CC6.1 and ISO27001 A.13.1.1

func ValidatePasswordStrength

func ValidatePasswordStrength(password string) error

ValidatePasswordStrength enforces password complexity requirements Complies with SOC2 CC6.1 and ISO27001 A.9.4.3

func ValidateSessionLimit

func ValidateSessionLimit(userID string, currentSessionCount int) error

ValidateSessionLimit checks if user has exceeded maximum concurrent sessions This can be used by services that need to enforce session limits Complies with SOC2 CC6.3 and ISO27001 A.9.4.2

func ValidateUserAgent

func ValidateUserAgent(userAgent string) bool

ValidateUserAgent checks for suspicious or malicious user agents Complies with SOC2 CC7.2 and ISO27001 A.12.4.1

Types

type LoginAttempt

type LoginAttempt struct {
	Identifier  string     // Username, email, or IP
	Attempts    int        // Number of failed attempts
	LastAttempt time.Time  // Time of last attempt
	LockedUntil *time.Time // Account locked until this time
}

LoginAttempt tracks failed login attempts for rate limiting Used by rate limiting functions to maintain attempt history

type SecurityEvent

type SecurityEvent struct {
	EventType string    `json:"event_type"`
	UserID    string    `json:"user_id,omitempty"`
	ClientID  string    `json:"client_id,omitempty"`
	ClientIP  string    `json:"client_ip,omitempty"`
	UserAgent string    `json:"user_agent,omitempty"`
	RequestID string    `json:"request_id,omitempty"`
	Endpoint  string    `json:"endpoint,omitempty"`
	Method    string    `json:"method,omitempty"`
	Timestamp time.Time `json:"timestamp"`
	Details   string    `json:"details,omitempty"`
	Severity  string    `json:"severity,omitempty"`
}

SecurityEvent represents a security-related event for audit logging Used for SOC2 CC7.2 and ISO27001 A.12.4.1 compliance Complies with SOC2 CC7.2 and ISO27001 A.12.4.1

Jump to

Keyboard shortcuts

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