Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ Use `--verbose` to include homepage, docs, and repo links for each detected tool
brief inspect build/tool
brief inspect dist/package.whl
brief inspect --json package.gem
brief inspect --markdown dist/package.whl
brief --markdown dist/package.whl
```

Passing a supported local artifact directly selects the same inspection path, so `brief dist/package.whl` works too. Archive inspection rejects more than 100,000 entries or 512 MiB of input or extracted content.
Expand Down
10 changes: 8 additions & 2 deletions cmd/brief/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func cmdInspect(args []string) {
fs := flag.NewFlagSet("brief inspect", flag.ExitOnError)
jsonFlag := fs.Bool("json", false, "Force JSON output")
humanFlag := fs.Bool("human", false, "Force human-readable output")
markdownFlag := fs.Bool("markdown", false, "Force markdown output")
_ = fs.Parse(args)

if fs.NArg() == 0 {
Expand All @@ -83,7 +84,9 @@ func cmdInspect(args []string) {
os.Exit(1)
}

if *jsonFlag || (!*humanFlag && !isTTY()) {
if *markdownFlag {
report.ArtifactMarkdown(os.Stdout, art)
} else if *jsonFlag || (!*humanFlag && !isTTY()) {
writeJSONOrExit(report.ArtifactJSON(os.Stdout, art))
} else {
report.ArtifactHuman(os.Stdout, art)
Expand Down Expand Up @@ -818,14 +821,17 @@ func isPEFile(f *os.File, size int64) bool {

// inspectAutoArgs builds the argument slice for an auto-routed inspect call
// from cmdScan's already-parsed shared flags.
func inspectAutoArgs(jsonFlag, humanFlag bool, path string) []string {
func inspectAutoArgs(jsonFlag, humanFlag, markdownFlag bool, path string) []string {
var args []string
if jsonFlag {
args = append(args, "-json")
}
if humanFlag {
args = append(args, "-human")
}
if markdownFlag {
args = append(args, "-markdown")
}
return append(args, "--", path)
}

Expand Down
35 changes: 35 additions & 0 deletions cmd/brief/inspect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,41 @@ import (

const inspectCondaHelperEnv = "BRIEF_INSPECT_CONDA_HELPER"

func TestInspectMarkdownCommand(t *testing.T) {
const helperEnv = "BRIEF_INSPECT_MARKDOWN_HELPER"
if mode := os.Getenv(helperEnv); mode != "" {
for i, arg := range os.Args {
if arg == "--" {
if mode == "auto" {
cmdScan(os.Args[i+1:])
} else {
cmdInspect(os.Args[i+1:])
}
os.Exit(0)
}
}
t.Fatal("missing helper arguments")
}

path := writeZip(t, map[string]string{"README.txt": "example package\n"})
for _, mode := range []string{"explicit", "auto"} {
for _, flags := range [][]string{{"--markdown"}, {"--markdown", "--json"}, {"--markdown", "--human"}} {
t.Run(mode+strings.Join(flags, ""), func(t *testing.T) {
args := append([]string{"-test.run=^TestInspectMarkdownCommand$", "--"}, flags...)
cmd := exec.Command(os.Args[0], append(args, path)...)
cmd.Env = append(os.Environ(), helperEnv+"="+mode)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("inspect failed: %v\n%s", err, out)
}
if !bytes.HasPrefix(out, []byte("# brief ")) || !bytes.Contains(out, []byte("**Format:** zip")) {
t.Fatalf("expected Markdown artifact output, got:\n%s", out)
}
})
}
}
}

func TestInspectPathBareObject(t *testing.T) {
bin := buildHello(t, runtime.GOOS, runtime.GOARCH)

Expand Down
4 changes: 2 additions & 2 deletions cmd/brief/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,11 @@ func cmdScan(args []string) {

// A regular-file argument that sniffs as a native object or archive is
// routed to inspect so `brief foo.whl` and `brief foo.so` work without
// the subcommand. Only the shared -json/-human flags carry over;
// the subcommand. Only the shared -json/-human/-markdown flags carry over;
// scan-specific flags are dropped rather than passed to a FlagSet that
// would reject them.
if shouldAutoInspect(path) {
cmdInspect(inspectAutoArgs(*jsonFlag, *humanFlag, path))
cmdInspect(inspectAutoArgs(*jsonFlag, *humanFlag, *markdownFlag, path))
return
}

Expand Down
139 changes: 139 additions & 0 deletions report/artifact_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package report

import (
"bytes"
"fmt"
"strings"
"testing"

"github.com/git-pkgs/brief"
"github.com/git-pkgs/brief/binary"
)

func TestArtifactMarkdown(t *testing.T) {
art := &brief.Artifact{
Version: "dev", Path: "package.whl", Format: "zip", SHA256: "abc123", Entries: 3,
DurationMS: 1.25,
NativeObjects: []binary.Object{
{
Path: "lib/example.so", Format: "elf", Arch: "amd64", SOName: "example.so.1",
Producer: []string{"clang", "rustc"}, Needed: []string{"libc.so.6", "libm.so.6"},
Go: &binary.GoBuild{
Version: "go1.27.3", Path: "example.org/tool", Main: "example.org/main v1.0.0",
Deps: []string{"example.org/dep v2.0.0"},
},
Static: []binary.Hint{{Library: "zlib", Version: "1.3", Match: "zlib 1.3"}},
},
{Path: "bin/tool.exe", Format: "pe", Arch: "arm64"},
},
}
var out bytes.Buffer
ArtifactMarkdown(&out, art)
for _, want := range []string{
"# brief dev — package.whl", "**Format:** zip", "**SHA256:** abc123",
"**Entries:** 3 files, 2 native objects", "## Object: lib/example.so", "**Format:** elf",
"**Architecture:** amd64", "**SOName:** example.so.1", "**Producers:**\n\n- clang\n- rustc",
"**Needed:**\n\n- libc.so.6\n- libm.so.6",
"**Go:** go1.27.3", "**Go path:** example.org/tool", "**Go main:** example.org/main v1.0.0",
"**Go dependencies:**\n\n- example.org/dep v2.0.0", "**Static (low confidence):** zlib 1.3",
"**Matched text:** zlib 1.3", "## Object: bin/tool.exe", "**Format:** pe",
"**Architecture:** arm64", "1.2ms",
} {
if !strings.Contains(out.String(), want) {
t.Errorf("missing %q in Markdown:\n%s", want, out.String())
}
}
}

func TestArtifactMarkdownEmpty(t *testing.T) {
var out bytes.Buffer
ArtifactMarkdown(&out, &brief.Artifact{Path: "empty.zip", Format: "zip"})
for _, unwanted := range []string{"**Entries:**", "## Object:", "**SHA256:**", "**Go:"} {
if strings.Contains(out.String(), unwanted) {
t.Errorf("unexpected optional field %q: %s", unwanted, out.String())
}
}
}

func TestArtifactMarkdownBareObject(t *testing.T) {
var out bytes.Buffer
ArtifactMarkdown(&out, &brief.Artifact{
Path: "build/tool", Format: "elf",
NativeObjects: []binary.Object{{Path: "build/tool", Format: "elf", Arch: "amd64"}},
})
if strings.Contains(out.String(), "**Entries:**") {
t.Errorf("bare binary reports archive entries: %s", out.String())
}
if !strings.Contains(out.String(), "## Object: build/tool") {
t.Errorf("bare binary is missing its object metadata: %s", out.String())
}
}

func TestArtifactMarkdownLists(t *testing.T) {
for _, count := range []int{0, 1, maxDisplayItems, maxDisplayItems + 3} {
t.Run(fmt.Sprint(count), func(t *testing.T) {
values := make([]string, count)
for i := range values {
values[i] = fmt.Sprintf("item-%02d", i)
}
var out bytes.Buffer
ArtifactMarkdown(&out, &brief.Artifact{NativeObjects: []binary.Object{{
Producer: values, Needed: values, Go: &binary.GoBuild{Deps: values},
}}})
for _, header := range []string{"Producers", "Needed", "Go dependencies"} {
if got := strings.Contains(out.String(), "**"+header+":**\n\n- item-00"); got != (count > 0) {
t.Errorf("%s list presence = %v for %d values:\n%s", header, got, count, out.String())
}
}
for i, value := range values {
want := 3
if i >= maxDisplayItems {
want = 0
}
if got := strings.Count(out.String(), "- "+value+"\n"); got != want {
t.Errorf("%s occurs %d times, want %d", value, got, want)
}
}
wantTruncated := 0
if count > maxDisplayItems {
wantTruncated = 3
}
if got := strings.Count(out.String(), "- ... and 3 more\n"); got != wantTruncated {
t.Errorf("truncation summaries = %d, want %d:\n%s", got, wantTruncated, out.String())
}
})
}
}

func TestArtifactMarkdownEscapesMetadata(t *testing.T) {
value := "[link](url)|`*_<script>\n## forged\r\tend\u202e\u2066\u2069\u200b"
art := &brief.Artifact{
Version: value, Path: value, Format: value, SHA256: value,
NativeObjects: []binary.Object{{
Path: value, Format: value, Arch: value, SOName: value,
Producer: []string{value}, Needed: []string{value},
Go: &binary.GoBuild{Version: value, Path: value, Main: value, Deps: []string{value}},
Static: []binary.Hint{{Library: value, Version: value, Match: value}},
}},
}
var out bytes.Buffer
ArtifactMarkdown(&out, art)
want := "\\[link\\](url)\\|\\`\\*\\_&lt;script&gt; \\#\\# forged end"
if n := strings.Count(out.String(), want); n != 17 {
t.Errorf("escaped metadata occurrences = %d, want 17:\n%s", n, out.String())
}
for _, unwanted := range []string{"[link](url)", "<script>", "\n## forged", "\r", "\t", "\u202e", "\u2066", "\u2069", "\u200b"} {
if strings.Contains(out.String(), unwanted) {
t.Errorf("unescaped metadata %q: %s", unwanted, out.String())
}
}
}

