database

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2025 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuditSummary

type AuditSummary struct {
	ID          string    `json:"id"`
	Type        string    `json:"type"`
	Status      string    `json:"status"`
	Description string    `json:"description"`
	Action      string    `json:"action"`
	Resource    string    `json:"resource"`
	Timestamp   time.Time `json:"timestamp"`
	User        string    `json:"user"`
}

AuditSummary represents an audit summary

type ComplianceViolation

type ComplianceViolation struct {
	ID          string    `json:"id"`
	Standard    string    `json:"standard"`
	Rule        string    `json:"rule"`
	Severity    string    `json:"severity"`
	Description string    `json:"description"`
	Resource    string    `json:"resource"`
	Status      string    `json:"status"`
	Timestamp   time.Time `json:"timestamp"`
}

ComplianceViolation represents a compliance violation

type DatabaseManager

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

DatabaseManager manages database connections and initialization

func NewDatabaseManager

func NewDatabaseManager(config InitConfig, logger *logger.Logger) *DatabaseManager

NewDatabaseManager creates a new database manager

func (*DatabaseManager) Close

func (dm *DatabaseManager) Close() error

Close closes the database connection

func (*DatabaseManager) GetDB

func (dm *DatabaseManager) GetDB() *sql.DB

GetDB returns the database connection

func (*DatabaseManager) GetMigrationStatus

func (dm *DatabaseManager) GetMigrationStatus(ctx context.Context) ([]Migration, error)

GetMigrationStatus returns the current migration status

func (*DatabaseManager) GetSchemaManager

func (dm *DatabaseManager) GetSchemaManager() *SchemaManager

GetSchemaManager returns the schema manager

func (*DatabaseManager) GetService

func (dm *DatabaseManager) GetService() *DatabaseService

GetService returns the database service

func (*DatabaseManager) HealthCheck

func (dm *DatabaseManager) HealthCheck(ctx context.Context) error

HealthCheck performs a health check on the database

func (*DatabaseManager) Initialize

func (dm *DatabaseManager) Initialize(ctx context.Context) error

Initialize initializes the database connection and runs migrations

func (*DatabaseManager) ValidateSchema

func (dm *DatabaseManager) ValidateSchema(ctx context.Context) error

ValidateSchema validates the database schema

type DatabaseService

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

DatabaseService provides CRUD operations for the database

func NewDatabaseService

func NewDatabaseService(dbConfig *config.DatabaseConfig) (*DatabaseService, error)

NewDatabaseService creates a new database service

func (*DatabaseService) Close

func (ds *DatabaseService) Close() error

Close closes the database connection

func (*DatabaseService) CreateOrganization

func (ds *DatabaseService) CreateOrganization(ctx context.Context, org *Organization) error

CreateOrganization creates a new organization record

func (*DatabaseService) CreateRepository

func (ds *DatabaseService) CreateRepository(ctx context.Context, repo *Repository) error

CreateRepository creates a new repository record

func (*DatabaseService) CreateScanJob

func (ds *DatabaseService) CreateScanJob(ctx context.Context, job *ScanJob) error

CreateScanJob creates a new scan job record

func (*DatabaseService) GetComplianceByStandard

func (ds *DatabaseService) GetComplianceByStandard(ctx context.Context) (map[string]float64, error)

GetComplianceByStandard returns compliance data grouped by standard

func (*DatabaseService) GetComplianceScore

func (ds *DatabaseService) GetComplianceScore(ctx context.Context) (float64, error)

GetComplianceScore returns the overall compliance score

func (*DatabaseService) GetComplianceTrends

func (ds *DatabaseService) GetComplianceTrends(ctx context.Context, days int) ([]TrendDataPoint, error)

GetComplianceTrends returns compliance trend data

func (*DatabaseService) GetComplianceViolations

func (ds *DatabaseService) GetComplianceViolations(ctx context.Context, limit int) ([]ComplianceViolation, error)

GetComplianceViolations returns recent compliance violations

func (*DatabaseService) GetDB added in v1.0.1

func (ds *DatabaseService) GetDB() *sql.DB

GetDB returns the underlying database connection

func (*DatabaseService) GetLastScanTime

func (ds *DatabaseService) GetLastScanTime(ctx context.Context) (*time.Time, error)

GetLastScanTime returns the timestamp of the last scan

func (*DatabaseService) GetMitigationStatus

func (ds *DatabaseService) GetMitigationStatus() (map[string]int, error)

