remote

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: 74 Imported by: 0

Documentation

Overview

Package remote owns outbound HTTP for remote repositories. Callers must authorize the repository and path before consulting either cache or upstream.

Index

Constants

View Source
const MavenCompanionKind = "maven.remote-companion"
View Source
const SmartOriginHeader = "X-Artifactory-Originated"

Variables

View Source
var (
	ErrRegistryChallenge = errors.New("remote: invalid upstream registry authentication challenge")
	ErrRegistryDenied    = errors.New("remote: upstream registry authentication denied")
)
View Source
var (
	ErrURL           = errors.New("remote: invalid url or path")
	ErrRequest       = errors.New("remote: request failed")
	ErrRedirect      = errors.New("remote: redirect refused")
	ErrConfiguration = errors.New("remote: invalid transport configuration")
	ErrClosed        = errors.New("remote: transport pool closed")
	ErrConnection    = errors.New("remote: connection unavailable")
	ErrSecurity      = errors.New("remote: transport security validation failed")
)
View Source
var ErrBusy = errors.New("remote: remote retrieval capacity exhausted")
View Source
var ErrGoResponse = errors.New("remote: invalid upstream go module response")

Functions

func GoResource

func GoResource(path, method string) (source.Resource, error)

GoResource separates the case-decoded storage/permission identity from the escaped GOPROXY target. Module ZIPs and go.mod files are immutable. Info, list and latest retain the existing format's metadata classification and remain authoritative upstream bytes, independent of downloaded cache items.

func MavenMetadata

func MavenMetadata(
	ctx context.Context,
	service *source.Service,
	q source.Request,
	metadataPath string,
) (maven.SourceMetadata, error)

MavenMetadata reads source metadata for both token resolution and the #213 upstream-version consumer. It never populates a binary to discover a version.

func RegistryResource

func RegistryResource(image, operation, reference string) (source.Resource, error)

RegistryResource fixes cache and authorization paths independently of an upstream namespace prefix. Manifest Accept is canonical so supported clients share exact bytes; delivery separately checks each caller's accepted types.

func ResolveMavenSource

func ResolveMavenSource(
	ctx context.Context,
	service *source.Service,
	items *item.Service,
	q source.Request,
) (string, error)

ResolveMavenSource uses authoritative metadata for Maven's changing version names. The caller must authorize the returned canonical path before fetching.

func SmartTrace

func SmartTrace(next http.Handler) http.Handler

SmartTrace carries only loop-prevention evidence. It grants no authority and is ignored by ordinary requests. A client can use it only to deny its own Smart request, never to authenticate or widen a repository scope.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is immutable and safe for concurrent use. Every successful Do or Fetch transfers response-body ownership to the caller, including non-2xx responses.

func NewClient

func NewClient(c repo.Config, opts Options) (*Client, error)

func (*Client) Close

func (c *Client) Close()

func (*Client) Do

func (c *Client) Do(ctx context.Context, r Request) (*http.Response, error)

func (*Client) Fetch

func (c *Client) Fetch(ctx context.Context, r Request) (*http.Response, error)

Fetch probes with HEAD unless bypassed. An unsupported HEAD falls back to GET; a definitive error or conditional 304 is returned directly. GET is authoritative when the resource changes between requests: no HEAD length/checksum is reused.

type Discovery

type Discovery struct {
	// contains filtered or unexported fields
}

Discovery retains an atomic layout/source snapshot. Upstream paths are traversal inputs only; consumers receive canonical paths after lossless translation and current authorization.

func NewDiscovery

func NewDiscovery(ctx context.Context, items *item.Service, c repo.Config) (*Discovery, error)

func (*Discovery) Canonical

func (d *Discovery) Canonical() *layout.Layout

func (*Discovery) MapFile

func (d *Discovery) MapFile(upstream string) (string, bool, error)

MapFile refuses lossy or ambiguous coordinates instead of keeping the raw upstream path. Non-artifact metadata/auxiliary names are not file results.

