source

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package source is the read boundary shared by remote package adapters. It is below HTTP routing and outside format write hooks: neither a resolver nor a body reader may run inside the transaction that publishes a cached item.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDenied         = errors.New("source: source read denied")
	ErrInvalidRequest = errors.New("source: invalid source request")
	ErrUnsupported    = errors.New("source: source kind or operation is not implemented")
	ErrUnavailable    = errors.New("source: source unavailable")
	ErrSuperseded     = errors.New("source: source configuration changed during retrieval")
	ErrInvalidResult  = errors.New("source: invalid source result")
)

Safe failures are protocol-independent. Routers map them to their own error envelopes; upstream response bodies, URLs and credentials are never messages.

Functions

func ValidGitLFSActionHeaders

func ValidGitLFSActionHeaders(headers http.Header) bool

ValidGitLFSActionHeaders limits upstream-selected basic-transfer headers to bounded end-to-end fields. The transport applies them only to the exact validated action URL and removes them before following any redirect.

Types

type Backend

type Backend interface {
	Read(context.Context, Request, Permit) (Result, error)
}

Backend resolves one already-authorized request. It owns freshness, fetching and optional publication, but cannot expand Permit. Network and body reads precede short conditional publication transactions. Any body returned with an error is closed by Service, so failed admission cannot leak a connection.

type CocoaPodsGitSource

type CocoaPodsGitSource struct {
	URL        string `json:"git"`
	Tag        string `json:"tag,omitempty"`
	Branch     string `json:"branch,omitempty"`
	Commit     string `json:"commit,omitempty"`
	Submodules bool   `json:"submodules,omitempty"`
}

CocoaPodsGitSource is the closed source contract for a pod's Git checkout. The remote backend reads Git objects without executing Git, checking out a filesystem, or handing upstream destinations to the downstream client.

func (CocoaPodsGitSource) Validate

func (g CocoaPodsGitSource) Validate() error

func (CocoaPodsGitSource) Variant

func (g CocoaPodsGitSource) Variant() string

Variant binds the cached archive to every checkout option, including the requested revision and whether Git submodules are materialized.

type FailureKind

type FailureKind int

FailureKind distinguishes status-bearing faults for freshness policy.

const (
	FailureKindHTTP FailureKind = iota + 1
	FailureKindConnectivity
	FailureKindTimeout
	FailureKindSecurity
	FailureKindIntegrity
	FailureKindProtocol
)

type HTTPError

type HTTPError struct {
	Kind       FailureKind
	Status     int
	RetryAfter time.Duration
}

HTTPError preserves an approved status without its upstream body, URL or authentication challenge. Confirmed 404 uses store.ErrNotFound; other failures must never be recorded as negative cache entries.

func (*HTTPError) Error

func (f *HTTPError) Error() string

type MetadataResponse

type MetadataResponse struct {
	BaseURL string
}

MetadataResponse is trusted adapter-only response context, never an HTTP header or log field. BaseURL contains only scheme, host and path after redirects. Adapters opting into this context must change Variant when upgrading old cache entries that did not retain their response base.

type Permit

type Permit struct {
	Identity               types.SourceIdentity
	Intent                 RetrievalIntent
	UpstreamNetworkAllowed bool
}

Permit is request-scoped authority. A future project backend may narrow UpstreamNetworkAllowed while retaining MayFetch to consult a producer's stored bytes. Each hop must narrow this permit; it cannot borrow a more privileged flight's newly fetched result. It is not a persisted credential.

type Representation

type Representation struct {
	// OriginalChecksums retain upstream declarations for Maven pass-through;
	// Checksums always describe the computed bytes.
	OriginalChecksums types.Checksums
	MediaType         string
	Size              int64
	ETag              string
	Modified          time.Time
	Checksums         types.Checksums
	ContentRange      string
}

Representation describes bytes safely, without arbitrary upstream headers or an upstream URL. Size is -1 when unknown. Validators describe these exact bytes; an adapter that rewrites metadata must replace them.

