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
15 changes: 15 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Agent Guidelines - envguard

## Agent skills

### Issue tracker

GitHub Issues via `gh` CLI. See `docs/agents/issue-tracker.md`.

### Triage labels

Canonical 5 triage roles (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`). See `docs/agents/triage-labels.md`.

### Domain docs

Single-context layout (`CONTEXT.md` + `docs/adr/`). See `docs/agents/domain.md`.
33 changes: 33 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# envguard

Security-focused CLI tool to detect and prevent committed or exposed environment files in Git repositories.

## Language

**Scanner**:
The recursive filesystem traversal and Git status coordinator that produces scan findings.
_Avoid_: Crawler, inspector, walker

**Detector**:
The rule evaluator that determines if a file path is an environment file and whether it matches safe allowlist templates.
_Avoid_: Matcher, filter, classifier

**Configuration**:
The project-level settings loaded from `.envguard.yaml`, `.envguard.yml`, or via `--config` to customize scanning and detection rules.
_Avoid_: Options, settings, preferences

**Allowlist**:
The collection of glob patterns for safe environment templates or sample files (e.g., `.env.example`) that should not raise security warnings.
_Avoid_: Whitelist, safe-list, permitted files

**Ignore Directory**:
A directory name skipped during recursive filesystem traversal (e.g., `node_modules`, `.git`).
_Avoid_: Excluded path, blacklisted folder

**Severity Override**:
An explicit configuration rule that replaces the calculated severity level for files matching a specific pattern.
_Avoid_: Custom rule, priority tweak

**Finding**:
A detected environment file with its assigned severity level, git status, and mitigation suggestions.
_Avoid_: Vulnerability, issue, report item
3 changes: 3 additions & 0 deletions docs/adr/0001-yaml-configuration-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 0001: YAML Configuration File Support (.envguard.yaml)

To allow repositories to customize detection rules, allowlists, ignored directories, and severity levels, `envguard` will support project configuration files (`.envguard.yaml` and `.envguard.yml`) and an explicit `--config` CLI flag. Configuration parsing uses strict decoding via `gopkg.in/yaml.v3`, failing fast on invalid syntax or unknown fields to prevent silent security misconfigurations. User-provided allowlists and ignore directories append to the built-in safe defaults by default.
51 changes: 51 additions & 0 deletions docs/agents/domain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Domain Docs

How the engineering skills should consume this repo's domain documentation when exploring the codebase.

## Before exploring, read these

- **`CONTEXT.md`** at the repo root, or
- **`CONTEXT-MAP.md`** at the repo root if it exists: it points at one `CONTEXT.md` per context. Read each one relevant to the topic.
- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.

If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.

## File structure

Single-context repo (most repos):

```
/
├── CONTEXT.md
├── docs/adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```

Multi-context repo (presence of `CONTEXT-MAP.md` at the root):

```
/
├── CONTEXT-MAP.md
├── docs/adr/ ← system-wide decisions
└── src/
├── ordering/
│ ├── CONTEXT.md
│ └── docs/adr/ ← context-specific decisions
└── billing/
├── CONTEXT.md
└── docs/adr/
```

## Use the glossary's vocabulary

When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids.

If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).

## Flag ADR conflicts

If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:

> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
45 changes: 45 additions & 0 deletions docs/agents/issue-tracker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Issue tracker: GitHub

Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations.

## Conventions

- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies.
- **Read an issue**: `gh issue view <number> --comments`, filtering comments by `jq` and also fetching labels.
- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters.
- **Comment on an issue**: `gh issue comment <number> --body "..."`
- **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."`
- **Close**: `gh issue close <number> --comment "..."`

Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone.

## Pull requests as a triage surface

**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_

When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents:

- **Read a PR**: `gh pr view <number> --comments` and `gh pr diff <number>` for the diff.
- **List external PRs for triage**: `gh pr list --state open --json number,title,body,labels,author,authorAssociation,comments` then keep only `authorAssociation` of `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, or `NONE` (drop `OWNER`/`MEMBER`/`COLLABORATOR`).
- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`.

GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`.

## When a skill says "publish to the issue tracker"

Create a GitHub issue.

## When a skill says "fetch the relevant ticket"

Run `gh issue view <number> --comments`.

## Wayfinding operations

Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.

- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`.
- **Child ticket**: an issue linked to the map as a GitHub sub-issue (`gh api` on the sub-issues endpoint). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: GitHub's **native issue dependencies**, the canonical, UI-visible representation. Add an edge with `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). GitHub reports `issue_dependencies_summary.blocked_by` (open blockers only, the live gate). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed.
- **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (`issue_dependencies_summary.blocked_by > 0`, or an open issue in the `Blocked by` line) or an assignee; first in map order wins.
- **Claim**: `gh issue edit <n> --add-assignee @me`, the session's first write.
- **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
15 changes: 15 additions & 0 deletions docs/agents/triage-labels.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Triage Labels

The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.

| Label in mattpocock/skills | Label in our tracker | Meaning |
| -------------------------- | -------------------- | ---------------------------------------- |
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
| `needs-info` | `needs-info` | Waiting on reporter for more information |
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
| `ready-for-human` | `ready-for-human` | Requires human implementation |
| `wontfix` | `wontfix` | Will not be actioned |

When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.

Edit the right-hand column to match whatever vocabulary you actually use.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/joaooncode/envguard

go 1.22.0

require gopkg.in/yaml.v3 v3.0.1 // indirect
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
12 changes: 11 additions & 1 deletion internal/cli/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"strings"

"github.com/joaooncode/envguard/internal/config"
"github.com/joaooncode/envguard/internal/reporter"
"github.com/joaooncode/envguard/internal/scanner"
)
Expand All @@ -17,6 +18,8 @@ func runCheckCommand(args []string, stdout, stderr io.Writer, scannerInstance *s
var cfg scanConfig
fs.StringVar(&cfg.path, "path", ".", "Target directory path to check")
fs.StringVar(&cfg.path, "p", ".", "Target directory path to check (shorthand)")
fs.StringVar(&cfg.configPath, "config", "", "Path to custom configuration file")
fs.StringVar(&cfg.configPath, "c", "", "Path to custom configuration file (shorthand)")
fs.StringVar(&cfg.format, "format", "text", "Output format: text|terminal|json")
fs.StringVar(&cfg.format, "f", "text", "Output format (shorthand)")
fs.StringVar(&cfg.severity, "severity", "all", "Minimum severity level to trigger check failure (info, warning, high, critical)")
Expand Down Expand Up @@ -46,8 +49,15 @@ func runCheckCommand(args []string, stdout, stderr io.Writer, scannerInstance *s
return ExitCodeUsageError
}

// Load configuration
appConfig, _, err := config.DiscoverAndLoad(cfg.path, cfg.configPath)
if err != nil {
fmt.Fprintf(stderr, "Error: %v\n", err)
return ExitCodeUsageError
}

if scannerInstance == nil {
scannerInstance = scanner.DefaultScanner
scannerInstance = scanner.NewWithConfig(nil, nil, appConfig)
}

result, err := scannerInstance.Scan(cfg.path)
Expand Down
75 changes: 75 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,78 @@ func TestCLICheckCommand(t *testing.T) {
}
})
}