func (*Discovery) MetadataResource

func (d *Discovery) MetadataResource(
	scope DiscoveryScope,
	upstream, variant string,
) (source.Resource, error)

MetadataResource separates the private cache/authority location from the upstream document. Callers must supply complete body validation before Read.

func (*Discovery) Read

func (d *Discovery) Read(
	ctx context.Context,
	service *source.Service,
	q source.Request,
) (source.Result, error)

Read pins the identity before Service acquires the source. A layout edit between preparing the mapping and Service.Resolve cannot adopt a new source generation with old mapping rules, even before the first network request.

func (*Discovery) Revalidate

func (d *Discovery) Revalidate(ctx context.Context) error

func (*Discovery) Scopes

func (d *Discovery) Scopes(values layout.Values) []DiscoveryScope

Scopes derives authority from complete canonical directory components. A constraint present only in a filename cannot borrow a sibling file's grant.

func (*Discovery) Upstream

func (d *Discovery) Upstream() *layout.Layout

func (*Discovery) VersionScope

func (d *Discovery) VersionScope(group, module, version string) (DiscoveryScope, bool)

VersionScope proves a version-specific artifact directory without guessing an extension, classifier or POM. Filename-only versions need actual files.

type DiscoveryScope

type DiscoveryScope struct {
	Path string
	Root bool
}

DiscoveryScope is a canonical query folder. Root requires actual root Read when the layout cannot encode the query's coordinates in a directory; a grant on an unrelated descendant cannot initiate that scan.

func (DiscoveryScope) Allows

func (s DiscoveryScope) Allows(q source.Request) bool

type FolderListing

type FolderListing struct {
	Entries []ListingEntry
	// contains filtered or unexported fields
}

FolderListing retains current authority for every page and visible child. Call Revalidate immediately before disclosing the result, including HEAD.

func ListFolder

func ListFolder(ctx context.Context, service *source.Service, q source.Request,
	folder string, budget *ListingBudget,
) (FolderListing, error)

ListFolder performs an explicit, nonrecursive source lookup. The entry point owns the documented listRemoteFolderItems policy; this source primitive does not infer an entry point from a caller-controlled parameter. CacheOnly is carried unchanged to every page.

func (FolderListing) Revalidate

func (l FolderListing) Revalidate(ctx context.Context) error

type GoSource

type GoSource struct {
	Source interface {
		Read(context.Context, source.Request) (source.Result, error)
	}
}

GoSource is the GOPROXY reader for the P10 virtual resolver. It deliberately installs no native remote HTTP route and never falls back to a VCS or sumdb. Source must be the application's authority-fenced source service, not a raw transport or cache backend. Callers retain the result's delivery/usage hooks.

func (GoSource) Read

type ListingBudget

type ListingBudget struct {
	// contains filtered or unexported fields
}

ListingBudget bounds an entire browsing/search operation, including multiple folders. A zero value is ready to use; the caller must not share it concurrently.

type ListingEntry

type ListingEntry struct {
	Path   string
	Folder bool
}

ListingEntry describes an upstream child, not a cached item. Listing never creates an item row or fetches the child's payload.

type MappedFolderListing

type MappedFolderListing struct {
	Files     []ListingEntry
	Folders   []string `json:"-"`
	Documents []string `json:"-"`
	// contains filtered or unexported fields
}

MappedFolderListing exposes only authorized canonical files. Folders are private upstream traversal cursors, never public paths or permission grants. Documents contains non-artifact control-document cursors. Consumers must validate their identities and read them under a derived canonical scope.

func ListMappedFolder

func ListMappedFolder(ctx context.Context, service *source.Service, q source.Request,
	discovery *Discovery, scope DiscoveryScope, upstreamFolder string, budget *ListingBudget,
) (MappedFolderListing, error)

ListMappedFolder uses one fixed canonical query scope for each bounded upstream page. It must never authorize an upstream lexical path, including subdirectories that the caller later traverses under that same query scope.