type Request

type Request struct {
	Repo      repo.Config
	Subject   authz.Subject
	Access    *authz.Decider
	Matrix    types.Matrix
	Resource  Resource
	CacheOnly bool
	Project   string
	Visited   []types.RepositoryIncarnation
}

Request carries the resolved repository and caller's permission snapshot. Adapters resolve repository existence before constructing it. Project and Visited retain the original consumer context for P11 and future P10 sources; neither is taken from caller-supplied headers.

type Resource

type Resource struct {
	// CocoaPodsGit requests a bounded Git-object archive through the normal
	// remote cache and current-authority publication fences.
	CocoaPodsGit *CocoaPodsGitSource
	// RequireSmart requests authenticated peer discovery before this prepared
	// metadata request. Only adapters set it; it conveys no network permission.
	RequireSmart bool
	// SmartAQL is a closed read-only items.find operation. It uses transient
	// metadata and the discovered peer search endpoint, never a generic POST.
	SmartAQL string
	// Adapter targets never change Path, which remains the authorization and
	// cache identity. UpstreamPath is escaped and repository-relative;
	// ExternalURL is a metadata-selected absolute URL subject to the transport's
	// DNS, redirect and credential-origin checks. They are mutually exclusive.
	UpstreamPath string
	ExternalURL  string
	// CheckURL narrows an adapter-selected destination and every redirect hop.
	// It never replaces transport DNS/credential policy and requires a Variant.
	CheckURL func(context.Context, *url.URL) error
	// NoCrossOriginAuth prevents a format-selected URL from borrowing remote
	// repository credentials, client certificates or cookies on another origin.
	NoCrossOriginAuth bool
	// GitLFSActionHeaders are bounded, validated headers supplied by an upstream
	// Git LFS download action. They apply only to that exact action URL, never
	// redirects or cached representations.
	GitLFSActionHeaders http.Header
	// Checksums pin the selected representation independently of the repository's
	// policy for optional upstream checksum headers. Variant identifies the
	// adapter validation schema; it must change if validation semantics change.
	Checksums           types.Checksums
	ExpectedContentType string
	// ExpectedContentTypes is an exact metadata MIME allowlist for negotiated APIs.
	// It requires complete body validation and cannot accompany the singular hint.
	ExpectedContentTypes []string
	Validate             func(context.Context, io.ReadSeeker, int64) error
	// ValidateMetadata validates complete metadata against the actual response
	// base after redirects. It is exclusive with Validate and requires Variant.
	ValidateMetadata func(context.Context, io.ReadSeeker, int64, MetadataResponse) error
	// PermissionFolder authorizes metadata against the folder it describes; the
	// adapter must filter its response to the readable descendants. Artifact
	// requests always authorize their exact cache path.
	PermissionFolder bool
	PermissionPath   string
	// PermissionRoot is a trusted metadata-discovery scope when a layout cannot
	// represent the query as a canonical folder. It requires actual root Read,
	// not a grant on any descendant, and disclosed files still need CheckRead.
	PermissionRoot bool
	// GoneIsMissing is a trusted protocol opt-in: GOPROXY permits member fallback
	// for both 404 and 410. Other protocols retain their existing error semantics.
	GoneIsMissing bool
	// ModuleDownloadLocation is a closed metadata projection for Terraform's
	// 204/X-Terraform-Get response. The backend retains the exact header in a
	// private JSON control representation; the adapter must validate its source
	// against the actual response base before admission and rewrite it on delivery.
	ModuleDownloadLocation bool
	// NuGetEmptyFeed projects a bodyless NuGet v2 204 into a fixed empty Atom
	// feed. Only trusted feed/query metadata adapters may opt in; complete
	// metadata validation, an Atom MIME expectation and a versioned schema remain required.
	NuGetEmptyFeed bool
	// ChecksumOnly is the trusted generic cold SHA-256 sidecar route. It must
	// remain transient and authorize the artifact it describes.
	ChecksumOnly bool
	// Mutable marks a refreshable artifact name, such as a non-unique Maven
	// snapshot. It does not turn a binary into metadata for zap semantics.
	Mutable     bool
	Kind        ResourceKind
	Path        string
	EscapedPath string
	Method      string
	// PostBody is a canonical, bounded format-owned metadata query. Only the
	// closed AI editor and Git LFS contracts below may use it. No caller
	// supplied headers or credentials are forwarded with it.
	PostBody []byte
	// Transient forbids persistent caching of a Git LFS batch response, whose
	// upstream transfer actions may carry expiring URLs or credentials.
	Transient       bool
	Query           string
	Variant         string
	Accept          string
	Range           string
	IfRange         string
	IfNoneMatch     string
	IfModifiedSince string
}

