Skip to content

feat: add PostgreSQL parser and reporting capabilities#2

Merged
KARTIKrocks merged 9 commits into
mainfrom
release/v0.1.0
Jun 8, 2026
Merged

feat: add PostgreSQL parser and reporting capabilities#2
KARTIKrocks merged 9 commits into
mainfrom
release/v0.1.0

Conversation

@KARTIKrocks

@KARTIKrocks KARTIKrocks commented Jun 8, 2026

Copy link
Copy Markdown
Owner
  • Implemented a new PostgreSQL parser in pgparser that provides structural analysis of SQL queries, including support for SELECT, INSERT, UPDATE, and DELETE statements.
  • Added unit tests for the PostgreSQL parser to ensure accurate parsing and structural fact extraction.
  • Introduced a ConsoleReporter for outputting analysis results to the terminal with color-coded severity levels.
  • Created a JSONReporter for outputting analysis results in JSON format.
  • Defined a Reporter interface for consistent reporting of analysis results across different formats.
  • Updated the main sqlguard package to support the new PostgreSQL parser and reporting features.

Summary by CodeRabbit

  • New Features

    • Full SQL analysis suite: built-in detections, redaction + stable fingerprints, EXPLAIN plan analysis with safety checks, CLI scan/explain, runtime middleware with N+1 detection, slow-query reporting, deduplication, and analysis caching.
    • Multiple ORM/driver integrations and console/JSON reporting.
    • Config discovery/loader with profile mapping and templates for issues/PRs.
  • Documentation

    • Added README, CONTRIBUTING, CHANGELOG, SECURITY, and issue/PR templates.
  • Chores

    • CI workflows, Dependabot, linters, Makefile and module tooling.
  • Tests

    • Extensive unit and integration coverage across analyzer, middleware, CLI, parsers, reporters, and integrations.

- Implemented a new PostgreSQL parser in `pgparser` that provides structural analysis of SQL queries, including support for SELECT, INSERT, UPDATE, and DELETE statements.
- Added unit tests for the PostgreSQL parser to ensure accurate parsing and structural fact extraction.
- Introduced a `ConsoleReporter` for outputting analysis results to the terminal with color-coded severity levels.
- Created a `JSONReporter` for outputting analysis results in JSON format.
- Defined a `Reporter` interface for consistent reporting of analysis results across different formats.
- Updated the main `sqlguard` package to support the new PostgreSQL parser and reporting features.
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ba2ff959-d904-4545-89fc-4a7afafcbac9

📥 Commits

Reviewing files that changed from the base of the PR and between c51e319 and d203993.

📒 Files selected for processing (13)
  • .coderabbit.yaml
  • CHANGELOG.md
  • README.md
  • analyzer/fallback.go
  • analyzer/redact.go
  • config/middleware_test.go
  • middleware/driver_test.go
  • parsers/mysqlparser/mysqlparser.go
  • parsers/mysqlparser/mysqlparser_test.go
  • reporter/console.go
  • reporter/console_test.go
  • reporter/json.go
  • reporter/json_test.go

Walkthrough

Adds the complete sqlguard initial release: analyzer (rules, fallback/grammar parsers, redaction, registry), middleware (Guard, cache, dedup, N+1, driver wrappers), CLI (scan/explain), config, reporters, integrations, tests, docs, and CI/tooling.

Changes

Initial release

