Help us shape the future of Go! Take the 2026 Go Developer Survey

utils

package
v0.7.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: MPL-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package utils holds the small provider-neutral helpers shared across the CLI: git remote detection and parsing, bounded file reads, FNV hashing, and container image reference normalization.

Index

Constants

This section is empty.

Variables

View Source
var CacheWriteSafeTriggers = map[string]bool{
	"push": true, "workflow_dispatch": true, "repository_dispatch": true, "delete": true,
	"registry_package": true, "page_build": true, "schedule": true,
	"pull_request": true, "pull_request_review": true, "pull_request_review_comment": true,
	"release": true, "merge_group": true,
}

CacheWriteSafeTriggers are the events allowed to write the cache: the triggers GitHub lets create or overwrite caches in the default branch's scope, plus pull_request and its review events, release and merge_group, which write only their own ref's scope. Mirrors cache_write_safe_triggers in policies/cache_poisoning.rego (ISSUE-705).

Functions

func CacheWriteExempt added in v0.7.0

func CacheWriteExempt(workflows, jobs []string, jobName, originFile string) bool

CacheWriteExempt reports whether a job is exempted from ISSUE-705 by an exemptWorkflows pattern on its workflow file name or an exemptJobs pattern on its name (`<workflow>/<job>`), with the rule's glob matching.

func CacheWriteRiskyTriggers added in v0.7.0

func CacheWriteRiskyTriggers(effectiveMode string, triggers []string) []string

CacheWriteRiskyTriggers returns, sorted, the triggers a job granted the effective cache-mode runs on that GitHub restricts to read-only cache access; nil when the mode grants no write (read, none, or unresolved) or every trigger is safe. A job it returns triggers for is the shape ISSUE-705 flags.

func CanonicalImageRepo added in v0.6.4

func CanonicalImageRepo(registry, name string) string

CanonicalImageRepo returns the tagless, digestless repository of an image in one spelling per image, so an exemption pattern matches it whichever collector parsed it. The GitHub collector leaves the registry empty and the host inside the name (`debian`, `ghcr.io/org/tool`); the GitLab one splits the host out (`docker.io` + `debian`) and emits "unknown" for a reference it could not resolve. Docker Hub images all end up as `docker.io/<namespace>/<name>`, with the implicit `library` namespace written out.

policies/image_mutable_tag.rego and policies/image_pinned_by_digest.rego implement the same function as _canonical_repo; the two must stay in step.

func CanonicalizeDockerHubRegistry added in v0.3.65

func CanonicalizeDockerHubRegistry(host string) string

CanonicalizeDockerHubRegistry maps any known Docker Hub registry-host alias to "docker.io". Non-Hub hosts pass through unchanged.

func CleanOriginPath added in v0.1.47

func CleanOriginPath(location string) string

CleanOriginPath normalizes a GitLab include/component path by stripping the version suffix and instance URL prefix, producing a bare path suitable for comparison (e.g. "components/sast/sast").

func DetectGitHeadSHA added in v0.3.26

func DetectGitHeadSHA(repoRoot string) string

DetectGitHeadSHA returns the full commit SHA of HEAD at repoRoot. Used to anchor remote source links to the exact code that was analysed instead of a mutable branch name. Returns "" when repoRoot is empty, not a git repository, or in a detached state with no resolvable HEAD (rare); callers fall back to a branch-name link.

func DetectGitRepoRoot added in v0.1.41

func DetectGitRepoRoot() string

DetectGitRepoRoot returns the absolute path to the root of the current git repository. Returns an empty string if not in a git repository.

func FoldDockerHubAliasInName added in v0.3.65

func FoldDockerHubAliasInName(name string) string

FoldDockerHubAliasInName rewrites the leading registry-host segment of an image name when that segment is a Docker Hub alias. Names without a leading host segment (e.g. bare "alpine") are returned unchanged.

func GenerateFNVHash

func GenerateFNVHash(data []byte) uint64

GenerateFNVHash generates a 64-bit FNV-1a hash from the input bytes

func GitOutput added in v0.4.59

func GitOutput(dir string, args ...string) (string, error)

