contracts

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 9 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 contracts defines the shared version 1 types, validation rules and component interfaces. It contains no archive extraction, tool execution or output publication.

Index

Constants

View Source
const (
	SchemaVersion              = 1
	MaxManifestBytes    int64  = 1 << 20
	MaxArchiveBytes     int64  = 2 << 30
	MaxPatches                 = 256
	MaxPatchBytes       int64  = 16 << 20
	MaxArchiveEntries          = 100000
	MaxExtractedBytes   int64  = 2 << 30
	MaxPatchLogBytes    int64  = 1 << 20
	PatchTimeoutSeconds        = 30
	NewFileMode         uint32 = 0644
	DirectoryMode       uint32 = 0755
	DigestDefinition           = "" /* 222-byte string literal not displayed */
	EvidenceLimitations        = "" /* 211-byte string literal not displayed */
)

Variables

This section is empty.

Functions

func StripPatchPath

func StripPatchPath(value string) (string, error)

StripPatchPath checks a diff header path and removes its first component: a/src/main.c becomes src/main.c. Quotes and whitespace, including Unicode whitespace, are unsupported. /dev/null returns an empty path; the diff parser must allow that marker only for the missing side of an addition or deletion.

func ValidateBasename

func ValidateBasename(value string) error

ValidateBasename applies ValidateRelativePath and requires a single name with no slash separators.

func ValidateRelativePath

func ValidateRelativePath(value string) error

ValidateRelativePath checks that a path is a nonempty UTF-8 relative path using slash separators, without control characters, backslashes, empty components, or . or .. components. It checks spelling only. Input readers must also reject symlinks using operations relative to open directories, so a pathname change between checking and opening cannot redirect a read.

Types

type ConfinedInputs

type ConfinedInputs interface {
	OpenRegular(context.Context, string) (io.ReadCloser, error)
	ReadDir(context.Context, string) ([]InputEntry, error)
}

ConfinedInputs is a read-only view of an input directory kept open throughout source and patch preparation. Paths are normalized relative slash paths. Implementations reject symlink components and nonregular input files. They open paths relative to retained directory handles so a changed pathname cannot redirect a read. ReadDir includes hidden entries and rejects symlinks and special files. The owner closes the root after preparation.

Reads return InputError with an unsafe-input, I/O or cancellation reason. Source and inventory callers add their stage with FailureFromError. Preparation hashes bytes while copying them into private files for all later use.

type ExecuteRequest

type ExecuteRequest struct {
	Source          PreparedSource
	Patches         []StagedPatch
	PatchExecutable string
}

type ExecutionResult

type ExecutionResult struct {
	Patches         []PatchResult
	Files           []FileRecord
	FinalTreeSHA256 string
	Failure         *Failure
	Diagnostics     string
}

ExecutionResult contains ordered patch results and, only after the whole series succeeds, file records and a final tree hash. Contents are hashed while readable, with intended final permissions included; final modes are then restored. New files receive 0644 and directories 0755. Failure stops execution, leaves later patches not_run, and returns no file records or tree hash. Diagnostics are bounded stderr material, excluded from reports and successful output packages.

type Executor

type Executor interface {
	Execute(context.Context, ExecuteRequest) (ExecutionResult, error)
}

type Failure

type Failure struct {
	Stage  Stage  `json:"stage"`
	Reason Reason `json:"reason"`
}

Failure records a stage and reason without host paths, timestamps or tool logs. Hash, inventory and patch application mismatches return this result with a nil error. Operational failures also return a RunError.

func FailureFromError

func FailureFromError(stage Stage, err error) Failure

FailureFromError extracts a stage and reason from a typed error. It uses the supplied stage unless a RunError provides its own valid failure stage. Unknown errors become I/O failures. Diagnostic text is never copied into the result.

type FileRecord

type FileRecord struct {
	Path   string `json:"path"`
	Mode   string `json:"mode"`
	SHA256 string `json:"sha256"`
}

FileRecord describes a regular file in the completed source tree. Path is relative to that tree and SHA256 hashes the contents. Mode is the file's final permissions as four octal digits, such as "0644". It excludes temporary access permissions used during preparation.

type InputEntry

type InputEntry struct {
	Name      string
	Directory bool
}

type InputError

type InputError struct {
	Reason Reason
	Err    error
}

InputError describes a failed read beneath the retained input directory. Input readers use ReasonUnsafeInput, ReasonIO or ReasonCancelled. Source and inventory preparation add their own stage while preserving this reason.

