rewrote packages

keyservice
joinservice
upgrade-agent
measurement-reader
debugd
disk-mapper

rewrote joinservice main

rewrote some unit tests

rewrote upgrade-agent + some grpc functions

rewrote measurement-reader

rewrote debugd

removed unused import

removed forgotten zap reference in measurements reader

rewrote disk-mapper + tests

rewrote packages

verify
disk-mapper
malicious join
bootstrapper
attestationconfigapi
versionapi
internal/cloud/azure
disk-mapper tests
image/upload/internal/cmd

rewrote verify (WIP with loglevel increase)

rewrote forgotten zap references in disk-mapper

rewrote malicious join

rewrote bootstrapper

rewrote parts of internal/

rewrote attestationconfigapi (WIP)

rewrote versionapi cli

rewrote internal/cloud/azure

rewrote disk-mapper tests (untested by me rn)

rewrote image/upload/internal/cmd

removed forgotten zap references in verify/cmd

rewrote packages

hack/oci-pin
hack/qemu-metadata-api
debugd/internal/debugd/deploy
hack/bazel-deps-mirror
cli/internal/cmd
cli-k8s-compatibility

rewrote hack/qemu-metadata-api/server

rewrote debugd/internal/debugd/deploy

rewrote hack/bazel-deps-mirror

rewrote rest of hack/qemu-metadata-api

rewrote forgotten zap references in joinservice server

rewrote cli/internal/cmd

rewrote cli-k8s-compatibility

rewrote packages

internal/staticupload
e2d/internal/upgrade
internal/constellation/helm
internal/attestation/aws/snp
internal/attestation/azure/trustedlaunch
joinservice/internal/certcache/amkds

some missed unit tests

rewrote e2e/internal/upgrade

rewrote internal/constellation/helm

internal/attestation/aws/snp

internal/attestation/azure/trustedlaunch

joinservice/internal/certcache/amkds

search and replace test logging over all left *_test.go
This commit is contained in:
miampf 2023-12-29 15:18:59 +01:00
parent 48d5a157dd
commit f16ccf5679
No known key found for this signature in database
GPG key ID: 376EAC0E5307A669
158 changed files with 3400 additions and 1278 deletions

View file

