remote

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 30 Imported by: ? 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 remote pulls files or directory trees onto a managed machine from one of three sources: a public HTTP URL, a version-controlled repository (Git in v1, with a pluggable interface for future drivers), or an anonymous S3-compatible endpoint.

It is the reusable building block behind a future ACTION_TYPE_REMOTE_SOURCE action — the agent executor for that action is intentionally NOT in this package. Anything that drives a Source (a CLI, a custom tool, a future action) gets idempotent fetches, drift detection, atomic placement, and the same safety guarantees without re-implementing them.

Usage

All three sources implement the Source interface:

type Source interface {
    Fetch(ctx context.Context, dest string) (Result, error)
    Wipe (ctx context.Context, dest string) error
    String() string
}

Pick a backend via one of the three factories:

src, err := remote.NewHTTP(remote.HTTPConfig{
    URL:            "https://example.test/release.tar.gz",
    ChecksumSHA256: "...",
    Extract:        true,
    Prune:          true,
    Mode:           "0644",
})

src, err := remote.NewGit(remote.GitConfig{
    URL:  "https://github.com/manchtools/example.git",
    Ref:  "v1.0.0",
    Prune: true,
})

src, err := remote.NewS3(remote.S3Config{
    Endpoint: "https://s3.amazonaws.com",
    Bucket:   "my-bucket",
    Key:      "config/", // trailing slash → prefix-sync mode
    Prune:    true,
})

Then drive Fetch / Wipe on the returned Source:

res, err := src.Fetch(ctx, "/var/lib/power-manage/release")
// res.Changed   — true on first fetch, false on a no-op drift hit.
// res.Revision  — opaque drift token; cache between cycles to skip
//                 no-op re-fetches.
// res.Digest    — sha256 of the payload (single file) or the
//                 canonicalised tree root (directory).

Drift detection

Each backend tracks an opaque drift token in Result.Revision. A follow-up Fetch with cfg unchanged calls into the cheap probe path:

  • HTTP: HEAD with If-None-Match. 304 → no-op short-circuit.
  • Git: ls-remote (no clone). Compares upstream commit SHA against the cached one.
  • S3: single key — HEAD with If-None-Match. prefix — paginated list + canonical hash compare.

