Skip to content

refactor(exporters): improve exported sarif rule and result metadata#7368

Open
dwisiswant0 wants to merge 2 commits into
devfrom
dwisiswant0/refactor/exporters/improve-exported-sarif-rule-and-result-metadata
Open

refactor(exporters): improve exported sarif rule and result metadata#7368
dwisiswant0 wants to merge 2 commits into
devfrom
dwisiswant0/refactor/exporters/improve-exported-sarif-rule-and-result-metadata

Conversation

@dwisiswant0

@dwisiswant0 dwisiswant0 commented Apr 29, 2026

Copy link
Copy Markdown
Member

Proposed changes

improve exported sarif rule and result metadata

Normalize rule ids and descriptions, attach help
text, references and GitHub security properties,
and enrich result messages with target, matcher,
extractor, extracted values and reproduction
details.

Keep rule indices stable, generate better artifact
locations, mark the invocation successful, and
export with normalization and empty-object pruning
enabled.

Also adapt the exporter to the updated sarif API.

Closes #7313

Proof

See #7313 (comment)

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • Improvements

    • Richer, more structured SARIF exports: clearer rule descriptions, help text, and result messages with normalized/truncated values.
    • More consistent rule indexing and enhanced location/URI handling, including GitHub security metadata and triage/reproduction details.
  • Tests

    • Added comprehensive unit and integration tests covering normalization, formatting helpers, exporter lifecycle, concurrency, and SARIF output validation.
  • Chores

    • Updated SARIF dependency to newer version.

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a0c1a780-dcb9-4c57-a002-847607b5b8cf

📥 Commits

Reviewing files that changed from the base of the PR and between 4340c6d and d0879db.

📒 Files selected for processing (1)
  • pkg/reporting/exporters/sarif/sarif_test.go
✅ Files skipped from review due to trivial changes (1)
  • pkg/reporting/exporters/sarif/sarif_test.go

Walkthrough

The PR refactors the SARIF exporter to generate standards-compliant output with enriched metadata and normalized values. The sarif library dependency is bumped to v0.1.0. Export logic now builds structured rule descriptors, result messages, and locations via helper functions, maintains stable rule indexing with integer-keyed mappings, and writes normalized SARIF to file with empty-object pruning enabled.

Changes

SARIF Export Validation Enhancement

Layer / File(s) Summary
Dependency Update
go.mod
Sarif library dependency bumped from v0.0.1 to v0.1.0.
Type Changes and Constants
pkg/reporting/exporters/sarif/sarif.go
rulemap changed from map[string]*int to map[string]int; constants introduced for max detail length, extracted values, rule references, and fallback rule ID.
Imports and Initialization
pkg/reporting/exporters/sarif/sarif.go
Imports updated to add os and strings packages; New() initializes rulemap and configures tool driver with DownloadUri and InformationUri fields.
Tool Metadata Configuration
pkg/reporting/exporters/sarif/sarif.go
Tool invocation metadata structured with CommandLine, Arguments, ResponseFiles, and ExecutionSuccessful set to true.
Export Method Refactoring
pkg/reporting/exporters/sarif/sarif.go
Export() rewritten to normalize rule IDs with fallback, build reporting descriptors using helpers, maintain stable rule indexing, and construct enriched result locations and messages with properties.
File Output and Close
pkg/reporting/exporters/sarif/sarif.go
Close() now exports SARIF with normalization and empty-object pruning options, then writes bytes to file.
Supporting Helper Functions
pkg/reporting/exporters/sarif/sarif.go
Added helpers for rule descriptor assembly, result message generation with triage and reproduction details, GitHub metadata properties, artifact URI/location construction, rule tagging and CWE extraction, and value normalization/truncation utilities.
Tests / Integration
pkg/reporting/exporters/sarif/sarif_test.go
Extensive unit and integration tests added for helper utilities, message/property generation, severity mapping, exporter lifecycle, stable indexing, fallback IDs, CVSS handling, and concurrency.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A rabbit nibbles SARIF lines tonight,