Layer / File(s) Summary
Repository foundation and runtime/CLI core
*
All repository templates, CI/workflows, issue/PR templates, docs (README/CONTRIBUTING/CHANGELOG/SECURITY), analyzer contracts/types/rules, fallback parser and optional grammar parsers, redaction/fingerprinting, suppression parsing, middleware (Guard, cache, dedup, N+1, driver wraps), CLI commands (scan, explain, root), config loading and middleware wiring, reporters (console/json), integrations (bunguard, entguard, gormguard, pgxguard, sqlxguard, xormguard), module files, and comprehensive tests and benchmarks across packages.

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Config
  participant Analyzer
  participant Guard
  participant DB
  participant Reporter
  CLI->>Config: resolve config/profile
  Config->>Analyzer: build analyzer with profile
  CLI->>Analyzer: static scan / prepare query
  Analyzer->>Guard: runtime Observe / Check
  Guard->>DB: run EXPLAIN (rolled-back) / execute via wrapped driver
  DB->>Guard: plan/rows
  Guard->>Analyzer: fingerprint / normalize
  Guard->>Reporter: report findings
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

Parsers hum and guards stand by,
Redact the whispers, fingerprint the sky,
N+1 counts, caches sigh, dedup keeps quiet nigh—
CI builds the watchful eye, release flags fly.

✨ 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 release/v0.1.0

@KARTIKrocks

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@github-advanced-security

Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

@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.

Actionable comments posted: 20

🤖 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.

Inline comments:
In @.github/workflows/ci.yml:
- Line 19: The checkout steps use actions/checkout@v6 without disabling
credential persistence; update each checkout step that uses actions/checkout@v6
(all occurrences) to include persist-credentials: false in the step definition
so the GITHUB_TOKEN is not left in the repo git config (add the
persist-credentials: false key under the uses: actions/checkout@v6 entries).
- Around line 3-7: Add a concurrency policy to the GitHub Actions workflow to
cancel stale runs: in the CI workflow definition (the top-level "on:" block
handling push and pull_request) add a "concurrency" key with a unique group name
(e.g., using github.ref and github.workflow) and set "cancel-in-progress: true"
so that overlapping runs triggered by rapid pushes are cancelled; update the
workflow metadata where "on:" is defined to include this new concurrency
configuration.

In @.github/workflows/codeql.yml:
- Around line 16-18: Add an inline comment above the permissions block
documenting why security-events: write is required (CodeQL uploads SARIF/results
and GitHub requires write access to the security-events permission), mention
that this suppresses the "excessive-permissions" false positive and that
contents: read is only used for workflow context; update the comment near the
permissions keys (security-events: write and contents: read) so reviewers and
scanners see the intent.
- Around line 25-26: The Checkout step using actions/checkout@v6 currently
leaves GITHUB_TOKEN persisted in git config; update the Checkout step (the job
step named "Checkout" that uses actions/checkout@v6) to add persist-credentials:
false so the action does not write the runner's GITHUB_TOKEN into git config and
reduce credential-leakage risk.

In @.gitignore:
- Around line 21-22: .gitignore contains an entry "sqlguard-website" that
doesn't exist elsewhere; either remove that entry or retain it but add an inline
comment explaining what generates or uses that path (e.g., build output, CI
artifact, local dev tool) so future readers know its purpose; update the
"sqlguard-website" line to either be deleted or changed to a commented note
referencing "sqlguard-website" to clarify its origin and intent.

