GeezerVison is showing github.com — fix(terraform/lock): record every platform hash on OpenTofu registry by loispostula · Pull Request #10851 · updatecli/updatecli
fix(terraform/lock): record every platform hash on OpenTofu registry
#10851
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.go
(4)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,6 +3,7 @@ package lock
import (
"context"
"fmt"
"slices"
"strings"
"github.com/go-viper/mapstructure/v2"
Expand All
@@ -11,6 +12,7 @@ import (
terraformRegistryAddress "github.com/hashicorp/terraform-registry-address"
"github.com/minamijoyo/tfupdate/lock"
"github.com/minamijoyo/tfupdate/tfregistry"
"github.com/updatecli/updatecli/pkg/core/httpclient"
"github.com/updatecli/updatecli/pkg/core/log"
"github.com/updatecli/updatecli/pkg/core/result"
"github.com/updatecli/updatecli/pkg/core/text"
Expand All
@@ -22,8 +24,9 @@ import (
type TerraformLock struct {
spec Spec
contentRetriever text.TextRetriever
files map[string]file // map of file paths to file contents
lockIndex lock.Index // index is a cached index for updating dependency lock files.
files map[string]file // map of file paths to file contents
lockIndex lock.Index // index is a cached index for updating dependency lock files.
registry tfregistry.ProviderV1API // registry retrieves the hashes of every platform published for a provider version.
provider terraformRegistryAddress.Provider
}
Expand Down
Expand Up
@@ -76,14 +79,20 @@ func New(spec interface{}) (*TerraformLock, error) {
newResource.provider = provider
lockIndex, err := lock.NewIndexFromConfig(tfregistry.Config{
BaseURL: fmt.Sprintf("https://%s/", provider.Hostname),
})
registryConfig := tfregistry.Config{
BaseURL: fmt.Sprintf("https://%s/", provider.Hostname),
HTTPClient: httpclient.NewRetryClient(),
}
newResource.lockIndex, err = lock.NewIndexFromConfig(registryConfig)
if err != nil {
return nil, err
}
newResource.lockIndex = lockIndex
newResource.registry, err = tfregistry.NewClient(registryConfig)
if err != nil {
return nil, err
}
return newResource, nil
}
Expand Down
Expand Up
@@ -190,7 +199,37 @@ func (t *TerraformLock) Changelog(from, to string) *result.Changelogs {
return nil
}
// openTofuRegistryHostname is the public OpenTofu registry, which publishes
// both the h1 and zh hashes of every platform in its provider package metadata.
const openTofuRegistryHostname = "registry.opentofu.org"
func (t *TerraformLock) getProviderHashes(version string) ([]string, error) {
// Without platforms, record the h1 and zh hashes of every platform published
// in the registry metadata, which is what "tofu init" writes for the OpenTofu registry.
// It fails if the registry does not publish h1 hashes, such as the Terraform registry.
if len(t.spec.Platforms) == 0 || t.provider.Hostname == openTofuRegistryHostname {
hashes, err := t.getAllPlatformsHashes(context.Background(), version)
if err == nil {
return hashes, nil
}
if len(t.spec.Platforms) == 0 {
return nil, fmt.Errorf("%s failed to query provider locks for provider: %q, version: %q, for all platforms: %s",
result.FAILURE,
t.spec.Provider,
version,
err.Error(),
)
}
log.Warningf("failed to query provider locks for provider %q, version %q, for all platforms, falling back to platforms %q: %s",
t.spec.Provider,
version,
t.spec.Platforms,
err.Error(),
)
}
pv, err := t.lockIndex.GetOrCreateProviderVersion(context.Background(), t.provider.ForDisplay(), version, t.spec.Platforms)
if err != nil {
return nil, fmt.Errorf("%s failed to query provider locks for provider: %q, version: %q, platforms: %q: %s",
Expand All
@@ -205,6 +244,61 @@ func (t *TerraformLock) getProviderHashes(version string) ([]string, error) {
return pv.AllHashes(), nil
}
// getAllPlatformsHashes returns the h1 and zh hashes of every platform published for a provider version.
// The package metadata of any platform lists the hashes of all of them, so it requests a platform
// published for this version rather than the runner's own, which the provider may not publish.
func (t *TerraformLock) getAllPlatformsHashes(ctx context.Context, version string) ([]string, error) {
versions, err := t.registry.ListProviderVersions(ctx, &tfregistry.ListProviderVersionsRequest{
Namespace: t.provider.Namespace,
Type: t.provider.Type,
})
if err != nil {
return nil, err
}
var platform *tfregistry.ProviderPlatform
for _, v := range versions.Versions {
if v.Version == version && len(v.Platforms) > 0 {
platform = &v.Platforms[0]
break
}
}
if platform == nil {
return nil, fmt.Errorf("the registry publishes no platform for version %q", version)
}
metadata, err := t.registry.ProviderPackageMetadata(ctx, &tfregistry.ProviderPackageMetadataRequest{
Namespace: t.provider.Namespace,
Type: t.provider.Type,
Version: version,
OS: platform.OS,
Arch: platform.Arch,
})
if err != nil {
return nil, err
}
var hashes []string
hasH1 := false
for _, pkg := range metadata.Packages {
for _, hash := range pkg.Hashes {
if strings.HasPrefix(hash, "h1:") {
hasH1 = true
}
hashes = append(hashes, hash)
}
}
if !hasH1 {
return nil, fmt.Errorf("the registry does not publish h1 hashes for version %q", version)
}
slices.Sort(hashes)
return slices.Compact(hashes), nil
}
// ReportConfig returns a new configuration object with only the necessary fields
// to identify the resource without any sensitive information or context specific data.
func (t *TerraformLock) ReportConfig() interface{} {
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,11 +1,14 @@
package lock
import (
"context"
"errors"
"fmt"
"slices"
"testing"
"github.com/minamijoyo/tfupdate/lock"
"github.com/minamijoyo/tfupdate/tfregistry"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/updatecli/updatecli/pkg/plugins/utils/pathresolver"
Expand Down
Expand Up
@@ -645,3 +648,150 @@ func TestUpdateAbsoluteFilePath(t *testing.T) {
})
}
}
// fakeIndex records the platforms downloaded to compute their hashes.
type fakeIndex struct {
requestedPlatforms [][]string
}
func (f *fakeIndex) GetOrCreateProviderVersion(_ context.Context, address string, version string, platforms []string) (*lock.ProviderVersion, error) {
f.requestedPlatforms = append(f.requestedPlatforms, platforms)
return lock.NewMockProviderVersion(address, version,
platforms,
map[string]string{"linux_amd64": "h1:linux"},
map[string]string{"darwin_arm64": "zh:darwin", "linux_amd64": "zh:linux"},
), nil
}
// fakeRegistry publishes version 3.2.1 for darwin_arm64 and linux_amd64 only, and
// publishes h1 hashes in its package metadata when allPlatformsSupported is set, like the OpenTofu registry.
type fakeRegistry struct {
allPlatformsSupported bool
requestedPlatforms []string
}
func (f *fakeRegistry) ListProviderVersions(_ context.Context, _ *tfregistry.ListProviderVersionsRequest) (*tfregistry.ListProviderVersionsResponse, error) {
return &tfregistry.ListProviderVersionsResponse{
Versions: []tfregistry.ProviderVersion{
{Version: "3.2.0", Platforms: []tfregistry.ProviderPlatform{{OS: "windows", Arch: "386"}}},
{Version: "3.2.1", Platforms: []tfregistry.ProviderPlatform{{OS: "darwin", Arch: "arm64"}, {OS: "linux", Arch: "amd64"}}},
},
}, nil
}
func (f *fakeRegistry) ProviderPackageMetadata(_ context.Context, req *tfregistry.ProviderPackageMetadataRequest) (*tfregistry.ProviderPackageMetadataResponse, error) {
platform := req.OS + "_" + req.Arch
f.requestedPlatforms = append(f.requestedPlatforms, platform)
if platform != "darwin_arm64" && platform != "linux_amd64" {
return nil, errors.New("unexpected HTTP Status Code: 404")
}
if !f.allPlatformsSupported {
return &tfregistry.ProviderPackageMetadataResponse{}, nil
}
return &tfregistry.ProviderPackageMetadataResponse{
Packages: map[string]tfregistry.Package{
"darwin_arm64": {Hashes: []string{"h1:darwin", "zh:darwin"}},
"linux_amd64": {Hashes: []string{"h1:linux", "zh:linux"}},
},
}, nil
}
func TestGetProviderHashes(t *testing.T) {
allPlatformsHashes := []string{"h1:darwin", "h1:linux", "zh:darwin", "zh:linux"}
linuxHashes := []string{"h1:linux", "zh:darwin", "zh:linux"}
testData := []struct {
name string
provider string
version string
platforms []string
allPlatformsSupported bool
expectedHashes []string
expectedMetadataPlatforms []string
expectedDownloadPlatforms [][]string
wantErr bool
}{
{
name: "OpenTofu registry records every published platform",
provider: "registry.opentofu.org/hashicorp/null",
platforms: []string{"windows_386"},
allPlatformsSupported: true,
expectedHashes: allPlatformsHashes,
expectedMetadataPlatforms: []string{"darwin_arm64"},
},
{
name: "OpenTofu registry falls back to platforms",
provider: "registry.opentofu.org/hashicorp/null",
platforms: []string{"linux_amd64"},
allPlatformsSupported: false,
expectedHashes: linuxHashes,
expectedMetadataPlatforms: []string{"darwin_arm64"},
expectedDownloadPlatforms: [][]string{{"linux_amd64"}},
},
{
name: "Terraform registry only queries platforms",
provider: "registry.terraform.io/hashicorp/null",
platforms: []string{"linux_amd64"},
allPlatformsSupported: true,
expectedHashes: linuxHashes,
expectedDownloadPlatforms: [][]string{{"linux_amd64"}},
},
{
name: "No platforms records every published platform",
provider: "registry.terraform.io/hashicorp/null",
allPlatformsSupported: true,
expectedHashes: allPlatformsHashes,
expectedMetadataPlatforms: []string{"darwin_arm64"},
},
{
name: "No platforms fails without h1 hashes from the registry",
provider: "registry.terraform.io/hashicorp/null",
allPlatformsSupported: false,
expectedMetadataPlatforms: []string{"darwin_arm64"},
wantErr: true,
},
{
name: "No platforms fails for a version the registry does not publish",
provider: "registry.terraform.io/hashicorp/null",
version: "9.9.9",
allPlatformsSupported: true,
wantErr: true,
},
}
for _, tt := range testData {
t.Run(tt.name, func(t *testing.T) {
l, err := New(Spec{
File: "testdata/terraform.lock.hcl",
Provider: tt.provider,
Platforms: tt.platforms,
})
require.NoError(t, err)
index := &fakeIndex{}
l.lockIndex = index
registry := &fakeRegistry{allPlatformsSupported: tt.allPlatformsSupported}
l.registry = registry
version := tt.version
if version == "" {
version = "3.2.1"
}
gotHashes, err := l.getProviderHashes(version)
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.expectedHashes, gotHashes)
assert.Equal(t, tt.expectedMetadataPlatforms, registry.requestedPlatforms)
assert.Equal(t, tt.expectedDownloadPlatforms, index.requestedPlatforms)
})
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -66,7 +66,10 @@ type Spec struct {
// * target
//
// remark:
// * "platforms" is required.
// * when empty, the hashes of every platform published by the registry are recorded,
// which requires a registry publishing h1 hashes, such as registry.opentofu.org.
// * with registry.opentofu.org, the hashes of every published platform are always recorded, like "tofu init" does,
// and "platforms" is only used as a fallback if the registry metadata can't be retrieved.
//
// example:
// * platforms:
Expand All
@@ -93,8 +96,6 @@ var (
ErrSpecFileUndefined = errors.New("terraform/lock file undefined")
// ErrSpecProviderUndefined is returned if a provider wasn't specified
ErrSpecProviderUndefined = errors.New("terraform/lock provider undefined")
// ErrSpecPlatformsUndefined is returned if a platforms wasn't specified
ErrSpecPlatformsUndefined = errors.New("terraform/lock platforms undefined")
// ErrSpecFileAndFilesDefined when we both spec File and Files have been specified
ErrSpecFileAndFilesDefined = errors.New("parameter \"file\" and \"files\" are mutually exclusive")
// ErrWrongSpec is returned when the Spec has wrong content
Expand All
@@ -116,10 +117,6 @@ func (s *Spec) Validate() error {
errs = append(errs, ErrSpecProviderUndefined)
}
if len(s.Platforms) == 0 {
errs = append(errs, ErrSpecPlatformsUndefined)
}
for _, e := range errs {
log.Errorln(e)
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -63,13 +63,11 @@ func TestValidate(t *testing.T) {
expectedErrorMsg: errors.New("wrong spec content"),
},
{
name: "Failure - No platforms",
name: "Success - No platforms",
spec: Spec{
File: "testdata/terraform.lock.hcl",
Provider: "registry.terraform.io /hashicorp/kubernetes",
Provider: "registry.opentofu.org /hashicorp/kubernetes",
},
wantErr: true,
expectedErrorMsg: errors.New("wrong spec content"),
},
}
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.