func TestCLIConfigFileIntegration(t *testing.T) {
t.Run("auto-discovered .envguard.yaml with allowlist", func(t *testing.T) {
tmpDir := t.TempDir()

// Write .envguard.yaml allowing .env.custom
configContent := `
detector:
allowlist:
- ".env.custom"
`
if err := os.WriteFile(filepath.Join(tmpDir, ".envguard.yaml"), []byte(configContent), 0644); err != nil {
t.Fatal(err)
}

// Write .env.custom (which would normally fail without config)
if err := os.WriteFile(filepath.Join(tmpDir, ".env.custom"), []byte("CUSTOM=1"), 0644); err != nil {
t.Fatal(err)
}

var stdout, stderr bytes.Buffer
code := cli.Run([]string{"scan", "--path", tmpDir, "--no-color"}, &stdout, &stderr)

if code != cli.ExitCodeSuccess {
t.Fatalf("expected exit code %d (PASSED due to allowlist in .envguard.yaml), got %d. stderr: %s", cli.ExitCodeSuccess, code, stderr.String())
}
if !strings.Contains(stdout.String(), "PASSED") {
t.Fatalf("expected PASSED in output, got: %s", stdout.String())
}
})

t.Run("explicit --config flag", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "custom-rules.yaml")

configContent := `
detector:
custom_patterns:
- "*.env.vault"
`
if err := os.WriteFile(configFile, []byte(configContent), 0644); err != nil {
t.Fatal(err)
}

if err := os.WriteFile(filepath.Join(tmpDir, "app.env.vault"), []byte("SECRET=1"), 0644); err != nil {
t.Fatal(err)
}

var stdout, stderr bytes.Buffer
code := cli.Run([]string{"check", "--path", tmpDir, "--config", configFile, "--no-color"}, &stdout, &stderr)

if code != cli.ExitCodeFindingsFound {
t.Fatalf("expected exit code %d (FINDINGS due to custom pattern), got %d", cli.ExitCodeFindingsFound, code)
}
if !strings.Contains(stdout.String(), "app.env.vault") {
t.Fatalf("expected app.env.vault in output, got: %s", stdout.String())
}
})

