getproviders

package
v0.24.3 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2023 License: Apache-2.0, MPL-2.0 Imports: 39 Imported by: 0

Documentation

Overview

Package getproviders is the lowest-level provider automatic installation functionality. It can answer questions about what providers and provider versions are available in a registry, and it can retrieve the URL for the distribution archive for a specific version of a specific provider targeting a particular platform.

This package is not responsible for choosing the best version to install from a set of available versions, or for any signature verification of the archives it fetches. Callers will use this package in conjunction with other logic elsewhere in order to construct a full provider installer.

Index

Constants

View Source
const HashicorpPartnersKey = `` /* 3194-byte string literal not displayed */

HashicorpPartnersKey is a key created by HashiCorp, used to generate and verify trust signatures for Partner tier providers.

View Source
const HashicorpPublicKey = `` /* 7716-byte string literal not displayed */

HashicorpPublicKey is the HashiCorp public key, also available at https://www.hashicorp.com/security

View Source
const NilHash = Hash("")

NilHash is the zero value of Hash. It isn't a valid hash, so all of its methods will panic.

View Source
const Wildcard string = "*"

Wildcard is a string value representing a wildcard element in the Include and Exclude patterns used with MultiSource. It is not valid to use Wildcard anywhere else.

Variables

View Source
var CurrentPlatform = Platform{
	OS:   runtime.GOOS,
	Arch: runtime.GOARCH,
}

CurrentPlatform is the platform where the current program is running.

If attempting to install providers for use on the same system where the installation process is running, this is the right platform to use.

View Source
var SupportedPluginProtocols = MustParseVersionConstraints(">= 5, <7")

Functions

func ErrIsNotExist

func ErrIsNotExist(err error) bool

ErrIsNotExist returns true if and only if the given error is one of the errors from this package that represents an affirmative response that a requested object does not exist.

This is as opposed to errors indicating that the source is unavailable or misconfigured in some way, where we therefore cannot say for certain whether the requested object exists.

If a caller needs to take a special action based on something not existing, such as falling back on some other source, use this function rather than direct type assertions so that the set of possible "not exist" errors can grow in future.

func HostFromRequest

func HostFromRequest(req *http.Request) string

HostFromRequest extracts host the same way net/http Request.Write would, accounting for empty Request.Host

func MissingProviderSuggestion

func MissingProviderSuggestion(ctx context.Context, addr addrs.Provider, source Source, reqs Requirements) addrs.Provider

MissingProviderSuggestion takes a provider address that failed installation due to the remote registry reporting that it didn't exist, and attempts to find another provider that the user might have meant to select.

If the result is equal to the given address then that indicates that there is no suggested alternative to offer, either because the function successfully determined there is no recorded alternative or because the lookup failed somehow. We don't consider a failure to find a suggestion as an installation failure, because the caller should already be reporting that the provider didn't exist anyway and this is only extra context for that error message.

The result of this is a best effort, so any UI presenting it should be careful to give it only as a possibility and not necessarily a suitable replacement for the given provider.

In practice today this function only knows how to suggest alternatives for "default" providers, which is to say ones that are in the hashicorp namespace in the Terraform registry. It will always return no result for any other provider. That might change in future if we introduce other ways to discover provider suggestions.

If the given context is cancelled then this function might not return a renaming suggestion even if one would've been available for a completed request.

func PackageMatchesAnyHash

func PackageMatchesAnyHash(loc PackageLocation, allowed []Hash) (bool, error)

PackageMatchesAnyHash returns true if the package at the given location matches at least one of the given hashes, or false otherwise.

If it cannot read from the given location, PackageMatchesAnyHash returns an error. Unlike the singular PackageMatchesHash, PackageMatchesAnyHash considers unsupported hash formats as successfully non-matching, rather than returning an error.

PackageMatchesAnyHash can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func PackageMatchesHash

func PackageMatchesHash(loc PackageLocation, want Hash) (bool, error)

PackageMatchesHash returns true if the package at the given location matches the given hash, or false otherwise.

If it cannot read from the given location, or if the given hash is in an unsupported format, PackageMatchesHash returns an error.

There is currently only one hash format, as implemented by HashV1. However, if others are introduced in future PackageMatchesHash may accept multiple formats, and may generate errors for any formats that become obsolete.

PackageMatchesHash can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func PackedFilePathForPackage

func PackedFilePathForPackage(baseDir string, provider addrs.Provider, version Version, platform Platform) string

PackedFilePathForPackage is similar to PackageMeta.PackedFilePath but makes its decision based on individually-passed provider address, version, and target platform so that it can be used by callers outside this package that may have other types that represent package identifiers.

func SearchLocalDirectory

func SearchLocalDirectory(baseDir string) (map[addrs.Provider]PackageMetaList, error)

SearchLocalDirectory performs an immediate, one-off scan of the given base directory for provider plugins using the directory structure defined for FilesystemMirrorSource.

This is separated to allow other callers, such as the provider plugin cache management in the "internal/providercache" package, to use the same directory structure conventions.

func UnpackedDirectoryPathForPackage

func UnpackedDirectoryPathForPackage(baseDir string, provider addrs.Provider, version Version, platform Platform) string

UnpackedDirectoryPathForPackage is similar to PackageMeta.UnpackedDirectoryPath but makes its decision based on individually-passed provider address, version, and target platform so that it can be used by callers outside this package that may have other types that represent package identifiers.

func VersionConstraintsString

func VersionConstraintsString(spec VersionConstraints) string

VersionConstraintsString returns a canonical string representation of a VersionConstraints value.

Types

type ErrHostNoProviders

