Skip to content
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

Bind flags as prefixed env variables #2346

Merged
merged 3 commits into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions cmd/cosign/cli/attach.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ func attachSignature() *cobra.Command {
o := &options.AttachSignatureOptions{}

cmd := &cobra.Command{
Use: "signature",
Short: "Attach signatures to the supplied container image",
Example: " cosign attach signature <image uri>",
Args: cobra.ExactArgs(1),
Use: "signature",
Short: "Attach signatures to the supplied container image",
Example: " cosign attach signature <image uri>",
PersistentPreRun: options.BindViper,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return attach.SignatureCmd(cmd.Context(), o.Registry, o.Signature, o.Payload, args[0])
},
Expand All @@ -61,10 +62,11 @@ func attachSBOM() *cobra.Command {
o := &options.AttachSBOMOptions{}

cmd := &cobra.Command{
Use: "sbom",
Short: "Attach sbom to the supplied container image",
Example: " cosign attach sbom <image uri>",
Args: cobra.ExactArgs(1),
Use: "sbom",
Short: "Attach sbom to the supplied container image",
Example: " cosign attach sbom <image uri>",
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
mediaType, err := o.MediaType()
if err != nil {
Expand Down Expand Up @@ -96,7 +98,8 @@ func attachAttestation() *cobra.Command {
cosign attach attestation --attestation <attestation bundle file path> <image uri>
`,

Args: cobra.MinimumNArgs(1),
Args: cobra.MinimumNArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return attach.AttestationCmd(cmd.Context(), o.Registry, o.Attestations, args[0])
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/cosign/cli/attest.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ func Attest() *cobra.Command {
# attach an attestation to a container image which does not fully support OCI media types
COSIGN_DOCKER_MEDIA_TYPES=1 cosign attest --predicate <FILE> --type <TYPE> --key cosign.key legacy-registry.example.com/my/image`,

Args: cobra.MinimumNArgs(1),
Args: cobra.MinimumNArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
oidcClientSecret, err := o.OIDC.ClientSecret()
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion cmd/cosign/cli/attest_blob.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ func AttestBlob() *cobra.Command {
# attach an attestation to a blob with a key pair stored in Hashicorp Vault
cosign attest-blob --predicate <FILE> --type <TYPE> --key hashivault://[KEY] <BLOB>`,

Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
v := attest.AttestBlobCommand{
KeyRef: o.Key,
Expand Down
9 changes: 5 additions & 4 deletions cmd/cosign/cli/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ func Clean() *cobra.Command {
c := &options.CleanOptions{}

cmd := &cobra.Command{
Use: "clean",
Short: "Remove all signatures from an image.",
Example: " cosign clean <IMAGE>",
Args: cobra.ExactArgs(1),
Use: "clean",
Short: "Remove all signatures from an image.",
Example: " cosign clean <IMAGE>",
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return CleanCmd(cmd.Context(), c.Registry, c.CleanType, args[0], c.Force)
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/cosign/cli/copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ func Copy() *cobra.Command {
# overwrite destination image and signatures
cosign copy -f example.com/src example.com/dest`,

Args: cobra.ExactArgs(2),
Args: cobra.ExactArgs(2),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return copy.CopyCmd(cmd.Context(), o.Registry, args[0], args[1], o.SignatureOnly, o.Force)
},
Expand Down
5 changes: 3 additions & 2 deletions cmd/cosign/cli/dockerfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ func dockerfileVerify() *cobra.Command {
o := &options.VerifyDockerfileOptions{}

cmd := &cobra.Command{
Use: "verify",
Short: "Verify a signature on the base image specified in the Dockerfile",
Use: "verify",
Short: "Verify a signature on the base image specified in the Dockerfile",
PersistentPreRun: options.BindViper,
Long: `Verify signature and annotations on images in a Dockerfile by checking claims
against the transparency log.

Expand Down
27 changes: 15 additions & 12 deletions cmd/cosign/cli/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,11 @@ func downloadSignature() *cobra.Command {
o := &options.RegistryOptions{}

cmd := &cobra.Command{
Use: "signature",
Short: "Download signatures from the supplied container image",
Example: " cosign download signature <image uri>",
Args: cobra.ExactArgs(1),
Use: "signature",
Short: "Download signatures from the supplied container image",
Example: " cosign download signature <image uri>",
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return download.SignatureCmd(cmd.Context(), *o, args[0])
},
Expand All @@ -63,10 +64,11 @@ func downloadSBOM() *cobra.Command {
do := &options.SBOMDownloadOptions{}

cmd := &cobra.Command{
Use: "sbom",
Short: "Download SBOMs from the supplied container image",
Example: " cosign download sbom <image uri>",
Args: cobra.ExactArgs(1),
Use: "sbom",
Short: "Download SBOMs from the supplied container image",
Example: " cosign download sbom <image uri>",
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Fprintln(os.Stderr, "WARNING: Downloading SBOMs this way does not ensure its authenticity. If you want to ensure a tamper-proof SBOM, download it using 'cosign download attestation <image uri>' or verify its signature using 'cosign verify --key <key path> --attachment sbom <image uri>'.")
_, err := download.SBOMCmd(cmd.Context(), *o, *do, args[0], cmd.OutOrStdout())
Expand All @@ -84,10 +86,11 @@ func downloadAttestation() *cobra.Command {
o := &options.RegistryOptions{}

cmd := &cobra.Command{
Use: "attestation",
Short: "Download in-toto attestations from the supplied container image",
Example: " cosign download attestation <image uri>",
Args: cobra.ExactArgs(1),
Use: "attestation",
Short: "Download in-toto attestations from the supplied container image",
Example: " cosign download attestation <image uri>",
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return download.AttestationCmd(cmd.Context(), *o, args[0])
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/cosign/cli/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ to sign payloads with your own tooling or algorithms.`,
# Use this payload in another tool
gpg --output image.sig --detach-sig <(cosign generate <IMAGE>)`,

Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
annotationMap, err := o.AnnotationsMap()
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions cmd/cosign/cli/generate_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ CAVEATS:
This command interactively prompts for a password. You can use
the COSIGN_PASSWORD environment variable to provide one.`,

PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return generate.GenerateKeyPairCmd(cmd.Context(), o.KMS, args)
},
Expand Down
2 changes: 1 addition & 1 deletion cmd/cosign/cli/import_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func ImportKeyPair() *cobra.Command {
CAVEATS:
This command interactively prompts for a password. You can use
the COSIGN_PASSWORD environment variable to provide one.`,

PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return importkeypair.ImportKeyPairCmd(cmd.Context(), o.Key, args)
},
Expand Down
1 change: 1 addition & 0 deletions cmd/cosign/cli/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ cosign initialize -root <url>

# initialize with an out-of-band root key file and custom repository mirror.
cosign initialize -mirror <url> -root <url>`,
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return initialize.DoInitialize(cmd.Context(), o.Root, o.Mirror)
},
Expand Down
11 changes: 6 additions & 5 deletions cmd/cosign/cli/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@ func Load() *cobra.Command {
o := &options.LoadOptions{}

cmd := &cobra.Command{
Use: "load",
Short: "Load a signed image on disk to a remote registry",
Long: "Load a signed image on disk to a remote registry",
Example: ` cosign load --dir <path to directory> <IMAGE>`,
Args: cobra.ExactArgs(1),
Use: "load",
Short: "Load a signed image on disk to a remote registry",
Long: "Load a signed image on disk to a remote registry",
Example: ` cosign load --dir <path to directory> <IMAGE>`,
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return LoadCmd(cmd.Context(), *o, args[0])
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/cosign/cli/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ against the transparency log.`,

# verify images with public key stored in Hashicorp Vault
cosign manifest verify --key hashivault://[KEY] <path/to/my-deployment.yaml>`,
Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
annotations, err := o.AnnotationsMap()
if err != nil {
Expand Down
30 changes: 30 additions & 0 deletions cmd/cosign/cli/options/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@
package options

import (
"fmt"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)

const EnvPrefix = "COSIGN"

// RootOptions define flags and options for the root cosign cli.
type RootOptions struct {
OutputFile string
Expand All @@ -45,3 +51,27 @@ func (o *RootOptions) AddFlags(cmd *cobra.Command) {
cmd.PersistentFlags().DurationVarP(&o.Timeout, "timeout", "t", DefaultTimeout,
"timeout for commands")
}

func BindViper(cmd *cobra.Command, args []string) {
v := viper.New()
v.SetEnvPrefix(EnvPrefix)
v.AutomaticEnv()
bindFlags(cmd, v)
}

func bindFlags(cmd *cobra.Command, v *viper.Viper) {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if strings.Contains(f.Name, "-") {
_ = v.BindEnv(f.Name, flagToEnvVar(f.Name))
}
if !f.Changed && v.IsSet((f.Name)) {
val := v.Get(f.Name)
_ = cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val))
}
})
}

func flagToEnvVar(f string) string {
hectorj2f marked this conversation as resolved.
Show resolved Hide resolved
f = strings.ToUpper(f)
return fmt.Sprintf("%s_%s", EnvPrefix, strings.ReplaceAll(f, "-", "_"))
}
59 changes: 59 additions & 0 deletions cmd/cosign/cli/options/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package options

import (
"testing"

"github.com/google/go-cmp/cmp"
)

func TestFlagToEnv(t *testing.T) {
testCases := []struct {
flag string
expected string
}{
{
flag: "rekor-url",
expected: "COSIGN_REKOR_URL",
},
{
flag: "certificate",
expected: "COSIGN_CERTIFICATE",
},
{
flag: "k8s-keychain",
expected: "COSIGN_K8S_KEYCHAIN",
},
{
flag: "output-file",
expected: "COSIGN_OUTPUT_FILE",
},
{
flag: "sbom",
expected: "COSIGN_SBOM",
},
}

for _, tc := range testCases {
t.Run(tc.flag, func(t *testing.T) {
result := flagToEnvVar(tc.flag)
if diff := cmp.Diff(result, tc.expected); diff != "" {
t.Fatal(diff)
}
})
}
}
14 changes: 8 additions & 6 deletions cmd/cosign/cli/piv_tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,10 @@ func pivToolSetManagementKey() *cobra.Command {
o := &options.PIVToolSetManagementKeyOptions{}

cmd := &cobra.Command{
Use: "set-management-key",
Short: "sets the management key of a hardware token",
Args: cobra.ExactArgs(0),
Use: "set-management-key",
Short: "sets the management key of a hardware token",
Args: cobra.ExactArgs(0),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return pivcli.SetManagementKeyCmd(cmd.Context(), o.OldKey, o.NewKey, o.RandomKey)
},
Expand All @@ -73,9 +74,10 @@ func pivToolSetPIN() *cobra.Command {
o := &options.PIVToolSetPINOptions{}

cmd := &cobra.Command{
Use: "set-pin",
Short: "sets the PIN on a hardware token",
Args: cobra.ExactArgs(0),
Use: "set-pin",
Short: "sets the PIN on a hardware token",
Args: cobra.ExactArgs(0),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return pivcli.SetPinCmd(cmd.Context(), o.OldPIN, o.NewPIN)
},
Expand Down
8 changes: 5 additions & 3 deletions cmd/cosign/cli/policy_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ func initPolicy() *cobra.Command {
Example: `
# extract public key from private key to a specified out file.
cosign policy init -ns <project_namespace> --maintainers {email_addresses} --threshold <int> --expires <int>(days)`,
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
var publicKeys []*tuf.Key

Expand Down Expand Up @@ -163,9 +164,10 @@ func signPolicy() *cobra.Command {
o := &options.PolicySignOptions{}

cmd := &cobra.Command{
Use: "sign",
Short: "sign a keyless policy.",
Long: "policy is used to manage a root.json policy\nfor keyless signing delegation. This is used to establish a policy for a registry namespace,\na signing threshold and a list of maintainers who can sign over the body section.",
Use: "sign",
Short: "sign a keyless policy.",
Long: "policy is used to manage a root.json policy\nfor keyless signing delegation. This is used to establish a policy for a registry namespace,\na signing threshold and a list of maintainers who can sign over the body section.",
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if ro.Timeout != 0 {
Expand Down
1 change: 1 addition & 0 deletions cmd/cosign/cli/public_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func PublicKey() *cobra.Command {
}
return nil
},
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
writer := publickey.NamedWriter{Name: "", Writer: nil}
var f *os.File
Expand Down
11 changes: 6 additions & 5 deletions cmd/cosign/cli/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ func Save() *cobra.Command {
o := &options.SaveOptions{}

cmd := &cobra.Command{
Use: "save",
Short: "Save the container image and associated signatures to disk at the specified directory.",
Long: "Save the container image and associated signatures to disk at the specified directory.",
Example: ` cosign save --dir <path to directory> <IMAGE>`,
Args: cobra.ExactArgs(1),
Use: "save",
Short: "Save the container image and associated signatures to disk at the specified directory.",
Long: "Save the container image and associated signatures to disk at the specified directory.",
Example: ` cosign save --dir <path to directory> <IMAGE>`,
Args: cobra.ExactArgs(1),
PersistentPreRun: options.BindViper,
RunE: func(cmd *cobra.Command, args []string) error {
return SaveCmd(cmd.Context(), *o, args[0])
},
Expand Down
Loading