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
- Variables
- func ErrIsNotExist(err error) bool
- func HashesMatchingPackage(loc PackageLocation, toTest []Hash) iter.Seq2[Hash, error]
- func HostFromRequest(req *http.Request) string
- func MissingProviderSuggestion(ctx context.Context, addr addrs.Provider, source Source, reqs Requirements) addrs.Provider
- func PackageMatchesAnyHash(loc PackageLocation, allowed []Hash) (bool, error)
- func PackageMatchesHash(loc PackageLocation, want Hash) (bool, error)
- func PackedFilePathForPackage(baseDir string, provider addrs.Provider, version Version, platform Platform) string
- func SearchLocalDirectory(baseDir string) (map[addrs.Provider]PackageMetaList, error)
- func ShouldEnforceGPGValidationForProvider(addr addrs.Provider) bool
- func UnpackedDirectoryPathForPackage(baseDir string, provider addrs.Provider, version Version, platform Platform) string
- func VersionConstraintsString(spec VersionConstraints) string
- type ErrHostNoProviders
- type ErrHostUnreachable
- type ErrPlatformNotSupported
- type ErrProtocolNotSupported
- type ErrProviderNotFound
- type ErrQueryFailed
- type ErrRegistryProviderNotKnown
- type ErrRequestCanceled
- type ErrUnauthorized
- type FilesystemMirrorSource
- func (s *FilesystemMirrorSource) AllAvailablePackages() (map[addrs.Provider]PackageMetaList, error)
- func (s *FilesystemMirrorSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s *FilesystemMirrorSource) ForDisplay(provider addrs.Provider) string
- func (s *FilesystemMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type HTTPMirrorSource
- func (s *HTTPMirrorSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s *HTTPMirrorSource) ForDisplay(provider addrs.Provider) string
- func (s *HTTPMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type HangingSource
- func (s *HangingSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s *HangingSource) ForDisplay(provider addrs.Provider) string
- func (s *HangingSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type Hash
- func HashLegacyZipSHAFromSHA(sum [sha256.Size]byte) Hash
- func MustParseHash(s string) Hash
- func PackageHash(loc PackageLocation) (Hash, error)
- func PackageHashLegacyZipSHA(loc PackageLocalArchive) (Hash, error)
- func PackageHashV1(loc PackageLocation) (Hash, error)
- func ParseHash(s string) (Hash, error)
- func PreferredHashes(given []Hash) []Hash
- type HashDisposition
- type HashDispositions
- type HashScheme
- type LocationConfig
- type MemoizeSource
- func (s *MemoizeSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s *MemoizeSource) ForDisplay(provider addrs.Provider) string
- func (s *MemoizeSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type MockSource
- func (s *MockSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s *MockSource) CallLog() [][]interface{}
- func (s *MockSource) ForDisplay(provider addrs.Provider) string
- func (s *MockSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type MultiSource
- func (s MultiSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s MultiSource) ForDisplay(provider addrs.Provider) string
- func (s MultiSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type MultiSourceMatchingPatterns
- type MultiSourceSelector
- type OCIRegistryMirrorSource
- func (o *OCIRegistryMirrorSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (o *OCIRegistryMirrorSource) ForDisplay(provider addrs.Provider) string
- func (o *OCIRegistryMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type OCIRepositoryStore
- type PackageAuthentication
- func NewArchiveChecksumAuthentication(platform Platform, wantSHA256Sum [sha256.Size]byte) PackageAuthentication
- func NewMatchingChecksumAuthentication(document []byte, filename string, wantSHA256Sum [sha256.Size]byte) PackageAuthentication
- func NewPackageHashAuthentication(platform Platform, validHashes []Hash, trustAllHashes bool) PackageAuthentication
- func NewRegistryPackageAuthentication(meta PackageMeta, sha256sum string, ...) PackageAuthentication
- func NewSignatureAuthentication(meta PackageMeta, document, signature []byte, keys []SigningKey, ...) PackageAuthentication
- func PackageAuthenticationAll(checks ...PackageAuthentication) PackageAuthentication
- type PackageAuthenticationResult
- func (t *PackageAuthenticationResult) GPGKeyIDsString() string
- func (t *PackageAuthenticationResult) HashesWithDisposition(cond func(*HashDisposition) bool) iter.Seq[Hash]
- func (t *PackageAuthenticationResult) Signed() bool
- func (t *PackageAuthenticationResult) SigningSkipped() bool
- func (t *PackageAuthenticationResult) String() string
- type PackageHTTPURL
- type PackageLocalArchive
- type PackageLocalDir
- type PackageLocation
- type PackageMeta
- func (m PackageMeta) Hash() (Hash, error)
- func (m PackageMeta) HashV1() (Hash, error)
- func (m PackageMeta) LessThan(other PackageMeta) bool
- func (m PackageMeta) MatchesAnyHash(acceptable []Hash) (bool, error)
- func (m PackageMeta) MatchesHash(want Hash) (bool, error)
- func (m PackageMeta) PackedFilePath(baseDir string) string
- func (m PackageMeta) UnpackedDirectoryPath(baseDir string) string
- type PackageMetaList
- func (l PackageMetaList) FilterPlatform(target Platform) PackageMetaList
- func (l PackageMetaList) FilterProviderExactVersion(provider addrs.Provider, version Version) PackageMetaList
- func (l PackageMetaList) FilterProviderPlatformExactVersion(provider addrs.Provider, platform Platform, version Version) PackageMetaList
- func (l PackageMetaList) Len() int
- func (l PackageMetaList) Less(i, j int) bool
- func (l PackageMetaList) Sort()
- func (l PackageMetaList) Swap(i, j int)
- type PackageOCIBlobArchive
- type Platform
- type ProvidersQualification
- type RegistryPlatformData
- type RegistrySource
- func (s *RegistrySource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
- func (s *RegistrySource) ForDisplay(provider addrs.Provider) string
- func (s *RegistrySource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
- type Requirements
- type ResourceRef
- type Selections
- type SigningKey
- type Source
- type Version
- type VersionConstraints
- type VersionList
- type VersionSet
- type Warnings
Constants ¶
const NilHash = Hash("")
NilHash is the zero value of Hash. It isn't a valid hash, so all of its methods will panic.
const TestingPublicKey = `` /* 7716-byte string literal not displayed */
TestingPublicKey is some public key used for testing.
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 ¶
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.
var ErrUnknownIssuer = fmt.Errorf("authentication signature from unknown issuer")
ErrUnknownIssuer indicates an error when no valid signature for a provider could be found.
var SupportedPluginProtocols = MustParseVersionConstraints(">= 5, <7")
Functions ¶
func ErrIsNotExist ¶
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 HashesMatchingPackage ¶
HashesMatchingPackage compares the given package location to each of the given hashes in turn and returns a sequence of only those that match the package.
Each iteration can potentially fail due to being unable to read from the given location, in which case it will yield NilHash and an error and no further iteration will be possible.
func HostFromRequest ¶
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 OpenTofu 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 ShouldEnforceGPGValidationForProvider ¶
ShouldEnforceGPGValidationForProvider returns true if GPG signature validation must be enforced for the given provider.
OpenTofu requires a valid GPG signature for any provider for which this function returns true. The result of this function only applies if the provider's origin registry does not return any signing keys for the provider; GPG signature is always required for any provider whose origin registry returns a signing key.
The situations where this function returns false are part of a pragmatic compromise to allow the main OpenTofu registry to serve providers for which it does not currently know a signing key. For more information, refer to:
https://github.com/opentofu/opentofu/issues/266
The result of this function also determines whether signature verification is required in order for a particular hash to be tracked for the given provider in a dependency lock file. If this returns false then the dependency lock file should include any hash that was reported by the provider's origin registry, even if not signed.
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
// HasOtherVersion is 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 OpenTofu.
//
// 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 OpenTofu, 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 ¶
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 ¶
ErrProtocolNotSupported is an error type used to indicate that a particular version of a provider is not supported by the current version of OpenTofu.
Specifically, 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 ¶
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 absence 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 ¶
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.opentofu.org/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 {
// 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(_ context.Context, 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(ctx context.Context, baseURL *url.URL, creds svcauth.CredentialsSource, requestTimeout time.Duration, sourceLocationCfg LocationConfig) *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 ¶
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 ¶
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 ¶
ParseHash parses the string representation of a Hash into a Hash value.
A particular version of OpenTofu 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 ¶
PreferredHashes examines all of the given hash strings and returns the one that the current version of OpenTofu 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.
In practice, this function is used in a variety of locations with a broader goal in mind. It is used to filter out any hashes that OpenTofu does not currently recognise. If this function is ever heavily modified, all call sites should be checked carefully.
func (Hash) GoString ¶
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 receiving hash. If the receiver is not using valid syntax then this method will panic.
type HashDisposition ¶
type HashDisposition struct {
// SignedByGPGKeyIDs is a set of GPG key IDs which provided signatures
// covering the associated hash.
//
// A hash that has at least one signing key ID but was not otherwise
// verified (as indicated by the other fields of this type) should be
// trusted only if at least one of the given signing keys is trusted.
// It's the responsibility of any subsystem relying on this information
// to define what it means for a key to be "trusted".
SignedByGPGKeyIDs collections.Set[string]
// ReportedByRegistry is set if this hash was reported by the associated
// provider's origin registry as being one of the official hashes for
// this provider release.
//
// Note that this signal alone is only trustworthy to the extent that
// the origin registry is trusted. Unless there is also at least one
// entry in SignedByGPGKeyIDs, this hash was not covered by any GPG
// signing key.
//
// This field must be set only by a source that directly interacted
// with the associated provider's origin registry. It MUST NOT be
// set by a source that interacts with any sort of "mirror".
ReportedByRegistry bool
// VerifiedLocally is set for any hash that was calculated locally,
// directly from a package for the provider that the hash is intended
// to verify.
//
// Note that this represents only that the artifact matched the
// associated hash; it does NOT mean that the associated hash is
// one of the official hashes as designated by the provider developer,
// unless the provider developer's signing key also appears in
// SignedByGPGKeyIDs.
VerifiedLocally bool
ReportedByTrustedMirror bool
// Optional, used for filtering
Platform *Platform
}
HashDisposition describes in what way a particular hash is related to a particular PackageAuthenticationResult, and thus what a caller might be able to assume about the trustworthiness of that hash.
func MergeHashDisposition ¶
func MergeHashDisposition(a, b *HashDisposition) *HashDisposition
MergeHashDisposition takes two HashDisposition objects and returns a new object that represents the union of the information from both.
func (HashDisposition) GPGSigningKeysString ¶
func (d HashDisposition) GPGSigningKeysString() string
GPGSigningKeysString returns a string representation of any GPG signing key IDs that signed an assertion that the associated hash is valid for the associated provider version.
If there are no such keys then the result is an empty string.
The result of this is intended for display to a human in the UI, rather than for machine-readable purposes. The exact format might change in future versions.
func (HashDisposition) SignedByAnyGPGKeys ¶
func (d HashDisposition) SignedByAnyGPGKeys() bool
SignedByAnyGPGKeys returns true if the receiver has at least one GPG key ID that signed an assertion that the associated hash is valid for the associated provider version.
Note that relying _only_ on the result of this function to make a trust decision implies that the caller considers all keys to be equally trustworthy, which is probably a risky assumption!
type HashDispositions ¶
type HashDispositions map[Hash]*HashDisposition
HashDispositions represents a collection of hashes that are associated with a provider as a result of installing it, each of which has a "disposition" that calling code can use to decide in what ways it is appropriate to make use of the hash.
For example, the provider installer might choose to ignore hashes that were not verified locally unless are marked as having been signed by a trusted GPG key.
func (HashDispositions) AllGPGSigningKeysString ¶
func (ds HashDispositions) AllGPGSigningKeysString() string
AllGPGSigningKeysString returns a string representation of all GPG signing key IDs that signed an assertion that one of the hashes is valid for the associated provider version.
If there are no such keys then the result is an empty string.
The result of this is intended for display to a human in the UI, rather than for machine-readable purposes. The exact format might change in future versions.
func (HashDispositions) HasAnyReportedByRegistry ¶
func (ds HashDispositions) HasAnyReportedByRegistry() bool
func (HashDispositions) HasAnyReportedByTrustedMirror ¶
func (ds HashDispositions) HasAnyReportedByTrustedMirror() bool
func (HashDispositions) HasAnySignedByGPGKeys ¶
func (ds HashDispositions) HasAnySignedByGPGKeys() bool
func (HashDispositions) Merge ¶
func (ds HashDispositions) Merge(other HashDispositions)
Merge modifies the receiver to also include all of the hashes and associated dispositions from the given other HashDispositions object.
If both collections contain the same hash then their dispositions are also merged, so that the receiver is left representing the union of the disposition information from both collections.
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 LocationConfig ¶
type LocationConfig struct {
// ProviderDownloadRetries is used for [PackageHTTPURL] to configure the
// http client to retry when a 5xx retryable error occurs.
ProviderDownloadRetries int
// TODO - use this when we'll introduce per installation method configuration
ProviderDownloadTimeout time.Duration
TrustAllHashes bool
}
LocationConfig provides configuration options to be carried from the Source to the PackageLocation where applicable.
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 receiver 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 ¶
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 absence of any include patterns is treated the same as a pattern that matches all addresses. Exclusions take priority over inclusions.
type OCIRegistryMirrorSource ¶
type OCIRegistryMirrorSource struct {
// contains filtered or unexported fields
}
OCIRegistryMirrorSource is a source that treats one or more repositories in a registry implementing the OCI Distribution protocol as a kind of provider mirror.
This is conceptually similar to HTTPMirrorSource, but whereas that one acts as a client for the OpenTofu-specific "provider mirror protocol" this one instead relies on a user-configured template to map provider source addresses onto OCI repository addresses and then uses tags in the selected registry to discover the available versions, and OCI manifests to represent their metadata.
This implementation is currently intended to be compatible with OCI Distribution v1.1.0:
https://github.com/opencontainers/distribution-spec/blob/v1.1.0/spec.md
func (*OCIRegistryMirrorSource) AvailableVersions ¶
func (o *OCIRegistryMirrorSource) AvailableVersions(ctx context.Context, provider addrs.Provider) (VersionList, Warnings, error)
AvailableVersions implements Source.
func (*OCIRegistryMirrorSource) ForDisplay ¶
func (o *OCIRegistryMirrorSource) ForDisplay(provider addrs.Provider) string
ForDisplay implements Source.
func (*OCIRegistryMirrorSource) PackageMeta ¶
func (o *OCIRegistryMirrorSource) PackageMeta(ctx context.Context, provider addrs.Provider, version Version, target Platform) (PackageMeta, error)
PackageMeta implements Source.
type OCIRepositoryStore ¶
type OCIRepositoryStore interface {
// Tags lists the tag names available in the repository.
//
// The OCI Distribution protocol uses pagination for the tag list and so
// the given function will be called for each page until either it returns
// an error or there are no pages left to retrieve.
//
// "last" is a token used to begin at some point other than the start of
// the list, but callers in this package always set it to an empty string
// to represent intent to retrieve the entire list and so implementers are
// allowed to return an error if "last" is non-empty.
Tags(ctx context.Context, last string, fn func(tags []string) error) error
// Resolve finds the descriptor associated with the given tag name in the
// repository, if any.
//
// tagName MUST conform to the pattern defined for "<reference> as a tag"
// from the OCI distribution specification, or the result is unspecified.
Resolve(ctx context.Context, tagName string) (ociv1.Descriptor, error)
// Fetch retrieves the content of a specific blob from the repository, identified
// by the digest in the given descriptor.
//
// Implementations of this function tend not to check that the returned content
// actually matches the digest and size in the descriptor, so callers MUST
// verify that somehow themselves before making use of the resulting content.
//
// Callers MUST close the returned reader after using it, since it's typically
// connected to an active network socket or file handle.
Fetch(ctx context.Context, target ociv1.Descriptor) (io.ReadCloser, error)
}
OCIRepositoryStore is the interface used by OCIRegistryMirrorSource to interact with the content in a specific OCI repository.
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, trustAllHashes bool) 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 OpenTofu.
This uses the hash algorithms implemented by functions PackageHash and MatchesHash. The PreferredHashes function will select which of the given hashes are considered by OpenTofu to be the strongest verification, and authentication succeeds as long as one of those matches.
func NewRegistryPackageAuthentication ¶
func NewRegistryPackageAuthentication(meta PackageMeta, sha256sum string, packageData map[Platform]RegistryPlatformData) PackageAuthentication
NewRegistryPackageAuthentication returns a PackageAuthentication implementation that ensures the SHA256SUM (verified elsewhere) is matches the respective registry package data entry.
This authentication returns a result where all of the entries are ReportedByRegistry. It should be combined with other authentications to be useful.
See the corresponding [RFC](rfc/20251027-provider-registry-hashes.md) for more information.
func NewSignatureAuthentication ¶
func NewSignatureAuthentication(meta PackageMeta, document, signature []byte, keys []SigningKey, source addrs.Provider) 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:
- If the signing key is the HashiCorp official key, it is an official provider;
- Otherwise, if the signing key has a trust signature from the HashiCorp Partners key, it is a partner provider;
- 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 the union of the results of all authentications, describing all of the checksums that were somehow involved in the authentication process and what we learned about each one along the way.
type PackageAuthenticationResult ¶
type PackageAuthenticationResult struct {
// 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 NewPackageAuthenticationResult ¶
func NewPackageAuthenticationResult(hashes HashDispositions) *PackageAuthenticationResult
NewPackageAuthenticationResult constructs a new PackageAuthenticationResult based on the given hash dispositions.
This is here primarily to allow constructing expected result values for tests in other packages. There isn't really any reason for non-test code outside of this package to directly construct package authentication results, since all of the "real" package authentication implementations should live in this package.
func (*PackageAuthenticationResult) GPGKeyIDsString ¶
func (t *PackageAuthenticationResult) GPGKeyIDsString() string
GPGKeyIDsString returns a UI-oriented string representation of all of the GPG key IDs that asserted the validity of at least one of the hashes related to this package's provider version.
func (*PackageAuthenticationResult) HashesWithDisposition ¶
func (t *PackageAuthenticationResult) HashesWithDisposition(cond func(*HashDisposition) bool) iter.Seq[Hash]
HashesWithDisposition returns a sequence of hashes whose disposition after authentication matches the rule implemented by the given function cond.
Use this to select the appropriate subset of hashes to record for the associated provider version in the dependency lock file, with the selection condition varying based on the authentication result and the current policy for whether signature verification is required and which keys are trusted.
func (*PackageAuthenticationResult) Signed ¶
func (t *PackageAuthenticationResult) Signed() bool
Signed returns whether the package was authenticated as signed by anyone.
func (*PackageAuthenticationResult) SigningSkipped ¶
func (t *PackageAuthenticationResult) SigningSkipped() bool
SigningSkipped returns whether the package was authenticated but the key validation was skipped.
func (*PackageAuthenticationResult) String ¶
func (t *PackageAuthenticationResult) String() string
type PackageHTTPURL ¶
type PackageHTTPURL struct {
// URL indicates the fully qualified location where the package
// resides and should be used as it is to perform a request.
URL string
// ClientBuilder is the external given function that is meant to
// construct a [*retryablehttp.Client] for making the actual request
// to the [PackageHTTPURL.URL] specified above.
// This came from the need of unifying the retries and timeout configurations
// into a single place. This way, the "creator" of this struct
// can inject a client by its liking to customize the requests
// accordingly.
ClientBuilder func(ctx context.Context) *retryablehttp.Client
}
PackageHTTPURL is a provider package location accessible via HTTP.
Its value is a URL string using either the http: scheme or the https: scheme. The URL should respond with a .zip archive whose contents are to be extracted into a local package directory.
This type evolved from a single specific HTTP URL location to a more evolved type since we had to extract the logic of making an HTTP request into a more configurable piece to be able to provider a more specific-per-configuration http client.
func (PackageHTTPURL) InstallProviderPackage ¶
func (p PackageHTTPURL) InstallProviderPackage(ctx context.Context, meta PackageMeta, targetDir string, allowedHashes []Hash) (*PackageAuthenticationResult, error)
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 OpenTofu is running.
func (PackageLocalArchive) InstallProviderPackage ¶
func (p PackageLocalArchive) InstallProviderPackage(ctx context.Context, meta PackageMeta, targetDir string, allowedHashes []Hash) (*PackageAuthenticationResult, error)
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 OpenTofu is running.
func (PackageLocalDir) InstallProviderPackage ¶
func (p PackageLocalDir) InstallProviderPackage(_ context.Context, meta PackageMeta, targetDir string, allowedHashes []Hash) (*PackageAuthenticationResult, error)
func (PackageLocalDir) String ¶
func (p PackageLocalDir) String() string
type PackageLocation ¶
type PackageLocation interface {
// InstallProviderPackage installs the provider package at the location
// represented by the implementer into a new directory at targetDir,
// and then verifies both that the newly-created package directory
// matches at least one of allowedHashes (if any) and that the
// authentication strategy represented by meta.Authentication succeeds.
InstallProviderPackage(ctx context.Context, meta PackageMeta, targetDir string, allowedHashes []Hash) (*PackageAuthenticationResult, error)
// String returns a concise string representation of the package location
// that is suitable to include in the UI to explain where a package
// is being installed from.
String() string
}
PackageLocation represents a location where a provider distribution package can be obtained.
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 receiving a PackageMeta must verify that it has a correct signature and supports a protocol version accepted by the current version of OpenTofu 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) Hash ¶
func (m PackageMeta) Hash() (Hash, error)
Hash computes a hash of the contents of the package at the location associated with the receiver, 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 target 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 singular 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 PackageOCIBlobArchive ¶
type PackageOCIBlobArchive struct {
// contains filtered or unexported fields
}
PackageOCIBlobArchive represents a provider package archive stored as a blob in an OCI Distribution repository.
A Source returning this kind of location must first choose the appropriate artifact from a provider's multi-platform index manifest, fetch that manifest, and identify the single leaf blob whose content is the provider package archive. This type does not interact with artifact manifests at all, expecting that whatever constructed it has already interrogated all of the relevant manifests.
func (PackageOCIBlobArchive) InstallProviderPackage ¶
func (p PackageOCIBlobArchive) InstallProviderPackage(ctx context.Context, meta PackageMeta, targetDir string, allowedHashes []Hash) (*PackageAuthenticationResult, error)
func (PackageOCIBlobArchive) String ¶
func (p PackageOCIBlobArchive) String() string
type Platform ¶
type Platform struct {
OS, Arch string
}
Platform represents a target platform that a provider is or might be available for.
func ParsePlatform ¶
ParsePlatform parses a string representation of a platform, like "linux_amd64", or returns an error if the string is not valid.
func (Platform) LessThan ¶
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.
type ProvidersQualification ¶
type ProvidersQualification struct {
Implicit map[addrs.Provider][]ResourceRef
Explicit map[addrs.Provider]struct{}
}
ProvidersQualification is storing the implicit/explicit reference qualification of the providers. This is necessary to be able to warn the user when the resources are referencing a provider that is not specifically defined in a required_providers block. When the implicitly referenced provider is tried to be downloaded without a specific provider requirement, it will be tried from the default namespace (hashicorp), failing to download it when it does not exist in the default namespace. Therefore, we want to let the user know what resources are generating this situation.
func (*ProvidersQualification) AddExplicitProvider ¶
func (pq *ProvidersQualification) AddExplicitProvider(provider addrs.Provider)
AddExplicitProvider saves an addrs.Provider that is specifically configured in a required_providers block.
func (*ProvidersQualification) AddImplicitProvider ¶
func (pq *ProvidersQualification) AddImplicitProvider(provider addrs.Provider, ref ResourceRef)
AddImplicitProvider saves an addrs.Provider with the place in the configuration where this is generated from.
func (*ProvidersQualification) Merge ¶
func (pq *ProvidersQualification) Merge(other *ProvidersQualification) *ProvidersQualification
type RegistryPlatformData ¶
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(ctx context.Context, services *disco.Disco, httpClient *retryablehttp.Client, locationCfg LocationConfig) *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 receiver 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 ResourceRef ¶
type ResourceRef struct {
CfgRes addrs.ConfigResource
Ref tfdiags.SourceRange
ProviderAttribute bool
}
type Selections ¶
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"`
}
SigningKey represents a key used to sign packages from a registry. 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 ¶
Version represents a particular single version of a provider.
var UnspecifiedVersion Version = versions.Unspecified
UnspecifiedVersion is the zero value of Version, representing the absence of a version number.
func MustParseVersion ¶
MustParseVersion is a variant of ParseVersion that panics if it encounters an error while parsing.
func ParseVersion ¶
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 ¶
VersionList represents a list of versions. It is a []Version with some extra methods for convenient filtering.
type VersionSet ¶
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.
Source Files
¶
- didyoumean.go
- doc.go
- errors.go
- filesystem_mirror_source.go
- filesystem_search.go
- hanging_source.go
- hash.go
- http_mirror_source.go
- location_config.go
- memoize_source.go
- mock_source.go
- multi_source.go
- oci_registry_mirror_source.go
- package_authentication.go
- package_location_http_archive.go
- package_location_local_archive.go
- package_location_local_dir.go
- package_location_oci_blob_archive.go
- public_keys.go
- registry_client.go
- registry_source.go
- source.go
- types.go