Drift state is per-process. The intended consumer (the upcoming REMOTE_SOURCE action's executor) persists Result.Revision per action so the skip survives restarts.

Safety

Every destination flows through sys/fs.ResolveAndValidatePath plus a deny-by-default subtree check (sys/fs.IsUnderProtectedPrefix): any path at or under a protected system root — /etc/cron.d/x, /usr/bin/x, /home/<u>/.ssh/x, /var/lib/x — is refused at ANY depth, not just the exact top-level dir. The only exemptions are the agent-owned managed roots (/var/lib/power-manage/, /etc/power-manage/). Wipe additionally requires the path to live under one of those managed roots OR to have been seen by a successful Fetch (RecordDest), and refuses a protected subtree even if it was somehow recorded; a hostile actor with action-creation rights can't instruct an agent to write or rm-rf /etc/cron.d by guessing a clever URL.

Archive extraction (HTTP Extract=true) refuses entries that contain "..", absolute paths, escape symlinks, NUL bytes, or anything that resolves outside the staging dir. The extractor is fuzzed (FuzzHTTPArchive_Tar) so adversarial inputs surface as errors, not panics or escapes.

HTTP and S3 fetches stream through an io.LimitReader capped at HTTPConfig.MaxBytes / defaultHTTPMaxBytes (2 GiB) to defeat zip-bomb-style inputs.

Pluggable version-control backends

The version-controlled Source is built on top of VersionControlBackend, an interface every driver implements. v1 ships one driver — github.com/go-git/go-git/v5, registered as "go-git" — but the contract is deliberately not git-named. A future release can register additional drivers (a shell-out git, Mercurial, Fossil) without proto change or downstream API churn:

type MyDriver struct{}
func (MyDriver) CloneOrSync(ctx, cfg, dest) (Result, error) { ... }
func (MyDriver) Resolve   (ctx, cfg)       (string, error) { ... }

func init() {
    remote.RegisterVersionControlBackend("my-vcs", MyDriver{})
}

Callers select the driver via GitConfig.Driver. Empty string normalises to "go-git".

Known limitations (v1)

  • Public sources only. None of the Config structs carry auth fields. v2 adds optional Auth types per source — additive and binary-compatible with v1 callers.
  • HTTP archive extraction supports tar.gz and zip. tar.xz is recognised and refused explicitly (the pure-Go xz dep is deferred to v2).
  • Anonymous S3 listing relies on the bucket's policy allowing unauthenticated ?list-type=2. Not every endpoint does even when individual objects are world-readable. A 403 surfaces as ErrInvalidConfig wrapping the URL so the operator knows where to look.
  • Git submodules + Prune interact in a "best effort" way; go-git's submodule cleanup is shallow. Documented as a known limitation; deeper handling is a v2 ticket.
  • HTTP archive Fetch is a strict mirror (staging-swap on every successful extract). The Prune flag is currently a no-op for the HTTP archive branch; an additive-overlay mode that honours Prune=false explicitly is a v2 follow-up.

Package remote pulls files or directory trees onto a managed machine from a public HTTP URL, a version-controlled repository (Git in v1), or an anonymous S3-compatible endpoint. It is the reusable building block behind a future ACTION_TYPE_REMOTE_SOURCE; the agent executor for that action is intentionally NOT in this package — this primitive can be driven from any SDK consumer (CLI, custom tooling, future actions).

Pattern: this package mirrors sdk/go/pkg's interface-+-factory shape (Source interface, NewHTTP/NewGit/NewS3 factories, one file per impl). It deliberately does NOT use the atomic-backend selector pattern from sys/encryption / sys/service, because multiple source types coexist per agent run and the choice is per call, not per startup.

Safety surface: every destination is run through sys/fs.ResolveAndValidatePath and a deny-by-default protected-subtree check (sys/fs.IsUnderProtectedPrefix, exempting only the agent-owned managed roots) before any filesystem mutation, archive entries are guarded against ../, absolute paths, and escape-symlinks, and HTTP fetches are size-capped to defeat zip-bomb-style inputs.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidConfig — the Config struct passed to a New* constructor
	// failed validation (bad URL, conflicting flags, missing required
	// field). Wraps the specific validation message.
	ErrInvalidConfig = errors.New("remote: invalid source config")

	// ErrUnsafeDestination — the destination path failed the path-safety
	// check (relative, traversal, protected prefix, symlink escape) OR an
	// archive entry would have written outside dest.
	ErrUnsafeDestination = errors.New("remote: unsafe destination path")

	// ErrIntegrity — fetched payload failed an integrity check (sha256
	// mismatch, size-cap breach treated as a tamper signal, etc.).
	ErrIntegrity = errors.New("remote: integrity check failed")

	// ErrToolMissing — a runtime tool the implementation needs (e.g. a
	// future shell-out git backend's `git` binary) isn't on PATH.
	// Reserved for the registry pattern in vc.go; go-git itself does not
	// raise this.
	ErrToolMissing = errors.New("remote: required tool missing")

	// ErrBackendNotFound — a registry lookup (e.g. cfg.Driver on
	// GitConfig) named a backend that was never registered.
	ErrBackendNotFound = errors.New("remote: backend not registered")
)

Sentinel errors. Callers branch on these with errors.Is.

Functions

func FetchBytes

func FetchBytes(ctx context.Context, cfg HTTPConfig) ([]byte, error)

FetchBytes downloads the configured HTTP payload entirely into memory, applying the SAME guards as Fetch — URL/scheme validation, the MaxBytes cap, the optional sha256 pin, and the default-or-injected client — but bounded for RAM. It is for SMALL payloads (a GPG key, a SHA256SUMS manifest), NOT large artifacts: use Fetch (streamed, atomic, to a file) for those.