In @.golangci.yml:
- Around line 30-33: The .golangci.yml contains an invalid top-level
"formatters" section with entries "gofmt" and "goimports"; remove that section
and instead enable these tools under the existing "linters" configuration (or
omit them and rely on your Makefile's make fmt). Specifically, delete the
"formatters:" block and add "gofmt" and/or "goimports" to the "linters.enable"
list (or ensure they are enforced via make fmt), so references to
gofmt/goimports are recognized by golangci-lint.

In `@analyzer/redact.go`:
- Line 126: Update the misleading comment above skipSingleQuoted: replace the
incorrect escape reference `s[i] == '\"` with the correct single-quote form so
it reads that the function returns the index past a single-quoted string literal
starting at s[i] == '\'' and honoring '' doubled-quote escapes; ensure the
comment text matches the function name skipSingleQuoted and the actual character
checked in the code.

In `@cmd/sqlguard/db.go`:
- Around line 11-18: The switch mapping dialect to driverName is redundant
(mapping "postgres"→"postgres" and "mysql"→"mysql"); replace the switch with a
simple validation that dialect is one of the supported values and then set
driverName = dialect (i.e., check if dialect != "postgres" && dialect != "mysql"
then return the fmt.Errorf("unsupported dialect: %s", dialect), otherwise assign
driverName = dialect) so the logic in the function using the dialect and
driverName is simplified and clearer.

In `@cmd/sqlguard/scan.go`:
- Around line 224-226: The call to filepath.Abs in shouldSkipDir currently
ignores its error; change it to capture the returned error (e.g., absPath, err
:= filepath.Abs(path)) and handle it by returning that error from shouldSkipDir
so callers can respond appropriately; then continue using absPath for the
comparison with absDir. Ensure the function signature and any upstream callers
already expect/handle the error return from shouldSkipDir.
- Around line 117-119: scanDir currently ignores the error from filepath.Abs
which can break downstream path normalization in keepFile; update scanDir to
check the error returned by filepath.Abs(dir) and return an appropriate error
(or wrap it) instead of proceeding with an empty/invalid absDir, so callers of
scanDir know the operation failed; reference the scanDir function and its use of
absDir (used by keepFile) and ensure the error is propagated from scanDir to the
caller rather than ignored.

In `@explain/explain.go`:
- Around line 178-213: The walkPgPlan function (and likewise analyzeMySQL) is
populating analyzer.Result.Query with the raw query string; call the canonical
redactor before constructing Results and use the redacted value instead.
Specifically, inside PlanAnalyzer.walkPgPlan and analyzeMySQL, compute redacted
:= analyzer.Redact(query) and replace uses of query in each analyzer.Result{
Query: ... } with redacted (leave rawQuery unchanged if needed); ensure every
Result creation (RuleName "seq-scan", "high-cost", and the three analyzeMySQL
results) uses analyzer.Redact to avoid leaking literals.

In `@integrations/pgxguard/go.mod`:
- Line 14: The go.mod entry for golang.org/x/crypto currently pins v0.37.0 which
OSV flags for multiple ssh-related vulnerabilities; update that module to a
patched release (replace the golang.org/x/crypto v0.37.0 line) by running
something like `go get golang.org/x/crypto@latest` (or a specific patched tag),
then run `go mod tidy` and your test suite; confirm the new version appears in
integrations/pgxguard/go.mod and re-scan to ensure the vulnerabilities are
resolved while addressing the pgx fixes.
- Line 7: The go.mod currently pins the dependency "github.com/jackc/pgx/v5
v5.7.6" which has known critical memory-safety and other advisories; update the
pgx module version to at least v5.9.2 by changing the version entry for
github.com/jackc/pgx/v5 to v5.9.2, then run module tooling (go get/go mod tidy)
to refresh go.sum and verify builds and tests; ensure any pgx-related imports or
code paths (uses of pgx types/functions) compile cleanly after the upgrade and
adjust callsites if any API changes surface.

In `@middleware/dedup_test.go`:
- Around line 132-147: TestGuard_DedupConcurrent uses sync.WaitGroup incorrectly
and the loop syntax is invalid; replace the "for range 100" with a standard for
i := 0; i < 100; i++ loop, call wg.Add(1) for each iteration before spawning a
goroutine, and inside the goroutine defer wg.Done() and call g.Check("DELETE
FROM accounts"); this fixes compilation and ensures the countingReporter
receives exactly one concurrent check under NewGuard/WithReporter.

In `@middleware/driver_test.go`:
- Line 16: The tests import the cgo-dependent driver "_
\"github.com/mattn/go-sqlite3\"" but lack a cgo build constraint, so add a Go
build tag to guard these tests: insert the line "//go:build cgo" (and the legacy
"+build cgo" if you want older toolchains) at the top of
middleware/driver_test.go (and the other test files that import "_
\"github.com/mattn/go-sqlite3\"") so the tests are only compiled/run when cgo is
enabled; alternatively, if you prefer runtime skipping, add a check in the test
entry (e.g., Test* functions) to detect CGO availability via build tags or
environment and call t.Skip when CGO is disabled.

In `@parsers/mysqlparser/mysqlparser.go`:
- Around line 120-136: The hasRealFrom function currently does a case-sensitive
comparison tn.Name.String() == "dual" which fails for quoted/backticked
identifiers like `DUAL`; update hasRealFrom to perform a case-insensitive
comparison (e.g., use strings.EqualFold(tn.Name.String(), "dual")) when checking
for "dual", and ensure the strings package is imported; also add unit tests
covering quoted/backticked DUAL variants (e.g., `DUAL`, `Dual`) to verify
HasFrom=false for those cases.

In `@parsers/pgparser/go.mod`:
- Around line 7-33: The go.mod for module parsers/pgparser pulls in
auxten/postgresql-parser v1.0.1 which transitively requires vulnerable versions
of google.golang.org/grpc, golang.org/x/text, github.com/sirupsen/logrus, and
google.golang.org/protobuf; fix by adding explicit require/replace directives in
parsers/pgparser/go.mod to pin those transitive modules to patched versions
(e.g., grpc >= v1.79.3 or at least the minimum patched release, x/text >=
v0.3.8, logrus >= v1.9.3, protobuf >= v1.33.0/1.29.1 as appropriate), or if
upstream auxten/postgresql-parser cannot be updated, fork/replace
auxten/postgresql-parser with a patched fork and point go.mod to that fork;
ensure the changes reference the existing module name auxten/postgresql-parser
v1.0.1 in the replace/require entries so the dependency graph is overridden.

In `@reporter/console.go`:
- Around line 20-23: The exported Out field on ConsoleReporter creates a race
because callers can reassign it while Report is running; make Out unexported
(rename to out) and provide either a constructor that accepts an io.Writer or a
synchronized setter (e.g., SetOut) that locks mu, then update all references
from c.Out to c.out and ensure Report continues to lock mu around any access to
the writer; alternatively, if you prefer to keep it exported, document
immutability and enforce write access via a SetOut method that acquires mu—apply
this change for ConsoleReporter, its Out usages, and any tests/consumers.

In `@reporter/json.go`:
- Around line 53-55: The JSON encoder error from enc.Encode(out) is being
ignored; update the Encode call in reporter.json's code that creates enc :=
json.NewEncoder(j.Out) (and uses enc.SetIndent) to check the returned error and,
since Reporter doesn't return errors, write a clear error message including the
encoding error to os.Stderr (e.g., via fmt.Fprintf(os.Stderr, ...)) so failures
writing to j.Out (closed writer, disk full, etc.) are visible; keep behavior
otherwise unchanged.
- Around line 13-16: The exported Out field on JSONReporter bypasses the mutex
(mu) and can be reassigned concurrently causing a data race; change the struct
to make Out unexported (rename to out) or otherwise ensure it cannot be modified
after construction, update all references to JSONReporter.Out to use the new
unexported field (e.g., JSONReporter.out) or an accessor, and ensure Report
still locks mu before writing; mirror the same fix you applied to
ConsoleReporter to eliminate the race.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: c5cd04aa-a31d-4177-8349-3e0fe8620421

📥 Commits

Reviewing files that changed from the base of the PR and between a8be5c2 and cb040cb.

⛔ Files ignored due to path filters (9)
  • go.sum is excluded by !**/*.sum
  • integrations/bunguard/go.sum is excluded by !**/*.sum
  • integrations/entguard/go.sum is excluded by !**/*.sum
  • integrations/gormguard/go.sum is excluded by !**/*.sum
  • integrations/pgxguard/go.sum is excluded by !**/*.sum
  • integrations/sqlxguard/go.sum is excluded by !**/*.sum
  • integrations/xormguard/go.sum is excluded by !**/*.sum
  • parsers/mysqlparser/go.sum is excluded by !**/*.sum
  • parsers/pgparser/go.sum is excluded by !**/*.sum
📒 Files selected for processing (86)
  • .github/ISSUE_TEMPLATE/bug_report.md
  • .github/ISSUE_TEMPLATE/config.yml
  • .github/ISSUE_TEMPLATE/feature_request.md
  • .github/PULL_REQUEST_TEMPLATE.md
  • .github/dependabot.yml
  • .github/workflows/ci.yml
  • .github/workflows/codeql.yml
  • .gitignore
  • .golangci.yml
  • .sqlguard.example.yml
  • CHANGELOG.md
  • CONTRIBUTING.md
  • Makefile
  • README.md
  • SECURITY.md
  • analyzer/analyzer.go
  • analyzer/analyzer_test.go
  • analyzer/fallback.go
  • analyzer/fallback_test.go
  • analyzer/parser.go
  • analyzer/profile_test.go
  • analyzer/redact.go
  • analyzer/redact_policy_test.go
  • analyzer/redact_test.go
  • analyzer/registry.go
  • analyzer/result.go
  • analyzer/rules.go
  • analyzer/severity.go
  • analyzer/statement.go
  • analyzer/suppress.go
  • cmd/sqlguard/db.go
  • cmd/sqlguard/explain.go
  • cmd/sqlguard/main.go
  • cmd/sqlguard/resolve_test.go
  • cmd/sqlguard/root.go
  • cmd/sqlguard/scan.go
  • cmd/sqlguard/scan_test.go
  • codecov.yml
  • config/config.go
  • config/config_test.go
  • config/middleware.go
  • config/middleware_test.go
  • explain/explain.go
  • explain/explain_test.go
  • go.mod
  • integrations/bunguard/bunguard.go
  • integrations/bunguard/bunguard_test.go
  • integrations/bunguard/go.mod
  • integrations/entguard/entguard.go
  • integrations/entguard/entguard_test.go
  • integrations/entguard/go.mod
  • integrations/gormguard/go.mod
  • integrations/gormguard/gormguard.go
  • integrations/gormguard/gormguard_test.go
  • integrations/pgxguard/go.mod
  • integrations/pgxguard/pgxguard.go
  • integrations/pgxguard/pgxguard_test.go
  • integrations/sqlxguard/go.mod
  • integrations/sqlxguard/sqlxguard.go
  • integrations/sqlxguard/sqlxguard_test.go
  • integrations/xormguard/go.mod
  • integrations/xormguard/xormguard.go
  • integrations/xormguard/xormguard_test.go
  • middleware/cache.go
  • middleware/cache_test.go
  • middleware/dedup.go
  • middleware/dedup_test.go
  • middleware/driver.go
  • middleware/driver_fallback_test.go
  • middleware/driver_test.go
  • middleware/guard.go
  • middleware/n_plus_one.go
  • middleware/n_plus_one_test.go
  • middleware/options.go
  • parsers/mysqlparser/go.mod
  • parsers/mysqlparser/mysqlparser.go
  • parsers/mysqlparser/mysqlparser_test.go
  • parsers/pgparser/go.mod
  • parsers/pgparser/pgparser.go
  • parsers/pgparser/pgparser_test.go
  • reporter/console.go
  • reporter/console_test.go
  • reporter/json.go
  • reporter/json_test.go
  • reporter/reporter.go
  • sqlguard.go

Comment thread .github/workflows/ci.yml
Comment thread .github/workflows/ci.yml
Comment thread .github/workflows/codeql.yml
Comment thread .github/workflows/codeql.yml
Comment thread .gitignore
Comment thread parsers/mysqlparser/mysqlparser.go
Comment thread parsers/pgparser/go.mod
Comment on lines +7 to +33
require (
github.com/auxten/postgresql-parser v1.0.1
github.com/certifi/gocertifi v0.0.0-20200922220541-2c3bb06c6054 // indirect
github.com/cockroachdb/apd v1.1.1-0.20181017181144-bced77f817b4 // indirect
github.com/cockroachdb/errors v1.8.2 // indirect
github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f // indirect
github.com/cockroachdb/redact v1.0.8 // indirect
github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/getsentry/raven-go v0.2.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.4.3 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect
github.com/kr/pretty v0.2.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lib/pq v1.9.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.6.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.0.0-20201214210602-f9fddec55a1e // indirect
golang.org/x/text v0.3.4 // indirect
google.golang.org/genproto v0.0.0-20200911024640-645f7a48b24f // indirect
google.golang.org/grpc v1.33.1 // indirect
google.golang.org/protobuf v1.25.0 // indirect
)

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.

⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if auxten/postgresql-parser has updates that pull in patched dependencies
gh api repos/auxten/postgresql-parser/releases --jq '.[0] | {tag_name, published_at}'

# Check for known security advisories in the current dependency tree
cd parsers/pgparser
go list -m all | grep -E 'grpc|x/text|logrus|protobuf' | while read mod ver; do
  echo "=== $mod $ver ==="
  gh api graphql -f query='
  {
    securityVulnerabilities(first: 10, ecosystem: GO, package: "'$mod'") {
      nodes {
        advisory { summary severity publishedAt }
        vulnerableVersionRange
        firstPatchedVersion { identifier }
      }
    }
  }' | jq -r '.data.securityVulnerabilities.nodes[] | select(.vulnerableVersionRange) | "[\(.advisory.severity)] \(.advisory.summary) | Patch: \(.firstPatchedVersion.identifier // "none")"'
done

Repository: KARTIKrocks/sqlguard

Length of output: 1598


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n --hidden --no-ignore -S "google\.golang\.org/grpc|grpc-go|logrus|Entry\.Writer|protojson|Unmarshal\(|golang\.org/x/text|x/text/language|rapid reset|gogo/protobuf|cockroachdb|sentry-go" parsers/pgparser || true
rg -n --hidden --no-ignore -S "google\.golang\.org/grpc|logrus|protojson|golang\.org/x/text" parsers/pgparser -g'*.go' || true

Repository: KARTIKrocks/sqlguard

Length of output: 4461


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cd parsers/pgparser
go mod graph | rg -n 'google\.golang\.org/grpc@|golang\.org/x/text@|github\.com/sirupsen/logrus@|google\.golang\.org/protobuf@' || true

Repository: KARTIKrocks/sqlguard

Length of output: 12170


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cd parsers/pgparser
# Show whether these modules appear in the build dependency list of ./...
go list -deps ./... | rg -n "google\.golang\.org/grpc|golang\.org/x/text|github\.com/sirupsen/logrus|google\.golang\.org/protobuf" || true

Repository: KARTIKrocks/sqlguard

Length of output: 2521


🏁 Script executed:

#!/bin/bash
set -euo pipefail
cd parsers/pgparser
go list -f '{{join .Imports "\n"}}' ./... 2>/dev/null | rg -n "google\.golang\.org/grpc|golang\.org/x/text|github\.com/sirupsen/logrus|google\.golang\.org/protobuf" || true

Repository: KARTIKrocks/sqlguard

Length of output: 46


CRITICAL: parsers/pgparser pulls in vulnerable transitive deps via auxten/postgresql-parser v1.0.1.

Building/enabling parsers/pgparser includes these known-vulnerable packages (even if not directly referenced in pgparser source code):

  • google.golang.org/grpc v1.33.1 (CRITICAL): authorization bypass via :path handling — patch 1.79.3; HTTP/2 Rapid Reset DoS — patches 1.58.3/1.57.1/1.56.3
  • golang.org/x/text v0.3.4 (HIGH): out-of-bounds read — patch 0.3.7; crafted Accept-Language DoS — patch 0.3.8
  • github.com/sirupsen/logrus v1.6.0 (HIGH): DoS via Entry.Writer() — patch 1.9.3
  • google.golang.org/protobuf v1.25.0 (HIGH): panic leading to DoS — patch 1.29.1; MODERATE: protojson.Unmarshal infinite loop — patch 1.33.0

Upstream auxten/postgresql-parser releases show latest at v1.0.1, so remediation likely requires adding replace/explicit require overrides (or forking) in parsers/pgparser/go.mod to force patched grpc/x/text/logrus/protobuf.

🤖 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 `@parsers/pgparser/go.mod` around lines 7 - 33, The go.mod for module
parsers/pgparser pulls in auxten/postgresql-parser v1.0.1 which transitively
requires vulnerable versions of google.golang.org/grpc, golang.org/x/text,
github.com/sirupsen/logrus, and google.golang.org/protobuf; fix by adding
explicit require/replace directives in parsers/pgparser/go.mod to pin those
transitive modules to patched versions (e.g., grpc >= v1.79.3 or at least the
minimum patched release, x/text >= v0.3.8, logrus >= v1.9.3, protobuf >=
v1.33.0/1.29.1 as appropriate), or if upstream auxten/postgresql-parser cannot
be updated, fork/replace auxten/postgresql-parser with a patched fork and point
go.mod to that fork; ensure the changes reference the existing module name
auxten/postgresql-parser v1.0.1 in the replace/require entries so the dependency
graph is overridden.

Comment thread reporter/console.go
Comment thread reporter/json.go
Comment thread reporter/json.go Outdated
KARTIKrocks and others added 7 commits June 8, 2026 16:13
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@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.

♻️ Duplicate comments (3)
analyzer/redact.go (1)

125-126: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix the regressed single-quote comment text.

Line 126 still has the wrong escape marker and a smart quote, so the doc no longer matches skipSingleQuoted, and it is the current lint hit on this file. Restore the literal to s[i] == '\''.

🛠️ Suggested fix
-// literal starting at s[i] == '\”, honoring '' doubled-quote escapes.
+// literal starting at s[i] == '\'', honoring '' doubled-quote escapes.
🤖 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 `@analyzer/redact.go` around lines 125 - 126, The doc comment above the
skipSingleQuoted function was regressed with a smart quote and incorrect escape;
update the comment text to restore the literal to s[i] == '\'' (i.e., an escaped
single-quote) so the comment accurately describes the condition checked in
skipSingleQuoted and removes the wrong escape marker and smart quote characters.

Source: Linters/SAST tools

reporter/json.go (1)

14-21: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make the output writer immutable or the mutex doesn't actually make this concurrent-safe.

Report serializes writes, but Out is still exported, so another goroutine can swap it out—or nil it—while json.NewEncoder(j.Out) is running. That leaves shared reporter instances racy even after this encode-error handling change.

🛠️ Suggested fix
 type JSONReporter struct {
-	Out io.Writer
+	out io.Writer
 	mu  sync.Mutex
 }

 // NewJSONReporter creates a JSONReporter that writes to stderr.
 func NewJSONReporter() *JSONReporter {
-	return &JSONReporter{Out: os.Stderr}
+	return &JSONReporter{out: os.Stderr}
 }
@@
-	enc := json.NewEncoder(j.Out)
+	enc := json.NewEncoder(j.out)

Also applies to: 36-38, 54-59

🤖 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 `@reporter/json.go` around lines 14 - 21, Make the writer immutable by renaming
the exported field Out to an unexported field (e.g., out io.Writer) and only
setting it in NewJSONReporter so callers cannot swap or nil it; update
JSONReporter usages (including Report and any other methods referencing Out) to
use the unexported field name, and ensure NewJSONReporter initializes out to
os.Stderr. Alternatively, if you must allow swapping, guard all accesses and
mutations of Out with the existing mu (lock in setter and lock around
json.NewEncoder(j.out) in Report) and nil-check before use; reference the
JSONReporter type, its Out field, mu mutex, NewJSONReporter constructor, and
Report method when making the change.
cmd/sqlguard/scan.go (1)

117-121: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Mirror the filepath.Abs error handling in shouldSkipDir.

scanDir now propagates filepath.Abs(dir) failures, but the AST fallback still does absPath, _ := filepath.Abs(path) at Line 228. If cwd resolution fails there, directory pruning becomes inconsistent and can skip or retain the wrong subtree.

🛠️ Suggested fix
 func shouldSkipDir(path, absDir string) error {
-	absPath, _ := filepath.Abs(path)
+	absPath, err := filepath.Abs(path)
+	if err != nil {
+		return err
+	}
 	if absPath != absDir {
 		base := filepath.Base(path)
 		if strings.HasPrefix(base, ".") || base == "vendor" || base == "node_modules" {

Also applies to: 227-229

🤖 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 `@cmd/sqlguard/scan.go` around lines 117 - 121, The filepath.Abs failure in the
AST fallback must be handled the same way as in scanDir: replace the silent
ignore (absPath, _ := filepath.Abs(path)) used in shouldSkipDir/AST fallback
with proper error handling that propagates or returns the error so directory
pruning is consistent; locate the absPath assignment in shouldSkipDir/AST
fallback and change it to call filepath.Abs(path), check the error and return it
(or bubble it up through shouldSkipDir/scanDir) rather than discarding the
error, ensuring callers like scanDir consistently handle and propagate cwd
resolution failures.
🤖 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.

Duplicate comments:
In `@analyzer/redact.go`:
- Around line 125-126: The doc comment above the skipSingleQuoted function was
regressed with a smart quote and incorrect escape; update the comment text to
restore the literal to s[i] == '\'' (i.e., an escaped single-quote) so the
comment accurately describes the condition checked in skipSingleQuoted and
removes the wrong escape marker and smart quote characters.

In `@cmd/sqlguard/scan.go`:
- Around line 117-121: The filepath.Abs failure in the AST fallback must be
handled the same way as in scanDir: replace the silent ignore (absPath, _ :=
filepath.Abs(path)) used in shouldSkipDir/AST fallback with proper error
handling that propagates or returns the error so directory pruning is
consistent; locate the absPath assignment in shouldSkipDir/AST fallback and
change it to call filepath.Abs(path), check the error and return it (or bubble
it up through shouldSkipDir/scanDir) rather than discarding the error, ensuring
callers like scanDir consistently handle and propagate cwd resolution failures.

In `@reporter/json.go`:
- Around line 14-21: Make the writer immutable by renaming the exported field
Out to an unexported field (e.g., out io.Writer) and only setting it in
NewJSONReporter so callers cannot swap or nil it; update JSONReporter usages
(including Report and any other methods referencing Out) to use the unexported
field name, and ensure NewJSONReporter initializes out to os.Stderr.
Alternatively, if you must allow swapping, guard all accesses and mutations of
Out with the existing mu (lock in setter and lock around json.NewEncoder(j.out)
in Report) and nil-check before use; reference the JSONReporter type, its Out
field, mu mutex, NewJSONReporter constructor, and Report method when making the
change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e60e9bc0-c742-4a35-875a-fbe7b10855a2

📥 Commits

Reviewing files that changed from the base of the PR and between b5f7fa9 and c51e319.

📒 Files selected for processing (3)
  • analyzer/redact.go
  • cmd/sqlguard/scan.go
  • reporter/json.go

@KARTIKrocks KARTIKrocks merged commit 6903d4f into main Jun 8, 2026
6 of 7 checks passed
@KARTIKrocks KARTIKrocks deleted the release/v0.1.0 branch June 8, 2026 11:24
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.

2 participants