t.Run("invalid config file returns UsageError", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "bad.yaml")
_ = os.WriteFile(configFile, []byte("scanner: [invalid"), 0644)

var stdout, stderr bytes.Buffer
code := cli.Run([]string{"scan", "--path", tmpDir, "--config", configFile}, &stdout, &stderr)

if code != cli.ExitCodeUsageError {
t.Fatalf("expected exit code %d for invalid config file, got %d", cli.ExitCodeUsageError, code)
}
if !strings.Contains(stderr.String(), "Error:") {
t.Fatalf("expected error message in stderr, got: %s", stderr.String())
}
})
}
21 changes: 16 additions & 5 deletions internal/cli/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@ import (
"io"
"strings"

"github.com/joaooncode/envguard/internal/config"
"github.com/joaooncode/envguard/internal/reporter"
"github.com/joaooncode/envguard/internal/scanner"
)

// scanConfig holds the parsed options for scan/check commands.
type scanConfig struct {
path string
format string
severity string
noColor bool
path string
configPath string
format string
severity string
noColor bool
}

func parseSeverity(s string) (scanner.Severity, bool) {
Expand Down Expand Up @@ -57,6 +59,8 @@ func runScanCommand(args []string, stdout, stderr io.Writer, scannerInstance *sc
var cfg scanConfig
fs.StringVar(&cfg.path, "path", ".", "Target directory path to scan")
fs.StringVar(&cfg.path, "p", ".", "Target directory path to scan (shorthand)")
fs.StringVar(&cfg.configPath, "config", "", "Path to custom configuration file")
fs.StringVar(&cfg.configPath, "c", "", "Path to custom configuration file (shorthand)")
fs.StringVar(&cfg.format, "format", "text", "Output format: text|terminal|json")
fs.StringVar(&cfg.format, "f", "text", "Output format (shorthand)")
fs.StringVar(&cfg.severity, "severity", "all", "Minimum severity level to report (info, warning, high, critical)")
Expand Down Expand Up @@ -86,8 +90,15 @@ func runScanCommand(args []string, stdout, stderr io.Writer, scannerInstance *sc
return ExitCodeUsageError
}

// Load configuration
appConfig, _, err := config.DiscoverAndLoad(cfg.path, cfg.configPath)
if err != nil {
fmt.Fprintf(stderr, "Error: %v\n", err)
return ExitCodeUsageError
}

if scannerInstance == nil {
scannerInstance = scanner.DefaultScanner
scannerInstance = scanner.NewWithConfig(nil, nil, appConfig)
}

result, err := scannerInstance.Scan(cfg.path)
Expand Down
Loading
Loading