@ -212,7 +212,6 @@ func runApply(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
spinner, err := newSpinnerOrStderr(cmd)
if err != nil {
return err
@ -396,7 +395,7 @@ func (a *applyCmd) apply(
// Apply Attestation Config
if !a.flags.skipPhases.contains(skipAttestationConfigPhase) {
a.log.Debugf("Applying new attestation config to cluster")
a.log.Debug("Applying new attestation config to cluster")
if err := a.applyJoinConfig(cmd, conf.GetAttestationConfig(), stateFile.ClusterValues.MeasurementSalt); err != nil {
return fmt.Errorf("applying attestation config: %w", err)
}
@ -443,7 +442,7 @@ func (a *applyCmd) apply(
func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationconfigapi.Fetcher) (*config.Config, *state.State, error) {
// Read user's config and state file
a.log.Debugf("Reading config from %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
a.log.Debug("Reading config from %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
conf, err := config.New(a.fileHandler, constants.ConfigFilename, configFetcher, a.flags.force)
var configValidationErr *config.ValidationError
if errors.As(err, &configValidationErr) {
@ -453,7 +452,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
return nil, nil, err
}
a.log.Debugf("Reading state file from %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
a.log.Debug("Reading state file from %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
stateFile, err := state.CreateOrRead(a.fileHandler, constants.StateFilename)
if err != nil {
return nil, nil, err
@ -473,7 +472,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
// in which case the workspace has to be clean
if preCreateValidateErr == nil {
// We can't skip the infrastructure phase if no infrastructure has been defined
a.log.Debugf("State file is in pre-create state, checking workspace")
a.log.Debug("State file is in pre-create state, checking workspace")
if a.flags.skipPhases.contains(skipInfrastructurePhase) {
return nil, nil, preInitValidateErr
}
@ -482,7 +481,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
return nil, nil, err
}
a.log.Debugf("No Terraform state found in current working directory. Preparing to create a new cluster.")
a.log.Debug("No Terraform state found in current working directory. Preparing to create a new cluster.")
printCreateWarnings(cmd.ErrOrStderr(), conf)
}
@ -491,7 +490,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
// If so, we need to run the init RPC
if preInitValidateErr == nil || (preCreateValidateErr == nil && !a.flags.skipPhases.contains(skipInitPhase)) {
// We can't skip the init phase if the init RPC hasn't been run yet
a.log.Debugf("State file is in pre-init state, checking workspace")
a.log.Debug("State file is in pre-init state, checking workspace")
if a.flags.skipPhases.contains(skipInitPhase) {
return nil, nil, postInitValidateErr
}
@ -507,7 +506,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
// If the state file is in a post-init state,
// we need to make sure specific files exist in the workspace
if postInitValidateErr == nil {
a.log.Debugf("State file is in post-init state, checking workspace")
a.log.Debug("State file is in post-init state, checking workspace")
if err := a.checkPostInitFilesExist(); err != nil {
return nil, nil, err
}
@ -522,16 +521,16 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
// If we need to run the init RPC, the version has to be valid
// Otherwise, we are able to use an outdated version, meaning we skip the K8s upgrade
// We skip version validation if the user explicitly skips the Kubernetes phase
a.log.Debugf("Validating Kubernetes version %s", conf.KubernetesVersion)
a.log.Debug("Validating Kubernetes version %s", conf.KubernetesVersion)
validVersion, err := versions.NewValidK8sVersion(string(conf.KubernetesVersion), true)
if err != nil {
a.log.Debugf("Kubernetes version not valid: %s", err)
a.log.Debug("Kubernetes version not valid: %s", err)
if !a.flags.skipPhases.contains(skipInitPhase) {
return nil, nil, err
}
if !a.flags.skipPhases.contains(skipK8sPhase) {
a.log.Debugf("Checking if user wants to continue anyway")
a.log.Debug("Checking if user wants to continue anyway")
if !a.flags.yes {
confirmed, err := askToConfirm(cmd,
fmt.Sprintf(
@ -548,7 +547,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
}
a.flags.skipPhases.add(skipK8sPhase)
a.log.Debugf("Outdated Kubernetes version accepted, Kubernetes upgrade will be skipped")
a.log.Debug("Outdated Kubernetes version accepted, Kubernetes upgrade will be skipped")
}
validVersionString, err := versions.ResolveK8sPatchVersion(xsemver.MajorMinor(string(conf.KubernetesVersion)))
@ -564,7 +563,7 @@ func (a *applyCmd) validateInputs(cmd *cobra.Command, configFetcher attestationc
cmd.PrintErrf("Warning: Constellation with Kubernetes %s is still in preview. Use only for evaluation purposes.\n", validVersion)
}
conf.KubernetesVersion = validVersion
a.log.Debugf("Target Kubernetes version set to %s", conf.KubernetesVersion)
a.log.Debug("Target Kubernetes version set to %s", conf.KubernetesVersion)
// Validate microservice version (helm versions) in the user's config matches the version of the CLI
// This makes sure we catch potential errors early, not just after we already ran Terraform migrations or the init RPC
@ -592,9 +591,9 @@ func (a *applyCmd) applyJoinConfig(cmd *cobra.Command, newConfig config.Attestat
) error {
clusterAttestationConfig, err := a.applier.GetClusterAttestationConfig(cmd.Context(), newConfig.GetVariant())
if err != nil {
a.log.Debugf("Getting cluster attestation config failed: %s", err)
a.log.Debug("Getting cluster attestation config failed: %s", err)
if k8serrors.IsNotFound(err) {
a.log.Debugf("Creating new join config")
a.log.Debug("Creating new join config")
return a.applier.ApplyJoinConfig(cmd.Context(), newConfig, measurementSalt)
}
return fmt.Errorf("getting cluster attestation config: %w", err)
@ -606,7 +605,7 @@ func (a *applyCmd) applyJoinConfig(cmd *cobra.Command, newConfig config.Attestat
return fmt.Errorf("comparing attestation configs: %w", err)
}
if equal {
a.log.Debugf("Current attestation config is equal to the new config, nothing to do")
a.log.Debug("Current attestation config is equal to the new config, nothing to do")
return nil
}
@ -685,7 +684,7 @@ func (a *applyCmd) checkCreateFilesClean() error {
if err := a.checkInitFilesClean(); err != nil {
return err
}
a.log.Debugf("Checking Terraform state")
a.log.Debug("Checking Terraform state")
if _, err := a.fileHandler.Stat(constants.TerraformWorkingDir); err == nil {
return fmt.Errorf(
"terraform state %q already exists in working directory, run 'constellation terminate' before creating a new cluster",
@ -700,7 +699,7 @@ func (a *applyCmd) checkCreateFilesClean() error {
// checkInitFilesClean ensures that the workspace is clean before running the init RPC.
func (a *applyCmd) checkInitFilesClean() error {
a.log.Debugf("Checking admin configuration file")
a.log.Debug("Checking admin configuration file")
if _, err := a.fileHandler.Stat(constants.AdminConfFilename); err == nil {
return fmt.Errorf(
"file %q already exists in working directory, run 'constellation terminate' before creating a new cluster",
@ -709,7 +708,7 @@ func (a *applyCmd) checkInitFilesClean() error {
} else if !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("checking for %q: %w", a.flags.pathPrefixer.PrefixPrintablePath(constants.AdminConfFilename), err)
}
a.log.Debugf("Checking master secrets file")
a.log.Debug("Checking master secrets file")
if _, err := a.fileHandler.Stat(constants.MasterSecretFilename); err == nil {
return fmt.Errorf(
"file %q already exists in working directory. Constellation won't overwrite previous master secrets. Move it somewhere or delete it before creating a new cluster",
@ -807,18 +806,18 @@ type warnLogger struct {
// Infof messages are reduced to debug messages, since we don't want
// the extra info when using the CLI without setting the debug flag.
func (wl warnLogger) Infof(fmtStr string, args ...any) {
wl.log.Debugf(fmtStr, args...)
func (wl warnLogger) Info(fmtStr string, args ...any) {
wl.log.Debug(fmtStr, args...)
}
// Warnf prints a formatted warning from the validator.
func (wl warnLogger) Warnf(fmtStr string, args ...any) {
func (wl warnLogger) Warn(fmtStr string, args ...any) {
wl.cmd.PrintErrf("Warning: %s\n", fmt.Sprintf(fmtStr, args...))
}
type warnLog interface {
Warnf(format string, args ...any)
Infof(format string, args ...any)
Warn(format string, args ...any)
Info(format string, args ...any)
}
// applier is used to run the different phases of the apply command.

View file

@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"path/filepath"
"strings"
"testing"
@ -196,7 +197,7 @@ func TestBackupHelmCharts(t *testing.T) {
applier: &stubConstellApplier{
stubKubernetesUpgrader: tc.backupClient,
},
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
}
err := a.backupHelmCharts(context.Background(), tc.helmApplier, tc.includesUpgrades, "")
@ -442,7 +443,7 @@ func TestValidateInputs(t *testing.T) {
cmd.SetIn(bytes.NewBufferString(tc.stdin))
a := applyCmd{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
fileHandler: fileHandler,
flags: tc.flags,
}

View file

@ -25,7 +25,7 @@ import (
// runHelmApply handles installing or upgrading helm charts for the cluster.
func (a *applyCmd) runHelmApply(cmd *cobra.Command, conf *config.Config, stateFile *state.State, upgradeDir string,
) error {
a.log.Debugf("Installing or upgrading Helm charts")
a.log.Debug("Installing or upgrading Helm charts")
var masterSecret uri.MasterSecret
if err := a.fileHandler.ReadJSON(constants.MasterSecretFilename, &masterSecret); err != nil {
return fmt.Errorf("reading master secret: %w", err)
@ -44,13 +44,13 @@ func (a *applyCmd) runHelmApply(cmd *cobra.Command, conf *config.Config, stateFi
AllowDestructive: helm.DenyDestructive,
}
a.log.Debugf("Getting service account URI")
a.log.Debug("Getting service account URI")
serviceAccURI, err := cloudcmd.GetMarshaledServiceAccountURI(conf, a.fileHandler)
if err != nil {
return err
}
a.log.Debugf("Preparing Helm charts")
a.log.Debug("Preparing Helm charts")
executor, includesUpgrades, err := a.applier.PrepareHelmCharts(options, stateFile, serviceAccURI, masterSecret, conf.Provider.OpenStack)
if errors.Is(err, helm.ErrConfirmationMissing) {
if !a.flags.yes {
@ -75,12 +75,12 @@ func (a *applyCmd) runHelmApply(cmd *cobra.Command, conf *config.Config, stateFi
cmd.PrintErrln(err)
}
a.log.Debugf("Backing up Helm charts")
a.log.Debug("Backing up Helm charts")
if err := a.backupHelmCharts(cmd.Context(), executor, includesUpgrades, upgradeDir); err != nil {
return err
}
a.log.Debugf("Applying Helm charts")
a.log.Debug("Applying Helm charts")
if !a.flags.skipPhases.contains(skipInitPhase) {
a.spinner.Start("Installing Kubernetes components ", false)
} else {
@ -108,10 +108,10 @@ func (a *applyCmd) backupHelmCharts(
if err := executor.SaveCharts(chartDir, a.fileHandler); err != nil {
return fmt.Errorf("saving Helm charts to disk: %w", err)
}
a.log.Debugf("Helm charts saved to %s", a.flags.pathPrefixer.PrefixPrintablePath(chartDir))
a.log.Debug("Helm charts saved to %s", a.flags.pathPrefixer.PrefixPrintablePath(chartDir))
if includesUpgrades {
a.log.Debugf("Creating backup of CRDs and CRs")
a.log.Debug("Creating backup of CRDs and CRs")
crds, err := a.applier.BackupCRDs(ctx, a.fileHandler, upgradeDir)
if err != nil {
return fmt.Errorf("creating CRD backup: %w", err)

View file

@ -29,13 +29,13 @@ import (
// On success, it writes the Kubernetes admin config file to disk.
// Therefore it is skipped if the Kubernetes admin config file already exists.
func (a *applyCmd) runInit(cmd *cobra.Command, conf *config.Config, stateFile *state.State) (*bytes.Buffer, error) {
a.log.Debugf("Creating aTLS Validator for %s", conf.GetAttestationConfig().GetVariant())
a.log.Debug("Creating aTLS Validator for %s", conf.GetAttestationConfig().GetVariant())
validator, err := choose.Validator(conf.GetAttestationConfig(), a.wLog)
if err != nil {
return nil, fmt.Errorf("creating validator: %w", err)
}
a.log.Debugf("Running init RPC")
a.log.Debug("Running init RPC")
masterSecret, err := a.generateAndPersistMasterSecret(cmd.OutOrStdout())
if err != nil {
return nil, fmt.Errorf("generating master secret: %w", err)
@ -74,9 +74,9 @@ func (a *applyCmd) runInit(cmd *cobra.Command, conf *config.Config, stateFile *s
}
return nil, err
}
a.log.Debugf("Initialization request successful")
a.log.Debug("Initialization request successful")
a.log.Debugf("Buffering init success message")
a.log.Debug("Buffering init success message")
bufferedOutput := &bytes.Buffer{}
if err := a.writeInitOutput(stateFile, resp, a.flags.mergeConfigs, bufferedOutput, measurementSalt); err != nil {
return nil, err
@ -121,7 +121,7 @@ func (a *applyCmd) writeInitOutput(
if err := a.fileHandler.Write(constants.AdminConfFilename, initResp.Kubeconfig, file.OptNone); err != nil {
return fmt.Errorf("writing kubeconfig: %w", err)
}
a.log.Debugf("Kubeconfig written to %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.AdminConfFilename))
a.log.Debug("Kubeconfig written to %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.AdminConfFilename))
if mergeConfig {
if err := a.merger.mergeConfigs(constants.AdminConfFilename, a.fileHandler); err != nil {
@ -136,7 +136,7 @@ func (a *applyCmd) writeInitOutput(
return fmt.Errorf("writing Constellation state file: %w", err)
}
a.log.Debugf("Constellation state file written to %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
a.log.Debug("Constellation state file written to %s", a.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
if !mergeConfig {
fmt.Fprintln(wr, "You can now connect to your cluster by executing:")

View file

@ -23,7 +23,7 @@ import (
// runTerraformApply checks if changes to Terraform are required and applies them.
func (a *applyCmd) runTerraformApply(cmd *cobra.Command, conf *config.Config, stateFile *state.State, upgradeDir string) error {
a.log.Debugf("Checking if Terraform migrations are required")
a.log.Debug("Checking if Terraform migrations are required")
terraformClient, removeClient, err := a.newInfraApplier(cmd.Context())
if err != nil {
return fmt.Errorf("creating Terraform client: %w", err)
@ -39,18 +39,18 @@ func (a *applyCmd) runTerraformApply(cmd *cobra.Command, conf *config.Config, st
if changesRequired, err := a.planTerraformChanges(cmd, conf, terraformClient); err != nil {
return fmt.Errorf("planning Terraform migrations: %w", err)
} else if !changesRequired {
a.log.Debugf("No changes to infrastructure required, skipping Terraform migrations")
a.log.Debug("No changes to infrastructure required, skipping Terraform migrations")
return nil
}
a.log.Debugf("Apply new Terraform resources for infrastructure changes")
a.log.Debug("Apply new Terraform resources for infrastructure changes")
newInfraState, err := a.applyTerraformChanges(cmd, conf, terraformClient, upgradeDir, isNewCluster)
if err != nil {
return err
}
// Merge the original state with the new infrastructure values
a.log.Debugf("Updating state file with new infrastructure state")
a.log.Debug("Updating state file with new infrastructure state")
if _, err := stateFile.Merge(
// temporary state with new infrastructure values
state.New().SetInfrastructure(newInfraState),
@ -68,7 +68,7 @@ func (a *applyCmd) runTerraformApply(cmd *cobra.Command, conf *config.Config, st
// planTerraformChanges checks if any changes to the Terraform state are required.
// If no state exists, this function will return true and the caller should create a new state.
func (a *applyCmd) planTerraformChanges(cmd *cobra.Command, conf *config.Config, terraformClient cloudApplier) (bool, error) {
a.log.Debugf("Planning Terraform changes")
a.log.Debug("Planning Terraform changes")
// Check if there are any Terraform changes to apply
@ -76,7 +76,7 @@ func (a *applyCmd) planTerraformChanges(cmd *cobra.Command, conf *config.Config,
//
// var manualMigrations []terraform.StateMigration
// for _, migration := range manualMigrations {
// u.log.Debugf("Adding manual Terraform migration: %s", migration.DisplayName)
// u.log.Debug("Adding manual Terraform migration: %s", migration.DisplayName)
// u.infraApplier.AddManualStateMigration(migration)
// }
@ -146,7 +146,7 @@ func (a *applyCmd) applyTerraformChangesWithMessage(
return state.Infrastructure{}, errors.New(abortErrorMsg)
}
}
a.log.Debugf("Applying Terraform changes")
a.log.Debug("Applying Terraform changes")
a.spinner.Start(progressMsg, false)
infraState, err := terraformClient.Apply(cmd.Context(), csp, attestation, rollbackBehavior)
@ -186,7 +186,7 @@ func printCreateInfo(out io.Writer, conf *config.Config, log debugLog) error {
}
}
if len(otherGroupNames) > 0 {
log.Debugf("Creating %d additional node groups: %v", len(otherGroupNames), otherGroupNames)
log.Debug("Creating %d additional node groups: %v", len(otherGroupNames), otherGroupNames)
}
fmt.Fprintf(out, "The following Constellation cluster will be created:\n")

View file

@ -93,7 +93,6 @@ func runConfigFetchMeasurements(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
fileHandler := file.NewHandler(afero.NewOsFs())
rekor, err := sigstore.NewRekor()
if err != nil {
@ -105,7 +104,7 @@ func runConfigFetchMeasurements(cmd *cobra.Command, _ []string) error {
if err := cfm.flags.parse(cmd.Flags()); err != nil {
return fmt.Errorf("parsing flags: %w", err)
}
cfm.log.Debugf("Using flags %+v", cfm.flags)
cfm.log.Debug("Using flags %+v", cfm.flags)
fetcher := attestationconfigapi.NewFetcherWithClient(http.DefaultClient, constants.CDNRepositoryURL)
return cfm.configFetchMeasurements(cmd, fileHandler, fetcher)
@ -119,7 +118,7 @@ func (cfm *configFetchMeasurementsCmd) configFetchMeasurements(
return errors.New("fetching measurements is not supported")
}
cfm.log.Debugf("Loading configuration file from %q", cfm.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
cfm.log.Debug("Loading configuration file from %q", cfm.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
conf, err := config.New(fileHandler, constants.ConfigFilename, fetcher, cfm.flags.force)
var configValidationErr *config.ValidationError
@ -134,11 +133,11 @@ func (cfm *configFetchMeasurementsCmd) configFetchMeasurements(
cmd.PrintErrln("Configured image doesn't look like a released production image. Double check image before deploying to production.")
}
cfm.log.Debugf("Creating context")
cfm.log.Debug("Creating context")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
cfm.log.Debugf("Updating URLs")
cfm.log.Debug("Updating URLs")
if err := cfm.flags.updateURLs(conf); err != nil {
return err
}
@ -155,12 +154,12 @@ func (cfm *configFetchMeasurementsCmd) configFetchMeasurements(
}
cfm.log.Debugf("Measurements: %#v\n", fetchedMeasurements)
cfm.log.Debugf("Updating measurements in configuration")
cfm.log.Debug("Updating measurements in configuration")
conf.UpdateMeasurements(fetchedMeasurements)
if err := fileHandler.WriteYAML(constants.ConfigFilename, conf, file.OptOverwrite); err != nil {
return err
}
cfm.log.Debugf("Configuration written to %s", cfm.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
cfm.log.Debug("Configuration written to %s", cfm.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
cmd.Print("Successfully fetched measurements and updated Configuration\n")
return nil
}

View file

@ -8,6 +8,7 @@ package cmd
import (
"context"
"log/slog"
"net/http"
"net/url"
"testing"
@ -180,7 +181,7 @@ func TestConfigFetchMeasurements(t *testing.T) {
err := fileHandler.WriteYAML(constants.ConfigFilename, gcpConfig, file.OptMkdirAll)
require.NoError(err)
fetcher := stubVerifyFetcher{err: tc.err}
cfm := &configFetchMeasurementsCmd{canFetchMeasurements: true, log: logger.NewTest(t), verifyFetcher: fetcher}
cfm := &configFetchMeasurementsCmd{canFetchMeasurements: true, log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)), verifyFetcher: fetcher}
cfm.flags.insecure = tc.insecureFlag
cfm.flags.force = true

View file

@ -8,6 +8,7 @@ package cmd
import (
"fmt"
"log/slog"
"strings"
"testing"
@ -92,7 +93,7 @@ func TestConfigGenerateDefault(t *testing.T) {
cmd := newConfigGenerateCmd()
cg := &configGenerateCmd{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
flags: generateFlags{
attestationVariant: variant.Dummy{},
k8sVersion: versions.Default,
@ -144,7 +145,7 @@ func TestConfigGenerateDefaultProviderSpecific(t *testing.T) {
wantConf.RemoveProviderAndAttestationExcept(tc.provider)
cg := &configGenerateCmd{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
flags: generateFlags{
attestationVariant: variant.Dummy{},
k8sVersion: versions.Default,
@ -177,7 +178,7 @@ func TestConfigGenerateDefaultExists(t *testing.T) {
cmd := newConfigGenerateCmd()
cg := &configGenerateCmd{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
flags: generateFlags{attestationVariant: variant.Dummy{}},
}
require.Error(cg.configGenerate(cmd, fileHandler, cloudprovider.Unknown, ""))

View file

@ -9,6 +9,7 @@ package cmd
import (
"bytes"
"context"
"log/slog"
"testing"
"github.com/edgelesssys/constellation/v2/internal/cloud/cloudprovider"
@ -227,7 +228,7 @@ func TestCreate(t *testing.T) {
skipPhases: newPhases(skipInitPhase, skipAttestationConfigPhase, skipCertSANsPhase, skipHelmPhase, skipImagePhase, skipK8sPhase),
},
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
spinner: &nopSpinner{},
newInfraApplier: func(_ context.Context) (cloudApplier, func(), error) {
@ -295,7 +296,7 @@ func TestCheckDirClean(t *testing.T) {
for _, f := range tc.existingFiles {
require.NoError(fh.Write(f, []byte{1, 2, 3}, file.OptNone))
}
a := &applyCmd{log: logger.NewTest(t), fileHandler: fh}
a := &applyCmd{log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)), fileHandler: fh}
err := a.checkInitFilesClean()
if tc.wantErr {

View file

@ -82,7 +82,6 @@ func runIAMCreate(cmd *cobra.Command, providerCreator providerIAMCreator, provid
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
iamCreator := &iamCreator{
cmd: cmd,
@ -134,7 +133,7 @@ func (c *iamCreator) create(ctx context.Context) error {
var conf config.Config
if c.flags.updateConfig {
c.log.Debugf("Parsing config %s", c.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
c.log.Debug("Parsing config %s", c.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
if err := c.fileHandler.ReadYAML(constants.ConfigFilename, &conf); err != nil {
return fmt.Errorf("error reading the configuration file: %w", err)
}
@ -154,7 +153,7 @@ func (c *iamCreator) create(ctx context.Context) error {
return err
}
c.cmd.Println() // Print empty line to separate after spinner ended.
c.log.Debugf("Successfully created the IAM cloud resources")
c.log.Debug("Successfully created the IAM cloud resources")
err = c.providerCreator.parseAndWriteIDFile(iamFile, c.fileHandler)
if err != nil {
@ -162,7 +161,7 @@ func (c *iamCreator) create(ctx context.Context) error {
}
if c.flags.updateConfig {
c.log.Debugf("Writing IAM configuration to %s", c.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
c.log.Debug("Writing IAM configuration to %s", c.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
c.providerCreator.writeOutputValuesToConfig(&conf, iamFile)
if err := c.fileHandler.WriteYAML(constants.ConfigFilename, conf, file.OptOverwrite); err != nil {
return err

View file

@ -8,6 +8,7 @@ package cmd
import (
"bytes"
"encoding/base64"
"log/slog"
"strings"
"testing"
@ -209,7 +210,7 @@ func TestIAMCreateAWS(t *testing.T) {
iamCreator := &iamCreator{
cmd: cmd,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
spinner: &nopSpinner{},
creator: tc.creator,
fileHandler: fileHandler,
@ -385,7 +386,7 @@ func TestIAMCreateAzure(t *testing.T) {
iamCreator := &iamCreator{
cmd: cmd,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
spinner: &nopSpinner{},
creator: tc.creator,
fileHandler: fileHandler,
@ -576,7 +577,7 @@ func TestIAMCreateGCP(t *testing.T) {
iamCreator := &iamCreator{
cmd: cmd,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
spinner: &nopSpinner{},
creator: tc.creator,
fileHandler: fileHandler,

View file

@ -58,7 +58,6 @@ func runIAMDestroy(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
spinner := newSpinner(cmd.ErrOrStderr())
destroyer := cloudcmd.NewIAMDestroyer()
fsHandler := file.NewHandler(afero.NewOsFs())
@ -78,25 +77,25 @@ type destroyCmd struct {
func (c *destroyCmd) iamDestroy(cmd *cobra.Command, spinner spinnerInterf, destroyer iamDestroyer, fsHandler file.Handler) error {
// check if there is a possibility that the cluster is still running by looking out for specific files
c.log.Debugf("Checking if %q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.AdminConfFilename))
c.log.Debug("Checking if %q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.AdminConfFilename))
if _, err := fsHandler.Stat(constants.AdminConfFilename); !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("file %q still exists, please make sure to terminate your cluster before destroying your IAM configuration", c.flags.pathPrefixer.PrefixPrintablePath(constants.AdminConfFilename))
}
c.log.Debugf("Checking if %q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
c.log.Debug("Checking if %q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
if _, err := fsHandler.Stat(constants.StateFilename); !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("file %q still exists, please make sure to terminate your cluster before destroying your IAM configuration", c.flags.pathPrefixer.PrefixPrintablePath(constants.StateFilename))
}
gcpFileExists := false
c.log.Debugf("Checking if %q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
c.log.Debug("Checking if %q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
if _, err := fsHandler.Stat(constants.GCPServiceAccountKeyFilename); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return err
}
} else {
c.log.Debugf("%q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
c.log.Debug("%q exists", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
gcpFileExists = true
}
@ -117,7 +116,7 @@ func (c *destroyCmd) iamDestroy(cmd *cobra.Command, spinner spinnerInterf, destr
}
if gcpFileExists {
c.log.Debugf("Starting to delete %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
c.log.Debug("Starting to delete %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
proceed, err := c.deleteGCPServiceAccountKeyFile(cmd, destroyer, fsHandler)
if err != nil {
return err
@ -128,7 +127,7 @@ func (c *destroyCmd) iamDestroy(cmd *cobra.Command, spinner spinnerInterf, destr
}
}
c.log.Debugf("Starting to destroy IAM configuration")
c.log.Debug("Starting to destroy IAM configuration")
spinner.Start("Destroying IAM configuration", false)
defer spinner.Stop()
@ -144,18 +143,18 @@ func (c *destroyCmd) iamDestroy(cmd *cobra.Command, spinner spinnerInterf, destr
func (c *destroyCmd) deleteGCPServiceAccountKeyFile(cmd *cobra.Command, destroyer iamDestroyer, fsHandler file.Handler) (bool, error) {
var fileSaKey gcpshared.ServiceAccountKey
c.log.Debugf("Parsing %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
c.log.Debug("Parsing %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
if err := fsHandler.ReadJSON(constants.GCPServiceAccountKeyFilename, &fileSaKey); err != nil {
return false, err
}
c.log.Debugf("Getting service account key from the tfstate")
c.log.Debug("Getting service account key from the tfstate")
tfSaKey, err := destroyer.GetTfStateServiceAccountKey(cmd.Context(), constants.TerraformIAMWorkingDir)
if err != nil {
return false, err
}
c.log.Debugf("Checking if keys are the same")
c.log.Debug("Checking if keys are the same")
if tfSaKey != fileSaKey {
cmd.Printf(
"The key in %q don't match up with your Terraform state. %q will not be deleted.\n",
@ -169,6 +168,6 @@ func (c *destroyCmd) deleteGCPServiceAccountKeyFile(cmd *cobra.Command, destroye
return false, err
}
c.log.Debugf("Successfully deleted %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
c.log.Debug("Successfully deleted %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.GCPServiceAccountKeyFilename))
return true, nil
}

View file

@ -7,6 +7,7 @@ package cmd
import (
"bytes"
"errors"
"log/slog"
"testing"
"github.com/edgelesssys/constellation/v2/internal/cloud/gcpshared"
@ -106,7 +107,7 @@ func TestIAMDestroy(t *testing.T) {
cmd.SetErr(&bytes.Buffer{})
cmd.SetIn(bytes.NewBufferString(tc.stdin))
c := &destroyCmd{log: logger.NewTest(t), flags: iamDestroyFlags{
c := &destroyCmd{log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)), flags: iamDestroyFlags{
yes: tc.yesFlag,
}}
@ -196,7 +197,7 @@ func TestDeleteGCPServiceAccountKeyFile(t *testing.T) {
cmd.SetErr(&bytes.Buffer{})
cmd.SetIn(bytes.NewBufferString(tc.stdin))
c := &destroyCmd{log: logger.NewTest(t)}
c := &destroyCmd{log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil))}
proceed, err := c.deleteGCPServiceAccountKeyFile(cmd, tc.destroyer, tc.fsHandler)
if tc.wantErr {

View file

@ -149,7 +149,7 @@ func (i iamUpgradeApplyCmd) iamUpgradeApply(cmd *cobra.Command, iamUpgrader iamU
return errors.New("IAM upgrade aborted by user")
}
}
i.log.Debugf("Applying Terraform IAM migrations")
i.log.Debug("Applying Terraform IAM migrations")
if err := iamUpgrader.ApplyIAMUpgrade(cmd.Context(), conf.GetProvider()); err != nil {
return fmt.Errorf("applying terraform migrations: %w", err)
}

View file

@ -8,6 +8,7 @@ package cmd
import (
"context"
"io"
"log/slog"
"path/filepath"
"strings"
"testing"
@ -131,7 +132,7 @@ func TestIamUpgradeApply(t *testing.T) {
iamUpgradeApplyCmd := &iamUpgradeApplyCmd{
fileHandler: tc.fh,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
configFetcher: tc.configFetcher,
flags: iamUpgradeApplyFlags{
yes: tc.yesFlag,

View file

@ -72,7 +72,7 @@ func (c *kubeconfigMerger) mergeConfigs(configPath string, fileHandler file.Hand
clientcmd.RecommendedHomeFile,
configPath, // our config should overwrite the default config
}
c.log.Debugf("Kubeconfig file loading precedence: %v", loadingRules.Precedence)
c.log.Debug("Kubeconfig file loading precedence: %v", loadingRules.Precedence)
// merge the kubeconfigs
cfg, err := loadingRules.Load()
@ -82,7 +82,7 @@ func (c *kubeconfigMerger) mergeConfigs(configPath string, fileHandler file.Hand
// Set the current context to the cluster we just created
cfg.CurrentContext = constellConfig.CurrentContext
c.log.Debugf("Set current context to %s", cfg.CurrentContext)
c.log.Debug("Set current context to %s", cfg.CurrentContext)
json, err := runtime.Encode(clientcodec.Codec, cfg)
if err != nil {
@ -97,7 +97,7 @@ func (c *kubeconfigMerger) mergeConfigs(configPath string, fileHandler file.Hand
if err := fileHandler.Write(clientcmd.RecommendedHomeFile, mergedKubeconfig, file.OptOverwrite); err != nil {
return fmt.Errorf("writing merged kubeconfig to file: %w", err)
}
c.log.Debugf("Merged kubeconfig into default config file: %s", clientcmd.RecommendedHomeFile)
c.log.Debug("Merged kubeconfig into default config file: %s", clientcmd.RecommendedHomeFile)
return nil
}

View file

@ -13,6 +13,7 @@ import (
"strings"
"testing"
"time"
"log/slog"
"github.com/edgelesssys/constellation/v2/bootstrapper/initproto"
"github.com/edgelesssys/constellation/v2/cli/internal/cmd/pathprefix"
@ -228,7 +229,7 @@ func TestInitialize(t *testing.T) {
rootFlags: rootFlags{force: true},
skipPhases: newPhases(skipInfrastructurePhase),
},
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
spinner: &nopSpinner{},
merger: &stubMerger{},
applier: &stubConstellApplier{
@ -368,8 +369,8 @@ func TestWriteOutput(t *testing.T) {
fileHandler: fileHandler,
spinner: &nopSpinner{},
merger: &stubMerger{},
log: logger.NewTest(t),
applier: constellation.NewApplier(logger.NewTest(t), &nopSpinner{}, constellation.ApplyContextCLI, nil),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
applier: constellation.NewApplier(slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)), &nopSpinner{}, constellation.ApplyContextCLI, nil),
}
err = i.writeInitOutput(stateFile, initOutput, false, &out, measurementSalt)
require.NoError(err)
@ -460,8 +461,8 @@ func TestGenerateMasterSecret(t *testing.T) {
var out bytes.Buffer
i := &applyCmd{
fileHandler: fileHandler,
log: logger.NewTest(t),
applier: constellation.NewApplier(logger.NewTest(t), &nopSpinner{}, constellation.ApplyContextCLI, nil),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
applier: constellation.NewApplier(slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)), &nopSpinner{}, constellation.ApplyContextCLI, nil),
}
secret, err := i.generateAndPersistMasterSecret(&out)

View file

@ -7,25 +7,25 @@ SPDX-License-Identifier: AGPL-3.0-only
package cmd
import (
"github.com/edgelesssys/constellation/v2/internal/logger"
"log/slog"
"os"
"github.com/spf13/cobra"
"go.uber.org/zap/zapcore"
)
type debugLog interface {
Debugf(format string, args ...any)
Sync()
Debug(format string, args ...any)
}
func newCLILogger(cmd *cobra.Command) (debugLog, error) {
logLvl := zapcore.InfoLevel
logLvl := slog.LevelInfo
debugLog, err := cmd.Flags().GetBool("debug")
if err != nil {
return nil, err
}
if debugLog {
logLvl = zapcore.DebugLevel
logLvl = slog.LevelDebug
}
return logger.New(logger.PlainLog, logLvl), nil
return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLvl})), nil
}

View file

@ -47,7 +47,6 @@ func runPatchMAA(cmd *cobra.Command, args []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
p := maa.NewAzurePolicyPatcher()
@ -57,7 +56,7 @@ func runPatchMAA(cmd *cobra.Command, args []string) error {
}
func (c *maaPatchCmd) patchMAA(cmd *cobra.Command, attestationURL string) error {
c.log.Debugf("Using attestation URL %s", attestationURL)
c.log.Debug("Using attestation URL %s", attestationURL)
if err := c.patcher.Patch(cmd.Context(), attestationURL); err != nil {
return fmt.Errorf("patching MAA attestation policy: %w", err)

View file

@ -8,6 +8,7 @@ package cmd
import (
"context"
"log/slog"
"testing"
"github.com/edgelesssys/constellation/v2/internal/logger"
@ -38,7 +39,7 @@ func TestMAAPatch(t *testing.T) {
t.Run(name, func(t *testing.T) {
require := require.New(t)
c := &maaPatchCmd{log: logger.NewTest(t), patcher: tc.patcher}
c := &maaPatchCmd{log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)), patcher: tc.patcher}
err := c.patchMAA(&cobra.Command{}, tc.attestationURL)
if tc.wantErr {
require.Error(err)

View file

@ -50,7 +50,6 @@ func runUp(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
m := &miniUpCmd{
log: log,
@ -152,7 +151,7 @@ func (m *miniUpCmd) prepareConfig(cmd *cobra.Command) (*config.Config, error) {
if err != nil {
return nil, fmt.Errorf("mini default config is invalid: %v", err)
}
m.log.Debugf("Prepared configuration")
m.log.Debug("Prepared configuration")
return config, m.fileHandler.WriteYAML(constants.ConfigFilename, config, file.OptOverwrite)
}

View file

@ -32,12 +32,12 @@ func (m *miniUpCmd) checkSystemRequirements(out io.Writer) error {
return fmt.Errorf("creation of a QEMU based Constellation is not supported for %s/%s, a linux/amd64 platform is required", runtime.GOOS, runtime.GOARCH)
}
m.log.Debugf("Checked arch and os")
m.log.Debug("Checked arch and os")
// check if /dev/kvm exists
if _, err := os.Stat("/dev/kvm"); err != nil {
return fmt.Errorf("unable to access KVM device: %w", err)
}
m.log.Debugf("Checked that /dev/kvm exists")
m.log.Debug("Checked that /dev/kvm exists")
// check CPU cores
if runtime.NumCPU() < 4 {
return fmt.Errorf("insufficient CPU cores: %d, at least 4 cores are required by MiniConstellation", runtime.NumCPU())
@ -45,7 +45,7 @@ func (m *miniUpCmd) checkSystemRequirements(out io.Writer) error {
if runtime.NumCPU() < 6 {
fmt.Fprintf(out, "WARNING: Only %d CPU cores available. This may cause performance issues.\n", runtime.NumCPU())
}
m.log.Debugf("Checked CPU cores - there are %d", runtime.NumCPU())
m.log.Debug("Checked CPU cores - there are %d", runtime.NumCPU())
// check memory
f, err := os.Open("/proc/meminfo")
@ -63,7 +63,7 @@ func (m *miniUpCmd) checkSystemRequirements(out io.Writer) error {
}
}
}
m.log.Debugf("Scanned for available memory")
m.log.Debug("Scanned for available memory")
memGB := memKB / 1024 / 1024
if memGB < 4 {
return fmt.Errorf("insufficient memory: %dGB, at least 4GB of memory are required by MiniConstellation", memGB)
@ -71,7 +71,7 @@ func (m *miniUpCmd) checkSystemRequirements(out io.Writer) error {
if memGB < 6 {
fmt.Fprintln(out, "WARNING: Less than 6GB of memory available. This may cause performance issues.")
}
m.log.Debugf("Checked available memory, you have %dGB available", memGB)
m.log.Debug("Checked available memory, you have %dGB available", memGB)
var stat unix.Statfs_t
if err := unix.Statfs(".", &stat); err != nil {
@ -81,7 +81,7 @@ func (m *miniUpCmd) checkSystemRequirements(out io.Writer) error {
if freeSpaceGB < 20 {
return fmt.Errorf("insufficient disk space: %dGB, at least 20GB of disk space are required by MiniConstellation", freeSpaceGB)
}
m.log.Debugf("Checked for free space available, you have %dGB available", freeSpaceGB)
m.log.Debug("Checked for free space available, you have %dGB available", freeSpaceGB)
return nil
}

View file

@ -76,7 +76,6 @@ func runRecover(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
fileHandler := file.NewHandler(afero.NewOsFs())
newDialer := func(validator atls.Validator) *dialer.Dialer {
return dialer.New(nil, validator, &net.Dialer{})
@ -85,7 +84,7 @@ func runRecover(cmd *cobra.Command, _ []string) error {
if err := r.flags.parse(cmd.Flags()); err != nil {
return err
}
r.log.Debugf("Using flags: %+v", r.flags)
r.log.Debug("Using flags: %+v", r.flags)
return r.recover(cmd, fileHandler, 5*time.Second, &recoverDoer{log: r.log}, newDialer)
}
@ -94,12 +93,12 @@ func (r *recoverCmd) recover(
doer recoverDoerInterface, newDialer func(validator atls.Validator) *dialer.Dialer,
) error {
var masterSecret uri.MasterSecret
r.log.Debugf("Loading master secret file from %s", r.flags.pathPrefixer.PrefixPrintablePath(constants.MasterSecretFilename))
r.log.Debug("Loading master secret file from %s", r.flags.pathPrefixer.PrefixPrintablePath(constants.MasterSecretFilename))
if err := fileHandler.ReadJSON(constants.MasterSecretFilename, &masterSecret); err != nil {
return err
}
r.log.Debugf("Loading configuration file from %q", r.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
r.log.Debug("Loading configuration file from %q", r.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
conf, err := config.New(fileHandler, constants.ConfigFilename, r.configFetcher, r.flags.force)
var configValidationErr *config.ValidationError
if errors.As(err, &configValidationErr) {
@ -130,16 +129,16 @@ func (r *recoverCmd) recover(
conf.UpdateMAAURL(stateFile.Infrastructure.Azure.AttestationURL)
}
r.log.Debugf("Creating aTLS Validator for %s", conf.GetAttestationConfig().GetVariant())
r.log.Debug("Creating aTLS Validator for %s", conf.GetAttestationConfig().GetVariant())
validator, err := choose.Validator(conf.GetAttestationConfig(), warnLogger{cmd: cmd, log: r.log})
if err != nil {
return fmt.Errorf("creating new validator: %w", err)
}
r.log.Debugf("Created a new validator")
r.log.Debug("Created a new validator")
doer.setDialer(newDialer(validator), endpoint)
r.log.Debugf("Set dialer for endpoint %s", endpoint)
r.log.Debug("Set dialer for endpoint %s", endpoint)
doer.setURIs(masterSecret.EncodeToURI(), uri.NoStoreURI)
r.log.Debugf("Set secrets")
r.log.Debug("Set secrets")
if err := r.recoverCall(cmd.Context(), cmd.OutOrStdout(), interval, doer); err != nil {
if grpcRetry.ServiceIsUnavailable(err) {
return nil
@ -167,12 +166,12 @@ func (r *recoverCmd) recoverCall(ctx context.Context, out io.Writer, interval ti
})
}
r.log.Debugf("Encountered error (retriable: %t): %s", retry, err)
r.log.Debug("Encountered error (retriable: %t): %s", retry, err)
return retry
}
retrier := retry.NewIntervalRetrier(doer, interval, retryOnceOnFailure)
r.log.Debugf("Created new interval retrier")
r.log.Debug("Created new interval retrier")
err = retrier.Do(ctx)
if err != nil {
break
@ -180,7 +179,7 @@ func (r *recoverCmd) recoverCall(ctx context.Context, out io.Writer, interval ti
fmt.Fprintln(out, "Pushed recovery key.")
ctr++
}
r.log.Debugf("Retry counter is %d", ctr)
r.log.Debug("Retry counter is %d", ctr)
if ctr > 0 {
fmt.Fprintf(out, "Recovered %d control-plane nodes.\n", ctr)
} else if grpcRetry.ServiceIsUnavailable(err) {
@ -222,11 +221,11 @@ func (d *recoverDoer) Do(ctx context.Context) (retErr error) {
if err != nil {
return fmt.Errorf("dialing recovery server: %w", err)
}
d.log.Debugf("Dialed recovery server")
d.log.Debug("Dialed recovery server")
defer conn.Close()
protoClient := recoverproto.NewAPIClient(conn)
d.log.Debugf("Created protoClient")
d.log.Debug("Created protoClient")
req := &recoverproto.RecoverMessage{
KmsUri: d.kmsURI,
@ -238,7 +237,7 @@ func (d *recoverDoer) Do(ctx context.Context) (retErr error) {
return fmt.Errorf("calling recover: %w", err)
}
d.log.Debugf("Received confirmation")
d.log.Debug("Received confirmation")
return nil
}

View file

@ -10,6 +10,7 @@ import (
"bytes"
"context"
"errors"
"log/slog"
"net"
"strconv"
"testing"
@ -164,7 +165,7 @@ func TestRecover(t *testing.T) {
newDialer := func(atls.Validator) *dialer.Dialer { return nil }
r := &recoverCmd{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
configFetcher: stubAttestationFetcher{},
flags: recoverFlags{
rootFlags: rootFlags{force: true},
@ -218,7 +219,7 @@ func TestDoRecovery(t *testing.T) {
go recoverServer.Serve(listener)
defer recoverServer.GracefulStop()
r := &recoverCmd{log: logger.NewTest(t)}
r := &recoverCmd{log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil))}
recoverDoer := &recoverDoer{
dialer: dialer.New(nil, nil, netDialer),
endpoint: addr,

View file

@ -43,7 +43,6 @@ func runStatus(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
fileHandler := file.NewHandler(afero.NewOsFs())

View file

@ -9,6 +9,7 @@ package cmd
import (
"bytes"
"errors"
"log/slog"
"testing"
"github.com/edgelesssys/constellation/v2/internal/constants"
@ -139,7 +140,7 @@ func TestTerminate(t *testing.T) {
fileHandler := file.NewHandler(tc.setupFs(require, tc.stateFile))
tCmd := &terminateCmd{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
fileHandler: fileHandler,
flags: terminateFlags{
yes: tc.yesFlag,

View file

@ -9,6 +9,7 @@ package cmd
import (
"bytes"
"context"
"log/slog"
"testing"
"github.com/edgelesssys/constellation/v2/cli/internal/cloudcmd"
@ -251,7 +252,7 @@ func TestUpgradeApply(t *testing.T) {
upgrader := &applyCmd{
fileHandler: fh,
flags: tc.flags,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
spinner: &nopSpinner{},
merger: &stubMerger{},
newInfraApplier: func(ctx context.Context) (cloudApplier, func(), error) {

View file

@ -92,7 +92,6 @@ func runUpgradeCheck(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
var flags upgradeCheckFlags
if err := flags.parse(cmd.Flags()); err != nil {
@ -188,7 +187,7 @@ func (u *upgradeCheckCmd) upgradeCheck(cmd *cobra.Command, fetcher attestationco
// get current image version of the cluster
csp := conf.GetProvider()
attestationVariant := conf.GetAttestationConfig().GetVariant()
u.log.Debugf("Using provider %s with attestation variant %s", csp.String(), attestationVariant.String())
u.log.Debug("Using provider %s with attestation variant %s", csp.String(), attestationVariant.String())
current, err := u.collect.currentVersions(cmd.Context())
if err != nil {
@ -199,18 +198,18 @@ func (u *upgradeCheckCmd) upgradeCheck(cmd *cobra.Command, fetcher attestationco
if err != nil {
return err
}
u.log.Debugf("Current cli version: %s", current.cli)
u.log.Debugf("Supported cli version(s): %s", supported.cli)
u.log.Debugf("Current service version: %s", current.service)
u.log.Debugf("Supported service version: %s", supported.service)
u.log.Debugf("Current k8s version: %s", current.k8s)
u.log.Debugf("Supported k8s version(s): %s", supported.k8s)
u.log.Debug("Current cli version: %s", current.cli)
u.log.Debug("Supported cli version(s): %s", supported.cli)
u.log.Debug("Current service version: %s", current.service)
u.log.Debug("Supported service version: %s", supported.service)
u.log.Debug("Current k8s version: %s", current.k8s)
u.log.Debug("Supported k8s version(s): %s", supported.k8s)
// Filter versions to only include upgrades
newServices := supported.service
if err := supported.service.IsUpgradeTo(current.service); err != nil {
newServices = consemver.Semver{}
u.log.Debugf("No valid service upgrades are available from %q to %q. The minor version can only drift by 1.\n", current.service.String(), supported.service.String())
u.log.Debug("No valid service upgrades are available from %q to %q. The minor version can only drift by 1.\n", current.service.String(), supported.service.String())
}
newKubernetes := filterK8sUpgrades(current.k8s, supported.k8s)
@ -222,13 +221,13 @@ func (u *upgradeCheckCmd) upgradeCheck(cmd *cobra.Command, fetcher attestationco
return err
}
u.log.Debugf("Planning Terraform migrations")
u.log.Debug("Planning Terraform migrations")
// Add manual migrations here if required
//
// var manualMigrations []terraform.StateMigration
// for _, migration := range manualMigrations {
// u.log.Debugf("Adding manual Terraform migration: %s", migration.DisplayName)
// u.log.Debug("Adding manual Terraform migration: %s", migration.DisplayName)
// u.terraformChecker.AddManualStateMigration(migration)
// }
cmd.Println("The following Terraform migrations are available with this CLI:")
@ -344,7 +343,7 @@ func (v *versionCollector) newMeasurements(ctx context.Context, csp cloudprovide
// get expected measurements for each image
upgrades := make(map[string]measurements.M)
for _, version := range versions {
v.log.Debugf("Fetching measurements for image: %s", version)
v.log.Debug("Fetching measurements for image: %s", version)
shortPath := version.ShortPath()
publicKey, err := keyselect.CosignPublicKeyForVersion(version)
@ -365,7 +364,7 @@ func (v *versionCollector) newMeasurements(ctx context.Context, csp cloudprovide
}
upgrades[shortPath] = measurements
}
v.log.Debugf("Compatible image measurements are %v", upgrades)
v.log.Debug("Compatible image measurements are %v", upgrades)
return upgrades, nil
}
@ -453,9 +452,9 @@ func (v *versionCollector) newImages(ctx context.Context, currentImageVersion co
if err != nil {
return nil, fmt.Errorf("calculating next image minor version: %w", err)
}
v.log.Debugf("Current image minor version is %s", currentImageMinorVer)
v.log.Debugf("Current CLI minor version is %s", currentCLIMinorVer)
v.log.Debugf("Next image minor version is %s", nextImageMinorVer)
v.log.Debug("Current image minor version is %s", currentImageMinorVer)
v.log.Debug("Current CLI minor version is %s", currentCLIMinorVer)
v.log.Debug("Next image minor version is %s", nextImageMinorVer)
allowedMinorVersions := []string{currentImageMinorVer, nextImageMinorVer}
switch cliImageCompare := semver.Compare(currentCLIMinorVer, currentImageMinorVer); {
@ -471,7 +470,7 @@ func (v *versionCollector) newImages(ctx context.Context, currentImageVersion co
case cliImageCompare > 0:
allowedMinorVersions = []string{currentImageMinorVer, nextImageMinorVer}
}
v.log.Debugf("Allowed minor versions are %#v", allowedMinorVersions)
v.log.Debug("Allowed minor versions are %#v", allowedMinorVersions)
newerImages, err := v.newerVersions(ctx, allowedMinorVersions)
if err != nil {
@ -494,7 +493,7 @@ func (v *versionCollector) newerVersions(ctx context.Context, allowedVersions []
patchList, err := v.verListFetcher.FetchVersionList(ctx, patchList)
var notFound *fetcher.NotFoundError
if errors.As(err, &notFound) {
v.log.Debugf("Skipping version: %s", err)
v.log.Debug("Skipping version: %s", err)
continue
}
if err != nil {
@ -502,7 +501,7 @@ func (v *versionCollector) newerVersions(ctx context.Context, allowedVersions []
}
updateCandidates = append(updateCandidates, patchList.StructuredVersions()...)
}
v.log.Debugf("Update candidates are %v", updateCandidates)
v.log.Debug("Update candidates are %v", updateCandidates)
return updateCandidates, nil
}
@ -604,7 +603,7 @@ func getCompatibleImageMeasurements(ctx context.Context, writer io.Writer, clien
}
var fetchedMeasurements measurements.M
log.Debugf("Fetching for measurement url: %s", measurementsURL)
log.Debug("Fetching for measurement url: %s", measurementsURL)
hash, err := fetchedMeasurements.FetchAndVerify(
ctx, client, cosign,
@ -658,7 +657,7 @@ func (v *versionCollector) newCLIVersions(ctx context.Context) ([]consemver.Semv
return nil, fmt.Errorf("parsing version %s: %w", version, err)
}
if err := target.IsUpgradeTo(v.cliVersion); err != nil {
v.log.Debugf("Skipping incompatible minor version %q: %s", version, err)
v.log.Debug("Skipping incompatible minor version %q: %s", version, err)
continue
}
list := versionsapi.List{
@ -692,7 +691,7 @@ func (v *versionCollector) filterCompatibleCLIVersions(ctx context.Context, cliP
var compatibleVersions []consemver.Semver
for _, version := range cliPatchVersions {
if err := version.IsUpgradeTo(v.cliVersion); err != nil {
v.log.Debugf("Skipping incompatible patch version %q: %s", version, err)
v.log.Debug("Skipping incompatible patch version %q: %s", version, err)
continue
}
req := versionsapi.CLIInfo{

View file

@ -11,6 +11,7 @@ import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"strings"
"testing"
@ -139,7 +140,7 @@ func TestGetCompatibleImageMeasurements(t *testing.T) {
}
})
upgrades, err := getCompatibleImageMeasurements(context.Background(), &bytes.Buffer{}, client, &stubCosignVerifier{}, singleUUIDVerifier(), csp, attestationVariant, versionZero, logger.NewTest(t))
upgrades, err := getCompatibleImageMeasurements(context.Background(), &bytes.Buffer{}, client, &stubCosignVerifier{}, singleUUIDVerifier(), csp, attestationVariant, versionZero, slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)))
assert.NoError(err)
for _, measurement := range upgrades {
@ -215,7 +216,7 @@ func TestUpgradeCheck(t *testing.T) {
collect: &tc.collector,
terraformChecker: tc.checker,
fileHandler: fileHandler,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
}
cmd := newUpgradeCheckCmd()

View file

@ -100,7 +100,6 @@ func runVerify(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("creating logger: %w", err)
}
defer log.Sync()
fileHandler := file.NewHandler(afero.NewOsFs())
verifyClient := &constellationVerifier{
@ -129,7 +128,7 @@ func runVerify(cmd *cobra.Command, _ []string) error {
if err := v.flags.parse(cmd.Flags()); err != nil {
return err
}
v.log.Debugf("Using flags: %+v", v.flags)
v.log.Debug("Using flags: %+v", v.flags)
fetcher := attestationconfigapi.NewFetcher()
return v.verify(cmd, verifyClient, formatterFactory, fetcher)
}
@ -137,7 +136,7 @@ func runVerify(cmd *cobra.Command, _ []string) error {
type formatterFactory func(output string, attestation variant.Variant, log debugLog) (attestationDocFormatter, error)
func (c *verifyCmd) verify(cmd *cobra.Command, verifyClient verifyClient, factory formatterFactory, configFetcher attestationconfigapi.Fetcher) error {
c.log.Debugf("Loading configuration file from %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
c.log.Debug("Loading configuration file from %q", c.flags.pathPrefixer.PrefixPrintablePath(constants.ConfigFilename))
conf, err := config.New(c.fileHandler, constants.ConfigFilename, configFetcher, c.flags.force)
var configValidationErr *config.ValidationError
if errors.As(err, &configValidationErr) {
@ -170,13 +169,13 @@ func (c *verifyCmd) verify(cmd *cobra.Command, verifyClient verifyClient, factor
}
conf.UpdateMAAURL(maaURL)
c.log.Debugf("Updating expected PCRs")
c.log.Debug("Updating expected PCRs")
attConfig := conf.GetAttestationConfig()
if err := updateInitMeasurements(attConfig, ownerID, clusterID); err != nil {
return fmt.Errorf("updating expected PCRs: %w", err)
}
c.log.Debugf("Creating aTLS Validator for %s", conf.GetAttestationConfig().GetVariant())
c.log.Debug("Creating aTLS Validator for %s", conf.GetAttestationConfig().GetVariant())
validator, err := choose.Validator(attConfig, warnLogger{cmd: cmd, log: c.log})
if err != nil {
return fmt.Errorf("creating aTLS validator: %w", err)
@ -186,7 +185,7 @@ func (c *verifyCmd) verify(cmd *cobra.Command, verifyClient verifyClient, factor
if err != nil {
return fmt.Errorf("generating random nonce: %w", err)
}
c.log.Debugf("Generated random nonce: %x", nonce)
c.log.Debug("Generated random nonce: %x", nonce)
rawAttestationDoc, err := verifyClient.Verify(
cmd.Context(),
@ -385,7 +384,7 @@ type constellationVerifier struct {
func (v *constellationVerifier) Verify(
ctx context.Context, endpoint string, req *verifyproto.GetAttestationRequest, validator atls.Validator,
) (string, error) {
v.log.Debugf("Dialing endpoint: %q", endpoint)
v.log.Debug("Dialing endpoint: %q", endpoint)
conn, err := v.dialer.DialInsecure(ctx, endpoint)
if err != nil {
return "", fmt.Errorf("dialing init server: %w", err)
@ -394,13 +393,13 @@ func (v *constellationVerifier) Verify(
client := verifyproto.NewAPIClient(conn)
v.log.Debugf("Sending attestation request")
v.log.Debug("Sending attestation request")
resp, err := client.GetAttestation(ctx, req)
if err != nil {
return "", fmt.Errorf("getting attestation: %w", err)
}
v.log.Debugf("Verifying attestation")
v.log.Debug("Verifying attestation")
signedData, err := validator.Validate(ctx, resp.Attestation, req.Nonce)
if err != nil {
return "", fmt.Errorf("validating attestation: %w", err)

View file

@ -18,6 +18,7 @@ import (
"strconv"
"strings"
"testing"
"log/slog"
"github.com/edgelesssys/constellation/v2/internal/atls"
"github.com/edgelesssys/constellation/v2/internal/attestation/measurements"
@ -210,7 +211,7 @@ func TestVerify(t *testing.T) {
v := &verifyCmd{
fileHandler: fileHandler,
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
flags: verifyFlags{
clusterID: tc.clusterIDFlag,
endpoint: tc.nodeEndpointFlag,
@ -242,7 +243,7 @@ func (f *stubAttDocFormatter) format(_ context.Context, _ string, _ bool, _ conf
func TestFormat(t *testing.T) {
formatter := func() *defaultAttestationDocFormatter {
return &defaultAttestationDocFormatter{
log: logger.NewTest(t),
log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil)),
}
}
@ -333,7 +334,7 @@ func TestVerifyClient(t *testing.T) {
go verifyServer.Serve(listener)
defer verifyServer.GracefulStop()
verifier := &constellationVerifier{dialer: dialer, log: logger.NewTest(t)}
verifier := &constellationVerifier{dialer: dialer, log: slog.New(slog.NewTextHandler(logger.TestWriter{T: t}, nil))}
request := &verifyproto.GetAttestationRequest{
Nonce: tc.nonce,
}