security

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package security is the last thing that runs before indexed content leaves the machine.

GraphLume indexes private source and serves excerpts of it to AI coding agents over MCP. That transport is the whole reason this package exists: a line of code returned to an agent is a line of code sent to a third party. Spec §24 and §57 draw the line at values — existence and location may be reported, the credential itself may not:

exists: true, source: Kubernetes Secret, key: DB_PASSWORD   ✅
value: hunter2                                              ❌

THE ERROR MODES ARE NOT SYMMETRIC. A false positive redacts a line of code: the agent loses a little context and someone files an annoyed issue. A false negative ships a live credential to a model provider's logs, and no release fixes that — the credential has to be rotated, assuming anyone notices. Every judgement call in this package therefore leans toward redacting, and every place where it leans the other way (to keep the tool usable) says why.

Two structural decisions follow from the same reasoning:

  • Only the standard library. A supply-chain compromise of a dependency in the redaction path would be invisible and total. stdlib regexp is also RE2: linear time, no catastrophic backtracking, so hostile input cannot turn redaction into a denial of service. FuzzRedact holds us to that.

  • Everything compiles once, at package init. Redact sits on the hot path of every MCP response; a regexp compiled per call would be a performance bug that only shows up under the load we care about.

The package covers four concerns:

Detect / Redact    content — replace secret values, keep structure
IsSensitivePath    paths whose entire content is a credential
ValidatePath       path arguments arriving from an agent (traversal)
ContainedPath      the same, errs-typed and stricter — prefer it in NEW code
OpenContained      ContainedPath plus a re-checked open, closing the TOCTOU

ValidatePath and ContainedPath are not interchangeable: ContainedPath requires the path to exist, refuses a symlinked final component and refuses a literal "..". containment.go's package comment lists every difference. Existing callers stay on ValidatePath because they match its sentinel errors with errors.Is.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyPath    = errors.New("security: empty path")
	ErrAbsolutePath = errors.New("security: absolute paths are not accepted")
	ErrOutsideRoot  = errors.New("security: path escapes the repository root")
	ErrBadRoot      = errors.New("security: repository root is unusable")
)

Errors returned by ValidatePath. They are sentinels so a caller can tell an attack apart from a typo — an MCP server may want to log the first loudly and the second not at all.

View Source
var (
	// ErrNotRegular: the path names a directory, FIFO, device or socket. Only
	// regular files are read — a FIFO with no writer would block the reader,
	// and a device need never end.
	ErrNotRegular = errors.New("security: not a regular file")
	// ErrTooLarge: the file is larger than the WithMaxBytes cap.
	ErrTooLarge = errors.New("security: file exceeds the size limit")
)

Functions

func ContainedPath

func ContainedPath(root, candidate string) (string, error)

ContainedPath resolves candidate relative to root and returns its absolute, symlink-resolved form, or an error if it escapes.

candidate must be relative. An absolute candidate is refused even when it happens to point inside root, because accepting it invites callers to build paths by concatenation somewhere else.

func IsSecretBearingPath

func IsSecretBearingPath(path string) bool

IsSecretBearingPath reports whether a file must never be OFFERED at all: not listed in a context pack, not excerpted, not downloaded from the UI.

It is wider than IsSensitivePath on purpose. IsSensitivePath decides whether content is suppressed wholesale or pattern-matched, and it lets an environment template (.env.example) through because its usual content is dummy values. A context pack is a different question: what an agent should be handed to read for a task. An environment file of any flavour holds the deployment's settings and, in practice, real values copied into a template often enough that "it is only an example" is not a safe assumption to ship. So every member of the env family, every key or keystore, SSH identity and credentials file is left out of what GraphLume offers, whatever its suffix.

func IsSensitivePath

func IsSensitivePath(path string) bool

IsSensitivePath reports whether a path's content should be suppressed wholesale rather than pattern-matched.

Pattern matching is the wrong tool for these files. In a .env or an id_rsa every line is credential material; a detector that catches nine lines out of ten has still leaked. Classifying by path is a cheap, total answer for the cases where it applies.

func OpenContained

func OpenContained(root, candidate string) (*os.File, error)

OpenContained opens candidate for reading after containment, then verifies the handle it actually got is the regular file it checked.

The post-open verification is the part that matters: between ContainedPath returning and the open completing, the entry can be replaced. Comparing the opened handle's identity against the checked path closes that window.

func ReadFileContained

func ReadFileContained(repoRoot, requested string, opts ...ReadOption) (data []byte, resolved string, err error)

ReadFileContained reads requested (a path relative to repoRoot) and returns its bytes along with the symlink-resolved absolute path ValidatePath vouched for, which callers use to classify the file (a link named notes.txt that points at .env is still a .env).

ValidatePath answers "does this name stay inside the root" at one instant; reading by the resolved path afterwards leaves a window in which a component can be swapped for a symlink or a Windows junction. So the validation is kept for its error sentinels and messages, and the read itself goes through os.Root, which refuses at open time any component that leads outside the directory — closing the check-then-open race.