When cfg.MaxBytes is unset it defaults to defaultBytesMaxBytes (64 MiB), NOT the 2 GiB file default, so a runaway or compromised origin cannot exhaust memory. A body exceeding the cap fails closed with ErrIntegrity and returns no data, and a set ChecksumSHA256 is verified before the bytes are returned. Extract/Prune are archive-to-directory concepts and are rejected here.

func RecordDest

func RecordDest(path string)

RecordDest registers a destination that a successful Fetch has just written to, so a later Wipe in the same process can clean it up even if the path lives outside the project-managed prefixes. Safe to call from multiple goroutines. Records both the cleaned and resolved forms so a later canWipe call matches either way.

func RegisterVersionControlBackend

func RegisterVersionControlBackend(name string, b VersionControlBackend)

RegisterVersionControlBackend adds a named driver to the registry. Calls with an empty name OR a nil backend are silently ignored — the goal is "registering is safe from any goroutine, including init" rather than surfacing programmer errors at startup time, where a panic in init can be very hard to diagnose.

Re-registering an existing name overrides the previous entry, which is the property tests rely on to swap in a fake backend.

Types

type GitConfig

type GitConfig struct {
	// URL of the repository. https:// only for v1; the constructor
	// rejects ssh / git / file schemes.
	URL string

	// Ref to check out — branch, tag, or commit SHA. Empty string
	// normalises to "main" at construction time.
	Ref string

	// Submodules controls submodule recursion during CloneOrSync. The
	// go-git driver in v1 best-effort handles submodules; the
	// Prune-vs-submodules interaction is intentionally not specified
	// (see Slice 13 doc.go).
	Submodules bool

	// Owner / Group — ownership applied to the dest clone directory after
	// CloneOrSync via sys/fs's fd-anchored no-follow chown (a git clone has no
	// mode input). Empty strings leave the OS default ownership.
	Owner string
	Group string

	// Prune forwards to the backend's "clean untracked files" step.
	// For Git this means a worktree.Clean after checkout.
	Prune bool

	// Driver picks the registered VersionControlBackend by name.
	// Empty string normalises to "go-git" at construction time.
	Driver string
}

GitConfig configures a version-controlled Source. The struct stays here (next to VersionControlBackend) because the interface accepts it; NewGit (Slice 9) layers the validation and factory wiring on top.

Authentication is deliberately not modelled — v1 is anonymous-only. v2 adds an Auth type without breaking this struct's binary layout.

type HTTPConfig

type HTTPConfig struct {
	// URL of the payload. https:// and http:// schemes only; no
	// userinfo, no fragment, no control characters.
	URL string

	// ChecksumSHA256 — optional, hex-encoded (64 chars). When set, the
	// fetched body is hashed during streaming and the result compared
	// against this value; mismatch is ErrIntegrity. Strongly recommended
	// for any production deploy, mandatory in combination with
	// Extract+Prune (a malicious origin could otherwise poison a
	// destructive sync).
	ChecksumSHA256 string

	// Extract — when true, the payload is treated as an archive
	// (tar.gz / zip / tar.xz, detected by Content-Type + filename)
	// and unpacked into the destination directory. When false, the
	// payload is written verbatim to the destination path. Slice 5
	// introduces this branch; Slice 4 covers the !Extract path.
	Extract bool

	// Prune — for archive payloads only. When true, files present
	// locally in the destination but absent from the archive are
	// removed after a successful extract (mirror-with-delete). For
	// single-file payloads this field is invalid (NewHTTP rejects it).
	Prune bool

	// MaxBytes — hard size cap on the streamed body. Zero means
	// defaultHTTPMaxBytes (2 GiB). The cap is enforced via a one-byte
	// over-read sentinel, so a runaway stream surfaces as ErrIntegrity
	// before the excess hits disk.
	MaxBytes int64

	// Mode / Owner / Group — applied to the destination after a
	// successful Fetch via os.Chmod / sys/fs.FchownNoFollow. Empty
	// strings leave the OS default in place.
	Mode  string
	Owner string
	Group string

	// Client overrides the *http.Client used for the HEAD/GET round-trips.
	// Nil (the default) uses an internal client with conservative timeouts and
	// the cross-origin / scheme-downgrade redirect guard. This is a TRANSPORT
	// seam — its purpose is to point a test at an httptest TLS server (whose
	// self-signed cert the default client refuses) or to mock the round-tripper.
	// It does NOT relax any Fetch invariant: the URL scheme check, the MaxBytes
	// cap, the sha256 pin, and the atomic rename are enforced in Fetch regardless
	// of which client transports the bytes. A supplied client owns its own
	// redirect/transport policy (it does not inherit the default redirect guard).
	Client *http.Client

	// Redirect selects which redirects the default client follows. The zero
	// value (RedirectSameOrigin) preserves the historical strict guard. Set
	// RedirectCrossOrigin for sources behind a CDN that bounces to another host
	// (e.g. GitHub release downloads). Ignored when Client is supplied — a
	// caller-provided client owns its own redirect policy.
	Redirect RedirectPolicy
}