func TestArtifactMarkdownEscapesListHeading(t *testing.T) {
art := &brief.Artifact{NativeObjects: []binary.Object{{Path: "lib.so", Producer: []string{"# forged"}}}}
var out bytes.Buffer
ArtifactMarkdown(&out, art)
if !strings.Contains(out.String(), "- \\# forged\n") {
t.Errorf("expected escaped heading marker in list item:\n%s", out.String())
}
}
2 changes: 1 addition & 1 deletion report/bibtex.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func mdBibTeX(w io.Writer, info *brief.BibTeXInfo, verbose bool) {
}
_, _ = fmt.Fprint(w, "\n**BibTeX:**\n\n")
for _, row := range rows {
_, _ = fmt.Fprintf(w, "- %s: %s\n", row.label, escapeCitationMarkdown(row.value))
_, _ = fmt.Fprintf(w, "- %s: %s\n", row.label, escapeMarkdown(row.value))
}
}

Expand Down
9 changes: 1 addition & 8 deletions report/citation.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func mdCitation(w io.Writer, info *brief.CitationInfo, verbose bool) {
}
_, _ = fmt.Fprint(w, "\n**Citation:**\n\n")
for _, row := range rows {
_, _ = fmt.Fprintf(w, "- %s: %s\n", row.label, escapeCitationMarkdown(row.value))
_, _ = fmt.Fprintf(w, "- %s: %s\n", row.label, escapeMarkdown(row.value))
}
}