Trims and normalizes each rule just right,
Helpers hum, descriptors take their place,
Findings march tidy into structured space,
v0.1.0 — a clean, validated sight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.42% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor(exporters): improve exported sarif rule and result metadata' accurately summarizes the main change: enhancing SARIF exporter metadata for rules and results.
Linked Issues check ✅ Passed The PR addresses all primary objectives from #7313: generating SARIF output with richer rule/result metadata (stable rule IDs, descriptions, help text, GitHub security properties, enriched result messages) to pass SARIF validation and improve readability in tools like GitHub Advanced Security.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the SARIF exporter refactoring: go.mod dependency bump, sarif.go implementation enhancements, and comprehensive test coverage; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dwisiswant0/refactor/exporters/improve-exported-sarif-rule-and-result-metadata

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Comment @coderabbitai help to get the list of available commands and usage tips.

@dwisiswant0
dwisiswant0 force-pushed the dwisiswant0/refactor/exporters/improve-exported-sarif-rule-and-result-metadata branch from 94fc6ba to ef5ad99 Compare April 29, 2026 22:40
@dwisiswant0

dwisiswant0 commented Apr 29, 2026

Copy link
Copy Markdown
Member Author

TODO:

@dwisiswant0
dwisiswant0 force-pushed the dwisiswant0/refactor/exporters/improve-exported-sarif-rule-and-result-metadata branch from ef5ad99 to 8abb99d Compare May 7, 2026 13:47
Normalize rule ids and descriptions, attach help
text, references and GitHub security properties,
and enrich result messages with target, matcher,
extractor, extracted values and reproduction
details.

Keep rule indices stable, generate better artifact
locations, mark the invocation successful, and
export with normalization and empty-object pruning
enabled.

Also adapt the exporter to the updated sarif API.

Signed-off-by: Dwi Siswanto <git@dw1.io>
@dwisiswant0
dwisiswant0 force-pushed the dwisiswant0/refactor/exporters/improve-exported-sarif-rule-and-result-metadata branch from 8abb99d to 4340c6d Compare May 7, 2026 13:51
@dwisiswant0
dwisiswant0 marked this pull request as ready for review May 7, 2026 14:25
@auto-assign
auto-assign Bot requested a review from Mzack9999 May 7, 2026 14:25

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pkg/reporting/exporters/sarif/sarif.go (1)

510-519: 💤 Low value

Consider adding a guard for small limit values.

If limit is less than 4, the truncation normalized[:limit-3] could produce unexpected results (empty string for limit=3) or panic (negative slice index for limit<3). Current usage with maxDetailValueLength=400 is safe, but the function could be made more defensive.

🛡️ Optional defensive fix
 func normalizeAndTruncate(value string, limit int) string {
 	normalized := normalizeValue(value)
 	if normalized == "" {
 		return ""
 	}
-	if limit > 0 && len(normalized) > limit {
+	if limit >= 4 && len(normalized) > limit {
 		return normalized[:limit-3] + "..."
 	}
 	return normalized
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/reporting/exporters/sarif/sarif.go` around lines 510 - 519,
normalizeAndTruncate currently assumes limit>=4 when it truncates with
normalized[:limit-3] + "...", which can produce empty slices or a negative index
for small limits; update normalizeAndTruncate (which calls normalizeValue) to be
defensive: if limit <= 0 return normalized (or ""), if limit <= 3 return
normalized[:min(len(normalized), limit)] without appending "..." (since there
isn’t room), and only when limit >= 4 perform the existing truncation logic
(normalized[:limit-3] + "...") after checking len(normalized) > limit.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/reporting/exporters/sarif/sarif.go`:
- Around line 510-519: normalizeAndTruncate currently assumes limit>=4 when it
truncates with normalized[:limit-3] + "...", which can produce empty slices or a
negative index for small limits; update normalizeAndTruncate (which calls
normalizeValue) to be defensive: if limit <= 0 return normalized (or ""), if
limit <= 3 return normalized[:min(len(normalized), limit)] without appending
"..." (since there isn’t room), and only when limit >= 4 perform the existing
truncation logic (normalized[:limit-3] + "...") after checking len(normalized) >
limit.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: da6405ed-657d-4888-a182-ebabe250f71c

📥 Commits

Reviewing files that changed from the base of the PR and between 1f8dd03 and 4340c6d.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (2)
  • go.mod
  • pkg/reporting/exporters/sarif/sarif.go

@neo-by-projectdiscovery-dev

neo-by-projectdiscovery-dev Bot commented May 7, 2026

Copy link
Copy Markdown

Neo - PR Security Review — Did Not Complete

Warning

Review Did Not Complete

The review process ended without producing a result. This usually means
the agent encountered a transient error mid-run.

To retry: Push a new commit or comment @pdneo review

Comment @pdneo help for available commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] SARIF export fails validation

2 participants