type ErrHostNoProviders struct {
	Hostname svchost.Hostname

	// HasOtherVersionis set to true if the discovery process detected
	// declarations of services named "providers" whose version numbers did not
	// match any version supported by the current version of Terraform.
	//
	// If this is set, it's helpful to hint to the user in an error message
	// that the provider host may be expecting an older or a newer version
	// of Terraform, rather than that it isn't a provider registry host at all.
	HasOtherVersion bool
}

ErrHostNoProviders is an error type used to indicate that a hostname given in a provider address does not support the provider registry protocol.

func (ErrHostNoProviders) Error

func (err ErrHostNoProviders) Error() string

type ErrHostUnreachable

type ErrHostUnreachable struct {
	Hostname svchost.Hostname
	Wrapped  error
}

ErrHostUnreachable is an error type used to indicate that a hostname given in a provider address did not resolve in DNS, did not respond to an HTTPS request for service discovery, or otherwise failed to correctly speak the service discovery protocol.

func (ErrHostUnreachable) Error

func (err ErrHostUnreachable) Error() string

func (ErrHostUnreachable) Unwrap

func (err ErrHostUnreachable) Unwrap() error

Unwrap returns the underlying error that occurred when trying to reach the indicated host.

type ErrPlatformNotSupported

type ErrPlatformNotSupported struct {
	Provider addrs.Provider
	Version  Version
	Platform Platform

	// MirrorURL, if non-nil, is the base URL of the mirror that serviced
	// the request in place of the provider's origin registry. MirrorURL
	// is nil for a direct query.
	MirrorURL *url.URL
}

ErrPlatformNotSupported is an error type used to indicate that a particular version of a provider isn't available for a particular target platform.

This is returned when DownloadLocation encounters a 404 Not Found response from the underlying registry, because it presumes that a caller will only ask for the DownloadLocation for a version it already found the existence of via AvailableVersions.

func (ErrPlatformNotSupported) Error

func (err ErrPlatformNotSupported) Error() string

type ErrProtocolNotSupported

type ErrProtocolNotSupported struct {
	Provider   addrs.Provider
	Version    Version
	Suggestion Version
}

ErrProtocolNotSupported is an error type used to indicate that a particular version of a provider is not supported by the current version of Terraform.

Specfically, this is returned when the version's plugin protocol is not supported.

When available, the error will include a suggested version that can be displayed to the user. Otherwise it will return UnspecifiedVersion

func (ErrProtocolNotSupported) Error

func (err ErrProtocolNotSupported) Error() string

type ErrProviderNotFound

type ErrProviderNotFound struct {
	Provider addrs.Provider
	Sources  []string
}

ErrProviderNotFound is an error type used to indicate that requested provider was not found in the source(s) included in the Description field. This can be used to produce user-friendly error messages.

func (ErrProviderNotFound) Error

func (err ErrProviderNotFound) Error() string

type ErrQueryFailed

type ErrQueryFailed struct {
	Provider addrs.Provider
	Wrapped  error

	// MirrorURL, if non-nil, is the base URL of the mirror that serviced
	// the request in place of the provider's origin registry. MirrorURL
	// is nil for a direct query.
	MirrorURL *url.URL
}

ErrQueryFailed is an error type used to indicate that the hostname given in a provider address does appear to be a provider registry but that when we queried it for metadata for the given provider the server returned an unexpected error.

This is used for any error responses other than "Not Found", which would indicate the absense of a provider and is thus reported using ErrProviderNotKnown instead.

func (ErrQueryFailed) Error

func (err ErrQueryFailed) Error() string

func (ErrQueryFailed) Unwrap

func (err ErrQueryFailed) Unwrap() error

Unwrap returns the underlying error that occurred when trying to reach the indicated host.

type ErrRegistryProviderNotKnown

type ErrRegistryProviderNotKnown struct {
	Provider addrs.Provider
}

ErrRegistryProviderNotKnown is an error type used to indicate that the hostname given in a provider address does appear to be a provider registry but that registry does not know about the given provider namespace or type.

A caller serving requests from an end-user should recognize this error type and use it to produce user-friendly hints for common errors such as failing to specify an explicit source for a provider not in the default namespace (one not under registry.terraform.io/hashicorp/). The default error message for this type is a direct description of the problem with no such hints, because we expect that the caller will have better context to decide what hints are appropriate, e.g. by looking at the configuration given by the user.

func (ErrRegistryProviderNotKnown) Error

func (err ErrRegistryProviderNotKnown) Error() string

type ErrRequestCanceled

type ErrRequestCanceled struct {
}

ErrRequestCanceled is an error type used to indicate that an operation failed due to being cancelled via the given context.Context object.

This error type doesn't include information about what was cancelled, because the expected treatment of this error type is to quickly abort and exit with minimal ceremony.

func (ErrRequestCanceled) Error

func (err ErrRequestCanceled) Error() string

type ErrUnauthorized

type ErrUnauthorized struct {
	Hostname svchost.Hostname

	// HaveCredentials is true when the request that failed included some
	// credentials, and thus it seems that those credentials were invalid.
	// Conversely, HaveCredentials is false if the request did not include
	// credentials at all, in which case it seems that credentials must be
	// provided.
	HaveCredentials bool
}

ErrUnauthorized is an error type used to indicate that a hostname given in a provider address returned a "401 Unauthorized" or "403 Forbidden" error response when we tried to access it.

func (ErrUnauthorized) Error

func (err ErrUnauthorized) Error() string

type FilesystemMirrorSource

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

FilesystemMirrorSource is a source that reads providers and their metadata from a directory prefix in the local filesystem.

func NewFilesystemMirrorSource

func NewFilesystemMirrorSource(baseDir string) *FilesystemMirrorSource

NewFilesystemMirrorSource constructs and returns a new filesystem-based mirror source with the given base directory.

func (*FilesystemMirrorSource) AllAvailablePackages

func (s *FilesystemMirrorSource) AllAvailablePackages() (map[addrs.Provider]PackageMetaList, error)

