Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

2.3 KB
Raw Blame
/*
©AngelaMos | 2026
json.go

JSON output reporter

Serializes scan results to indented JSON with a findings array and a summary
block. Secrets are masked before output. Implements the Reporter interface.

Connects to:
  reporter/reporter.go - returned by New("json")
  pkg/types/types.go - reads ScanResult and Finding fields
*/

package reporter

import (
	"encoding/json"
	"io"

	"github.com/CarterPerez-dev/portia/pkg/types"
)

type JSON struct{}

type jsonOutput struct {
	Findings []jsonFinding `json:"findings"`
	Summary  jsonSummary   `json:"summary"`
}

type jsonFinding struct {
	RuleID      string  `json:"rule_id"`
	Description string  `json:"description"`
	Severity    string  `json:"severity"`
	Secret      string  `json:"secret"` //nolint:gosec
	Entropy     float64 `json:"entropy,omitempty"`
	File        string  `json:"file"`
	Line        int     `json:"line"`
	Commit      string  `json:"commit,omitempty"`
	Author      string  `json:"author,omitempty"`
	HIBPStatus  string  `json:"hibp_status,omitempty"`
	BreachCount int     `json:"breach_count,omitempty"`
}

type jsonSummary struct {
	TotalFiles    int    `json:"total_files"`
	TotalFindings int    `json:"total_findings"`
	TotalRules    int    `json:"total_rules"`
	Duration      string `json:"duration"`
	HIBPChecked   int    `json:"hibp_checked,omitempty"`
	HIBPBreached  int    `json:"hibp_breached,omitempty"`
}

func (j *JSON) Report(
	w io.Writer, result *types.ScanResult,
) error {
	output := jsonOutput{
		Summary: jsonSummary{
			TotalFiles:    result.TotalFiles,
			TotalFindings: len(result.Findings),
			TotalRules:    result.TotalRules,
			Duration:      result.Duration.String(),
			HIBPChecked:   result.HIBPChecked,
			HIBPBreached:  result.HIBPBreached,
		},
	}

	output.Findings = make([]jsonFinding, len(result.Findings))
	for i, f := range result.Findings {
		output.Findings[i] = jsonFinding{
			RuleID:      f.RuleID,
			Description: f.Description,
			Severity:    f.Severity.String(),
			Secret:      maskSecret(f.Secret),
			Entropy:     f.Entropy,
			File:        f.FilePath,
			Line:        f.LineNumber,
			Commit:      f.CommitSHA,
			Author:      f.Author,
			HIBPStatus:  f.HIBPStatus.String(),
			BreachCount: f.BreachCount,
		}
	}

	enc := json.NewEncoder(w)
	enc.SetIndent("", "  ")
	return enc.Encode(output)
}