diff --git a/.dockerignore b/.dockerignore index 046c390..7f71795 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,7 @@ # Binary argus +bin/ +dist/ # Git .git diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..30cd053 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + ci: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Install toolchain from mise.toml + uses: jdx/mise-action@v4 + with: + cache: true + + - uses: actions/cache@v6 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: ${{ runner.os }}-go- + + - name: Run CI pipeline + run: task ci diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index 5a8b897..ae5ce38 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -17,7 +17,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Set up QEMU uses: docker/setup-qemu-action@v3 @@ -34,7 +34,7 @@ jobs: - name: Get short SHA id: sha - run: echo "short=${GITHUB_SHA::7}" >> $GITHUB_OUTPUT + run: echo "short=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT" - name: Extract Docker metadata id: meta @@ -42,7 +42,7 @@ jobs: with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | - type=raw,value=latest + type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }} type=sha,prefix= type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000..41b8000 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,100 @@ +name: Nightly + +on: + schedule: + - cron: '0 6 * * *' + workflow_dispatch: + +permissions: + contents: write + actions: write + +jobs: + nightly: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Check for new commits + id: check + run: | + LATEST_NIGHTLY=$(git tag -l 'v*-nightly.*' --sort=-v:refname | head -1) + if [ -z "$LATEST_NIGHTLY" ]; then + echo "No previous nightly tag found, proceeding" + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + COMMITS_SINCE=$(git rev-list "${LATEST_NIGHTLY}..HEAD" --count) + if [ "$COMMITS_SINCE" -gt 0 ]; then + echo "Found $COMMITS_SINCE new commits since $LATEST_NIGHTLY" + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + echo "No new commits since $LATEST_NIGHTLY, skipping" + echo "has_changes=false" >> "$GITHUB_OUTPUT" + fi + fi + + - name: Compute next patch version + if: steps.check.outputs.has_changes == 'true' + id: version + run: | + # The manifest holds the last released version. A nightly must sort + # above it under semver, so tag the next patch: 0.15.0 -> v0.15.1-nightly.. + RELEASED=$(jq -r '.["."]' .release-please-manifest.json) + IFS=. read -r MAJOR MINOR PATCH <<< "$RELEASED" + echo "version=${MAJOR}.${MINOR}.$((PATCH + 1))" >> "$GITHUB_OUTPUT" + + - name: Create nightly tag + if: steps.check.outputs.has_changes == 'true' + run: | + DATE=$(date -u +%Y%m%d) + TAG="v${{ steps.version.outputs.version }}-nightly.${DATE}" + echo "Creating tag: $TAG" + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git tag -a "$TAG" -m "Nightly build $DATE" + git push origin "$TAG" + gh workflow run prerelease.yml --ref "$TAG" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + cleanup: + runs-on: ubuntu-latest + steps: + - name: Delete old nightly releases + uses: actions/github-script@v9 + with: + script: | + const cutoff = new Date(); + cutoff.setDate(cutoff.getDate() - 7); + + const releases = await github.rest.repos.listReleases({ + owner: context.repo.owner, + repo: context.repo.repo, + per_page: 100, + }); + + for (const release of releases.data) { + if (!release.tag_name.includes('-nightly.')) continue; + if (new Date(release.created_at) >= cutoff) continue; + + console.log(`Deleting old nightly release: ${release.tag_name}`); + + await github.rest.repos.deleteRelease({ + owner: context.repo.owner, + repo: context.repo.repo, + release_id: release.id, + }); + + try { + await github.rest.git.deleteRef({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: `tags/${release.tag_name}`, + }); + } catch (e) { + console.log(`Tag ${release.tag_name} already deleted or not found`); + } + } diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 403e13d..ec305d0 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -6,6 +6,8 @@ on: - 'v*-rc*' - 'v*-beta*' - 'v*-alpha*' + - 'v*-nightly*' + workflow_dispatch: permissions: contents: write @@ -15,17 +17,24 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 - - name: Set up Go - uses: actions/setup-go@v5 + - uses: jdx/mise-action@v4 with: - go-version-file: go.mod + cache: true + + - uses: actions/cache@v6 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: ${{ runner.os }}-go- - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 + uses: goreleaser/goreleaser-action@v7 with: distribution: goreleaser version: "~> v2" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 75a41a2..e7ee16b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} steps: - - uses: googleapis/release-please-action@v4 + - uses: googleapis/release-please-action@v5 id: release with: token: ${{ secrets.GITHUB_TOKEN }} @@ -28,18 +28,25 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 ref: ${{ needs.release-please.outputs.tag_name }} - - name: Set up Go - uses: actions/setup-go@v5 + - uses: jdx/mise-action@v4 with: - go-version-file: go.mod + cache: true + + - uses: actions/cache@v6 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: ${{ runner.os }}-go- - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 + uses: goreleaser/goreleaser-action@v7 with: distribution: goreleaser version: "~> v2" diff --git a/.gitignore b/.gitignore index e8ed6e0..10c90e8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ # Compiled binary argus +bin/ +dist/ +.task/ # Environment files (contain secrets) .env diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 8c35871..2d15897 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -27,6 +27,9 @@ archives: - tar.gz name_template: >- {{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }} + files: + - README.md + - LICENSE* checksum: name_template: 'checksums.txt' @@ -58,11 +61,12 @@ changelog: - '^chore' - '^docs' - '^test' + - '^ci' - '^Merge' release: github: - owner: SentioLabs + owner: sentiolabs name: argus draft: false prerelease: auto diff --git a/Dockerfile b/Dockerfile index 965e43d..d592371 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build stage - runs on native platform for fast cross-compilation -FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS builder +FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS builder ARG TARGETARCH ARG VERSION=dev diff --git a/Makefile b/Makefile deleted file mode 100644 index 6c2b091..0000000 --- a/Makefile +++ /dev/null @@ -1,68 +0,0 @@ -.PHONY: help build run test lint clean release-snapshot - -BINARY_NAME := argus -VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev") -COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo "none") -BUILD_DATE := $(shell date -u '+%Y-%m-%dT%H:%M:%SZ') -LDFLAGS := -s -w \ - -X github.com/sentiolabs/argus/cmd.Version=$(VERSION) \ - -X github.com/sentiolabs/argus/cmd.Commit=$(COMMIT) \ - -X github.com/sentiolabs/argus/cmd.BuildDate=$(BUILD_DATE) - -## help: Show this help message -help: - @echo "Usage: make [target]" - @echo "" - @echo "Targets:" - @sed -n 's/^## //p' $(MAKEFILE_LIST) | column -t -s ':' - -## build: Build the argus binary -build: - go build -ldflags="$(LDFLAGS)" -o $(BINARY_NAME) . - -## run: Run argus sync in dry-run mode -run: build - ./$(BINARY_NAME) sync --dry-run - -## test: Run all tests -test: - go test ./... - -## test-verbose: Run all tests with verbose output -test-verbose: - go test -v ./... - -## test-coverage: Run tests with coverage report -test-coverage: - go test -coverprofile=coverage.out ./... - go tool cover -html=coverage.out -o coverage.html - @echo "Coverage report: coverage.html" - -## lint: Run golangci-lint -lint: - golangci-lint run - -## lint-fix: Run golangci-lint with auto-fix -lint-fix: - golangci-lint run --fix - -## clean: Remove build artifacts -clean: - rm -f $(BINARY_NAME) - rm -f coverage.out coverage.html - -## verify: Validate config and check environment -verify: build - ./$(BINARY_NAME) config validate - -## version: Show version information -version: build - ./$(BINARY_NAME) version - -## install: Install argus via go install with version info -install: - go install -ldflags="$(LDFLAGS)" . - -## release-snapshot: Build release snapshot locally (no tag required) -release-snapshot: - goreleaser release --snapshot --clean diff --git a/README.md b/README.md index 40e822d..7947c25 100644 --- a/README.md +++ b/README.md @@ -40,12 +40,32 @@ go install github.com/sentiolabs/argus@latest ### Build from source +Tool versions are pinned in `mise.toml`. Install [mise](https://mise.jdx.dev) once, then: + ```bash git clone https://github.com/sentiolabs/argus.git cd argus -make build +mise install +task build +./bin/argus version +``` + +Run `task` with no arguments to list every task, including `test`, `lint`, and `ci`. + +### Updating + +A binary installed with the quick-install script or built from a release can update itself: + +```bash +argus self update # install the newest release on your channel +argus self update --check # report whether an update is available, install nothing +argus self channel # show the current channel (stable by default) +argus self channel rc # follow release candidates +argus self channel nightly # follow nightly builds from main ``` +The update downloads the release archive for your OS and architecture, verifies it against the release's `checksums.txt`, and replaces the running binary in place. Binaries managed by Homebrew, Nix, or a system package manager are refused with a hint to use that manager's upgrade command instead. + ### Docker ```bash diff --git a/Taskfile.yml b/Taskfile.yml new file mode 100644 index 0000000..02be547 --- /dev/null +++ b/Taskfile.yml @@ -0,0 +1,122 @@ +version: '3' + +vars: + BIN_DIR: ./bin + CLI_BIN: '{{.BIN_DIR}}/argus' + GO: go + MODULE: github.com/sentiolabs/argus + VERSION: + sh: git describe --tags --always --dirty 2>/dev/null || echo dev + COMMIT: + sh: git rev-parse --short HEAD 2>/dev/null || echo none + BUILD_DATE: + sh: date -u '+%Y-%m-%dT%H:%M:%SZ' + LDFLAGS: >- + -s -w + -X {{.MODULE}}/cmd.Version={{.VERSION}} + -X {{.MODULE}}/cmd.Commit={{.COMMIT}} + -X {{.MODULE}}/cmd.BuildDate={{.BUILD_DATE}} + +tasks: + default: + desc: Show available tasks + cmds: + - task --list + silent: true + + build: + desc: Build the argus binary into ./bin + cmds: + - mkdir -p {{.BIN_DIR}} + - '{{.GO}} build -ldflags="{{.LDFLAGS}}" -o {{.CLI_BIN}} .' + + run: + desc: Build and run argus sync in dry-run mode + cmds: + - task: build + - '{{.CLI_BIN}} sync --dry-run' + + test: + desc: Run unit tests with race detection and coverage + cmds: + - '{{.GO}} test -race -cover ./...' + + test:verbose: + desc: Run unit tests with verbose output + cmds: + - '{{.GO}} test -race -cover -v ./...' + + test:coverage: + desc: Run unit tests and write an HTML coverage report + cmds: + - '{{.GO}} test -race -coverprofile=coverage.out ./...' + - '{{.GO}} tool cover -html=coverage.out -o coverage.html' + - 'echo "Coverage report: coverage.html"' + + lint: + desc: Run golangci-lint + cmds: + - golangci-lint run + + lint:fix: + desc: Run golangci-lint with auto-fix + cmds: + - golangci-lint run --fix + + fmt: + desc: Format Go sources + cmds: + - '{{.GO}} fmt ./...' + + release:snapshot: + desc: Build a release snapshot locally with goreleaser (no tag required) + cmds: + - goreleaser release --snapshot --clean + + check:versions: + desc: Assert mise.toml and go.mod agree on the Go version + silent: true + cmds: + - cmd: | + mise_go="$(grep -E '^go[[:space:]]*=' mise.toml | head -1 | sed -E 's/.*"([^"]+)".*/\1/')" + mod_go="$(grep -E '^go ' go.mod | head -1 | awk '{print $2}')" + if [ -z "$mise_go" ] || [ -z "$mod_go" ]; then + echo "ERROR: could not read Go version (mise.toml='$mise_go' go.mod='$mod_go')" >&2 + exit 1 + fi + if [ "$mise_go" != "$mod_go" ]; then + echo "ERROR: Go version mismatch: mise.toml=$mise_go, go.mod=$mod_go" >&2 + echo "Update mise.toml to match go.mod." >&2 + exit 1 + fi + echo "Go version aligned: $mod_go" + + verify: + desc: Build, then validate the argus config + cmds: + - task: build + - '{{.CLI_BIN}} config validate' + + version: + desc: Build, then print version information + cmds: + - task: build + - '{{.CLI_BIN}} version' + + install: + desc: Install argus into GOPATH/bin with version ldflags + cmds: + - '{{.GO}} install -ldflags="{{.LDFLAGS}}" .' + + clean: + desc: Remove build artifacts and coverage reports + cmds: + - rm -rf {{.BIN_DIR}} dist + - rm -f coverage.out coverage.html + + ci: + desc: Run the local CI pipeline (version guard, tests, lint) + cmds: + - task: check:versions + - task: test + - task: lint diff --git a/cmd/cache.go b/cmd/cache.go index 2043760..89f879f 100644 --- a/cmd/cache.go +++ b/cmd/cache.go @@ -99,12 +99,12 @@ func runCacheStatus(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get total count: %w", err) } - providers, err := store.GetMeta(projectKey, "providers") + providers, err := store.GetMeta(cmd.Context(), projectKey, "providers") if err != nil { return fmt.Errorf("failed to get providers metadata: %w", err) } - fetchedAt, err := store.GetMeta(projectKey, "fetched_at") + fetchedAt, err := store.GetMeta(cmd.Context(), projectKey, "fetched_at") if err != nil { return fmt.Errorf("failed to get fetched_at metadata: %w", err) } diff --git a/cmd/search.go b/cmd/search.go index de8c6d8..7592866 100644 --- a/cmd/search.go +++ b/cmd/search.go @@ -68,7 +68,7 @@ func runSearch(cmd *cobra.Command, args []string) error { if err != nil { return fmt.Errorf("failed to create cache manager: %w", err) } - defer mgr.Close() + defer func() { _ = mgr.Close() }() // If --refresh flag OR cache not valid: load config and refresh if searchRefresh || !mgr.IsValid() { @@ -119,7 +119,8 @@ func runSearch(cmd *cobra.Command, args []string) error { // Convert to search-specific output rows rows := make([]output.SearchResultRow, len(results)) - for i, r := range results { + for i := range results { + r := &results[i] rows[i] = output.SearchResultRow{ Provider: r.Provider, Severity: r.Severity, diff --git a/cmd/self.go b/cmd/self.go new file mode 100644 index 0000000..6719471 --- /dev/null +++ b/cmd/self.go @@ -0,0 +1,44 @@ +package cmd + +import ( + "github.com/sentiolabs/selfupdate-go" + "github.com/sentiolabs/selfupdate-go/cobracmd" + + "github.com/sentiolabs/argus/internal/update" +) + +// selfCmd is the go-selfupdate command tree: `argus self update` and +// `argus self channel`. The -c shorthand for --check is free on the root +// command (--config has no shorthand, -v is verbose). +var selfCmd = cobracmd.New(newSelfUpdater(), cobracmd.WithCheckShorthand("c")) + +func init() { + rootCmd.AddCommand(selfCmd) +} + +// newSelfUpdater wires GitHub releases of sentiolabs/argus to the zero-value +// ArchiveInstaller, whose defaults match .goreleaser.yaml: the archive is +// argus___.tar.gz and checksums.txt is sha256. Version is +// the ldflags value from version.go: "0.7.0", "0.7.0-rc.1", or "dev". No +// hooks: argus has no daemon to stop and nothing to back up around the swap. +func newSelfUpdater() *selfupdate.Updater { + return &selfupdate.Updater{ + Name: "argus", + Version: Version, + Source: &selfupdate.GitHubSource{Owner: "sentiolabs", Repo: "argus"}, + Store: channelStore(), + Installer: &selfupdate.ArchiveInstaller{}, + } +} + +// channelStore returns a FileStore at update.DefaultPath(). When the user +// config directory cannot be resolved (no HOME or XDG_CONFIG_HOME), Path is +// left empty: `self update` reads stable and `self channel ` fails +// with update.ErrNoPath instead of pretending to persist. +func channelStore() selfupdate.Store { + path, err := update.DefaultPath() + if err != nil { + return update.FileStore{} + } + return update.FileStore{Path: path} +} diff --git a/cmd/self_test.go b/cmd/self_test.go new file mode 100644 index 0000000..182879b --- /dev/null +++ b/cmd/self_test.go @@ -0,0 +1,66 @@ +package cmd + +import ( + "bytes" + "testing" + + "github.com/sentiolabs/selfupdate-go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/sentiolabs/argus/internal/update" +) + +func TestNewSelfUpdater(t *testing.T) { + u := newSelfUpdater() + assert.Equal(t, "argus", u.Name) + assert.Equal(t, Version, u.Version) + + src, ok := u.Source.(*selfupdate.GitHubSource) + require.True(t, ok, "Source should be *selfupdate.GitHubSource, got %T", u.Source) + assert.Equal(t, "sentiolabs", src.Owner) + assert.Equal(t, "argus", src.Repo) + + assert.IsType(t, &selfupdate.ArchiveInstaller{}, u.Installer) + assert.IsType(t, update.FileStore{}, u.Store) + assert.Nil(t, u.PreInstall, "argus has no daemon to stop; no PreInstall hook") + assert.Nil(t, u.PostInstall, "argus has no daemon to start; no PostInstall hook") +} + +func TestChannelStore_UsesDefaultPath(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + + s, ok := channelStore().(update.FileStore) + require.True(t, ok, "channelStore should return update.FileStore, got %T", channelStore()) + want, err := update.DefaultPath() + require.NoError(t, err) + assert.Equal(t, want, s.Path) + assert.NotEmpty(t, s.Path) +} + +func TestSelfHelpListsSubcommands(t *testing.T) { + var out bytes.Buffer + rootCmd.SetOut(&out) + rootCmd.SetErr(&out) + rootCmd.SetArgs([]string{"self", "--help"}) + t.Cleanup(func() { + rootCmd.SetOut(nil) + rootCmd.SetErr(nil) + rootCmd.SetArgs(nil) + }) + + require.NoError(t, rootCmd.Execute()) + help := out.String() + assert.Contains(t, help, "update") + assert.Contains(t, help, "channel") + assert.Contains(t, help, "Manage the argus CLI itself") +} + +func TestSelfUpdateHasCheckShorthand(t *testing.T) { + updateCmd, _, err := rootCmd.Find([]string{"self", "update"}) + require.NoError(t, err) + f := updateCmd.Flags().Lookup("check") + require.NotNil(t, f, "self update should define --check") + assert.Equal(t, "c", f.Shorthand) +} diff --git a/go.mod b/go.mod index 5dedb0d..eeac2e0 100644 --- a/go.mod +++ b/go.mod @@ -1,12 +1,13 @@ module github.com/sentiolabs/argus -go 1.25.5 +go 1.27.1 require ( github.com/andygrunwald/go-jira/v2 v2.0.0-20250914065312-05fb5bc92aec github.com/google/go-github/v57 v57.0.0 github.com/mitchellh/mapstructure v1.5.0 github.com/olekukonko/tablewriter v1.1.2 + github.com/sentiolabs/selfupdate-go v0.2.0-rc.1 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 @@ -46,6 +47,7 @@ require ( github.com/subosito/gotenv v1.6.0 // indirect github.com/trivago/tgo v1.0.7 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/mod v0.33.0 // indirect golang.org/x/sys v0.42.0 // indirect golang.org/x/text v0.28.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index ccbbfd2..e4581b0 100644 --- a/go.sum +++ b/go.sum @@ -72,6 +72,8 @@ github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/f github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/sentiolabs/selfupdate-go v0.2.0-rc.1 h1:TxUE3CywQe0/NH8vR+wbXhyWwaINi8Ek7FdfrMi31rw= +github.com/sentiolabs/selfupdate-go v0.2.0-rc.1/go.mod h1:j9hPo8QlYVPi8WSpOhh7XdtRhYWMIKdayyp26iNf/1Y= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= diff --git a/internal/cache/cache.go b/internal/cache/cache.go index 3e0db67..2bac0eb 100644 --- a/internal/cache/cache.go +++ b/internal/cache/cache.go @@ -1,3 +1,5 @@ +// Package cache stores fetched vulnerabilities in a local SQLite database +// so repeated searches do not hit the providers again. package cache import ( @@ -14,6 +16,7 @@ import ( "github.com/sentiolabs/argus/internal/provider" ) +// DefaultTTL is how long a cached fetch stays valid before search refreshes it. const DefaultTTL = 24 * time.Hour // Manager handles cache lifecycle for a project. @@ -34,7 +37,7 @@ func NewManager(ttl time.Duration, verbose bool) (*Manager, error) { dbPath := DBPath() // Ensure parent directory exists - if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(dbPath), 0o750); err != nil { return nil, fmt.Errorf("failed to create cache directory: %w", err) } @@ -71,7 +74,7 @@ func (m *Manager) Close() error { // IsValid checks if the current project's cache exists and is within TTL. func (m *Manager) IsValid() bool { - fetchedAt, err := m.store.GetMeta(m.projectKey, "fetched_at") + fetchedAt, err := m.store.GetMeta(context.Background(), m.projectKey, "fetched_at") if err != nil || fetchedAt == "" { return false } @@ -156,8 +159,8 @@ func (m *Manager) Refresh(ctx context.Context, cfg *config.Config, providerScope // enabledProviders returns the list of provider names to fetch from. func enabledProviders(cfg *config.Config, scope string) []string { var names []string - for name, p := range cfg.Providers { - if !p.Enabled { + for name := range cfg.Providers { + if !cfg.Providers[name].Enabled { continue } if scope == "all" || scope == name { diff --git a/internal/cache/store.go b/internal/cache/store.go index b056204..dd31e52 100644 --- a/internal/cache/store.go +++ b/internal/cache/store.go @@ -3,6 +3,7 @@ package cache import ( "context" "database/sql" + "errors" "fmt" "strings" "time" @@ -10,7 +11,7 @@ import ( "github.com/sentiolabs/argus/internal/provider" "github.com/sentiolabs/argus/internal/search" - _ "modernc.org/sqlite" + _ "modernc.org/sqlite" // registers the "sqlite" database/sql driver ) // Store wraps a SQLite database connection for vulnerability caching. @@ -34,15 +35,15 @@ func Open(dsn string) (*Store, error) { } // Enable WAL mode for better concurrent read performance - if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil { - db.Close() + if _, err := db.ExecContext(context.Background(), "PRAGMA journal_mode=WAL"); err != nil { + _ = db.Close() return nil, fmt.Errorf("set WAL mode: %w", err) } s := &Store{db: db} if err := s.initSchema(); err != nil { - db.Close() + _ = db.Close() return nil, fmt.Errorf("init schema: %w", err) } @@ -90,7 +91,7 @@ func (s *Store) initSchema() error { } for _, stmt := range stmts { - if _, err := s.db.Exec(stmt); err != nil { + if _, err := s.db.ExecContext(context.Background(), stmt); err != nil { return fmt.Errorf("schema exec: %w\nSQL: %s", err, stmt) } } @@ -131,15 +132,16 @@ func (s *Store) WriteVulnerabilities(ctx context.Context, projectKey string, vul if err != nil { return fmt.Errorf("prepare insert: %w", err) } - defer insertVuln.Close() + defer func() { _ = insertVuln.Close() }() insertFTS, err := tx.PrepareContext(ctx, `INSERT INTO vuln_fts (rowid, content) VALUES (?, ?)`) if err != nil { return fmt.Errorf("prepare fts insert: %w", err) } - defer insertFTS.Close() + defer func() { _ = insertFTS.Close() }() - for _, v := range vulns { + for i := range vulns { + v := &vulns[i] var discoveredAt *string if !v.DiscoveredAt.IsZero() { s := v.DiscoveredAt.Format(time.RFC3339) @@ -303,7 +305,7 @@ func (s *Store) queryResults(ctx context.Context, query string, args []interface if err != nil { return nil, fmt.Errorf("search query: %w", err) } - defer rows.Close() + defer func() { _ = rows.Close() }() var results []SearchResult for rows.Next() { @@ -342,6 +344,14 @@ func (s *Store) queryResults(ctx context.Context, query string, args []interface return results, rows.Err() } +// getByIDQueryTmpl is the GetByID query with a %s placeholder for the WHERE clause. +const getByIDQueryTmpl = ` + SELECT project_key, id, cve, severity, cvss, package, version, fixed_version, + repository, description, url, discovered_at, provider + FROM vulnerabilities + WHERE %s + LIMIT 1` + // GetByID fetches a single vulnerability by ID or CVE, with optional project filter. // Returns nil, nil if not found. func (s *Store) GetByID(ctx context.Context, projectKey string, id string) (*provider.Vulnerability, error) { @@ -357,12 +367,7 @@ func (s *Store) GetByID(ctx context.Context, projectKey string, id string) (*pro args = append(args, projectKey) } - querySQL := fmt.Sprintf(` - SELECT project_key, id, cve, severity, cvss, package, version, fixed_version, - repository, description, url, discovered_at, provider - FROM vulnerabilities - WHERE %s - LIMIT 1`, strings.Join(where, " AND ")) + querySQL := fmt.Sprintf(getByIDQueryTmpl, strings.Join(where, " AND ")) //nolint:gosec // where holds fixed column predicates; values are bound with ? row := s.db.QueryRowContext(ctx, querySQL, args...) @@ -432,10 +437,10 @@ func (s *Store) Clear(ctx context.Context, projectKey string) error { } // GetMeta returns a metadata value for a project key+name. Returns "" if not found. -func (s *Store) GetMeta(projectKey, key string) (string, error) { - row := s.db.QueryRow(`SELECT value FROM cache_meta WHERE project_key = ? AND meta_key = ? LIMIT 1`, projectKey, key) +func (s *Store) GetMeta(ctx context.Context, projectKey, key string) (string, error) { + row := s.db.QueryRowContext(ctx, `SELECT value FROM cache_meta WHERE project_key = ? AND meta_key = ? LIMIT 1`, projectKey, key) var val string - if err := row.Scan(&val); err == sql.ErrNoRows { + if err := row.Scan(&val); errors.Is(err, sql.ErrNoRows) { return "", nil } else if err != nil { return "", fmt.Errorf("get meta %s/%s: %w", projectKey, key, err) @@ -444,11 +449,11 @@ func (s *Store) GetMeta(projectKey, key string) (string, error) { } // SetMeta sets a metadata value for a project key+name (upsert via delete-then-insert). -func (s *Store) SetMeta(projectKey, key, value string) error { - if _, err := s.db.Exec(`DELETE FROM cache_meta WHERE project_key = ? AND meta_key = ?`, projectKey, key); err != nil { +func (s *Store) SetMeta(ctx context.Context, projectKey, key, value string) error { + if _, err := s.db.ExecContext(ctx, `DELETE FROM cache_meta WHERE project_key = ? AND meta_key = ?`, projectKey, key); err != nil { return fmt.Errorf("delete meta %s/%s: %w", projectKey, key, err) } - if _, err := s.db.Exec(`INSERT INTO cache_meta (project_key, meta_key, value) VALUES (?, ?, ?)`, projectKey, key, value); err != nil { + if _, err := s.db.ExecContext(ctx, `INSERT INTO cache_meta (project_key, meta_key, value) VALUES (?, ?, ?)`, projectKey, key, value); err != nil { return fmt.Errorf("insert meta %s/%s: %w", projectKey, key, err) } return nil diff --git a/internal/cache/store_test.go b/internal/cache/store_test.go index d594fa1..f6e4c5f 100644 --- a/internal/cache/store_test.go +++ b/internal/cache/store_test.go @@ -5,10 +5,11 @@ import ( "testing" "time" - "github.com/sentiolabs/argus/internal/provider" - "github.com/sentiolabs/argus/internal/search" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/sentiolabs/argus/internal/provider" + "github.com/sentiolabs/argus/internal/search" ) func testVulns() []provider.Vulnerability { @@ -211,25 +212,26 @@ func TestStore_WriteReplacesExistingProvider(t *testing.T) { func TestStore_Meta(t *testing.T) { s := openTestStore(t) + ctx := context.Background() // Set and get - err := s.SetMeta("proj1", "fetched_at", "2026-04-08T00:00:00Z") + err := s.SetMeta(ctx, "proj1", "fetched_at", "2026-04-08T00:00:00Z") require.NoError(t, err) - val, err := s.GetMeta("proj1", "fetched_at") + val, err := s.GetMeta(ctx, "proj1", "fetched_at") require.NoError(t, err) assert.Equal(t, "2026-04-08T00:00:00Z", val) // Overwrite - err = s.SetMeta("proj1", "fetched_at", "2026-04-09T00:00:00Z") + err = s.SetMeta(ctx, "proj1", "fetched_at", "2026-04-09T00:00:00Z") require.NoError(t, err) - val, err = s.GetMeta("proj1", "fetched_at") + val, err = s.GetMeta(ctx, "proj1", "fetched_at") require.NoError(t, err) assert.Equal(t, "2026-04-09T00:00:00Z", val) // Cross-project isolation - val2, err := s.GetMeta("proj2", "fetched_at") + val2, err := s.GetMeta(ctx, "proj2", "fetched_at") require.NoError(t, err) assert.Equal(t, "", val2, "proj2 should not have proj1's meta") } diff --git a/internal/output/output.go b/internal/output/output.go index 588597c..464b958 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -270,7 +270,7 @@ func FormatDetail(d VulnDetail) string { // PrintDetail outputs a detailed vulnerability view in the specified format. func PrintDetail(d VulnDetail, format string) error { - if strings.ToLower(format) == "json" { + if strings.EqualFold(format, "json") { encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") return encoder.Encode(d) diff --git a/internal/search/search.go b/internal/search/search.go index a9fc5db..08064a9 100644 --- a/internal/search/search.go +++ b/internal/search/search.go @@ -1,3 +1,5 @@ +// Package search parses free-text queries with field filters +// (severity:critical package:rack) into structured search terms. package search import ( diff --git a/internal/search/search_test.go b/internal/search/search_test.go index 75901f5..b56f7d4 100644 --- a/internal/search/search_test.go +++ b/internal/search/search_test.go @@ -57,51 +57,51 @@ func TestParse_BareWords(t *testing.T) { func TestParse_FieldFilters(t *testing.T) { tests := []struct { - name string - input string - wantFilters map[string]string + name string + input string + wantFilters map[string]string wantSemantic string }{ { - name: "severity filter", - input: "severity:critical", - wantFilters: map[string]string{"severity": "critical"}, + name: "severity filter", + input: "severity:critical", + wantFilters: map[string]string{"severity": "critical"}, wantSemantic: "", }, { - name: "package filter", - input: "package:lodash", - wantFilters: map[string]string{"package": "lodash"}, + name: "package filter", + input: "package:lodash", + wantFilters: map[string]string{"package": "lodash"}, wantSemantic: "", }, { - name: "repo alias maps to repository", - input: "repo:my-repo", - wantFilters: map[string]string{"repository": "my-repo"}, + name: "repo alias maps to repository", + input: "repo:my-repo", + wantFilters: map[string]string{"repository": "my-repo"}, wantSemantic: "", }, { - name: "repository long form", - input: "repository:my-org/my-repo", - wantFilters: map[string]string{"repository": "my-org/my-repo"}, + name: "repository long form", + input: "repository:my-org/my-repo", + wantFilters: map[string]string{"repository": "my-org/my-repo"}, wantSemantic: "", }, { - name: "provider filter", - input: "provider:github", - wantFilters: map[string]string{"provider": "github"}, + name: "provider filter", + input: "provider:github", + wantFilters: map[string]string{"provider": "github"}, wantSemantic: "", }, { - name: "cve filter", - input: "cve:CVE-2023-1234", - wantFilters: map[string]string{"cve": "CVE-2023-1234"}, + name: "cve filter", + input: "cve:CVE-2023-1234", + wantFilters: map[string]string{"cve": "CVE-2023-1234"}, wantSemantic: "", }, { - name: "id filter", - input: "id:SNYK-JS-LODASH-1234", - wantFilters: map[string]string{"id": "SNYK-JS-LODASH-1234"}, + name: "id filter", + input: "id:SNYK-JS-LODASH-1234", + wantFilters: map[string]string{"id": "SNYK-JS-LODASH-1234"}, wantSemantic: "", }, { @@ -114,9 +114,9 @@ func TestParse_FieldFilters(t *testing.T) { wantSemantic: "", }, { - name: "unrecognized prefix treated as bare word", - input: "unknown:value", - wantFilters: map[string]string{}, + name: "unrecognized prefix treated as bare word", + input: "unknown:value", + wantFilters: map[string]string{}, wantSemantic: "unknown:value", }, } diff --git a/internal/update/store.go b/internal/update/store.go new file mode 100644 index 0000000..ac968b2 --- /dev/null +++ b/internal/update/store.go @@ -0,0 +1,67 @@ +// Package update persists the self-update release channel for the argus CLI. +package update + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/sentiolabs/selfupdate-go" +) + +// ErrNoPath is returned by SetChannel when Path is empty. +var ErrNoPath = errors.New("update: no channel file path (is HOME set?)") + +const ( + dirMode = 0o700 + fileMode = 0o600 +) + +// FileStore keeps the channel as the trimmed contents of a single file. +// A missing file, or an empty Path, reads as the empty channel, which the +// updater treats as stable. Writes need a Path. +type FileStore struct{ Path string } + +// DefaultPath returns /argus/update-channel. +func DefaultPath() (string, error) { + dir, err := os.UserConfigDir() + if err != nil { + return "", fmt.Errorf("resolve user config dir: %w", err) + } + return filepath.Join(dir, "argus", "update-channel"), nil +} + +// Channel reads Path. An empty Path or a missing file yields "" and a nil +// error. Any other read error is wrapped and returned. +func (s FileStore) Channel() (selfupdate.Channel, error) { + if s.Path == "" { + return "", nil + } + data, err := os.ReadFile(s.Path) //nolint:gosec // Path comes from os.UserConfigDir, not user input + if errors.Is(err, fs.ErrNotExist) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("read update channel %s: %w", s.Path, err) + } + return selfupdate.Channel(strings.TrimSpace(string(data))), nil +} + +// SetChannel returns ErrNoPath when Path is empty. Otherwise it creates the +// parent directory with mode 0o700 when missing and writes c to Path with +// mode 0o600. +func (s FileStore) SetChannel(c selfupdate.Channel) error { + if s.Path == "" { + return ErrNoPath + } + if err := os.MkdirAll(filepath.Dir(s.Path), dirMode); err != nil { + return fmt.Errorf("create update channel dir: %w", err) + } + if err := os.WriteFile(s.Path, []byte(string(c)+"\n"), fileMode); err != nil { + return fmt.Errorf("write update channel %s: %w", s.Path, err) + } + return nil +} diff --git a/internal/update/store_test.go b/internal/update/store_test.go new file mode 100644 index 0000000..298bef6 --- /dev/null +++ b/internal/update/store_test.go @@ -0,0 +1,79 @@ +package update_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/sentiolabs/selfupdate-go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/sentiolabs/argus/internal/update" +) + +// --- Contract assertions --- +// These verify the design spec. Do NOT modify without updating the approved plan. + +// FileStore satisfies selfupdate.Store. +var _ selfupdate.Store = update.FileStore{} + +// --- Behavior tests --- + +func TestFileStore_MissingFileReadsEmpty(t *testing.T) { + s := update.FileStore{Path: filepath.Join(t.TempDir(), "update-channel")} + ch, err := s.Channel() + require.NoError(t, err) + assert.Equal(t, selfupdate.Channel(""), ch) +} + +func TestFileStore_RoundTrip(t *testing.T) { + s := update.FileStore{Path: filepath.Join(t.TempDir(), "nested", "argus", "update-channel")} + require.NoError(t, s.SetChannel(selfupdate.ChannelRC)) + ch, err := s.Channel() + require.NoError(t, err) + assert.Equal(t, selfupdate.ChannelRC, ch) +} + +func TestFileStore_SetChannelCreatesDirAndModes(t *testing.T) { + s := update.FileStore{Path: filepath.Join(t.TempDir(), "argus", "update-channel")} + require.NoError(t, s.SetChannel(selfupdate.ChannelStable)) + info, err := os.Stat(s.Path) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + dirInfo, err := os.Stat(filepath.Dir(s.Path)) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), dirInfo.Mode().Perm()) +} + +func TestFileStore_TrimsWhitespace(t *testing.T) { + path := filepath.Join(t.TempDir(), "update-channel") + require.NoError(t, os.WriteFile(path, []byte(" rc \n"), 0o600)) + ch, err := update.FileStore{Path: path}.Channel() + require.NoError(t, err) + assert.Equal(t, selfupdate.ChannelRC, ch) +} + +func TestFileStore_EmptyPath(t *testing.T) { + s := update.FileStore{} + ch, err := s.Channel() + require.NoError(t, err) + assert.Equal(t, selfupdate.Channel(""), ch) + assert.ErrorIs(t, s.SetChannel(selfupdate.ChannelRC), update.ErrNoPath) +} + +func TestFileStore_ReadErrorIsWrapped(t *testing.T) { + // A directory at Path makes ReadFile fail with something other than ErrNotExist. + s := update.FileStore{Path: t.TempDir()} + _, err := s.Channel() + require.Error(t, err) + assert.Contains(t, err.Error(), "read update channel") +} + +func TestDefaultPath(t *testing.T) { + p, err := update.DefaultPath() + require.NoError(t, err) + assert.True(t, strings.HasSuffix(p, filepath.Join("argus", "update-channel")), p) + assert.True(t, filepath.IsAbs(p), p) +} diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..7e9b593 --- /dev/null +++ b/mise.toml @@ -0,0 +1,8 @@ +# Toolchain pins for argus. `mise install` provisions everything the +# Taskfile invokes. `go` must match the go directive in go.mod; +# `task check:versions` asserts this. +[tools] +go = "1.27.1" +task = "3" +golangci-lint = "2.13.2" +goreleaser = "2.17.1"