AllAvailablePackages scans the directory structure under the source's base directory for locally-mirrored packages for all providers, returning a map of the discovered packages with the fully-qualified provider names as keys.

This is not an operation generally supported by all Source implementations, but the filesystem implementation offers it because we also use the filesystem mirror source directly to scan our auto-install plugin directory and in other automatic discovery situations.

func (*FilesystemMirrorSource) AvailableVersions

func (s *FilesystemMirrorSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

AvailableVersions scans the directory structure under the source's base directory for locally-mirrored packages for the given provider, returning a list of version numbers for the providers it found.

func (*FilesystemMirrorSource) ForDisplay

func (s *FilesystemMirrorSource) ForDisplay(provider addrs.Provider) string

func (*FilesystemMirrorSource) PackageMeta

func (s *FilesystemMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

PackageMeta checks to see if the source's base directory contains a local copy of the distribution package for the given provider version on the given target, and returns the metadata about it if so.

type HTTPMirrorSource

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

HTTPMirrorSource is a source that reads provider metadata from a provider mirror that is accessible over the HTTP provider mirror protocol.

func NewHTTPMirrorSource

func NewHTTPMirrorSource(baseURL *url.URL, creds svcauth.CredentialsSource) *HTTPMirrorSource

NewHTTPMirrorSource constructs and returns a new network mirror source with the given base URL. The relative URL offsets defined by the HTTP mirror protocol will be resolve relative to the given URL.

The given URL must use the "https" scheme, or this function will panic. (When the URL comes from user input, such as in the CLI config, it's the UI/config layer's responsibility to validate this and return a suitable error message for the end-user audience.)

func (*HTTPMirrorSource) AvailableVersions

func (s *HTTPMirrorSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

AvailableVersions retrieves the available versions for the given provider from the object's underlying HTTP mirror service.

func (*HTTPMirrorSource) ForDisplay

func (s *HTTPMirrorSource) ForDisplay(provider addrs.Provider) string

ForDisplay returns a string description of the source for user-facing output.

func (*HTTPMirrorSource) PackageMeta

func (s *HTTPMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

PackageMeta retrieves metadata for the requested provider package from the object's underlying HTTP mirror service.

type HangingSource

type HangingSource struct {
}

HangingSource is an implementation of Source which hangs until the given context is cancelled. This is useful only for unit tests of user-controlled cancels.

func (*HangingSource) AvailableVersions

func (s *HangingSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

func (*HangingSource) ForDisplay

func (s *HangingSource) ForDisplay(provider addrs.Provider) string

func (*HangingSource) PackageMeta

func (s *HangingSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

type Hash

type Hash string

Hash is a specially-formatted string representing a checksum of a package or the contents of the package.

A Hash string is always starts with a scheme, which is a short series of alphanumeric characters followed by a colon, and then the remainder of the string has a different meaning depending on the scheme prefix.

The currently-valid schemes are defined as the constants of type HashScheme in this package.

Callers outside of this package must not create Hash values via direct conversion. Instead, use either the HashScheme.New method on one of the HashScheme contents (for a hash of a particular scheme) or the ParseHash function (if hashes of any scheme are acceptable).

func HashLegacyZipSHAFromSHA

func HashLegacyZipSHAFromSHA(sum [sha256.Size]byte) Hash

HashLegacyZipSHAFromSHA is a convenience method to produce the schemed-string hash format from an already-calculated hash of a provider .zip archive.

This just adds the "zh:" prefix and encodes the string in hex, so that the result is in the same format as PackageHashLegacyZipSHA.

func MustParseHash

func MustParseHash(s string) Hash

MustParseHash is a wrapper around ParseHash that panics if it returns an error.

func PackageHash

func PackageHash(loc PackageLocation) (Hash, error)

PackageHash computes a hash of the contents of the package at the given location, using whichever hash algorithm is the current default.

Currently, this method returns version 1 hashes as produced by the function PackageHashV1, but this function may switch to other versions in later releases. Call PackageHashV1 directly if you specifically need a V1 hash.

PackageHash can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func PackageHashLegacyZipSHA

func PackageHashLegacyZipSHA(loc PackageLocalArchive) (Hash, error)

PackageHashLegacyZipSHA implements the old provider package hashing scheme of taking a SHA256 hash of the containing .zip archive itself, rather than of the contents of the archive.

The result is a hash string with the "zh:" prefix, which is intended to represent "zip hash". After the prefix is a lowercase-hex encoded SHA256 checksum, intended to exactly match the formatting used in the registry API (apart from the prefix) so that checksums can be more conveniently compared by humans.

Because this hashing scheme uses the official provider .zip file as its input, it accepts only PackageLocalArchive locations.

func PackageHashV1

func PackageHashV1(loc PackageLocation) (Hash, error)

PackageHashV1 computes a hash of the contents of the package at the given location using hash algorithm 1. The resulting Hash is guaranteed to have the scheme HashScheme1.

The hash covers the paths to files in the directory and the contents of those files. It does not cover other metadata about the files, such as permissions.

This function is named "PackageHashV1" in anticipation of other hashing algorithms being added in a backward-compatible way in future. The result from PackageHashV1 always begins with the prefix "h1:" so that callers can distinguish the results of potentially multiple different hash algorithms in future.

PackageHashV1 can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func ParseHash

func ParseHash(s string) (Hash, error)

ParseHash parses the string representation of a Hash into a Hash value.

A particular version of Terraform only supports a fixed set of hash schemes, but this function intentionally allows unrecognized schemes so that we can silently ignore other schemes that may be introduced in the future. For that reason, the Scheme method of the returned Hash may return a value that isn't in one of the HashScheme constants in this package.

This function doesn't verify that the value portion of the given hash makes sense for the given scheme. Invalid values are just considered to not match any packages.

If this function returns an error then the returned Hash is invalid and must not be used.

func PreferredHashes

func PreferredHashes(given []Hash) []Hash

PreferredHashes examines all of the given hash strings and returns the one that the current version of Terraform considers to provide the strongest verification.

Returns an empty string if none of the given hashes are of a supported format. If PreferredHash returns a non-empty string then it will be one of the hash strings in "given", and that hash is the one that must pass verification in order for a package to be considered valid.

func (Hash) GoString

func (h Hash) GoString() string

GoString returns a Go syntax representation of the receiving hash.

This is here primarily to help with producing descriptive test failure output; these results are not particularly useful at runtime.

func (Hash) HasScheme

func (h Hash) HasScheme(want HashScheme) bool

HasScheme returns true if the given scheme matches the receiver's scheme, or false otherwise.

If the receiver is not using valid syntax then this method will panic.

func (Hash) Scheme

func (h Hash) Scheme() HashScheme

Scheme returns the scheme of the recieving hash. If the receiver is not using valid syntax then this method will panic.

func (Hash) String

func (h Hash) String() string

String returns a string representation of the receiving hash.

func (Hash) Value

func (h Hash) Value() string

Value returns the scheme-specific value from the recieving hash. The meaning of this value depends on the scheme.

If the receiver is not using valid syntax then this method will panic.

type HashScheme

type HashScheme string

HashScheme is an enumeration of schemes that are allowed for values of type Hash.

const (
	// HashScheme1 is the scheme identifier for the first hash scheme.
	//
	// Use HashV1 (or one of its wrapper functions) to calculate hashes with
	// this scheme.
	HashScheme1 HashScheme = HashScheme("h1:")

	// HashSchemeZip is the scheme identifier for the legacy hash scheme that
	// applies to distribution archives (.zip files) rather than package
	// contents, and can therefore only be verified against the original
	// distribution .zip file, not an extracted directory.
	//
	// Use PackageHashLegacyZipSHA to calculate hashes with this scheme.
	HashSchemeZip HashScheme = HashScheme("zh:")
)

func (HashScheme) New

func (hs HashScheme) New(value string) Hash

New creates a new Hash value with the receiver as its scheme and the given raw string as its value.

It's the caller's responsibility to make sure that the given value makes sense for the selected scheme.

type MemoizeSource

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

MemoizeSource is a Source that wraps another Source and remembers its results so that they can be returned more quickly on future calls to the same object.

Each MemoizeSource maintains a cache of response it has seen as part of its body. All responses are retained for the remaining lifetime of the object. Errors from the underlying source are also cached, and so subsequent calls with the same arguments will always produce the same errors.

A MemoizeSource can be called concurrently, with incoming requests processed sequentially.

func NewMemoizeSource

func NewMemoizeSource(underlying Source) *MemoizeSource

NewMemoizeSource constructs and returns a new MemoizeSource that wraps the given underlying source and memoizes its results.

func (*MemoizeSource) AvailableVersions

func (s *MemoizeSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

AvailableVersions requests the available versions from the underlying source and caches them before returning them, or on subsequent calls returns the result directly from the cache.

func (*MemoizeSource) ForDisplay

func (s *MemoizeSource) ForDisplay(provider addrs.Provider) string

func (*MemoizeSource) PackageMeta

func (s *MemoizeSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

PackageMeta requests package metadata from the underlying source and caches the result before returning it, or on subsequent calls returns the result directly from the cache.

type MockSource

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

MockSource is an in-memory-only, statically-configured source intended for use only in unit tests of other subsystems that consume provider sources.

The MockSource also tracks calls to it in case a calling test wishes to assert that particular calls were made.

This should not be used outside of unit test code.

func NewMockSource

func NewMockSource(packages []PackageMeta, warns map[addrs.Provider]Warnings) *MockSource

NewMockSource creates and returns a MockSource with the given packages.

The given packages don't necessarily need to refer to objects that actually exist on disk or over the network, unless the calling test is planning to use (directly or indirectly) the results for further provider installation actions.

func (*MockSource) AvailableVersions

func (s *MockSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

AvailableVersions returns all of the versions of the given provider that are available in the fixed set of packages that were passed to NewMockSource when creating the receiving source.

func (*MockSource) CallLog

func (s *MockSource) CallLog() [][]interface{}

CallLog returns a list of calls to other methods of the receiever that have been called since it was created, in case a calling test wishes to verify a particular sequence of operations.

The result is a slice of slices where the first element of each inner slice is the name of the method that was called, and then any subsequent elements are positional arguments passed to that method.

Callers are forbidden from modifying any objects accessible via the returned value.

func (*MockSource) ForDisplay

func (s *MockSource) ForDisplay(provider addrs.Provider) string

func (*MockSource) PackageMeta

func (s *MockSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

PackageMeta returns the first package from the list given to NewMockSource when creating the receiver that has the given provider, version, and target platform.

If none of the packages match, it returns ErrPlatformNotSupported to simulate the situation where a provider release isn't available for a particular platform.

Note that if the list of packages passed to NewMockSource contains more than one with the same provider, version, and target this function will always return the first one in the list, which may not match the behavior of other sources in an equivalent situation because it's a degenerate case with undefined results.

type MultiSource

type MultiSource []MultiSourceSelector

MultiSource is a Source that wraps a series of other sources and combines their sets of available providers and provider versions.

A MultiSource consists of a sequence of selectors that each specify an underlying source to query and a set of matching patterns to decide which providers can be retrieved from which sources. If multiple selectors find a given provider version then the earliest one in the sequence takes priority for deciding the package metadata for the provider.

For underlying sources that make network requests, consider wrapping each one in a MemoizeSource so that availability information retrieved in AvailableVersions can be reused in PackageMeta.

func (MultiSource) AvailableVersions

func (s MultiSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

AvailableVersions retrieves all of the versions of the given provider that are available across all of the underlying selectors, while respecting each selector's matching patterns.

func (MultiSource) ForDisplay

func (s MultiSource) ForDisplay(provider addrs.Provider) string

func (MultiSource) PackageMeta

func (s MultiSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

PackageMeta retrieves the package metadata for the requested provider package from the first selector that indicates availability of it.

type MultiSourceMatchingPatterns

type MultiSourceMatchingPatterns []addrs.Provider

MultiSourceMatchingPatterns is a set of patterns that together define a set of providers by matching on the segments of the provider FQNs.

The Provider address values in a MultiSourceMatchingPatterns are special in that any of Hostname, Namespace, or Type can be getproviders.Wildcard to indicate that any concrete value is permitted for that segment.

func ParseMultiSourceMatchingPatterns

func ParseMultiSourceMatchingPatterns(strs []string) (MultiSourceMatchingPatterns, error)

ParseMultiSourceMatchingPatterns parses a slice of strings containing the string form of provider matching patterns and, if all the given strings are valid, returns the corresponding, normalized, MultiSourceMatchingPatterns value.

func (MultiSourceMatchingPatterns) MatchesProvider

func (ps MultiSourceMatchingPatterns) MatchesProvider(addr addrs.Provider) bool

MatchesProvider tests whether the receiving matching patterns match with the given concrete provider address.

type MultiSourceSelector

type MultiSourceSelector struct {
	// Source is the underlying source that this selector applies to.
	Source Source

	// Include and Exclude are sets of provider matching patterns that
	// together define which providers are eligible to be potentially
	// installed from the corresponding Source.
	Include, Exclude MultiSourceMatchingPatterns
}

MultiSourceSelector is an element of the source selection configuration on MultiSource. A MultiSource has zero or more of these to configure which underlying sources it should consult for a given provider.

func (MultiSourceSelector) CanHandleProvider

func (s MultiSourceSelector) CanHandleProvider(addr addrs.Provider) bool

CanHandleProvider returns true if and only if the given provider address is both included by the selector's include patterns and _not_ excluded by its exclude patterns.

The absense of any include patterns is treated the same as a pattern that matches all addresses. Exclusions take priority over inclusions.

type PackageAuthentication

type PackageAuthentication interface {
	// AuthenticatePackage takes the local location of a package (which may or
	// may not be the same as the original source location), and returns a
	// PackageAuthenticationResult, or an error if the authentication checks
	// fail.
	//
	// The local location is guaranteed not to be a PackageHTTPURL: a remote
	// package will always be staged locally for inspection first.
	AuthenticatePackage(localLocation PackageLocation) (*PackageAuthenticationResult, error)
}

PackageAuthentication is an interface implemented by the optional package authentication implementations a source may include on its PackageMeta objects.

A PackageAuthentication implementation is responsible for authenticating that a package is what its distributor intended to distribute and that it has not been tampered with.

func NewArchiveChecksumAuthentication

func NewArchiveChecksumAuthentication(platform Platform, wantSHA256Sum [sha256.Size]byte) PackageAuthentication

NewArchiveChecksumAuthentication returns a PackageAuthentication implementation that checks that the original distribution archive matches the given hash.

This authentication is suitable only for PackageHTTPURL and PackageLocalArchive source locations, because the unpacked layout (represented by PackageLocalDir) does not retain access to the original source archive. Therefore this authenticator will return an error if its given localLocation is not PackageLocalArchive.

NewPackageHashAuthentication is preferable to use when possible because it uses the newer hashing scheme (implemented by function PackageHash) that can work with both packed and unpacked provider packages.

func NewMatchingChecksumAuthentication

func NewMatchingChecksumAuthentication(document []byte, filename string, wantSHA256Sum [sha256.Size]byte) PackageAuthentication

NewMatchingChecksumAuthentication returns a PackageAuthentication implementation that scans a registry-provided SHA256SUMS document for a specified filename, and compares the SHA256 hash against the expected hash. This is necessary to ensure that the signed SHA256SUMS document matches the declared SHA256 hash for the package, and therefore that a valid signature of this document authenticates the package.

This authentication always returns a nil result, since it alone cannot offer any assertions about package integrity. It should be combined with other authentications to be useful.

func NewPackageHashAuthentication

func NewPackageHashAuthentication(platform Platform, validHashes []Hash) PackageAuthentication

NewPackageHashAuthentication returns a PackageAuthentication implementation that checks whether the contents of the package match whatever subset of the given hashes are considered acceptable by the current version of Terraform.

This uses the hash algorithms implemented by functions PackageHash and MatchesHash. The PreferredHashes function will select which of the given hashes are considered by Terraform to be the strongest verification, and authentication succeeds as long as one of those matches.

func NewSignatureAuthentication

func NewSignatureAuthentication(document, signature []byte, keys []SigningKey) PackageAuthentication

NewSignatureAuthentication returns a PackageAuthentication implementation that verifies the cryptographic signature for a package against any of the provided keys.

The signing key for a package will be auto detected by attempting each key in turn until one is successful. If such a key is found, there are three possible successful authentication results:

  1. If the signing key is the HashiCorp official key, it is an official provider;
  2. Otherwise, if the signing key has a trust signature from the HashiCorp Partners key, it is a partner provider;
  3. If neither of the above is true, it is a community provider.

Any failure in the process of validating the signature will result in an unauthenticated result.

func PackageAuthenticationAll

func PackageAuthenticationAll(checks ...PackageAuthentication) PackageAuthentication

PackageAuthenticationAll combines several authentications together into a single check value, which passes only if all of the given ones pass.

The checks are processed in the order given, so a failure of an earlier check will prevent execution of a later one.

The returned result is from the last authentication, so callers should take care to order the authentications such that the strongest is last.

The returned object also implements the AcceptableHashes method from interface PackageAuthenticationHashes, returning the hashes from the last of the given checks that indicates at least one acceptable hash, or no hashes at all if none of the constituents indicate any. The result may therefore be incomplete if there is more than one check that can provide hashes and they disagree about which hashes are acceptable.

type PackageAuthenticationHashes

type PackageAuthenticationHashes interface {
	PackageAuthentication

	// AcceptableHashes returns a set of hashes that this authenticator
	// considers to be valid for the current package or, where possible,
	// equivalent packages on other platforms. The order of the items in
	// the result is not significant, and it may contain duplicates
	// that are also not significant.
	//
	// This method's result should only be used to create a "lock" for a
	// particular provider if an earlier call to AuthenticatePackage for
	// the corresponding package succeeded. A caller might choose to apply
	// differing levels of trust for the acceptable hashes depending on
	// the authentication result: a "verified checksum" result only checked
	// that the downloaded package matched what the source claimed, which
	// could be considered to be less trustworthy than a check that includes
	// verifying a signature from the origin registry, depending on what the
	// hashes are going to be used for.
	//
	// Implementations of PackageAuthenticationHashes may return multiple
	// hashes with different schemes, which means that all of them are equally
	// acceptable. Implementors may also return hashes that use schemes the
	// current version of the authenticator would not allow but that could be
	// accepted by other versions of Terraform, e.g. if a particular hash
	// scheme has been deprecated.
	//
	// Authenticators that don't use hashes as their authentication procedure
	// will either not implement this interface or will have an implementation
	// that returns an empty result.
	AcceptableHashes() []Hash
}

PackageAuthenticationHashes is an optional interface implemented by PackageAuthentication implementations that are able to return a set of hashes they would consider valid if a given PackageLocation referred to a package that matched that hash string.

This can be used to record a set of acceptable hashes for a particular package in a lock file so that future install operations can determine whether the package has changed since its initial installation.

type PackageAuthenticationResult

type PackageAuthenticationResult struct {
	KeyID string
	// contains filtered or unexported fields
}

PackageAuthenticationResult is returned from a PackageAuthentication implementation. It is a mostly-opaque type intended for use in UI, which implements Stringer.

A failed PackageAuthentication attempt will return an "unauthenticated" result, which is represented by nil.

func (*PackageAuthenticationResult) SignedByAnyParty

func (t *PackageAuthenticationResult) SignedByAnyParty() bool

SignedByAnyParty returns whether the package was authenticated as signed by either HashiCorp or by a third-party.

func (*PackageAuthenticationResult) SignedByHashiCorp

func (t *PackageAuthenticationResult) SignedByHashiCorp() bool

SignedByHashiCorp returns whether the package was authenticated as signed by HashiCorp.

func (*PackageAuthenticationResult) String

func (t *PackageAuthenticationResult) String() string

func (*PackageAuthenticationResult) ThirdPartySigned

func (t *PackageAuthenticationResult) ThirdPartySigned() bool

ThirdPartySigned returns whether the package was authenticated as signed by a party other than HashiCorp.

type PackageHTTPURL

type PackageHTTPURL string

PackageHTTPURL is a provider package location accessible via HTTP. Its value is a URL string using either the http: scheme or the https: scheme.

func (PackageHTTPURL) String

func (p PackageHTTPURL) String() string

type PackageLocalArchive

type PackageLocalArchive string

PackageLocalArchive is the location of a provider distribution archive file in the local filesystem. Its value is a local filesystem path using the syntax understood by Go's standard path/filepath package on the operating system where Terraform is running.

func (PackageLocalArchive) String

func (p PackageLocalArchive) String() string

type PackageLocalDir

type PackageLocalDir string

PackageLocalDir is the location of a directory containing an unpacked provider distribution archive in the local filesystem. Its value is a local filesystem path using the syntax understood by Go's standard path/filepath package on the operating system where Terraform is running.

func (PackageLocalDir) String

func (p PackageLocalDir) String() string

type PackageLocation

type PackageLocation interface {
	String() string
	// contains filtered or unexported methods
}

PackageLocation represents a location where a provider distribution package can be obtained. A value of this type contains one of the following concrete types: PackageLocalArchive, PackageLocalDir, or PackageHTTPURL.

type PackageMeta

type PackageMeta struct {
	Provider addrs.Provider
	Version  Version

	ProtocolVersions VersionList
	TargetPlatform   Platform

	Filename string
	Location PackageLocation

	// Authentication, if non-nil, is a request from the source that produced
	// this meta for verification of the target package after it has been
	// retrieved from the indicated Location.
	//
	// Different sources will support different authentication strategies --
	// or possibly no strategies at all -- depending on what metadata they
	// have available to them, such as checksums provided out-of-band by the
	// original package author, expected signing keys, etc.
	//
	// If Authentication is non-nil then no authentication is requested.
	// This is likely appropriate only for packages that are already available
	// on the local system.
	Authentication PackageAuthentication
}

PackageMeta represents the metadata related to a particular downloadable provider package targeting a single platform.

Package findproviders does no signature verification or protocol version compatibility checking of its own. A caller receving a PackageMeta must verify that it has a correct signature and supports a protocol version accepted by the current version of Terraform before trying to use the described package.

func FakeInstallablePackageMeta

func FakeInstallablePackageMeta(provider addrs.Provider, version Version, protocols VersionList, target Platform, execFilename string) (PackageMeta, func(), error)

FakeInstallablePackageMeta constructs and returns a PackageMeta that points to a temporary archive file that could actually be installed in principle.

Installing it will not produce a working provider though: just a fake file posing as an executable. The filename for the executable defaults to the standard terraform-provider-NAME_X.Y.Z format, but can be overridden with the execFilename argument.

It's the caller's responsibility to call the close callback returned alongside the result in order to clean up the temporary file. The caller should call the callback even if this function returns an error, because some error conditions leave a partially-created file on disk.

func FakePackageMeta

func FakePackageMeta(provider addrs.Provider, version Version, protocols VersionList, target Platform) PackageMeta

FakePackageMeta constructs and returns a PackageMeta that carries the given metadata but has fake location information that is likely to fail if attempting to install from it.

func (PackageMeta) AcceptableHashes

func (m PackageMeta) AcceptableHashes() []Hash

AcceptableHashes returns a set of hashes that could be recorded for comparison to future results for the same provider version, to implement a "trust on first use" scheme.

The AcceptableHashes result is a platform-agnostic set of hashes, with the intent that in most cases it will be used as an additional cross-check in addition to a platform-specific hash check made during installation. However, there are some situations (such as verifying an already-installed package that's on local disk) where Terraform would check only against the results of this function, meaning that it would in principle accept another platform's package as a substitute for the correct platform. That's a pragmatic compromise to allow lock files derived from the result of this method to be portable across platforms.

Callers of this method should typically also verify the package using the object in the Authentication field, and consider how much trust to give the result of this method depending on the authentication result: an unauthenticated result or one that only verified a checksum could be considered less trustworthy than one that checked the package against a signature provided by the origin registry.

The AcceptableHashes result is actually provided by the object in the Authentication field. AcceptableHashes therefore returns an empty result for a PackageMeta that has no authentication object, or has one that does not make use of hashes.

func (PackageMeta) Hash

func (m PackageMeta) Hash() (Hash, error)

Hash computes a hash of the contents of the package at the location associated with the reciever, using whichever hash algorithm is the current default.

This method will change to use new hash versions as they are introduced in future. If you need a specific hash version, call the method for that version directly instead, such as HashV1.

Hash can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func (PackageMeta) HashV1

func (m PackageMeta) HashV1() (Hash, error)

HashV1 computes a hash of the contents of the package at the location associated with the receiver using hash algorithm 1.

The hash covers the paths to files in the directory and the contents of those files. It does not cover other metadata about the files, such as permissions.

HashV1 can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func (PackageMeta) LessThan

func (m PackageMeta) LessThan(other PackageMeta) bool

LessThan returns true if the receiver should sort before the given other PackageMeta in a sorted list of PackageMeta.

Sorting preference is given first to the provider address, then to the taget platform, and the to the version number (using semver precedence). Packages that differ only in semver build metadata have no defined precedence and so will always return false.

This ordering is primarily just to maximize the chance that results of functions in this package will be deterministic. The ordering is not intended to have any semantic meaning and is subject to change in future.

func (PackageMeta) MatchesAnyHash

func (m PackageMeta) MatchesAnyHash(acceptable []Hash) (bool, error)

MatchesAnyHash returns true if the package at the location associated with the receiver matches at least one of the given hashes, or false otherwise.

If it cannot read from the given location, MatchesHash returns an error. Unlike the signular MatchesHash, MatchesAnyHash considers an unsupported hash format to be a successful non-match.

func (PackageMeta) MatchesHash

func (m PackageMeta) MatchesHash(want Hash) (bool, error)

MatchesHash returns true if the package at the location associated with the receiver matches the given hash, or false otherwise.

If it cannot read from the given location, or if the given hash is in an unsupported format, MatchesHash returns an error.

MatchesHash can be used only with the two local package location types PackageLocalDir and PackageLocalArchive, because it needs to access the contents of the indicated package in order to compute the hash. If given a non-local location this function will always return an error.

func (PackageMeta) PackedFilePath

func (m PackageMeta) PackedFilePath(baseDir string) string

PackedFilePath determines the path under the given base directory where SearchLocalDirectory or the FilesystemMirrorSource would expect to find packed copy (a .zip archive) of the receiving PackageMeta.

The result always uses forward slashes as path separator, even on Windows, to produce a consistent result on all platforms. Windows accepts both direction of slash as long as each individual path string is self-consistent.

func (PackageMeta) UnpackedDirectoryPath

func (m PackageMeta) UnpackedDirectoryPath(baseDir string) string

UnpackedDirectoryPath determines the path under the given base directory where SearchLocalDirectory or the FilesystemMirrorSource would expect to find an unpacked copy of the receiving PackageMeta.

The result always uses forward slashes as path separator, even on Windows, to produce a consistent result on all platforms. Windows accepts both direction of slash as long as each individual path string is self-consistent.

type PackageMetaList

type PackageMetaList []PackageMeta

PackageMetaList is a list of PackageMeta. It's just []PackageMeta with some methods for convenient sorting and filtering.

func (PackageMetaList) FilterPlatform

func (l PackageMetaList) FilterPlatform(target Platform) PackageMetaList

FilterPlatform constructs a new PackageMetaList that contains only the elements of the receiver that are for the given target platform.

Pass CurrentPlatform to filter only for packages targeting the platform where this code is running.

func (PackageMetaList) FilterProviderExactVersion

func (l PackageMetaList) FilterProviderExactVersion(provider addrs.Provider, version Version) PackageMetaList

FilterProviderExactVersion constructs a new PackageMetaList that contains only the elements of the receiver that relate to the given provider address and exact version.

The version matching for this function is exact, including matching on semver build metadata, because it's intended for handling a single exact version selected by the caller from a set of available versions.

func (PackageMetaList) FilterProviderPlatformExactVersion

func (l PackageMetaList) FilterProviderPlatformExactVersion(provider addrs.Provider, platform Platform, version Version) PackageMetaList

FilterProviderPlatformExactVersion is a combination of both FilterPlatform and FilterProviderExactVersion that filters by all three criteria at once.

func (PackageMetaList) Len

func (l PackageMetaList) Len() int

func (PackageMetaList) Less

func (l PackageMetaList) Less(i, j int) bool

func (PackageMetaList) Sort

func (l PackageMetaList) Sort()

Sort performs an in-place, stable sort on the contents of the list, using the ordering given by method Less. This ordering is primarily to help encourage deterministic results from functions and does not have any semantic meaning.

func (PackageMetaList) Swap

func (l PackageMetaList) Swap(i, j int)

type Platform

type Platform struct {
	OS, Arch string
}

Platform represents a target platform that a provider is or might be available for.

func ParsePlatform

func ParsePlatform(str string) (Platform, error)

ParsePlatform parses a string representation of a platform, like "linux_amd64", or returns an error if the string is not valid.

func (Platform) LessThan

func (p Platform) LessThan(other Platform) bool

LessThan returns true if the receiver should sort before the other given Platform in an ordered list of platforms.

The ordering is lexical first by OS and then by Architecture. This ordering is primarily just to ensure that results of functions in this package will be deterministic. The ordering is not intended to have any semantic meaning and is subject to change in future.

func (Platform) String

func (p Platform) String() string

type RegistrySource

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

RegistrySource is a Source that knows how to find and install providers from their originating provider registries.

func NewRegistrySource

func NewRegistrySource(services *disco.Disco) *RegistrySource

NewRegistrySource creates and returns a new source that will install providers from their originating provider registries.

func (*RegistrySource) AvailableVersions

func (s *RegistrySource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)

AvailableVersions returns all of the versions available for the provider with the given address, or an error if that result cannot be determined.

If the request fails, the returned error might be an value of ErrHostNoProviders, ErrHostUnreachable, ErrUnauthenticated, ErrProviderNotKnown, or ErrQueryFailed. Callers must be defensive and expect errors of other types too, to allow for future expansion.

func (*RegistrySource) ForDisplay

func (s *RegistrySource) ForDisplay(provider addrs.Provider) string

func (*RegistrySource) PackageMeta

func (s *RegistrySource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)

PackageMeta returns metadata about the location and capabilities of a distribution package for a particular provider at a particular version targeting a particular platform.

Callers of PackageMeta should first call AvailableVersions and pass one of the resulting versions to this function. This function cannot distinguish between a version that is not available and an unsupported target platform, so if it encounters either case it will return an error suggesting that the target platform isn't supported under the assumption that the caller already checked that the version is available at all.

To find a package suitable for the platform where the provider installation process is running, set the "target" argument to getproviders.CurrentPlatform.

If the request fails, the returned error might be an value of ErrHostNoProviders, ErrHostUnreachable, ErrUnauthenticated, ErrPlatformNotSupported, or ErrQueryFailed. Callers must be defensive and expect errors of other types too, to allow for future expansion.

type Requirements

type Requirements map[addrs.Provider]VersionConstraints

Requirements gathers together requirements for many different providers into a single data structure, as a convenient way to represent the full set of requirements for a particular configuration or state or both.

If an entry in a Requirements has a zero-length VersionConstraints then that indicates that the provider is required but that any version is acceptable. That's different than a provider being absent from the map altogether, which means that it is not required at all.

func (Requirements) Merge

func (r Requirements) Merge(other Requirements) Requirements

Merge takes the requirements in the receiever and the requirements in the other given value and produces a new set of requirements that combines all of the requirements of both.

The resulting requirements will permit only selections that both of the source requirements would've allowed.

type Selections

type Selections map[addrs.Provider]Version

Selections gathers together version selections for many different providers.

This is the result of provider installation: a specific version selected for each provider given in the requested Requirements, selected based on the given version constraints.

type SigningKey

type SigningKey struct {
	ASCIIArmor     string `json:"ascii_armor"`
	TrustSignature string `json:"trust_signature"`
}

SigningKey represents a key used to sign packages from a registry, along with an optional trust signature from the registry operator. These are both in ASCII armored OpenPGP format.

The JSON struct tags represent the field names used by the Registry API.

type Source

type Source interface {
	AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
	PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
	ForDisplay(provider addrs.Provider) string
}

A Source can query a particular source for information about providers that are available to install.

type Version

type Version = versions.Version

Version represents a particular single version of a provider.

var UnspecifiedVersion Version = versions.Unspecified

UnspecifiedVersion is the zero value of Version, representing the absense of a version number.

func MustParseVersion

func MustParseVersion(str string) Version

MustParseVersion is a variant of ParseVersion that panics if it encounters an error while parsing.

func ParseVersion

func ParseVersion(str string) (Version, error)

ParseVersion parses a "semver"-style version string into a Version value, which is the version syntax we use for provider versions.

type VersionConstraints

type VersionConstraints = constraints.IntersectionSpec

VersionConstraints represents a set of version constraints, which can define the membership of a VersionSet by exclusion.

func MustParseVersionConstraints

func MustParseVersionConstraints(str string) VersionConstraints

MustParseVersionConstraints is a variant of ParseVersionConstraints that panics if it encounters an error while parsing.

func ParseVersionConstraints

func ParseVersionConstraints(str string) (VersionConstraints, error)

ParseVersionConstraints parses a "Ruby-like" version constraint string into a VersionConstraints value.

type VersionList

type VersionList = versions.List

VersionList represents a list of versions. It is a []Version with some extra methods for convenient filtering.

type VersionSet

type VersionSet = versions.Set

VersionSet represents a set of versions, usually describing the acceptable versions that can be selected under a particular version constraint provided by the end-user.

func MeetingConstraints

func MeetingConstraints(vc VersionConstraints) VersionSet

MeetingConstraints returns a version set that contains all of the versions that meet the given constraints, specified using the Spec type from the constraints package.

type Warnings

type Warnings = []string

Warnings represents a list of warnings returned by a Registry source.

Jump to

Keyboard shortcuts

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