func (MappedFolderListing) Revalidate

func (l MappedFolderListing) Revalidate(ctx context.Context) error

type MavenBackend

type MavenBackend struct {
	Policy *Policy
	Eager  func(context.Context, source.Request, source.Permit)
}

MavenBackend opts only Maven-family routes into format-aware source retrieval. Other adapters keep the shared policy's existing behavior.

func (*MavenBackend) PrepareUpload

func (m *MavenBackend) PrepareUpload(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
	opts Options,
	u *item.CacheUpload,
) error

PrepareUpload retrieves optional external checksum files only for a newly fetched representation. Warm cache hits need no sidecar requests; pass-thru additionally preserves each available upstream digest. Every auxiliary call uses the same guarded transport and deadline.

func (*MavenBackend) Read

func (m *MavenBackend) Read(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
) (source.Result, error)

type MavenEager

type MavenEager struct {
	// contains filtered or unexported fields
}

MavenEager persists deduplicated companion work without retaining credentials. Two workers share the regular source admission limits. Pending/leased/parked jobs together are bounded to 256; failures park after three attempts. Shutdown returns interrupted leases so another process can safely resume them.

func NewMavenEager

func NewMavenEager(
	ctx context.Context,
	service *source.Service,
	policy *Policy,
	authenticator *auth.Authenticator,
	log *slog.Logger,
) (*MavenEager, error)

func (*MavenEager) Close

func (e *MavenEager) Close()

func (*MavenEager) Queue

func (e *MavenEager) Queue(ctx context.Context, q source.Request, permit source.Permit)

type Options

type Options struct {
	ProxyURL  *url.URL
	TLSConfig *tls.Config
	Revision  string
	Jar       http.CookieJar
	// CheckURL authorizes metadata-provided absolute destinations.
	CheckURL      func(context.Context, *url.URL) error
	WrapTransport func(*http.Transport) (http.RoundTripper, func())
	Prepare       func(*http.Request) error
	CheckRedirect func(*http.Request, []*http.Request) error
	// MaxResponseHeaderBytes defaults to 1 MiB; tests can lower it.
	MaxResponseHeaderBytes int64
}

Options contains resolved connection settings. Revision must change whenever externally resolved settings (proxy, trust, credentials) change. Prepare runs for initial requests and redirects, after the transport removes credentials from requests crossing origins. It must not forward downstream credentials.

type Policy

type Policy struct {
	Smart *Smart
	// Fetch overrides only the protocol exchange. Authentication adapters retain
	// the source identity and credential revision used by this cache operation.
	Fetch func(context.Context, source.Request, source.Permit, Options, Request) (*http.Response, error)
	// PrepareUpload performs bounded adapter work outside SQL, after the main
	// response succeeds and before validation/publication. It uses the same
	// transport security and cannot replace the final CheckCurrent fence.
	PrepareUpload func(context.Context, source.Request, source.Permit, Options, *item.CacheUpload) error
	Store         store.Store
	Blobs         blob.Store
	Items         *item.Service
	Pool          *Pool
	Options       func(context.Context, repo.Config) (Options, error)
	CheckCurrent  func(context.Context, store.Store, source.Request, source.Permit, string) error
	// Key is a stable keyring-derived HMAC key, never a logged cache identifier.
	Key           []byte
	Now           func() time.Time
	MetadataLimit int64
	// contains filtered or unexported fields
}

Policy implements the shared remote retrieval table. Authorization belongs to source.Service; CheckCurrent repeats it inside the short publication transaction and verifies the effective credential revision without network access.

func (*Policy) Read

func (p *Policy) Read(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
) (out source.Result, retErr error)

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool reuses a repository's connections until its configuration or resolved credential revision changes. Remove closes a deleted repository's idle clients; Close drains all idle clients during application shutdown. Active requests are owned by their caller contexts and may finish against the previous revision.