HTTPConfig configures a public-HTTP Source. Authentication is deliberately not modelled — v1 is anonymous-only. v2 adds an Auth type without breaking this struct's binary layout.

type RedirectPolicy added in v0.5.2

type RedirectPolicy int

RedirectPolicy governs which HTTP redirects a fetch follows. The zero value (RedirectSameOrigin) keeps the historical default so existing callers are unchanged; RedirectNone is stricter (no redirects at all) and RedirectCrossOrigin looser (also follows host changes). The constants are declared so the default is the zero value, NOT in strictness order. An https -> http downgrade is refused at EVERY level (a redirect must never strip TLS), and the chain is bounded to 10 hops wherever redirects are followed.

const (
	// RedirectSameOrigin (the default / zero value) follows only same-scheme,
	// same-host redirects (path or query changes); a host or scheme change is
	// refused. This pins the bytes to the configured origin for unpinned fetches.
	RedirectSameOrigin RedirectPolicy = iota
	// RedirectNone refuses every redirect — the fetch must reach exactly its URL.
	RedirectNone
	// RedirectCrossOrigin additionally follows host changes and http -> https
	// upgrades (e.g. a CDN such as GitHub releases redirecting github.com ->
	// release-assets.githubusercontent.com). Integrity for cross-origin fetches
	// must come from a ChecksumSHA256 pin, not from host-pinning.
	RedirectCrossOrigin
)

type Result

type Result struct {
	// Changed is false when the drift token matched and nothing was
	// written. Callers should treat this as a successful no-op.
	Changed bool

	// BytesWritten is the total payload size copied to dest on this call.
	// Zero when Changed is false.
	BytesWritten int64

	// FilesTouched is the count of leaf files placed or updated.
	// Always 1 for single-file HTTP / S3-key fetches; >1 for archive
	// extraction, Git checkouts, and S3 prefix syncs.
	FilesTouched int

	// Digest is the sha256 of the fetched payload (single file) or the
	// canonicalised tree root (directory). Hex-encoded.
	Digest string

	// Revision is an opaque drift token. HTTP: ETag or
	// content-sha256. Git: commit SHA. S3: object ETag or list-hash.
	// Callers persist this between cycles to enable idempotent re-runs.
	Revision string
}

Result is what every Source returns from Fetch. Callers compare Revision against a cached value to short-circuit no-op syncs.

type S3Config

