Skip to content

Commit

Permalink
refactor: use internal.ui lib instead of printf directly (#2607)
Browse files Browse the repository at this point in the history
In some of these cases, we're moving output from STDOUT to STDERR but it always
should have been on STDERR.

Signed-off-by: Zachary Newman <zjn@chainguard.dev>

Signed-off-by: Zachary Newman <zjn@chainguard.dev>
  • Loading branch information
znewman01 authored Jan 14, 2023
1 parent c604bfd commit da51656
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 24 deletions.
22 changes: 11 additions & 11 deletions cmd/cosign/cli/sign/sign.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func SignCmd(ro *options.RootOptions, ko options.KeyOpts, signOpts options.SignO

var staticPayload []byte
if signOpts.PayloadPath != "" {
fmt.Fprintln(os.Stderr, "Using payload from:", signOpts.PayloadPath)
ui.Info(ctx, "Using payload from:", signOpts.PayloadPath)
staticPayload, err = os.ReadFile(filepath.Clean(signOpts.PayloadPath))
if err != nil {
return fmt.Errorf("payload from file: %w", err)
Expand Down Expand Up @@ -295,7 +295,7 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti
return fmt.Errorf("create certificate file: %w", err)
}
// TODO: maybe accept a --b64 flag as well?
fmt.Printf("Certificate wrote in the file %s\n", outputCertificate)
ui.Info(ctx, "Certificate wrote in the file %s", outputCertificate)
}

if !upload {
Expand All @@ -317,9 +317,9 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti
// Check if we are overriding the signatures repository location
repo, _ := ociremote.GetEnvTargetRepository()
if repo.RepositoryStr() == "" {
fmt.Fprintln(os.Stderr, "Pushing signature to:", digest.Repository)
ui.Info(ctx, "Pushing signature to:", digest.Repository)
} else {
fmt.Fprintln(os.Stderr, "Pushing signature to:", repo.RepositoryStr())
ui.Info(ctx, "Pushing signature to:", repo.RepositoryStr())
}

// Publish the signatures associated with this entity
Expand All @@ -330,7 +330,7 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti
return nil
}

func signerFromSecurityKey(keySlot string) (*SignerVerifier, error) {
func signerFromSecurityKey(ctx context.Context, keySlot string) (*SignerVerifier, error) {
sk, err := pivkey.GetKeyWithSlot(keySlot)
if err != nil {
return nil, err
Expand All @@ -348,7 +348,7 @@ func signerFromSecurityKey(keySlot string) (*SignerVerifier, error) {
certFromPIV, err := sk.Certificate()
var pemBytes []byte
if err != nil {
fmt.Fprintln(os.Stderr, "warning: no x509 certificate retrieved from the PIV token")
ui.Warn(ctx, "no x509 certificate retrieved from the PIV token")
} else {
pemBytes, err = cryptoutils.MarshalCertificateToPEM(certFromPIV)
if err != nil {
Expand Down Expand Up @@ -384,7 +384,7 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin
certSigner.close = pkcs11Key.Close

if certFromPKCS11 == nil {
fmt.Fprintln(os.Stderr, "warning: no x509 certificate retrieved from the PKCS11 token")
ui.Warn(ctx, "no x509 certificate retrieved from the PKCS11 token")
} else {
pemBytes, err := cryptoutils.MarshalCertificateToPEM(certFromPKCS11)
if err != nil {
Expand Down Expand Up @@ -437,7 +437,7 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin
return nil, fmt.Errorf("marshaling certificate to PEM: %w", err)
}
if certSigner.Cert != nil {
fmt.Fprintln(os.Stderr, "warning: overriding x509 certificate retrieved from the PKCS11 token")
ui.Warn(ctx, "overriding x509 certificate retrieved from the PKCS11 token")
}
leafCert = parsedCert
certSigner.Cert = pemBytes
Expand Down Expand Up @@ -519,15 +519,15 @@ func keylessSigner(ctx context.Context, ko options.KeyOpts) (*SignerVerifier, er

func SignerFromKeyOpts(ctx context.Context, certPath string, certChainPath string, ko options.KeyOpts) (*SignerVerifier, error) {
if ko.Sk {
return signerFromSecurityKey(ko.Slot)
return signerFromSecurityKey(ctx, ko.Slot)
}

if ko.KeyRef != "" {
return signerFromKeyRef(ctx, certPath, certChainPath, ko.KeyRef, ko.PassFunc)
}

// Default Keyless!
fmt.Fprintln(os.Stderr, "Generating ephemeral keys...")
ui.Info(ctx, "Generating ephemeral keys...")
return keylessSigner(ctx, ko)
}

Expand All @@ -546,7 +546,7 @@ func (c *SignerVerifier) Close() {

func (c *SignerVerifier) Bytes(ctx context.Context) ([]byte, error) {
if c.Cert != nil {
fmt.Fprintf(os.Stderr, "using ephemeral certificate:\n%s\n", string(c.Cert))
ui.Info(ctx, "using ephemeral certificate:\n%s", string(c.Cert))
return c.Cert, nil
}

Expand Down
9 changes: 5 additions & 4 deletions pkg/cosign/tlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/transparency-dev/merkle/proof"
"github.com/transparency-dev/merkle/rfc6962"

"github.com/sigstore/cosign/v2/internal/ui"
"github.com/sigstore/cosign/v2/pkg/cosign/bundle"
"github.com/sigstore/cosign/v2/pkg/cosign/env"
"github.com/sigstore/rekor/pkg/generated/client"
Expand Down Expand Up @@ -180,7 +181,7 @@ func doUpload(ctx context.Context, rekorClient *client.Rekor, pe models.Proposed
// Here, we display the proof and succeed.
var existsErr *entries.CreateLogEntryConflict
if errors.As(err, &existsErr) {
fmt.Println("Signature already exists. Displaying proof")
ui.Info(ctx, "Signature already exists. Displaying proof")
uriSplit := strings.Split(existsErr.Location.String(), "/")
uuid := uriSplit[len(uriSplit)-1]
e, err := GetTlogEntry(ctx, rekorClient, uuid)
Expand All @@ -191,7 +192,7 @@ func doUpload(ctx context.Context, rekorClient *client.Rekor, pe models.Proposed
if err != nil {
return nil, err
}
return e, VerifyTLogEntryOffline(e, rekorPubsFromAPI)
return e, VerifyTLogEntryOffline(ctx, e, rekorPubsFromAPI)
}
return nil, err
}
Expand Down Expand Up @@ -409,7 +410,7 @@ func FindTlogEntry(ctx context.Context, rekorClient *client.Rekor,

// VerifyTLogEntryOffline verifies a TLog entry against a map of trusted rekorPubKeys indexed
// by log id.
func VerifyTLogEntryOffline(e *models.LogEntryAnon, rekorPubKeys *TrustedTransparencyLogPubKeys) error {
func VerifyTLogEntryOffline(ctx context.Context, e *models.LogEntryAnon, rekorPubKeys *TrustedTransparencyLogPubKeys) error {
if e.Verification == nil || e.Verification.InclusionProof == nil {
return errors.New("inclusion proof not provided")
}
Expand Down Expand Up @@ -460,7 +461,7 @@ func VerifyTLogEntryOffline(e *models.LogEntryAnon, rekorPubKeys *TrustedTranspa
return fmt.Errorf("verifying signedEntryTimestamp: %w", err)
}
if pubKey.Status != tuf.Active {
fmt.Fprintf(os.Stderr, "**Info** Successfully verified Rekor entry using an expired verification key\n")
ui.Info(ctx, "Successfully verified Rekor entry using an expired verification key")
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/cosign/tlog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func TestVerifyTLogEntryOfflineFailsWithInvalidPublicKey(t *testing.T) {
t.Fatalf("failed to add RSA key to transparency log public keys: %v", err)
}

err = VerifyTLogEntryOffline(&models.LogEntryAnon{Verification: &models.LogEntryAnonVerification{InclusionProof: &models.InclusionProof{}}}, &rekorPubKeys)
err = VerifyTLogEntryOffline(context.Background(), &models.LogEntryAnon{Verification: &models.LogEntryAnonVerification{InclusionProof: &models.InclusionProof{}}}, &rekorPubKeys)
if err == nil {
t.Fatal("Wanted error got none")
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/cosign/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ func tlogValidateEntry(ctx context.Context, client *client.Rekor, rekorPubKeys *
entryVerificationErrs := make([]string, 0)
for _, e := range tlogEntries {
entry := e
if err := VerifyTLogEntryOffline(&entry, rekorPubKeys); err != nil {
if err := VerifyTLogEntryOffline(ctx, &entry, rekorPubKeys); err != nil {
entryVerificationErrs = append(entryVerificationErrs, err.Error())
continue
}
Expand Down
14 changes: 7 additions & 7 deletions pkg/policy/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ package policy
import (
"context"
"fmt"
"log"

"cuelang.org/go/cue/cuecontext"
"github.com/sigstore/cosign/v2/internal/ui"
"github.com/sigstore/cosign/v2/pkg/cosign"
"github.com/sigstore/cosign/v2/pkg/cosign/rego"
)
Expand Down Expand Up @@ -53,9 +53,9 @@ func EvaluatePolicyAgainstJSON(ctx context.Context, name, policyType string, pol
}

// evaluateCue evaluates a cue policy `evaluator` against `attestation`
func evaluateCue(_ context.Context, attestation []byte, evaluator string) error {
log.Printf("Evaluating attestation: %s", string(attestation))
log.Printf("Evaluator: %s", evaluator)
func evaluateCue(ctx context.Context, attestation []byte, evaluator string) error {
ui.Info(ctx, "Evaluating attestation: %s", string(attestation))
ui.Info(ctx, "Evaluator: %s", evaluator)

cueCtx := cuecontext.New()
cueEvaluator := cueCtx.CompileString(evaluator)
Expand All @@ -74,9 +74,9 @@ func evaluateCue(_ context.Context, attestation []byte, evaluator string) error
}

// evaluateRego evaluates a rego policy `evaluator` against `attestation`
func evaluateRego(_ context.Context, attestation []byte, evaluator string) (warnings error, errors error) {
log.Printf("Evaluating attestation: %s", string(attestation))
log.Printf("Evaluating evaluator: %s", evaluator)
func evaluateRego(ctx context.Context, attestation []byte, evaluator string) (warnings error, errors error) {
ui.Info(ctx, "Evaluating attestation: %s", string(attestation))
ui.Info(ctx, "Evaluating evaluator: %s", evaluator)

return rego.ValidateJSONWithModuleInput(attestation, evaluator)
}

0 comments on commit da51656

Please sign in to comment.