GetMitigationStatus returns mitigation status statistics from policy violations

func (*DatabaseService) GetOrganization

func (ds *DatabaseService) GetOrganization(ctx context.Context, platform, login string) (*Organization, error)

GetOrganization retrieves an organization by platform and login

func (*DatabaseService) GetRecentAudits

func (ds *DatabaseService) GetRecentAudits(ctx context.Context, limit int) ([]AuditSummary, error)

GetRecentAudits returns recent audit summaries

func (*DatabaseService) GetRecentScans

func (ds *DatabaseService) GetRecentScans(ctx context.Context, limit int) ([]*EnterpriseScanSummary, error)

GetRecentScans returns recent scan summaries

func (*DatabaseService) GetRepositoriesByOrganization

func (ds *DatabaseService) GetRepositoriesByOrganization(ctx context.Context, orgID string, limit, offset int) ([]*Repository, error)

GetRepositoriesByOrganization retrieves repositories for an organization

func (*DatabaseService) GetRepositoryCount

func (ds *DatabaseService) GetRepositoryCount(ctx context.Context) (int64, error)

GetRepositoryCount returns the total number of repositories

func (*DatabaseService) GetRepositoryLanguageStats

func (ds *DatabaseService) GetRepositoryLanguageStats(ctx context.Context) (map[string]int64, error)

GetRepositoryLanguageStats returns language statistics for repositories

func (*DatabaseService) GetRepositoryPlatformStats

func (ds *DatabaseService) GetRepositoryPlatformStats(ctx context.Context) (map[string]int64, error)

GetRepositoryPlatformStats returns repository statistics by platform

func (*DatabaseService) GetScanJob

func (ds *DatabaseService) GetScanJob(ctx context.Context, jobID string) (*ScanJob, error)

GetScanJob retrieves a scan job by ID

func (*DatabaseService) GetScanJobStats

func (ds *DatabaseService) GetScanJobStats(ctx context.Context) (*ScanJobStats, error)

GetScanJobStats returns scan job statistics

func (*DatabaseService) GetScanTrends

func (ds *DatabaseService) GetScanTrends(ctx context.Context, duration time.Duration, points int) ([]*TrendDataPoint, error)

GetScanTrends returns scan trend data

func (*DatabaseService) GetSecurityTrends

func (ds *DatabaseService) GetSecurityTrends(days int) ([]TrendDataPoint, error)

GetSecurityTrends returns security trend data

func (*DatabaseService) GetThreatStats

func (ds *DatabaseService) GetThreatStats(ctx context.Context) (*ThreatStats, error)

GetThreatStats returns threat statistics

func (*DatabaseService) GetThreatTrend

func (ds *DatabaseService) GetThreatTrend(ctx context.Context, duration time.Duration) (float64, error)

GetThreatTrend returns threat trend data (simplified implementation)

func (*DatabaseService) GetThreatsByType

func (ds *DatabaseService) GetThreatsByType() (map[string]int64, error)

GetThreatsByType returns threat counts by type (simplified implementation)

func (*DatabaseService) GetTopThreats

func (ds *DatabaseService) GetTopThreats(limit int) ([]ThreatSummary, error)

GetTopThreats returns top threats based on scan job data

func (*DatabaseService) HealthCheck

func (ds *DatabaseService) HealthCheck(ctx context.Context) error

HealthCheck performs a database health check

func (*DatabaseService) UpdateScanJobStatus

func (ds *DatabaseService) UpdateScanJobStatus(ctx context.Context, jobID, status string, progress float64) error

UpdateScanJobStatus updates the status and progress of a scan job

type EnterpriseScanSummary added in v1.0.1

type EnterpriseScanSummary struct {
	ID          string    `json:"id"`
	JobType     string    `json:"job_type"`
	Status      string    `json:"status"`
	ThreatCount int64     `json:"threat_count"`
	Duration    int64     `json:"duration"`
	StartedAt   time.Time `json:"started_at"`
	CompletedAt time.Time `json:"completed_at"`
}

EnterpriseScanSummary represents a summary of an enterprise scan

type InitConfig