Resource contains only downstream fields a source may use. There is no caller-supplied header bag: credentials, cookies and forwarding headers cannot accidentally reach an upstream. Path is decoded and repository-relative; Query and Variant are opaque and must never be included in logs.

type ResourceKind

type ResourceKind int

ResourceKind distinguishes protocol metadata and version queries from bytes. Version lists remain authoritative upstream representations, not a listing of the subset of artifacts present in the local cache.

const (
	ResourceKindArtifact ResourceKind = iota + 1
	ResourceKindMetadata
	ResourceKindVersions
)

type Result

type Result struct {
	Metadata MetadataResponse `json:"-"`

	// CheckRead checks a disclosed descendant against current authority. It is
	// bounded by the originally authorized metadata folder and never fetches.
	CheckRead func(context.Context, string) error
	// CheckFolder checks whether a disclosed descendant folder can contain
	// readable items. It preserves narrow grants without granting file access.
	CheckFolder func(context.Context, string) error
	// Revalidate fences backend-specific credentials immediately before delivery.
	Revalidate func(context.Context) error
	Item       *types.Item
	Stream     *Stream
	Identity   types.SourceIdentity
	// Used records successful content delivery using the backend's opaque cache
	// token. The delivery adapter calls it after a successful GET/range or signed
	// URL issuance, never on lookup, HEAD, 304 or a failed body. Nil for no-store.
	Used func(context.Context) error
}

Result holds exactly one of Item and Stream. A persisted Item belongs to the consumer's cache; a stream must not be presented as a fake persisted item. Identity allows consumers and publication code to retain the source revision.

type RetrievalIntent

type RetrievalIntent int

RetrievalIntent is computed from the authorized entry point, never from an HTTP header or query parameter. CacheOnly cannot traverse a source or join a MayFetch flight, even if another request is already filling the same path.

const (
	RetrievalIntentCacheOnly RetrievalIntent = iota + 1
	RetrievalIntentMayFetch
)

type Service

type Service struct {
	Resolve    func(context.Context, repo.Config) (types.SourceIdentity, error)
	Revalidate func(context.Context, Request, Permit) error
	HTTP       Backend
	Cache      Backend
}

Service registers only the implemented HTTP source kind. Resolve obtains the durable identity matching the supplied configuration snapshot (#619), without network I/O. Revalidate, when supplied, rechecks current caller/repository authority before lookup and before returning bytes (P11 adds share revisions). The application must not install this service in production routes until the relevant adapter is ready. Nil Cache is a cache miss, never a network fallback.

func (*Service) Read

func (s *Service) Read(ctx context.Context, q Request) (Result, error)

Read applies path, permission and repository restrictions before any backend work, then fences the returned representation against a changed source. No store transaction is opened here or propagated by this package.

type Stream

type Stream struct {
	Body   io.ReadCloser
	Status int
	Representation
}

Stream is an unpersisted representation (including storeArtifactsLocally=false). Status is 200, 206 or 304. Body ownership transfers to the caller on success; the caller closes it on every path, including HEAD and downstream disconnect. Service also closes it when the request context is canceled.

Jump to

Keyboard shortcuts

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