go-ai/cmd/security/cmd_security.go
Virgil bc3b36c3da
All checks were successful
Security Scan / security (push) Successful in 10s
Test / test (push) Successful in 1m12s
refactor(ax): tighten remaining AX naming and examples
Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-31 07:44:10 +00:00

285 lines
8.3 KiB
Go

package security
import (
"fmt"
"os/exec"
"slices"
"strings"
"dappco.re/go/core/i18n"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
"dappco.re/go/core/scm/repos"
"forge.lthn.ai/core/cli/pkg/cli"
)
var (
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) {
command := &cli.Command{
Use: "security",
Short: i18n.T("cmd.security.short"),
Long: i18n.T("cmd.security.long"),
}
addAlertsCommand(command)
addDepsCommand(command)
addScanCommand(command)
addSecretsCommand(command)
addJobsCommand(command)
root.AddCommand(command)
}
// DependabotAlert maps one response item from GitHub's dependabot alerts API.
//
// alerts, _ := fetchDependabotAlerts("host-uk/core-php")
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 maps one response item from GitHub's code-scanning alerts API.
//
// alerts, _ := fetchCodeScanningAlerts("host-uk/core-php")
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 maps one response item from GitHub's secret-scanning alerts API.
//
// alerts, _ := fetchSecretScanningAlerts("host-uk/core-php")
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 != "" {
registry, err := repos.LoadRegistry(io.Local, registryPath)
if err != nil {
return nil, cli.Wrap(err, "load registry")
}
return registry, nil
}
path, err := repos.FindRegistry(io.Local)
if err != nil {
return nil, cli.Wrap(err, "find registry")
}
registry, err := repos.LoadRegistry(io.Local, path)
if err != nil {
return nil, cli.Wrap(err, "load registry")
}
return registry, 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) {
ghCommand := exec.Command("gh", "api", endpoint, "--paginate")
output, err := ghCommand.Output()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
stderr := string(exitErr.Stderr)
if strings.Contains(stderr, "404") || strings.Contains(stderr, "Not Found") {
return []byte("[]"), nil
}
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
}
severityLower := strings.ToLower(severity)
return slices.ContainsFunc(slices.Collect(strings.SplitSeq(strings.ToLower(filter), ",")), func(filterEntry string) bool {
return strings.TrimSpace(filterEntry) == severityLower
})
}
// getReposToCheck returns a single repo when repoFilter is set, or all repos in the registry.
//
// getReposToCheck(registry, "core-php") // → [core-php]
// getReposToCheck(registry, "") // → all repos
func getReposToCheck(registry *repos.Registry, repoFilter string) []*repos.Repo {
if repoFilter != "" {
if matchedRepo, ok := registry.Get(repoFilter); ok {
return []*repos.Repo{matchedRepo}
}
return nil
}
return registry.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) {
targetParts := strings.SplitN(target, "/", 2)
if len(targetParts) != 2 || targetParts[0] == "" || targetParts[1] == "" {
return nil, ""
}
return &repos.Repo{Name: targetParts[1]}, target
}
// AlertSummary tracks alert counts by severity across a scan run.
//
// summary := &AlertSummary{}
// summary.Add("critical")
// summary.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.
//
// summary.Add("critical") // summary.Critical == 1, summary.Total == 1
func (summary *AlertSummary) Add(severity string) {
summary.Total++
switch strings.ToLower(severity) {
case "critical":
summary.Critical++
case "high":
summary.High++
case "medium":
summary.Medium++
case "low":
summary.Low++
default:
summary.Unknown++
}
}
// String renders a styled, human-readable summary of alert counts.
//
// (&AlertSummary{Critical: 1, High: 2}).String() // → "1 critical | 2 high"
func (summary *AlertSummary) String() string {
segments := []string{}
if summary.Critical > 0 {
segments = append(segments, cli.ErrorStyle.Render(fmt.Sprintf("%d critical", summary.Critical)))
}
if summary.High > 0 {
segments = append(segments, cli.WarningStyle.Render(fmt.Sprintf("%d high", summary.High)))
}
if summary.Medium > 0 {
segments = append(segments, cli.ValueStyle.Render(fmt.Sprintf("%d medium", summary.Medium)))
}
if summary.Low > 0 {
segments = append(segments, cli.DimStyle.Render(fmt.Sprintf("%d low", summary.Low)))
}
if summary.Unknown > 0 {
segments = append(segments, cli.DimStyle.Render(fmt.Sprintf("%d unknown", summary.Unknown)))
}
if len(segments) == 0 {
return cli.SuccessStyle.Render("No alerts")
}
return strings.Join(segments, " | ")
}