go-ai/cmd/security/cmd_alerts.go
Snider 45e76101bf
Some checks failed
Security Scan / security (push) Successful in 9s
Test / test (push) Failing after 36s
refactor(ax): round 6 AX sweep — usage examples, test coverage, package docs
- Add usage-example comments (AX-2) to all private run* and add*Command
  functions in cmd/security and cmd/metrics
- Add package-level doc comment to empty cmd/security/cmd.go (AX-3)
- Add usage-example comment to cmd/rag/cmd.go re-export
- Add Bad and Ugly test categories to ai/metrics_test.go (AX-10):
  TestMetrics_Record_Bad_DirectoryAsFile, TestMetrics_ReadEvents_Bad_InvalidHome,
  TestMetrics_Record_Ugly_ConcurrentWrites
- Document the embed-bench init() side-effect with intent comment (AX-5)

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-31 14:12:12 +01:00

350 lines
9.7 KiB
Go

package security
import (
"encoding/json"
"fmt"
"dappco.re/go/core/i18n"
"forge.lthn.ai/core/cli/pkg/cli"
)
// addAlertsCommand registers the alerts subcommand under parent.
//
// addAlertsCommand(securityCmd) // → core security alerts --repo core-php --severity high
func addAlertsCommand(parent *cli.Command) {
command := &cli.Command{
Use: "alerts",
Short: i18n.T("cmd.security.alerts.short"),
Long: i18n.T("cmd.security.alerts.long"),
RunE: func(_ *cli.Command, _ []string) error {
return runAlerts()
},
}
command.Flags().StringVar(&securityRegistryPath, "registry", "", i18n.T("common.flag.registry"))
command.Flags().StringVar(&securityRepo, "repo", "", i18n.T("cmd.security.flag.repo"))
command.Flags().StringVar(&securitySeverity, "severity", "", i18n.T("cmd.security.flag.severity"))
command.Flags().BoolVar(&securityJSON, "json", false, i18n.T("common.flag.json"))
command.Flags().StringVar(&securityTarget, "target", "", i18n.T("cmd.security.flag.target"))
parent.AddCommand(command)
}
// AlertOutput is the unified alert row used by the security commands.
//
// AlertOutput{Repo: "core-php", Severity: "high", Type: "dependabot"}
type AlertOutput struct {
Repo string `json:"repo"`
Severity string `json:"severity"`
ID string `json:"id"`
Package string `json:"package,omitempty"`
Version string `json:"version,omitempty"`
Location string `json:"location,omitempty"`
Type string `json:"type"`
Message string `json:"message"`
}
// runAlerts fetches and displays unified security alerts across all repos or a single target.
//
// // via CLI: core security alerts --repo core-php --severity high
// runAlerts()
func runAlerts() error {
if err := checkGH(); err != nil {
return err
}
if securityTarget != "" {
return runAlertsForTarget(securityTarget)
}
registry, err := loadRegistry(securityRegistryPath)
if err != nil {
return err
}
repoList := getReposToCheck(registry, securityRepo)
if len(repoList) == 0 {
return cli.Err("repo not found: %s", securityRepo)
}
var allAlerts []AlertOutput
summary := &AlertSummary{}
for _, repo := range repoList {
repoFullName := fmt.Sprintf("%s/%s", registry.Org, repo.Name)
dependabotAlerts, err := fetchDependabotAlerts(repoFullName)
if err == nil {
for _, alert := range dependabotAlerts {
if alert.State != "open" {
continue
}
severity := alert.Advisory.Severity
if !filterBySeverity(severity, securitySeverity) {
continue
}
summary.Add(severity)
allAlerts = append(allAlerts, AlertOutput{
Repo: repo.Name,
Severity: severity,
ID: alert.Advisory.CVEID,
Package: alert.Dependency.Package.Name,
Version: alert.SecurityVulnerability.VulnerableVersionRange,
Type: "dependabot",
Message: alert.Advisory.Summary,
})
}
}
codeScanningAlerts, err := fetchCodeScanningAlerts(repoFullName)
if err == nil {
for _, alert := range codeScanningAlerts {
if alert.State != "open" {
continue
}
severity := alert.Rule.Severity
if !filterBySeverity(severity, securitySeverity) {
continue
}
summary.Add(severity)
location := fmt.Sprintf("%s:%d", alert.MostRecentInstance.Location.Path, alert.MostRecentInstance.Location.StartLine)
allAlerts = append(allAlerts, AlertOutput{
Repo: repo.Name,
Severity: severity,
ID: alert.Rule.ID,
Location: location,
Type: alert.Tool.Name,
Message: alert.Rule.Description,
})
}
}
secretScanningAlerts, err := fetchSecretScanningAlerts(repoFullName)
if err == nil {
for _, alert := range secretScanningAlerts {
if alert.State != "open" {
continue
}
if !filterBySeverity("high", securitySeverity) {
continue
}
summary.Add("high")
allAlerts = append(allAlerts, AlertOutput{
Repo: repo.Name,
Severity: "high",
ID: fmt.Sprintf("secret-%d", alert.Number),
Type: "secret-scanning",
Message: alert.SecretType,
})
}
}
}
if securityJSON {
output, err := json.MarshalIndent(allAlerts, "", " ")
if err != nil {
return cli.Wrap(err, "marshal JSON output")
}
cli.Text(string(output))
return nil
}
cli.Blank()
cli.Print("%s %s\n", cli.DimStyle.Render("Alerts:"), summary.String())
cli.Blank()
if len(allAlerts) == 0 {
return nil
}
for _, alert := range allAlerts {
severityRenderer := severityStyle(alert.Severity)
location := alert.Package
if location == "" {
location = alert.Location
}
if alert.Version != "" {
location = fmt.Sprintf("%s %s", location, cli.DimStyle.Render(alert.Version))
}
cli.Print("%-20s %s %-16s %-40s %s\n",
cli.ValueStyle.Render(alert.Repo),
severityRenderer.Render(fmt.Sprintf("%-8s", alert.Severity)),
alert.ID,
location,
cli.DimStyle.Render(alert.Type),
)
}
cli.Blank()
return nil
}
// runAlertsForTarget runs unified alert checks against an external owner/repo target.
//
// runAlertsForTarget("wailsapp/wails")
func runAlertsForTarget(target string) error {
repo, fullName := buildTargetRepo(target)
if repo == nil {
return cli.Err("invalid target format: use owner/repo (e.g. wailsapp/wails)")
}
var allAlerts []AlertOutput
summary := &AlertSummary{}
dependabotAlerts, err := fetchDependabotAlerts(fullName)
if err == nil {
for _, alert := range dependabotAlerts {
if alert.State != "open" {
continue
}
severity := alert.Advisory.Severity
if !filterBySeverity(severity, securitySeverity) {
continue
}
summary.Add(severity)
allAlerts = append(allAlerts, AlertOutput{
Repo: repo.Name,
Severity: severity,
ID: alert.Advisory.CVEID,
Package: alert.Dependency.Package.Name,
Version: alert.SecurityVulnerability.VulnerableVersionRange,
Type: "dependabot",
Message: alert.Advisory.Summary,
})
}
}
codeScanningAlerts, err := fetchCodeScanningAlerts(fullName)
if err == nil {
for _, alert := range codeScanningAlerts {
if alert.State != "open" {
continue
}
severity := alert.Rule.Severity
if !filterBySeverity(severity, securitySeverity) {
continue
}
summary.Add(severity)
location := fmt.Sprintf("%s:%d", alert.MostRecentInstance.Location.Path, alert.MostRecentInstance.Location.StartLine)
allAlerts = append(allAlerts, AlertOutput{
Repo: repo.Name,
Severity: severity,
ID: alert.Rule.ID,
Location: location,
Type: alert.Tool.Name,
Message: alert.Rule.Description,
})
}
}
secretScanningAlerts, err := fetchSecretScanningAlerts(fullName)
if err == nil {
for _, alert := range secretScanningAlerts {
if alert.State != "open" {
continue
}
if !filterBySeverity("high", securitySeverity) {
continue
}
summary.Add("high")
allAlerts = append(allAlerts, AlertOutput{
Repo: repo.Name,
Severity: "high",
ID: fmt.Sprintf("secret-%d", alert.Number),
Type: "secret-scanning",
Message: alert.SecretType,
})
}
}
if securityJSON {
output, err := json.MarshalIndent(allAlerts, "", " ")
if err != nil {
return cli.Wrap(err, "marshal JSON output")
}
cli.Text(string(output))
return nil
}
cli.Blank()
cli.Print("%s %s\n", cli.DimStyle.Render("Alerts ("+fullName+"):"), summary.String())
cli.Blank()
if len(allAlerts) == 0 {
return nil
}
for _, alert := range allAlerts {
severityRenderer := severityStyle(alert.Severity)
location := alert.Package
if location == "" {
location = alert.Location
}
if alert.Version != "" {
location = fmt.Sprintf("%s %s", location, cli.DimStyle.Render(alert.Version))
}
cli.Print("%-20s %s %-16s %-40s %s\n",
cli.ValueStyle.Render(alert.Repo),
severityRenderer.Render(fmt.Sprintf("%-8s", alert.Severity)),
alert.ID,
location,
cli.DimStyle.Render(alert.Type),
)
}
cli.Blank()
return nil
}
// fetchDependabotAlerts returns open Dependabot vulnerability alerts for the given repo.
//
// alerts, _ := fetchDependabotAlerts("host-uk/core-php")
func fetchDependabotAlerts(repoFullName string) ([]DependabotAlert, error) {
endpoint := fmt.Sprintf("repos/%s/dependabot/alerts?state=open", repoFullName)
output, err := runGHAPI(endpoint)
if err != nil {
return nil, cli.Wrap(err, fmt.Sprintf("fetch dependabot alerts for %s", repoFullName))
}
var alerts []DependabotAlert
if err := json.Unmarshal(output, &alerts); err != nil {
return nil, cli.Wrap(err, fmt.Sprintf("parse dependabot alerts for %s", repoFullName))
}
return alerts, nil
}
// fetchCodeScanningAlerts returns open code-scanning alerts for the given repo.
//
// alerts, _ := fetchCodeScanningAlerts("host-uk/core-php")
func fetchCodeScanningAlerts(repoFullName string) ([]CodeScanningAlert, error) {
endpoint := fmt.Sprintf("repos/%s/code-scanning/alerts?state=open", repoFullName)
output, err := runGHAPI(endpoint)
if err != nil {
return nil, cli.Wrap(err, fmt.Sprintf("fetch code-scanning alerts for %s", repoFullName))
}
var alerts []CodeScanningAlert
if err := json.Unmarshal(output, &alerts); err != nil {
return nil, cli.Wrap(err, fmt.Sprintf("parse code-scanning alerts for %s", repoFullName))
}
return alerts, nil
}
// fetchSecretScanningAlerts returns open secret-scanning alerts for the given repo.
//
// alerts, _ := fetchSecretScanningAlerts("host-uk/core-php")
func fetchSecretScanningAlerts(repoFullName string) ([]SecretScanningAlert, error) {
endpoint := fmt.Sprintf("repos/%s/secret-scanning/alerts?state=open", repoFullName)
output, err := runGHAPI(endpoint)
if err != nil {
return nil, cli.Wrap(err, fmt.Sprintf("fetch secret-scanning alerts for %s", repoFullName))
}
var alerts []SecretScanningAlert
if err := json.Unmarshal(output, &alerts); err != nil {
return nil, cli.Wrap(err, fmt.Sprintf("parse secret-scanning alerts for %s", repoFullName))
}
return alerts, nil
}