type InitConfig struct {
	Host            string        `yaml:"host" env:"DB_HOST" default:"localhost"`
	Port            int           `yaml:"port" env:"DB_PORT" default:"5432"`
	Database        string        `yaml:"database" env:"DB_NAME" default:"typosentinel"`
	Username        string        `yaml:"username" env:"DB_USER" default:"postgres"`
	Password        string        `yaml:"password" env:"DB_PASSWORD" default:""`
	SSLMode         string        `yaml:"ssl_mode" env:"DB_SSL_MODE" default:"disable"`
	MaxOpenConns    int           `yaml:"max_open_conns" env:"DB_MAX_OPEN_CONNS" default:"25"`
	MaxIdleConns    int           `yaml:"max_idle_conns" env:"DB_MAX_IDLE_CONNS" default:"5"`
	ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" env:"DB_CONN_MAX_LIFETIME" default:"1h"`
	ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time" env:"DB_CONN_MAX_IDLE_TIME" default:"30m"`
}

InitConfig holds database initialization configuration

type Migration

type Migration struct {
	Version   int
	Name      string
	Filename  string
	SQL       string
	AppliedAt *time.Time
	Checksum  string
}

Migration represents a database migration

type OSSService added in v1.0.1

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

OSSService provides a simplified PostgreSQL-based database service for OSS

func NewOSSService added in v1.0.1

func NewOSSService(dbConfig *config.DatabaseConfig) (*OSSService, error)

NewOSSService creates a new OSS database service with PostgreSQL or SQLite

func (*OSSService) Close added in v1.0.1

func (s *OSSService) Close() error

Close closes the database connection

func (*OSSService) CreateScan added in v1.0.1

func (s *OSSService) CreateScan(ctx context.Context, scan *PackageScan) error

CreateScan creates a new package scan record

func (*OSSService) GetDB added in v1.0.1

func (s *OSSService) GetDB() *sql.DB

GetDB returns the underlying database connection

func (*OSSService) GetRecentScans added in v1.0.1

func (s *OSSService) GetRecentScans(ctx context.Context, limit int) ([]*ScanSummary, error)

GetRecentScans returns recent scan summaries

func (*OSSService) GetScan added in v1.0.1

func (s *OSSService) GetScan(ctx context.Context, id string) (*PackageScan, error)

GetScan retrieves a scan by ID

func (*OSSService) GetScanStats added in v1.0.1

func (s *OSSService) GetScanStats(ctx context.Context) (map[string]interface{}, error)

GetScanStats returns basic statistics about scans

func (*OSSService) SearchScans added in v1.0.1

func (s *OSSService) SearchScans(ctx context.Context, packageName string, limit int) ([]*ScanSummary, error)

SearchScans searches for scans by package name

func (*OSSService) UpdateScan added in v1.0.1

func (s *OSSService) UpdateScan(ctx context.Context, scan *PackageScan) error

UpdateScan updates an existing scan record

type Organization

