auth

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package auth provides authentication utilities for the Scanorama API server. This package implements API key generation, validation, and management functions with security best practices including secure random generation and bcrypt hashing.

Package auth provides database operations for API key management. This file implements CRUD operations for API keys stored in PostgreSQL, including creation, validation, updating, and revocation of keys.

Package auth provides role-based access control (RBAC) structures and utilities. This file implements the Role structure and permission management for the Scanorama API.

Index

Constants

View Source
const (
	// APIKeyLength is the length of the random part of an API key
	APIKeyLength = 32
	// APIKeyPrefix is the standard prefix for all API keys
	APIKeyPrefix = "sk"
	// DisplayPrefixLength is the length of prefix shown in UI (e.g., "sk_abc...")
	DisplayPrefixLength = 12

	// BcryptCost is the bcrypt cost for hashing API keys (12 is a good balance of security and performance)
	BcryptCost = 12
	// BcryptMaxInputLength is the maximum input length for bcrypt (72 bytes)
	BcryptMaxInputLength = 72

	// MinAPIKeyNameLength is the minimum length for API key names
	MinAPIKeyNameLength = 1
	// MaxAPIKeyNameLength is the maximum length for API key names
	MaxAPIKeyNameLength = 255
)

API key generation and validation constants

View Source
const (
	PermissionRead   = "read"
	PermissionWrite  = "write"
	PermissionDelete = "delete"
	PermissionAdmin  = "*" // Wildcard for all actions
)

Permission actions

View Source
const (
	ResourceAll       = "*" // Wildcard for all resources
	ResourceScans     = "scans"
	ResourceHosts     = "hosts"
	ResourceNetworks  = "networks"
	ResourceProfiles  = "profiles"
	ResourceDiscovery = "discovery"
	ResourceAPIKeys   = "apikeys"
	ResourceAdmin     = "admin"
)

Resource types

View Source
const (
	RoleAdmin    = "admin"
	RoleReadonly = "readonly"
	RoleOperator = "operator"
)

System role names

View Source
const (
	MinRoleNameLength = 1
	MaxRoleNameLength = 100
	MaxRoleDescLength = 1000
)

Role validation constants

Variables

This section is empty.

Functions

func CheckPermissions

func CheckPermissions(roles []Role, resource, action string) bool

CheckPermissions checks if a set of roles has a specific permission

func CreateDisplayPrefix

func CreateDisplayPrefix(apiKey string) string

CreateDisplayPrefix creates a safe-to-display prefix from a full API key

func HashAPIKey

func HashAPIKey(apiKey string) (string, error)

HashAPIKey creates a bcrypt hash of an API key for secure storage

func IsValidAPIKeyFormat

func IsValidAPIKeyFormat(apiKey string) bool

IsValidAPIKeyFormat checks if an API key has the correct format

func MarshalPermissions

func MarshalPermissions(permissions map[string]interface{}) ([]byte, error)

MarshalPermissions converts permissions to JSON for database storage

func PermissionsEqual

func PermissionsEqual(a, b map[string]interface{}) bool

PermissionsEqual checks if two permission sets are equal

func UnmarshalPermissions

func UnmarshalPermissions(data []byte) (map[string]interface{}, error)

UnmarshalPermissions converts JSON permissions from database

func ValidateAPIKey

func ValidateAPIKey(apiKey, storedHash string) bool

ValidateAPIKey checks if a provided API key matches the stored hash

func ValidatePermissions

func ValidatePermissions(permissions map[string]interface{}) error

ValidatePermissions validates the structure of permissions

func ValidateRoleDescription

func ValidateRoleDescription(description string) error

ValidateRoleDescription validates a role description

func ValidateRoleName

func ValidateRoleName(name string) error

ValidateRoleName validates a role name format

Types

type APIKeyInfo

type APIKeyInfo struct {
	ID         string     `json:"id" db:"id"`
	Name       string     `json:"name" db:"name" validate:"required,min=1,max=255"`
	KeyPrefix  string     `json:"key_prefix" db:"key_prefix"`
	CreatedAt  time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at" db:"updated_at"`
	LastUsedAt *time.Time `json:"last_used_at,omitempty" db:"last_used_at"`
	ExpiresAt  *time.Time `json:"expires_at,omitempty" db:"expires_at"`
	IsActive   bool       `json:"is_active" db:"is_active"`
	UsageCount int        `json:"usage_count" db:"usage_count"`
	Notes      string     `json:"notes,omitempty" db:"notes"`

	// Phase 2 ready fields (RBAC support)
	// Note: Roles are now managed through api_key_roles junction table
	Permissions map[string]interface{} `json:"permissions,omitempty" db:"permissions"` // Deprecated: use roles instead
	CreatedBy   *string                `json:"created_by,omitempty" db:"created_by"`
}

APIKeyInfo contains metadata about an API key

func (*APIKeyInfo) IsExpired

func (k *APIKeyInfo) IsExpired() bool

IsExpired checks if an API key has expired

func (*APIKeyInfo) IsValid