func (*InputError) Error

func (e *InputError) Error() string

func (*InputError) Unwrap

func (e *InputError) Unwrap() error

type InventoryResult

type InventoryResult struct {
	Patches []StagedPatch
	Failure *Failure
}

type Manifest

type Manifest struct {
	SchemaVersion int     `json:"schema_version" yaml:"schema_version"`
	Source        Source  `json:"source" yaml:"source"`
	PatchDir      string  `json:"patch_dir" yaml:"patch_dir"`
	Patches       []Patch `json:"patches" yaml:"patches"`
}

Manifest describes a source archive and a sequence of patches. It records declarations, not verified input bytes. Validate checks values constructed or changed in Go as well as values returned by the YAML loader.

func (Manifest) Validate

func (m Manifest) Validate() error

Validate checks manifest values without opening the files they name. It applies equally to manifests loaded from YAML and values constructed or changed in Go. Audit repeats these checks before using a manifest.

type Operation

type Operation string
const (
	OperationModify Operation = "modify"
	OperationAdd    Operation = "add"
	OperationDelete Operation = "delete"
)

type Options

type Options struct {
	// InputRoot is an existing directory containing the declared inputs.
	// Symlinks are rejected in every path component.
	InputRoot string
	// OutputDir is a new path outside InputRoot, beneath an existing parent.
	// The parent must have no symlink components and support atomic rename
	// without replacement on Linux.
	OutputDir string
	// PatchExecutable selects GNU patch. Empty uses "patch" from PATH.
	PatchExecutable string
}

Options selects the local input, output and GNU patch paths for an audit. These paths are used to run the audit and do not enter its report.

type Outcome

type Outcome string

Outcome says whether the complete patch series was reproduced.

const (
	OutcomeReproduced Outcome = "reproduced"
	OutcomeFailed     Outcome = "failed"
)

type Patch

type Patch struct {
	ID       string   `json:"id" yaml:"id"`
	File     string   `json:"file" yaml:"file"`
	SHA256   string   `json:"sha256" yaml:"sha256"`
	Upstream string   `json:"upstream" yaml:"upstream"`
	CVEs     []string `json:"cves,omitempty" yaml:"cves,omitempty"`
}

Patch identifies one file in the patch directory. Upstream and CVEs describe declared origins and CVE associations; the audit does not authenticate them.

type PatchInventory

type PatchInventory interface {
	Prepare(context.Context, PatchRequest) (InventoryResult, error)
}

type PatchRequest

type PatchRequest struct {
	Inputs     ConfinedInputs
	PatchDir   string
	Patches    []Patch
	StagingDir string
}

type PatchResult

type PatchResult struct {
	Patch
	Status PatchStatus `json:"status"`
	Reason Reason      `json:"reason"`
}

PatchResult combines a patch declaration with its application status and reason. Results stay in manifest order. Preparation or tooling failures leave every patch not_run. Once execution stops, all later patches remain not_run.

type PatchStatus

type PatchStatus string

PatchStatus describes whether a patch was not run, applied or failed.

const (
	PatchNotRun  PatchStatus = "not_run"
	PatchApplied PatchStatus = "applied"
	PatchFailed  PatchStatus = "failed"
)

type PatchTarget

type PatchTarget struct {
	OldPath   string
	NewPath   string
	Operation Operation
}

PatchTarget describes a target that passed diff header validation. Paths have their first component removed. OldPath is empty for an addition, and NewPath is empty for a deletion; a modification uses equal paths. Renames and mode changes are unsupported. Git mode metadata does not override version 1 final permissions, and multiple mode declarations must agree. Targets remain in diff order. Patch inventory is responsible for parsing hunks.

type PreparedSource

type PreparedSource struct {
	Archive       StagedFile
	WorkspaceDir  string
	IntendedModes map[string]uint32
}

PreparedSource describes the extracted workspace. Files remain readable and writable by their owner until final hashing. IntendedModes records original file permissions masked to 0777; output directories receive 0755. Archive owner and group IDs and timestamps are discarded.

type Reason

type Reason string

Reason is a stable classification for an audit result or error.