func (*Pool) Client

func (p *Pool) Client(c repo.Config, opts Options) (*Client, error)

func (*Pool) Close

func (p *Pool) Close()

func (*Pool) Remove

func (p *Pool) Remove(key string)

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry authenticates read-only Distribution v2 requests. It is bound to one resolved repository revision; RegistryPool also fences its source incarnation. Native adapters own authorization, cache publication and digest validation.

func NewRegistry

func NewRegistry(c repo.Config, opts RegistryOptions) (*Registry, error)

func (*Registry) Close

func (r *Registry) Close()

func (*Registry) Do

func (r *Registry) Do(ctx context.Context, image string, q Request) (*http.Response, error)

Do addresses a registry resource relative to an image, for example Do(ctx, "team/image", Request{Method: "GET", Path: "manifests/latest"}). A request retries authentication at most once. All returned bodies are owned by the caller, including terminal non-authentication error statuses.

func (*Registry) Image

func (r *Registry) Image(name string) (string, error)

Image returns the upstream name used in both the URL and the pull scope. dockerProjectId is an explicit namespace prefix. Docker Hub shorthand gets its protocol-defined library namespace; other registries retain the name.

func (*Registry) Probe

func (r *Registry) Probe(ctx context.Context) (*http.Response, error)

Probe performs /v2/ discovery through the same bounded challenge flow.

type RegistryContent

type RegistryContent struct {
	Policy  *Policy
	Pool    *RegistryPool
	Options func(context.Context, repo.Config) (RegistryOptions, error)
	// contains filtered or unexported fields
}

RegistryContent installs Distribution authentication and validation on a fresh shared policy. The pool and resolver belong to the application lifetime.

func (*RegistryContent) Install

func (c *RegistryContent) Install()

func (*RegistryContent) Read

func (c *RegistryContent) Read(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
) (source.Result, error)

type RegistryOptions

type RegistryOptions struct {
	Transport Options
	Now       func() time.Time
	// contains filtered or unexported fields
}

RegistryOptions comes from Resolver.RegistryOptions, never downstream headers. Now is an optional clock for deterministic expiry tests.

type RegistryPool

type RegistryPool struct {
	// contains filtered or unexported fields
}

RegistryPool owns token and connection lifetimes. A changed repository incarnation, source generation or credential revision starts an empty cache.

func (*RegistryPool) Client

func (p *RegistryPool) Client(
	c repo.Config,
	identity types.SourceIdentity,
	opts RegistryOptions,
) (*Registry, error)

func (*RegistryPool) Close

func (p *RegistryPool) Close()

func (*RegistryPool) Remove

func (p *RegistryPool) Remove(key string)

type Request

type Request struct {

	// ExternalURL is a metadata/token-realm URL, never combined with Path/Query.
	// It requires a resolved destination policy.
	ExternalURL string
	// CheckURL is a request-scoped restriction, never retained by the pooled client.
	// It applies before the initial request and each redirected request is sent.
	CheckURL          func(context.Context, *url.URL) error
	NoCrossOriginAuth bool
	// GitLFSActionHeaders belong only to the exact, validated download action.
	// They are never copied to a redirected request.
	GitLFSActionHeaders http.Header
	Method              string
	Path                string
	Query               string
	Header              http.Header
	Metadata            bool
	// Body is admitted only for closed format-owned metadata POST contracts.
	Body []byte
	// contains filtered or unexported fields
}

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

func NewResolver

func NewResolver(st store.Store, keyring *crypt.Keyring, opts ResolverOptions) (*Resolver, error)

func (*Resolver) Options

func (r *Resolver) Options(ctx context.Context, c repo.Config) (Options, error)

Options reloads sealed secrets through the store, rather than treating an API's masked view as usable credentials. A stale non-secret configuration fails closed. Revision is a stable HMAC of source-affecting settings, not cache/access policy.

func (*Resolver) RegistryOptions