type Organization struct {
	ID          string                 `json:"id"`
	Platform    string                 `json:"platform"`
	Login       string                 `json:"login"`
	Name        *string                `json:"name"`
	Description *string                `json:"description"`
	HTMLURL     *string                `json:"html_url"`
	AvatarURL   *string                `json:"avatar_url"`
	Type        string                 `json:"type"`
	Location    *string                `json:"location"`
	Email       *string                `json:"email"`
	Blog        *string                `json:"blog"`
	Twitter     *string                `json:"twitter"`
	Company     *string                `json:"company"`
	PublicRepos int                    `json:"public_repos"`
	PublicGists int                    `json:"public_gists"`
	Followers   int                    `json:"followers"`
	Following   int                    `json:"following"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
	ScanStatus  string                 `json:"scan_status"`
	LastScanAt  *time.Time             `json:"last_scan_at"`
	Metadata    map[string]interface{} `json:"metadata"`
}

Organization represents an organization record

type PackageScan added in v1.0.1

type PackageScan struct {
	ID          string                 `json:"id"`
	PackageName string                 `json:"package_name"`
	Registry    string                 `json:"registry"`
	Version     string                 `json:"version,omitempty"`
	Status      string                 `json:"status"` // pending, running, completed, failed
	RiskLevel   string                 `json:"risk_level,omitempty"`
	Threats     []ThreatResult         `json:"threats,omitempty"`
	Summary     string                 `json:"summary,omitempty"`
	StartedAt   time.Time              `json:"started_at"`
	CompletedAt *time.Time             `json:"completed_at,omitempty"`
	Duration    int64                  `json:"duration,omitempty"` // seconds
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

PackageScan represents a package scan result

type Repository

type Repository struct {
	ID            string                 `json:"id"`
	Platform      string                 `json:"platform"`
	OrgID         *string                `json:"org_id"`
	Owner         string                 `json:"owner"`
	Name          string                 `json:"name"`
	FullName      string                 `json:"full_name"`
	Description   *string                `json:"description"`
	HTMLURL       string                 `json:"html_url"`
	CloneURL      string                 `json:"clone_url"`
	SSHURL        string                 `json:"ssh_url"`
	Homepage      *string                `json:"homepage"`
	Language      *string                `json:"language"`
	IsPrivate     bool                   `json:"is_private"`
	IsFork        bool                   `json:"is_fork"`
	IsArchived    bool                   `json:"is_archived"`
	IsDisabled    bool                   `json:"is_disabled"`
	Size          int64                  `json:"size"`
	StarsCount    int                    `json:"stars_count"`
	WatchersCount int                    `json:"watchers_count"`
	ForksCount    int                    `json:"forks_count"`
	IssuesCount   int                    `json:"issues_count"`
	Topics        []string               `json:"topics"`
	Branches      []string               `json:"branches"`
	CreatedAt     time.Time              `json:"created_at"`
	UpdatedAt     time.Time              `json:"updated_at"`
	PushedAt      *time.Time             `json:"pushed_at"`
	ScanStatus    string                 `json:"scan_status"`
	LastScanAt    *time.Time             `json:"last_scan_at"`
	Metadata      map[string]interface{} `json:"metadata"`
}

Repository represents a repository record

type ScanJob

type ScanJob struct {
	ID              string                 `json:"id"`
	OrgID           string                 `json:"org_id"`
	JobType         string                 `json:"job_type"`
	Configuration   map[string]interface{} `json:"configuration"`
	Status          string                 `json:"status"`
	Progress        float64                `json:"progress"`
	StartedAt       *time.Time             `json:"started_at"`
	CompletedAt     *time.Time             `json:"completed_at"`
	EstimatedTime   *time.Duration         `json:"estimated_time"`
	ActualTime      *time.Duration         `json:"actual_time"`
	TotalRepos      int                    `json:"total_repos"`
	ScannedRepos    int                    `json:"scanned_repos"`
	FailedRepos     int                    `json:"failed_repos"`
	TotalThreats    int                    `json:"total_threats"`
	CriticalThreats int                    `json:"critical_threats"`
	HighThreats     int                    `json:"high_threats"`
	MediumThreats   int                    `json:"medium_threats"`
	LowThreats      int                    `json:"low_threats"`
	WorkerID        *string                `json:"worker_id"`
	RetryCount      int                    `json:"retry_count"`
	MaxRetries      int                    `json:"max_retries"`
	ErrorMessage    *string                `json:"error_message"`
	ErrorDetails    map[string]interface{} `json:"error_details"`
	CreatedAt       time.Time              `json:"created_at"`
	UpdatedAt       time.Time              `json:"updated_at"`
	Metadata        map[string]interface{} `json:"metadata"`
}

ScanJob represents a scan job record

type ScanJobStats

type ScanJobStats struct {
	TotalScans     int64 `json:"total_scans"`
	CompletedScans int64 `json:"completed_scans"`
	FailedScans    int64 `json:"failed_scans"`
	RunningScans   int64 `json:"running_scans"`
}

ScanJobStats represents scan job statistics

type ScanSummary

type ScanSummary struct {
	ID          string                   `json:"id"`
	PackageName string                   `json:"package_name"`
	Registry    string                   `json:"registry"`
	Status      string                   `json:"status"`
	RiskLevel   string                   `json:"risk_level"`
	ThreatCount int                      `json:"threat_count"`
	Duration    int64                    `json:"duration"`
	StartedAt   time.Time                `json:"started_at"`
	CompletedAt *time.Time               `json:"completed_at"`
	Threats     []map[string]interface{} `json:"threats,omitempty"`
}

ScanSummary represents a scan summary for dashboard

type SchemaManager

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

SchemaManager handles database schema migrations and initialization

func NewSchemaManager

func NewSchemaManager(db *sql.DB, logger *logger.Logger) *SchemaManager

NewSchemaManager creates a new schema manager

func (*SchemaManager) GetMigrationStatus

func (sm *SchemaManager) GetMigrationStatus(ctx context.Context) ([]Migration, error)

GetMigrationStatus returns the status of all migrations

func (*SchemaManager) Initialize

func (sm *SchemaManager) Initialize(ctx context.Context) error

Initialize sets up the database schema and runs migrations

func (*SchemaManager) ValidateSchema

func (sm *SchemaManager) ValidateSchema(ctx context.Context) error

ValidateSchema validates that the current database schema matches expectations

type ThreatDB

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

ThreatDB represents the PostgreSQL threat database

func NewThreatDB

func NewThreatDB(dbConfig *config.DatabaseConfig) (*ThreatDB, error)

NewThreatDB creates a new threat database instance

func (*ThreatDB) AddPattern

func (tdb *ThreatDB) AddPattern(pattern *ThreatPattern) error

AddPattern adds a new threat detection pattern

func (*ThreatDB) AddThreat

func (tdb *ThreatDB) AddThreat(threat *ThreatRecord) error

AddThreat adds a new threat record to the database

func (*ThreatDB) Close

func (tdb *ThreatDB) Close() error

Close closes the database connection

func (*ThreatDB) DeleteThreat

func (tdb *ThreatDB) DeleteThreat(packageName, registry string) error

DeleteThreat removes a threat record

func (*ThreatDB) GetPatterns

func (tdb *ThreatDB) GetPatterns(patternType string) ([]*ThreatPattern, error)

GetPatterns retrieves all enabled threat patterns

func (*ThreatDB) GetStats

func (tdb *ThreatDB) GetStats() (map[string]int, error)

GetStats returns database statistics

func (*ThreatDB) GetThreat

func (tdb *ThreatDB) GetThreat(packageName, registry string) (*ThreatRecord, error)

GetThreat retrieves a threat by package name and registry

func (*ThreatDB) GetThreats

func (tdb *ThreatDB) GetThreats(registry, threatType string, limit int) ([]*ThreatRecord, error)

GetThreats retrieves all threats matching the given criteria

type ThreatPattern

type ThreatPattern struct {
	ID          int64     `json:"id"`
	Name        string    `json:"name"`
	Pattern     string    `json:"pattern"`
	PatternType string    `json:"pattern_type"` // regex, exact, fuzzy
	ThreatType  string    `json:"threat_type"`
	Severity    string    `json:"severity"`
	Enabled     bool      `json:"enabled"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

ThreatPattern represents a threat detection pattern

type ThreatRecord

type ThreatRecord struct {
	ID          int64     `json:"id"`
	PackageName string    `json:"package_name"`
	Registry    string    `json:"registry"`
	ThreatType  string    `json:"threat_type"`
	Severity    string    `json:"severity"`
	Confidence  float64   `json:"confidence"`
	Description string    `json:"description"`
	Source      string    `json:"source"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	Metadata    string    `json:"metadata"` // JSON string for additional data
}

ThreatRecord represents a threat record in the database

func (*ThreatRecord) ConvertToThreat

func (tr *ThreatRecord) ConvertToThreat() *types.Threat

ConvertToThreat converts a ThreatRecord to types.Threat

type ThreatResult added in v1.0.1

type ThreatResult struct {
	Type               string   `json:"type"`
	Severity           string   `json:"severity"`
	Confidence         float64  `json:"confidence"`
	Description        string   `json:"description"`
	Source             string   `json:"source"`
	AffectedVersions   string   `json:"affected_versions,omitempty"`
	FixedVersion       string   `json:"fixed_version,omitempty"`
	ProposedCorrection string   `json:"proposed_correction,omitempty"`
	CVE                string   `json:"cve,omitempty"`
	References         []string `json:"references,omitempty"`
}

ThreatResult represents a detected threat

type ThreatStats

type ThreatStats struct {
	TotalThreats     int64   `json:"total_threats"`
	CriticalThreats  int64   `json:"critical_threats"`
	HighThreats      int64   `json:"high_threats"`
	MediumThreats    int64   `json:"medium_threats"`
	LowThreats       int64   `json:"low_threats"`
	AverageRiskScore float64 `json:"average_risk_score"`
}

ThreatStats represents threat statistics

type ThreatSummary

type ThreatSummary struct {
	Type        string `json:"type"`
	Count       int    `json:"count"`
	Severity    string `json:"severity"`
	Description string `json:"description"`
}

ThreatSummary represents a summary of threats

type TrendDataPoint

type TrendDataPoint struct {
	Timestamp time.Time `json:"timestamp"`
	Value     float64   `json:"value"`
	Label     string    `json:"label"`
}

TrendDataPoint represents a data point in a trend

Jump to

Keyboard shortcuts

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