type S3Config struct {
	// Endpoint — the base URL of the S3-compatible service.
	// e.g. "https://s3.amazonaws.com" or "https://my-minio:9000".
	Endpoint string

	// Bucket — the bucket name. 1–63 chars, mirroring AWS's published
	// limit; permissive on character set since most S3-compatibles
	// honour the standard rules and surfacing a wrong-bucket later via
	// a server 404 is just as informative.
	Bucket string

	// Key — the object key, OR a prefix ending in "/" for the Slice-12
	// prefix-sync mode. v1 single-key mode uses a non-slash-terminated
	// key.
	Key string

	// Mode / Owner / Group — applied to dest after a successful fetch.
	Mode  string
	Owner string
	Group string

	// Prune — used by the prefix-sync path (Slice 12). For single-key
	// fetches the field is currently a no-op; NewS3 accepts the
	// combination so callers can flip between single and prefix modes
	// without re-validating.
	Prune bool
}

S3Config configures an anonymous-read S3 Source. The endpoint can be any S3-compatible HTTP service (AWS, MinIO, R2, Backblaze B2's S3 gateway, …); v1 only speaks the unauthenticated path-style GET / HEAD surface, so the endpoint must serve the object at `${endpoint}/${bucket}/${key}` without signing.

Authentication is deliberately not modelled — v1 is anonymous-only. v2 adds an Auth type without breaking this struct's binary layout.

type Source

type Source interface {
	// Fetch brings the remote content to dest, idempotent on the drift
	// token: a second call against an unchanged upstream returns
	// Changed=false without re-downloading.
	Fetch(ctx context.Context, dest string) (Result, error)

	// Wipe removes dest entirely. Used for desired-state ABSENT.
	// Implementations must refuse paths outside the allow-list documented
	// on the package-level Wipe guard (see paths.go).
	Wipe(ctx context.Context, dest string) error

	// String is a short, human-readable handle ("https://… (sha256)",
	// "git https://… @ main", "s3 endpoint/bucket/key"). Used in log
	// lines and CommandOutput summaries.
	String() string
}

Source is the unified contract every backend implements. Implementations must be safe to call from multiple goroutines, though concurrent Fetch calls against the same dest will race in the obvious way (last writer wins, with the atomic-write guarantees of the individual backends).

func NewGit

func NewGit(cfg GitConfig) (Source, error)

NewGit validates cfg, resolves the version-control backend named by cfg.Driver (default "go-git"), and returns a Source. Validation failures surface as ErrInvalidConfig; an unknown driver surfaces as ErrBackendNotFound — both at construction, never deferred to Fetch where the caller has already committed to a network round trip.

func NewHTTP

func NewHTTP(cfg HTTPConfig) (Source, error)

NewHTTP validates cfg and returns a Source. Returns ErrInvalidConfig on any validation failure.

func NewS3

func NewS3(cfg S3Config) (Source, error)

NewS3 validates cfg and returns a Source. Pre-builds the full object URL so the Fetch path doesn't re-parse the endpoint every call.

type VersionControlBackend

type VersionControlBackend interface {
	// CloneOrSync brings the repo at cfg.URL to dest, checked out at
	// cfg.Ref. Idempotent on the revision: calling twice with cfg
	// unchanged leaves dest unchanged and returns Result.Changed=false.
	CloneOrSync(ctx context.Context, cfg GitConfig, dest string) (Result, error)

	// Resolve returns the current upstream revision (commit SHA,
	// changeset hash, etc.) for cfg.Ref without touching dest. Used by
	// gitSource.Fetch to short-circuit no-op pulls when the cached
	// Revision matches.
	Resolve(ctx context.Context, cfg GitConfig) (revision string, err error)
}

VersionControlBackend is the abstraction every version-controlled source driver implements. Git via go-git is the v1 driver; a future release could add a shell-out "git-binary" backend, a Mercurial / Fossil backend, etc., by Register-ing under a new name.

The interface is deliberately NOT git-named. It's modelled on the "clone or sync to a working tree at a named revision" contract that Git, Mercurial, Fossil, and Bazaar all support — the name reflects what the operation *does*, not which implementation does it.

Implementations must be safe for concurrent use across different (URL, dest) pairs. Concurrent calls against the same dest race in the obvious way and the caller is responsible for serialising.

Jump to

Keyboard shortcuts

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