func (k *APIKeyInfo) IsValid() bool

IsValid checks if an API key is active and not expired

type APIKeyRepository

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

APIKeyRepository provides database operations for API keys

func NewAPIKeyRepository

func NewAPIKeyRepository(database *db.DB) *APIKeyRepository

NewAPIKeyRepository creates a new API key repository

func (*APIKeyRepository) CheckConfigAPIKeys

func (r *APIKeyRepository) CheckConfigAPIKeys(configKeys []string) ([]string, error)

CheckConfigAPIKeys validates that configured API keys exist in database

func (*APIKeyRepository) CleanupExpiredKeys

func (r *APIKeyRepository) CleanupExpiredKeys() (int, error)

CleanupExpiredKeys deactivates expired API keys

func (*APIKeyRepository) CreateAPIKey

func (r *APIKeyRepository) CreateAPIKey(generatedKey *GeneratedAPIKey) (*APIKeyInfo, error)

CreateAPIKey stores a new API key in the database

func (*APIKeyRepository) FindAPIKeyByIdentifier

func (r *APIKeyRepository) FindAPIKeyByIdentifier(identifier string) (*APIKeyInfo, error)

FindAPIKeyByIdentifier finds an API key by ID or prefix

func (*APIKeyRepository) GetAPIKeyStats

func (r *APIKeyRepository) GetAPIKeyStats() (map[string]interface{}, error)

GetAPIKeyStats returns statistics about API key usage

func (*APIKeyRepository) ListAPIKeys

func (r *APIKeyRepository) ListAPIKeys(showExpired, showInactive bool) ([]APIKeyInfo, error)

ListAPIKeys retrieves API keys with optional filters

func (*APIKeyRepository) RevokeAPIKey

func (r *APIKeyRepository) RevokeAPIKey(keyID string) error

RevokeAPIKey deactivates an API key

func (*APIKeyRepository) UpdateAPIKey

func (r *APIKeyRepository) UpdateAPIKey(keyID string, updates map[string]interface{}) (*APIKeyInfo, error)

UpdateAPIKey updates an API key's metadata

func (*APIKeyRepository) ValidateAPIKey

func (r *APIKeyRepository) ValidateAPIKey(apiKey string) (*APIKeyInfo, error)

ValidateAPIKey checks if an API key is valid for authentication

type APIKeyValidator

type APIKeyValidator struct {
}

APIKeyValidator provides methods for validating API keys

func NewAPIKeyValidator

func NewAPIKeyValidator() *APIKeyValidator

NewAPIKeyValidator creates a new API key validator

type APIKeyWithRoles

type APIKeyWithRoles struct {
	APIKeyInfo
	Roles []Role `json:"roles"`
}

APIKeyWithRoles represents an API key with its associated roles

type GeneratedAPIKey

type GeneratedAPIKey struct {
	Key       string     `json:"key"`        // The actual API key (only shown once)
	KeyInfo   APIKeyInfo `json:"key_info"`   // Metadata about the key
	KeyPrefix string     `json:"key_prefix"` // Display-safe prefix
}

GeneratedAPIKey contains a newly generated API key and its metadata

func GenerateAPIKey

func GenerateAPIKey(name string) (*GeneratedAPIKey, error)

GenerateAPIKey creates a new API key with the specified name

type Permission

type Permission struct {
	Resource string   `json:"resource"`
	Actions  []string `json:"actions"`
}

Permission represents a structured permission

type Role

type Role struct {
	ID          string                 `json:"id" db:"id"`
	Name        string                 `json:"name" db:"name" validate:"required,min=1,max=100"`
	Description string                 `json:"description,omitempty" db:"description"`
	Permissions map[string]interface{} `json:"permissions" db:"permissions"`
	IsActive    bool                   `json:"is_active" db:"is_active"`
	IsSystem    bool                   `json:"is_system" db:"is_system"`
	CreatedAt   time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at" db:"updated_at"`
	CreatedBy   *string                `json:"created_by,omitempty" db:"created_by"`
}

Role represents a role in the RBAC system

func DefaultRoles

func DefaultRoles() []Role

DefaultRoles returns the default system roles

func NewRole

func NewRole(name, description string, permissions map[string]interface{}) (*Role, error)

NewRole creates a new role with validation

func (*Role) CanBeDeleted

func (r *Role) CanBeDeleted() bool

CanBeDeleted checks if the role can be deleted

func (*Role) GetPermissionsSummary

func (r *Role) GetPermissionsSummary() []string

GetPermissionsSummary returns a human-readable summary of permissions

func (*Role) HasPermission

func (r *Role) HasPermission(resource, action string) bool

HasPermission checks if the role has a specific permission

func (*Role) IsSystemRole

func (r *Role) IsSystemRole() bool

IsSystemRole checks if this is a system role

type RolePermissions

type RolePermissions struct {
	Permissions []Permission `json:"permissions"`
}

RolePermissions represents the structured permissions for a role

Jump to

Keyboard shortcuts

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