func (r *Resolver) RegistryOptions(ctx context.Context, c repo.Config) (RegistryOptions, error)

RegistryOptions preserves the shared destination, proxy and TLS policy while keeping registry Basic credentials separate from ordinary HTTP Bearer mode.

type ResolverOptions

type ResolverOptions struct {
	// RevisionKey is trusted, stable application key material for installations
	// without a master key. It never comes from a repository or HTTP request.
	RevisionKey           []byte
	RootCAsPEM            []byte
	AllowedPrivateOrigins []string
	LookupIP              func(context.Context, string) ([]net.IPAddr, error)
}

ResolverOptions is trusted application configuration, never upstream metadata. RootCAsPEM augments system trust. AllowedPrivateOrigins grants exact additional authorities private-network access without authorizing credential forwarding. LookupIP is injectable for deterministic DNS/rebinding tests; nil uses net.Resolver.

type Smart

type Smart struct {
	// contains filtered or unexported fields
}

Smart adds authenticated discovery and bounded durable side effects to one shared policy. Registry and ordinary policies keep separate validators.

func NewSmart

func NewSmart(
	ctx context.Context,
	p *Policy,
	pool *Pool,
	a *auth.Authenticator,
	kind string,
	log *slog.Logger,
) (*Smart, error)

func (*Smart) Close

func (s *Smart) Close()

func (*Smart) Discover

func (s *Smart) Discover(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
) (SmartPeer, error)

Discover requires the caller's existing permit. Public adapters invoke it through RequireSmart and source.Service, never manufacture their own permit.

func (*Smart) Read

func (s *Smart) Read(
	ctx context.Context,
	q source.Request,
	permit source.Permit,
) (source.Result, error)

func (*Smart) Status

func (s *Smart) Status(ctx context.Context, key, path string) (SmartStatus, error)

Status reads one exact path under a source lifetime lock. Options resolves only stored settings: this endpoint never discovers or contacts a peer.

type SmartPeer

type SmartPeer struct {
	BaseURL    string
	Repository string
	Class      repo.Class
	Version    string
	// contains filtered or unexported fields
}

SmartPeer identifies only the configured peer. Parsing it does not negotiate capabilities or grant network authority; callers use source.Service.Read. Class and Version are filled only by authenticated discovery.

func ParseSmartPeer

func ParseSmartPeer(c repo.Config) (SmartPeer, error)

ParseSmartPeer accepts repository endpoints, including the documented api/<package>/<repository> forms. Query-bearing and ambiguous endpoint paths cannot safely identify a different management API and are refused.

func (SmartPeer) StorageURL

func (p SmartPeer) StorageURL(path string, query url.Values) (string, error)

StorageURL constructs a peer storage endpoint without accepting another authority, repository, or a preescaped traversal. It never performs I/O.

type SmartRepresentationStatus

type SmartRepresentationStatus struct {
	PropertiesCheckedAt time.Time         `json:"properties_checked_at"`
	OriginCheckedAt     time.Time         `json:"origin_checked_at"`
	OriginAbsent        *bool             `json:"origin_absent,omitempty"`
	Downloads           int64             `json:"downloads"`
	Claimed             int64             `json:"claimed"`
	Uncertain           int64             `json:"uncertain"`
	Work                []SmartWorkStatus `json:"work"`
}

type SmartStatus

type SmartStatus struct {
	Repository      string                      `json:"repository"`
	Path            string                      `json:"path"`
	Representations []SmartRepresentationStatus `json:"representations"`
	Truncated       bool                        `json:"truncated"`
}

SmartStatus is an artifactweave diagnostic, not an Artifactory storage wire document. A zero origin timestamp means unknown, never confirmed absent.

type SmartWorkStatus

type SmartWorkStatus struct {
	Operation string          `json:"operation"`
	State     types.WorkState `json:"state"`
	Attempts  int             `json:"attempts"`
}

Jump to

Keyboard shortcuts

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