GitOutput runs a read-only git command in dir and returns its trimmed stdout, with the same safe.directory declaration and the same failure diagnostics every git shell-out in this package gets. It exists so that a caller outside this package (`plumber init`, reading the origin remote) does not reach for exec.Command directly and quietly reintroduce #464: a raw invocation is refused on a checkout owned by another uid, and says nothing about why.

The contract on runGit applies unchanged: local inspections only, never a network-touching git command.

func HasDigestPin added in v0.3.0

func HasDigestPin(ref string) bool

HasDigestPin reports whether ref contains a digest reference using any algorithm allowed by the OCI image spec — sha256 today, sha512 already in production at some registries, and any future algorithm without a code change. Empty refs return false.

func ImageExempt added in v0.6.4

func ImageExempt(patterns, forbiddenTags []string, registry, name, tag string) bool

ImageExempt reports whether containerImageMustNotUseForbiddenTags exempts the image: its repository matches one of the exemptImages patterns AND its tag is one of the forbidden tags. The same image on any other tag is judged as usual. Patterns use the glob syntax of trustedUrls (OPA glob.match with no delimiters, so `*` spans `/` and `.`); a pattern that does not compile exempts nothing, as it matches nothing in rego either.

func ReadFileLimit added in v0.3.89

func ReadFileLimit(path string, max int64) ([]byte, error)

ReadFileLimit reads a file but returns an error if it exceeds max bytes, bounding memory when reading files whose size is not trusted. The open error is returned unwrapped so callers can still use os.IsNotExist.

func SplitGitHubImageRef added in v0.7.13

func SplitGitHubImageRef(ref string) ir.Image

SplitGitHubImageRef parses a GitHub Actions image reference (a job's `container:`, a `uses: docker://` step without the scheme) into an ir.Image, folding Docker Hub registry-host aliases to docker.io. A reference with neither tag nor digest gets the tag `latest`, the one Docker pulls for it; one still holding a `${{ }}` expression keeps no tag, since the value is only known at run time.

func TagForbidden added in v0.6.4

func TagForbidden(patterns []string, tag string) bool

TagForbidden reports whether tag matches one of the forbidden tag patterns, with the glob.match semantics image_mutable_tag.rego applies.

Types

type GitRemoteInfo added in v0.1.30

type GitRemoteInfo struct {
	Host        string // e.g., "gitlab.com", "github.com", "gitlab.example.com"
	ProjectPath string // e.g., "group/project" or "group/subgroup/project"
	URL         string // The full instance URL, e.g., "https://gitlab.com"
	RepoRoot    string // Absolute path to the git repository root
	Provider    string // "gitlab" or "github" — derived from Host; default "gitlab" for unknown hosts (self-hosted GitLab is the common case).
	// ProviderReason is a short, user-facing explanation of why Provider was
	// chosen (host match, .github/workflows marker, or the GitLab default),
	// surfaced in the detection banner. Empty when set host-only by
	// ParseGitRemoteURL (no working tree available).
	ProviderReason string
}

GitRemoteInfo contains parsed information from a git remote URL.

func DetectGitRemote added in v0.1.30

func DetectGitRemote() *GitRemoteInfo

DetectGitRemote attempts to detect GitLab URL and project path from git remote. It tries the "origin" remote first. Returns nil if detection fails (not a git repo, no remote, not a GitLab URL, etc.)

func ParseGitRemoteURL added in v0.1.30

func ParseGitRemoteURL(remoteURL string) *GitRemoteInfo

ParseGitRemoteURL parses a git remote URL and extracts host and project path. Supports the following formats:

  • SSH URL: ssh://git@host[:port]/group/project.git
  • SSH SCP-like: git@host:group/project.git
  • HTTPS: https://host[:port]/group/project.git
  • Git protocol: git://host[:port]/group/project.git

Returns nil if the URL cannot be parsed.

type OverriddenJobDetail added in v0.1.47

type OverriddenJobDetail struct {
	JobName        string   `json:"jobName"`
	OverriddenKeys []string `json:"overriddenKeys"`
}

OverriddenJobDetail captures which job was overridden and with which forbidden CI/CD keywords. Shared across control (detection) and pbom (reporting) packages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL