- ai/ai.go: replace architectural prose with concrete usage examples (AX-2) - ai/metrics.go: add usage examples to all exported/unexported functions; rename metricsWriteMutex (already was changed in round 1); drop redundant prose comment on the day-iteration loop - ai/metrics_bench_test.go: remove dead `dir` allocation and `_ = dir` suppression; rename `n` param → `count` in seedEvents; add usage examples to helpers (AX-1/AX-2) - ai/rag.go: rename qdrantCfg/ollamaCfg/queryCfg → qdrantConfig/ollamaConfig/queryConfig (AX-1) - cmd/metrics/cmd.go: rename local `n` → `count` in parseDuration (AX-1) - cmd/security/cmd_security.go: add usage example to checkGH and AlertSummary.Add (AX-2) - cmd/security/cmd_alerts.go: add usage-example comments to fetch* functions (AX-2) - cmd/security/cmd_jobs.go: rename `sb` → `builder` in buildJobIssueBody; add usage examples to createJobForTarget and buildJobIssueBody (AX-1/AX-2) - cmd/security/cmd_scan.go: remove redundant "Default if not specified" inline comment (AX-2) Co-Authored-By: Virgil <virgil@lethean.io>
281 lines
7.9 KiB
Go
281 lines
7.9 KiB
Go
package security
|
|
|
|
import (
|
|
"fmt"
|
|
"os/exec"
|
|
"slices"
|
|
"strings"
|
|
|
|
"forge.lthn.ai/core/cli/pkg/cli"
|
|
"dappco.re/go/core/i18n"
|
|
"dappco.re/go/core/io"
|
|
coreerr "dappco.re/go/core/log"
|
|
"dappco.re/go/core/scm/repos"
|
|
)
|
|
|
|
var (
|
|
// Command flags
|
|
securityRegistryPath string
|
|
securityRepo string
|
|
securitySeverity string
|
|
securityJSON bool
|
|
securityTarget string // External repo target (e.g. "wailsapp/wails")
|
|
)
|
|
|
|
// AddSecurityCommands registers the security subcommand tree.
|
|
//
|
|
// security.AddSecurityCommands(rootCmd) // → core security alerts|deps|scan|secrets|jobs
|
|
func AddSecurityCommands(root *cli.Command) {
|
|
secCmd := &cli.Command{
|
|
Use: "security",
|
|
Short: i18n.T("cmd.security.short"),
|
|
Long: i18n.T("cmd.security.long"),
|
|
}
|
|
|
|
addAlertsCommand(secCmd)
|
|
addDepsCommand(secCmd)
|
|
addScanCommand(secCmd)
|
|
addSecretsCommand(secCmd)
|
|
addJobsCommand(secCmd)
|
|
|
|
root.AddCommand(secCmd)
|
|
}
|
|
|
|
// DependabotAlert is a GitHub Dependabot vulnerability alert (from repos/{org}/{repo}/dependabot/alerts).
|
|
type DependabotAlert struct {
|
|
Number int `json:"number"`
|
|
State string `json:"state"`
|
|
Advisory struct {
|
|
Severity string `json:"severity"`
|
|
CVEID string `json:"cve_id"`
|
|
Summary string `json:"summary"`
|
|
Description string `json:"description"`
|
|
} `json:"security_advisory"`
|
|
Dependency struct {
|
|
Package struct {
|
|
Name string `json:"name"`
|
|
Ecosystem string `json:"ecosystem"`
|
|
} `json:"package"`
|
|
ManifestPath string `json:"manifest_path"`
|
|
} `json:"dependency"`
|
|
SecurityVulnerability struct {
|
|
Package struct {
|
|
Name string `json:"name"`
|
|
Ecosystem string `json:"ecosystem"`
|
|
} `json:"package"`
|
|
FirstPatchedVersion struct {
|
|
Identifier string `json:"identifier"`
|
|
} `json:"first_patched_version"`
|
|
VulnerableVersionRange string `json:"vulnerable_version_range"`
|
|
} `json:"security_vulnerability"`
|
|
}
|
|
|
|
// CodeScanningAlert is a GitHub code scanning alert (from repos/{org}/{repo}/code-scanning/alerts).
|
|
type CodeScanningAlert struct {
|
|
Number int `json:"number"`
|
|
State string `json:"state"`
|
|
DismissedReason string `json:"dismissed_reason"`
|
|
Rule struct {
|
|
ID string `json:"id"`
|
|
Severity string `json:"severity"`
|
|
Description string `json:"description"`
|
|
Tags []string `json:"tags"`
|
|
} `json:"rule"`
|
|
Tool struct {
|
|
Name string `json:"name"`
|
|
Version string `json:"version"`
|
|
} `json:"tool"`
|
|
MostRecentInstance struct {
|
|
Location struct {
|
|
Path string `json:"path"`
|
|
StartLine int `json:"start_line"`
|
|
EndLine int `json:"end_line"`
|
|
} `json:"location"`
|
|
Message struct {
|
|
Text string `json:"text"`
|
|
} `json:"message"`
|
|
} `json:"most_recent_instance"`
|
|
}
|
|
|
|
// SecretScanningAlert is a GitHub secret scanning alert (from repos/{org}/{repo}/secret-scanning/alerts).
|
|
type SecretScanningAlert struct {
|
|
Number int `json:"number"`
|
|
State string `json:"state"`
|
|
SecretType string `json:"secret_type"`
|
|
Secret string `json:"secret"`
|
|
PushProtection bool `json:"push_protection_bypassed"`
|
|
Resolution string `json:"resolution"`
|
|
}
|
|
|
|
// loadRegistry loads the registry from registryPath, or auto-discovers it from the working directory.
|
|
//
|
|
// loadRegistry("") // auto-discover repos.yaml
|
|
// loadRegistry("/path/to/repos.yaml")
|
|
func loadRegistry(registryPath string) (*repos.Registry, error) {
|
|
if registryPath != "" {
|
|
reg, err := repos.LoadRegistry(io.Local, registryPath)
|
|
if err != nil {
|
|
return nil, cli.Wrap(err, "load registry")
|
|
}
|
|
return reg, nil
|
|
}
|
|
|
|
path, err := repos.FindRegistry(io.Local)
|
|
if err != nil {
|
|
return nil, cli.Wrap(err, "find registry")
|
|
}
|
|
reg, err := repos.LoadRegistry(io.Local, path)
|
|
if err != nil {
|
|
return nil, cli.Wrap(err, "load registry")
|
|
}
|
|
return reg, nil
|
|
}
|
|
|
|
// checkGH returns an error if the gh CLI is not on PATH.
|
|
//
|
|
// if err := checkGH(); err != nil { return err }
|
|
func checkGH() error {
|
|
if _, err := exec.LookPath("gh"); err != nil {
|
|
return coreerr.E("security.checkGH", i18n.T("error.gh_not_found"), nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// runGHAPI calls gh api with pagination and returns the raw JSON body.
|
|
//
|
|
// runGHAPI("repos/host-uk/core-php/dependabot/alerts?state=open")
|
|
func runGHAPI(endpoint string) ([]byte, error) {
|
|
cmd := exec.Command("gh", "api", endpoint, "--paginate")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
|
stderr := string(exitErr.Stderr)
|
|
// Handle common errors gracefully
|
|
if strings.Contains(stderr, "404") || strings.Contains(stderr, "Not Found") {
|
|
return []byte("[]"), nil // Return empty array for not found
|
|
}
|
|
if strings.Contains(stderr, "403") {
|
|
return nil, coreerr.E("security.runGHAPI", "access denied (check token permissions)", nil)
|
|
}
|
|
}
|
|
return nil, cli.Wrap(err, "run gh api")
|
|
}
|
|
return output, nil
|
|
}
|
|
|
|
// severityStyle maps a severity string to its terminal render style.
|
|
//
|
|
// severityStyle("critical") // → cli.ErrorStyle
|
|
// severityStyle("high") // → cli.WarningStyle
|
|
func severityStyle(severity string) *cli.AnsiStyle {
|
|
switch strings.ToLower(severity) {
|
|
case "critical":
|
|
return cli.ErrorStyle
|
|
case "high":
|
|
return cli.WarningStyle
|
|
case "medium":
|
|
return cli.ValueStyle
|
|
default:
|
|
return cli.DimStyle
|
|
}
|
|
}
|
|
|
|
// filterBySeverity reports whether severity matches the comma-separated filter list.
|
|
//
|
|
// filterBySeverity("high", "critical,high") // → true
|
|
// filterBySeverity("low", "critical,high") // → false
|
|
// filterBySeverity("high", "") // → true (empty = all pass)
|
|
func filterBySeverity(severity, filter string) bool {
|
|
if filter == "" {
|
|
return true
|
|
}
|
|
|
|
sev := strings.ToLower(severity)
|
|
return slices.ContainsFunc(slices.Collect(strings.SplitSeq(strings.ToLower(filter), ",")), func(s string) bool {
|
|
return strings.TrimSpace(s) == sev
|
|
})
|
|
}
|
|
|
|
// getReposToCheck returns a single repo when repoFilter is set, or all repos in the registry.
|
|
//
|
|
// getReposToCheck(reg, "core-php") // → [core-php]
|
|
// getReposToCheck(reg, "") // → all repos
|
|
func getReposToCheck(reg *repos.Registry, repoFilter string) []*repos.Repo {
|
|
if repoFilter != "" {
|
|
if repo, ok := reg.Get(repoFilter); ok {
|
|
return []*repos.Repo{repo}
|
|
}
|
|
return nil
|
|
}
|
|
return reg.List()
|
|
}
|
|
|
|
// buildTargetRepo parses an owner/repo target string into a Repo and its full name.
|
|
//
|
|
// buildTargetRepo("wailsapp/wails") // → &Repo{Name:"wails"}, "wailsapp/wails"
|
|
func buildTargetRepo(target string) (*repos.Repo, string) {
|
|
parts := strings.SplitN(target, "/", 2)
|
|
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
|
return nil, ""
|
|
}
|
|
return &repos.Repo{Name: parts[1]}, target
|
|
}
|
|
|
|
// AlertSummary tracks alert counts by severity across a scan run.
|
|
//
|
|
// s := &AlertSummary{}
|
|
// s.Add("critical")
|
|
// s.String() // → "1 critical"
|
|
type AlertSummary struct {
|
|
Critical int
|
|
High int
|
|
Medium int
|
|
Low int
|
|
Unknown int
|
|
Total int
|
|
}
|
|
|
|
// Add increments the counter for the given severity level.
|
|
//
|
|
// s.Add("critical") // s.Critical == 1, s.Total == 1
|
|
func (s *AlertSummary) Add(severity string) {
|
|
s.Total++
|
|
switch strings.ToLower(severity) {
|
|
case "critical":
|
|
s.Critical++
|
|
case "high":
|
|
s.High++
|
|
case "medium":
|
|
s.Medium++
|
|
case "low":
|
|
s.Low++
|
|
default:
|
|
s.Unknown++
|
|
}
|
|
}
|
|
|
|
// String renders a styled, human-readable summary of alert counts.
|
|
//
|
|
// (&AlertSummary{Critical: 1, High: 2}).String() // → "1 critical | 2 high"
|
|
func (s *AlertSummary) String() string {
|
|
parts := []string{}
|
|
if s.Critical > 0 {
|
|
parts = append(parts, cli.ErrorStyle.Render(fmt.Sprintf("%d critical", s.Critical)))
|
|
}
|
|
if s.High > 0 {
|
|
parts = append(parts, cli.WarningStyle.Render(fmt.Sprintf("%d high", s.High)))
|
|
}
|
|
if s.Medium > 0 {
|
|
parts = append(parts, cli.ValueStyle.Render(fmt.Sprintf("%d medium", s.Medium)))
|
|
}
|
|
if s.Low > 0 {
|
|
parts = append(parts, cli.DimStyle.Render(fmt.Sprintf("%d low", s.Low)))
|
|
}
|
|
if s.Unknown > 0 {
|
|
parts = append(parts, cli.DimStyle.Render(fmt.Sprintf("%d unknown", s.Unknown)))
|
|
}
|
|
if len(parts) == 0 {
|
|
return cli.SuccessStyle.Render("No alerts")
|
|
}
|
|
return strings.Join(parts, " | ")
|
|
}
|