mirror of
https://github.com/hashicorp/packer.git
synced 2026-09-22 16:01:43 -04:00
* hcl2template: pass user variable values to plugins as packer_user_variables (#13686) HCL2 builds do not send the packer_user_variables config key to the builder, provisioner and post-processor plugins. Legacy JSON builds send this key (through CoreBuild.packerConfig()). Without the key, the plugin SDK keeps interpolate.Context.UserVariables nil. Then the template function {{ user "name" }} fails with 'error calling user: test'. This failure occurs in each string that a plugin interpolates at run time, for example the contents of the vagrant post-processor's vagrantfile_template. Add the function PackerConfig.userVariableValues(). This function converts the input variable values to strings, equivalent to the legacy user variables. The core sends the map at each plugin handoff point: builder, provisioner, post-processor, and enforced provisioner. The map does not contain the sensitive variables. A sensitive value goes to a plugin only if the template refers to it explicitly. The map does not contain values that are not primitive (lists, maps, objects). Legacy user variables were always strings. Co-authored-by: Claude Fable 5 <[email protected]> * Dependency upgrade (#13689) * go.mod version upgrade * actions upgrade * plugin-getter: install plugins from non-GitHub HTTP sources (#13691) Packer can only install plugins from github.com, with releases.hashicorp.com consulted first for HashiCorp-published plugins. This has been a long-standing gap for air-gapped and policy-restricted environments (#11164): the source address parser already accepts any hostname, but both existing getters reject non-github.com sources at install time. Add a remote plugin getter that installs plugins from the host named in a required_plugins source address. The host serves the directory structure of releases.hashicorp.com under the source's path: an index.json listing versions, and per version a SHA256SUMS file, the zips it lists, and - when the zip names carry no plugin protocol version - the version's manifest.json. A plugin published on releases.hashicorp.com is therefore mirrored as a verbatim copy of its tree, with every checksum file and signature upstream-authored. A plugin published as GitHub release assets is mirrored by copying each release's assets into a version directory, renaming their SHA256SUMS file to the unprefixed convention with content unchanged, and writing an index.json listing the versions. Both kinds of content can be served side by side by one host. Getter selection happens per source address: github.com sources keep the release and github getters unchanged, while any other host is served by the remote getter over HTTPS. Sources with three or more components are supported, up to the existing 16-component limit, so nested artifact-repository paths and hosts that embed the upstream origin in their path all resolve. Version discovery, constraint solving, checksum verification, and the binary naming rules match the existing getters. The installed filename is rebuilt from validated checksum-file fields and never taken from the server's response, checksum entries matching neither known naming shape are rejected rather than guessed at, and nothing the remote metadata supplies is used to fetch from another origin or path. index.json parsing is covered by fixtures captured from the live releases API, so a format change there fails tests rather than user installs. Closes #11164 * fix: update link to CONTRIBUTING.md for consistency with main branch * Merge pull request #13701 from hashicorp/sanya-hashicorp/fix-vuln Module Dependency update * build(deps): bump google.golang.org/grpc (#13704) Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.83.1 to 1.83.2. - [Release notes](https://github.com/grpc/grpc-go/releases) - [Commits](https://github.com/grpc/grpc-go/compare/v1.83.1...v1.83.2) --- updated-dependencies: - dependency-name: google.golang.org/grpc dependency-version: 1.83.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * [COMPLIANCE] Add/Update Copyright Headers (#13699) * [COMPLIANCE] Add/Update Copyright Headers * make generate update * make generate --------- Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com> Co-authored-by: sanya <[email protected]> Co-authored-by: Sanya <[email protected]> * Packer release 1.16.1 (#13705) * Module upgrade (#13707) --------- Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: Erik Berg <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Benjamin Holmes <[email protected]> Co-authored-by: elomito <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com>
343 lines
9.2 KiB
Go
343 lines
9.2 KiB
Go
// Copyright IBM Corp. 2024, 2026
|
|
// SPDX-License-Identifier: BUSL-1.1
|
|
|
|
package github
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
plugingetter "github.com/hashicorp/packer/packer/plugin-getter"
|
|
|
|
"github.com/google/go-github/v75/github"
|
|
"github.com/hashicorp/packer/hcl2template/addrs"
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
const (
|
|
ghTokenAccessor = "PACKER_GITHUB_API_TOKEN"
|
|
defaultUserAgent = "packer-github-plugin-getter"
|
|
defaultHostname = "github.com"
|
|
)
|
|
|
|
type Getter struct {
|
|
Client *github.Client
|
|
UserAgent string
|
|
Name string
|
|
}
|
|
|
|
var _ plugingetter.Getter = &Getter{}
|
|
|
|
type PluginMetadata struct {
|
|
Versions map[string]PluginVersion `json:"versions"`
|
|
}
|
|
|
|
type PluginVersion struct {
|
|
Name string `json:"name"`
|
|
Version string `json:"version"`
|
|
}
|
|
|
|
func TransformChecksumStream() func(in io.ReadCloser) (io.ReadCloser, error) {
|
|
return func(in io.ReadCloser) (io.ReadCloser, error) {
|
|
defer in.Close()
|
|
rd := bufio.NewReader(in)
|
|
buffer := bytes.NewBufferString("[")
|
|
json := json.NewEncoder(buffer)
|
|
for i := 0; ; i++ {
|
|
line, err := rd.ReadString('\n')
|
|
if err != nil {
|
|
if err != io.EOF {
|
|
return nil, fmt.Errorf(
|
|
"Error reading checksum file: %s", err)
|
|
}
|
|
break
|
|
}
|
|
parts := strings.Fields(line)
|
|
switch len(parts) {
|
|
case 2: // nominal case
|
|
checksumString, checksumFilename := parts[0], parts[1]
|
|
|
|
if i > 0 {
|
|
_, _ = buffer.WriteString(",")
|
|
}
|
|
if err := json.Encode(struct {
|
|
Checksum string `json:"checksum"`
|
|
Filename string `json:"filename"`
|
|
}{
|
|
Checksum: checksumString,
|
|
Filename: checksumFilename,
|
|
}); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
}
|
|
_, _ = buffer.WriteString("]")
|
|
return io.NopCloser(buffer), nil
|
|
}
|
|
}
|
|
|
|
// transformVersionStream get a stream from github tags and transforms it into
|
|
// something Packer wants, namely a json list of Release.
|
|
func transformVersionStream(in io.ReadCloser) (io.ReadCloser, error) {
|
|
if in == nil {
|
|
return nil, fmt.Errorf("transformVersionStream got nil body")
|
|
}
|
|
defer in.Close()
|
|
dec := json.NewDecoder(in)
|
|
|
|
m := []struct {
|
|
Ref string `json:"ref"`
|
|
}{}
|
|
if err := dec.Decode(&m); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
out := []plugingetter.Release{}
|
|
for _, m := range m {
|
|
out = append(out, plugingetter.Release{
|
|
Version: strings.TrimPrefix(m.Ref, "refs/tags/"),
|
|
})
|
|
}
|
|
|
|
buf := &bytes.Buffer{}
|
|
if err := json.NewEncoder(buf).Encode(out); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return io.NopCloser(buf), nil
|
|
}
|
|
|
|
// HostSpecificTokenAuthTransport makes sure the http roundtripper only sets an
|
|
// auth token for requests aimed at a specific host.
|
|
//
|
|
// This helps for example to get release files from Github as Github will
|
|
// redirect to s3 which will error if we give it a Github auth token.
|
|
type HostSpecificTokenAuthTransport struct {
|
|
// Host to TokenSource map
|
|
TokenSources map[string]oauth2.TokenSource
|
|
|
|
// actual RoundTripper, nil means we use the default one from http.
|
|
Base http.RoundTripper
|
|
}
|
|
|
|
// RoundTrip authorizes and authenticates the request with an
|
|
// access token from Transport's Source.
|
|
func (t *HostSpecificTokenAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
source, found := t.TokenSources[req.Host]
|
|
if found {
|
|
reqBodyClosed := false
|
|
if req.Body != nil {
|
|
defer func() {
|
|
if !reqBodyClosed {
|
|
req.Body.Close()
|
|
}
|
|
}()
|
|
}
|
|
|
|
if source == nil {
|
|
return nil, errors.New("transport's Source is nil")
|
|
}
|
|
token, err := source.Token()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
token.SetAuthHeader(req)
|
|
|
|
// req.Body is assumed to be closed by the base RoundTripper.
|
|
reqBodyClosed = true
|
|
}
|
|
|
|
return t.base().RoundTrip(req)
|
|
}
|
|
|
|
func (t *HostSpecificTokenAuthTransport) base() http.RoundTripper {
|
|
if t.Base != nil {
|
|
return t.Base
|
|
}
|
|
return http.DefaultTransport
|
|
}
|
|
|
|
type GithubPlugin struct {
|
|
Hostname string
|
|
Namespace string
|
|
Type string
|
|
}
|
|
|
|
func NewGithubPlugin(source *addrs.Plugin) (*GithubPlugin, error) {
|
|
parts := source.Parts()
|
|
if len(parts) != 3 {
|
|
return nil, fmt.Errorf("Invalid github.com URI %q: a Github-compatible source must be in the github.com/<namespace>/<name> format.", source.String())
|
|
}
|
|
|
|
if parts[0] != defaultHostname {
|
|
return nil, fmt.Errorf("%q doesn't appear to be a valid %q source address; check source and try again.", source.String(), defaultHostname)
|
|
}
|
|
|
|
return &GithubPlugin{
|
|
Hostname: parts[0],
|
|
Namespace: parts[1],
|
|
Type: strings.Replace(parts[2], "packer-plugin-", "", 1),
|
|
}, nil
|
|
}
|
|
|
|
func (gp GithubPlugin) RealRelativePath() string {
|
|
return path.Join(
|
|
gp.Namespace,
|
|
fmt.Sprintf("packer-plugin-%s", gp.Type),
|
|
)
|
|
}
|
|
|
|
func (gp GithubPlugin) PluginType() string {
|
|
return fmt.Sprintf("packer-plugin-%s", gp.Type)
|
|
}
|
|
|
|
func (g *Getter) Get(what string, opts plugingetter.GetOptions) (io.ReadCloser, error) {
|
|
log.Printf("[TRACE] Getting %s of %s plugin from %s", what, opts.PluginRequirement.Identifier, g.Name)
|
|
ghURI, err := NewGithubPlugin(opts.PluginRequirement.Identifier)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ctx := context.TODO()
|
|
if g.Client == nil {
|
|
var tc *http.Client
|
|
if tk := os.Getenv(ghTokenAccessor); tk != "" {
|
|
log.Printf("[DEBUG] github-getter: using %s", ghTokenAccessor)
|
|
ts := oauth2.StaticTokenSource(
|
|
&oauth2.Token{AccessToken: tk},
|
|
)
|
|
tc = &http.Client{
|
|
Transport: &HostSpecificTokenAuthTransport{
|
|
TokenSources: map[string]oauth2.TokenSource{
|
|
"api.github.com": ts,
|
|
},
|
|
},
|
|
}
|
|
} else {
|
|
log.Printf("[WARNING] github-getter: no GitHub token set, if you intend to install plugins often, please set the %s env var", ghTokenAccessor)
|
|
}
|
|
g.Client = github.NewClient(tc)
|
|
g.Client.UserAgent = defaultUserAgent
|
|
if g.UserAgent != "" {
|
|
g.Client.UserAgent = g.UserAgent
|
|
}
|
|
}
|
|
|
|
var req *http.Request
|
|
transform := func(in io.ReadCloser) (io.ReadCloser, error) {
|
|
return in, nil
|
|
}
|
|
|
|
switch what {
|
|
case "releases":
|
|
u := filepath.ToSlash("/repos/" + ghURI.RealRelativePath() + "/git/matching-refs/tags")
|
|
req, err = g.Client.NewRequest("GET", u, nil)
|
|
transform = transformVersionStream
|
|
case "sha256":
|
|
// something like https://github.com/sylviamoss/packer-plugin-comment/releases/download/v0.2.11/packer-plugin-comment_v0.2.11_x5_SHA256SUMS
|
|
u := filepath.ToSlash("https://github.com/" + ghURI.RealRelativePath() + "/releases/download/" + opts.Version() + "/" + opts.PluginRequirement.FilenamePrefix() + opts.Version() + "_SHA256SUMS")
|
|
req, err = g.Client.NewRequest(
|
|
"GET",
|
|
u,
|
|
nil,
|
|
)
|
|
transform = TransformChecksumStream()
|
|
case "zip":
|
|
u := filepath.ToSlash("https://github.com/" + ghURI.RealRelativePath() + "/releases/download/" + opts.Version() + "/" + opts.ExpectedZipFilename())
|
|
req, err = g.Client.NewRequest(
|
|
"GET",
|
|
u,
|
|
nil,
|
|
)
|
|
|
|
default:
|
|
return nil, fmt.Errorf("%q not implemented", what)
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
log.Printf("[DEBUG] github-getter: getting %q", req.URL)
|
|
resp, err := g.Client.BareDo(ctx, req)
|
|
if err != nil {
|
|
// here BareDo will return an err if the request failed or if the status
|
|
// is not considered a valid http status. So we have to close the body
|
|
// if it's not nil.
|
|
if resp != nil {
|
|
resp.Body.Close()
|
|
}
|
|
switch err := err.(type) {
|
|
case *github.RateLimitError:
|
|
return nil, &plugingetter.RateLimitError{
|
|
SetableEnvVar: ghTokenAccessor,
|
|
Err: err,
|
|
ResetTime: err.Rate.Reset.Time,
|
|
}
|
|
default:
|
|
log.Printf("[TRACE] failed requesting: %T. %v", err, err)
|
|
return nil, err
|
|
}
|
|
|
|
}
|
|
|
|
return transform(resp.Body)
|
|
}
|
|
|
|
// Init method: a file inside will look like so:
|
|
//
|
|
// packer-plugin-comment_v0.2.12_x5.0_freebsd_amd64.zip
|
|
func (g *Getter) Init(req *plugingetter.Requirement, entry *plugingetter.ChecksumFileEntry) error {
|
|
filename := entry.Filename
|
|
res := strings.TrimPrefix(filename, req.FilenamePrefix())
|
|
// res now looks like v0.2.12_x5.0_freebsd_amd64.zip
|
|
|
|
entry.Ext = filepath.Ext(res)
|
|
|
|
res = strings.TrimSuffix(res, entry.Ext)
|
|
// res now looks like v0.2.12_x5.0_freebsd_amd64
|
|
|
|
parts := strings.Split(res, "_")
|
|
// ["v0.2.12", "x5.0", "freebsd", "amd64"]
|
|
if len(parts) < 4 {
|
|
return fmt.Errorf("malformed filename expected %s{version}_x{protocol-version}_{os}_{arch}", req.FilenamePrefix())
|
|
}
|
|
|
|
entry.BinVersion, entry.ProtVersion, entry.Os, entry.Arch = parts[0], parts[1], parts[2], parts[3]
|
|
|
|
return nil
|
|
}
|
|
|
|
func (g *Getter) Validate(opt plugingetter.GetOptions, expectedVersion string, installOpts plugingetter.BinaryInstallationOptions, entry *plugingetter.ChecksumFileEntry) error {
|
|
expectedBinVersion := "v" + expectedVersion
|
|
if entry.BinVersion != expectedBinVersion {
|
|
return fmt.Errorf("wrong version: %s does not match expected %s", entry.BinVersion, expectedBinVersion)
|
|
}
|
|
if entry.Os != installOpts.OS || entry.Arch != installOpts.ARCH {
|
|
return fmt.Errorf("wrong system, expected %s_%s", installOpts.OS, installOpts.ARCH)
|
|
}
|
|
|
|
return installOpts.CheckProtocolVersion(entry.ProtVersion)
|
|
}
|
|
|
|
func (g *Getter) ExpectedFileName(pr *plugingetter.Requirement, version string, entry *plugingetter.ChecksumFileEntry, _ string) string {
|
|
pluginSourceParts := strings.Split(pr.Identifier.Source, "/")
|
|
return strings.Join([]string{
|
|
"packer-plugin-" + pluginSourceParts[2],
|
|
entry.BinVersion,
|
|
entry.ProtVersion,
|
|
entry.Os,
|
|
entry.Arch + entry.Ext,
|
|
}, "_")
|
|
}
|