The relative path handed to the Root is the cleaned request, not the ValidatePath result, so the two checks are independent: either one alone rejects an escape.

Only a regular file is read (ErrNotRegular otherwise). The open is non-blocking on Unix, so a FIFO swapped in after any earlier check cannot hang the reader; the type is judged on the opened handle, not on a name.

func ValidatePath

func ValidatePath(repoRoot, requested string) (string, error)

ValidatePath resolves requested against repoRoot and refuses anything that escapes it, returning the cleaned absolute path.

This is a real attack surface, not a formality. MCP tools take path arguments from an agent, and an agent's arguments are derived from content it read — an issue description, a README, a code comment in a cloned repository. Any of those can be attacker-influenced, so "../../../../.ssh/id_rsa" arrives here as an ordinary-looking tool call.

Three escapes are handled:

absolute paths     /etc/passwd, C:\Windows, and drive-relative C:foo
dot-dot            ../../etc/passwd, a/../../etc/passwd
symlinks           a link inside the repo pointing anywhere outside it

The symlink case is why both sides are passed through EvalSymlinks. Comparing a resolved target against an UNRESOLVED root is the classic bug: on macOS /tmp is a symlink to /private/tmp, so a root of /tmp/repo resolves to /private/tmp/repo and a naive prefix test rejects every legitimate path in the repository — or, with the operands the other way round, accepts paths outside it. Both sides are evaluated, and the comparison is done with filepath.Rel so separators and case are handled by the standard library.

A path that does not exist yet is NOT an error: existence is the caller's business (its os.Open will say so), while containment is ours. The deepest existing ancestor is resolved and checked, so a non-existent path under a symlinked-out directory is still rejected.

Types

type Category

type Category string

Category names the kind of credential a Finding describes.

The value is part of the output contract, not an internal label: it is what the agent sees inside the placeholder. "[REDACTED:aws-access-key]" tells the agent an AWS key lives on this line — which is the useful half of the fact — without telling it the key.

const (
	CategoryPrivateKey       Category = "private-key"
	CategoryConnectionString Category = "connection-string"
	CategoryAWSAccessKey     Category = "aws-access-key"
	CategoryAWSSecretKey     Category = "aws-secret-key"
	CategoryGitHubToken      Category = "github-token"
	CategorySlackToken       Category = "slack-token"
	CategorySlackWebhook     Category = "slack-webhook"
	CategoryStripeKey        Category = "stripe-key"
	CategoryGoogleAPIKey     Category = "google-api-key"
	CategoryJWT              Category = "jwt"
	CategoryPassword         Category = "generic-password"
	CategoryAPIKey           Category = "generic-api-key"
	CategoryToken            Category = "generic-token"
	CategorySecret           Category = "generic-secret"
	CategoryHighEntropy      Category = "high-entropy"
	CategorySensitiveFile    Category = "sensitive-file"
)

type Finding

type Finding struct {
	Category Category
	Line     int
	Col      int
	Length   int // byte length of the value that was removed
}

Finding records that a credential exists, where it is, and what kind it is. Deliberately everything EXCEPT the value: that is the whole contract of this package restated as a struct.

Line/Col follow model.Position — 1-indexed line, 0-indexed byte column — so a caller can turn a Finding into model.Evidence without adjusting anything.

func Detect

func Detect(text string) []Finding

Detect reports the secrets in text without rewriting it, for callers that only need to answer "does this file contain credentials, and where" — the "exists: true, key: DB_PASSWORD" shape from spec §24.

func Redact

func Redact(text string) (string, []Finding)

Redact replaces every secret VALUE in text with a categorised placeholder and returns what it found.

Structure survives on purpose. "DB_PASSWORD=[REDACTED:generic-password]" still tells the agent that this file configures a database password and what the variable is called, which is the fact it can actually use; the seven bytes it loses are the seven bytes it must never have.

Redact is idempotent: Redact(Redact(x)) == Redact(x), with no findings on the second pass.

func RedactFile

func RedactFile(path, content string) (string, []Finding)

RedactFile applies path classification before content scanning.

For a file whose very identity is a credential (.env, id_rsa, a kubeconfig) pattern matching is the wrong tool: the whole file is the secret, every line of it, and a pattern that misses one line leaks. So the content is suppressed wholesale and replaced with a statement of what was suppressed — which is still useful to an agent ("this service is configured by a .env with 14 entries") and cannot leak.

func (Finding) Placeholder

func (f Finding) Placeholder() string

Placeholder is the text that replaced the value.

func (Finding) String

func (f Finding) String() string

String renders a finding the way it is safe to log: location and kind only.

type ReadOption

type ReadOption func(*readOptions)

ReadOption configures ReadFileContained.

func WithMaxBytes

func WithMaxBytes(n int64) ReadOption

WithMaxBytes refuses, with ErrTooLarge, a file larger than n bytes, and never reads more than n+1 of them. n <= 0 means no cap.

Jump to

Keyboard shortcuts

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