Expand Down Expand Up @@ -139,10 +139,3 @@ func citationText(value string) string {
}
return value
}

func escapeCitationMarkdown(value string) string {
return strings.NewReplacer(
"\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "[", "\\[", "]", "\\]",
"<", "&lt;", ">", "&gt;", "&", "&amp;", "|", "\\|",
).Replace(value)
}
2 changes: 1 addition & 1 deletion report/codemeta.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func mdCodemeta(w io.Writer, info *brief.CodemetaInfo, verbose bool) {
}
_, _ = fmt.Fprint(w, "\n**CodeMeta:**\n\n")
for _, row := range rows {
_, _ = fmt.Fprintf(w, "- %s: %s\n", row.label, escapeCitationMarkdown(citationText(row.value)))
_, _ = fmt.Fprintf(w, "- %s: %s\n", row.label, escapeMarkdown(citationText(row.value)))
}
}

Expand Down
63 changes: 63 additions & 0 deletions report/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"strings"
"unicode"

"github.com/git-pkgs/brief"
)
Expand Down Expand Up @@ -431,3 +432,65 @@ func SinksMarkdown(w io.Writer, r *brief.SinkReport) {
_, _ = fmt.Fprintf(w, "| %s | `%s` | %s | %s |\n", s.Tool, s.Symbol, s.Threat, s.CWE)
}
}

// ArtifactMarkdown writes the artifact report in Markdown format.
func ArtifactMarkdown(w io.Writer, a *brief.Artifact) {
text := func(value string) string {
value = strings.Map(func(r rune) rune {
if unicode.Is(unicode.Cf, r) {
return -1
}
return r
}, sanitizeLine(value))
return strings.ReplaceAll(escapeMarkdown(value), "#", `\#`)
}
list := func(header string, values []string) {
items := make([]string, len(values))
for i, value := range values {
items[i] = text(value)
}
mdTruncatedList(w, header, items)
}
field := func(label, value string) {
if value != "" {
_, _ = fmt.Fprintf(w, "**%s:** %s\n\n", label, text(value))
}
}
_, _ = fmt.Fprintf(w, "# brief %s — %s\n\n", text(a.Version), text(a.Path))
field("Format", a.Format)
field("SHA256", a.SHA256)
if a.Entries > 0 {
_, _ = fmt.Fprintf(w, "**Entries:** %d files, %d native objects\n\n", a.Entries, len(a.NativeObjects))
}

for _, obj := range a.NativeObjects {
_, _ = fmt.Fprintf(w, "## Object: %s\n\n", text(obj.Path))
field("Format", obj.Format)
field("Architecture", obj.Arch)
field("SOName", obj.SOName)
list("Producers", obj.Producer)
list("Needed", obj.Needed)
if obj.Go != nil {
field("Go", obj.Go.Version)
field("Go path", obj.Go.Path)
field("Go main", obj.Go.Main)
list("Go dependencies", obj.Go.Deps)
}
for _, hint := range obj.Static {
label := hint.Library
if hint.Version != "" {
label += " " + hint.Version
}
field("Static (low confidence)", label)
field("Matched text", hint.Match)
}
}
_, _ = fmt.Fprintf(w, "---\n\n%.1fms\n", a.DurationMS)
}

func escapeMarkdown(value string) string {
return strings.NewReplacer(
"\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "[", "\\[", "]", "\\]",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"<", "&lt;", ">", "&gt;", "&", "&amp;", "|", "\\|",
).Replace(value)
}
Loading