const (
	ReasonNone                   Reason = "none"
	ReasonInvalidManifest        Reason = "invalid_manifest"
	ReasonHashMismatch           Reason = "hash_mismatch"
	ReasonInventoryMismatch      Reason = "inventory_mismatch"
	ReasonPatchFailed            Reason = "patch_failed"
	ReasonUnsafeInput            Reason = "unsafe_input"
	ReasonLimitExceeded          Reason = "limit_exceeded"
	ReasonIO                     Reason = "io_failure"
	ReasonToolUnavailable        Reason = "tool_unavailable"
	ReasonUnsupportedTool        Reason = "unsupported_tool"
	ReasonTimeout                Reason = "timeout"
	ReasonCancelled              Reason = "cancelled"
	ReasonOutputExists           Reason = "output_exists"
	ReasonUnsupportedPublication Reason = "unsupported_publication"
	ReasonOutputWrite            Reason = "output_write_failure"
)

func (Reason) Expected

func (r Reason) Expected() bool

Expected reports whether the reason is a hash, patch inventory or patch application mismatch. Audits return those failures as results with a nil error. Other failure reasons identify operational errors.

func (Reason) Valid

func (r Reason) Valid() bool

Valid reports whether r is a recognized version 1 reason.

type Report

type Report struct {
	SchemaVersion    int           `json:"schema_version"`
	Outcome          Outcome       `json:"outcome"`
	Stage            Stage         `json:"stage"`
	Reason           Reason        `json:"reason"`
	Source           Source        `json:"source"`
	Patches          []PatchResult `json:"patches"`
	FinalTreeSHA256  string        `json:"final_tree_sha256,omitempty"`
	Files            []FileRecord  `json:"files,omitempty"`
	DigestDefinition string        `json:"digest_definition"`
	Limitations      string        `json:"limitations"`
}

Report records an audit's input declarations and result without host paths, timestamps or raw tool logs. Patches remain in application order. Files are sorted by their relative paths' UTF-8 bytes. Files and FinalTreeSHA256 are present only on success. Writers validate the report without repeating the audit.

func (Report) ExitCode

func (r Report) ExitCode(err error) int

ExitCode combines the report and error into a CLI exit status: 0 for complete success, 1 for an expected mismatch, or 2 for an operational error or invalid report. Always pass the returned error; any non-nil error takes precedence, including a report-write failure after complete output has been published.

func (Report) Validate

func (r Report) Validate() error

Validate checks the report's structure, required fields and consistency. It does not repeat patch application, recalculate hashes or authenticate external claims. Report writers and ExitCode use these checks to reject incomplete or contradictory results.

type RunError

type RunError struct {
	Stage  Stage
	Reason Reason
	Err    error
}

RunError describes invalid input, setup or I/O problems, tooling failures, timeouts or cancellation. Stage and Reason are stable classifications. Err is an optional diagnostic cause; it must never be copied into a Report.

func (*RunError) Error

func (e *RunError) Error() string

Error formats the stage, reason and optional diagnostic cause.

func (*RunError) Unwrap

func (e *RunError) Unwrap() error

Unwrap exposes the diagnostic cause to errors.Is and errors.As.

type Source

type Source struct {
	Path    string `json:"path" yaml:"path"`
	SHA256  string `json:"sha256" yaml:"sha256"`
	RootDir string `json:"root_dir" yaml:"root_dir"`
}

Source identifies a source archive by its relative path and expected hash. RootDir is the single archive root directory removed during extraction.

type SourcePreparer

type SourcePreparer interface {
	Prepare(context.Context, SourceRequest) (SourceResult, error)
}

type SourceRequest

type SourceRequest struct {
	Inputs       ConfinedInputs
	Source       Source
	StagingDir   string
	WorkspaceDir string
}

type SourceResult

type SourceResult struct {
	Source  PreparedSource
	Failure *Failure
}

type Stage

type Stage string

Stage identifies the part of an audit associated with a result or error.

const (
	StageComplete    Stage = "complete"
	StageManifest    Stage = "manifest"
	StageSource      Stage = "source"
	StageInventory   Stage = "inventory"
	StageTool        Stage = "tool"
	StageExecution   Stage = "execution"
	StageDigest      Stage = "digest"
	StagePublication Stage = "publication"
	StageOutput      Stage = "output"
)

func (Stage) Valid

func (s Stage) Valid() bool

Valid reports whether s is a recognized version 1 stage.

type StagedFile

type StagedFile struct {
	Path   string
	SHA256 string
	Size   int64
}

StagedFile identifies a private verified copy of an input file. SHA256 and Size describe those exact bytes. Path is used to run the audit, not stored in reports.

type StagedPatch

type StagedPatch struct {
	Patch   Patch
	Input   StagedFile
	Targets []PatchTarget
}

Jump to

Keyboard shortcuts

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