|
| 1 | +package create |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/goccy/go-yaml" |
| 9 | + "github.com/spf13/cobra" |
| 10 | + "github.com/stackitcloud/stackit-cli/internal/cmd/params" |
| 11 | + "github.com/stackitcloud/stackit-cli/internal/pkg/args" |
| 12 | + cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors" |
| 13 | + "github.com/stackitcloud/stackit-cli/internal/pkg/services/kms/client" |
| 14 | + |
| 15 | + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" |
| 16 | + "github.com/stackitcloud/stackit-cli/internal/pkg/flags" |
| 17 | + "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags" |
| 18 | + "github.com/stackitcloud/stackit-cli/internal/pkg/print" |
| 19 | + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" |
| 20 | + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" |
| 21 | + "github.com/stackitcloud/stackit-sdk-go/services/kms" |
| 22 | +) |
| 23 | + |
| 24 | +const ( |
| 25 | + keyRingIdFlag = "key-ring" |
| 26 | + |
| 27 | + algorithmFlag = "algorithm" |
| 28 | + backendFlag = "backend" |
| 29 | + descriptionFlag = "description" |
| 30 | + displayNameFlag = "name" |
| 31 | + importOnlyFlag = "import-only" |
| 32 | + purposeFlag = "purpose" |
| 33 | +) |
| 34 | + |
| 35 | +type inputModel struct { |
| 36 | + *globalflags.GlobalFlagModel |
| 37 | + KeyRingId string |
| 38 | + |
| 39 | + Algorithm *string |
| 40 | + Backend string // Keep "backend" as a variable, but set the default to "software" (see UI) |
| 41 | + Description *string |
| 42 | + Name *string |
| 43 | + ImportOnly *bool // Default false |
| 44 | + Purpose *string |
| 45 | +} |
| 46 | + |
| 47 | +func NewCmd(params *params.CmdParams) *cobra.Command { |
| 48 | + cmd := &cobra.Command{ |
| 49 | + Use: "create", |
| 50 | + Short: "Creates a KMS Key", |
| 51 | + Long: "Creates a KMS Key.", |
| 52 | + Args: args.NoArgs, |
| 53 | + Example: examples.Build( |
| 54 | + examples.NewExample( |
| 55 | + `Create a Symmetric KMS Key`, |
| 56 | + `$ stakit beta kms key create --key-ring "my-keyring-id" --algorithm "rsa_2048_oaep_sha256" --name "my-key-name" --purpose "symmetric_encrypt_decrypt"`), |
| 57 | + examples.NewExample( |
| 58 | + `Create a Message Authentication KMS Key`, |
| 59 | + `$ stakit beta kms key create --key-ring "my-keyring-id" --algorithm "hmac_sha512" --name "my-key-name" --purpose "message_authentication_code"`), |
| 60 | + ), |
| 61 | + RunE: func(cmd *cobra.Command, _ []string) error { |
| 62 | + ctx := context.Background() |
| 63 | + model, err := parseInput(params.Printer, cmd) |
| 64 | + if err != nil { |
| 65 | + return err |
| 66 | + } |
| 67 | + |
| 68 | + // Configure API client |
| 69 | + apiClient, err := client.ConfigureClient(params.Printer, params.CliVersion) |
| 70 | + if err != nil { |
| 71 | + return err |
| 72 | + } |
| 73 | + |
| 74 | + projectLabel, err := projectname.GetProjectName(ctx, params.Printer, params.CliVersion, cmd) |
| 75 | + if err != nil { |
| 76 | + params.Printer.Debug(print.ErrorLevel, "get project name: %v", err) |
| 77 | + projectLabel = model.ProjectId |
| 78 | + } |
| 79 | + |
| 80 | + if !model.AssumeYes { |
| 81 | + prompt := fmt.Sprintf("Are you sure you want to create a KMS Key for project %q?", projectLabel) |
| 82 | + err = params.Printer.PromptForConfirmation(prompt) |
| 83 | + if err != nil { |
| 84 | + return err |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + // Call API |
| 89 | + req, _ := buildRequest(ctx, model, apiClient) |
| 90 | + if err != nil { |
| 91 | + return err |
| 92 | + } |
| 93 | + |
| 94 | + key, err := req.Execute() |
| 95 | + if err != nil { |
| 96 | + return fmt.Errorf("create KMS Key: %w", err) |
| 97 | + } |
| 98 | + |
| 99 | + // No wait exists for the key creation |
| 100 | + return outputResult(params.Printer, model.OutputFormat, projectLabel, key) |
| 101 | + }, |
| 102 | + } |
| 103 | + configureFlags(cmd) |
| 104 | + return cmd |
| 105 | +} |
| 106 | + |
| 107 | +func parseInput(p *print.Printer, cmd *cobra.Command) (*inputModel, error) { |
| 108 | + globalFlags := globalflags.Parse(p, cmd) |
| 109 | + if globalFlags.ProjectId == "" { |
| 110 | + return nil, &cliErr.ProjectIdError{} |
| 111 | + } |
| 112 | + |
| 113 | + // What checks could this need? |
| 114 | + // I would rather let the creation fail instead of checking all possible algorithms |
| 115 | + model := inputModel{ |
| 116 | + GlobalFlagModel: globalFlags, |
| 117 | + KeyRingId: flags.FlagToStringValue(p, cmd, keyRingIdFlag), |
| 118 | + Algorithm: flags.FlagToStringPointer(p, cmd, algorithmFlag), |
| 119 | + Backend: flags.FlagWithDefaultToStringValue(p, cmd, backendFlag), |
| 120 | + Name: flags.FlagToStringPointer(p, cmd, displayNameFlag), |
| 121 | + Description: flags.FlagToStringPointer(p, cmd, descriptionFlag), |
| 122 | + ImportOnly: flags.FlagToBoolPointer(p, cmd, importOnlyFlag), |
| 123 | + Purpose: flags.FlagToStringPointer(p, cmd, purposeFlag), |
| 124 | + } |
| 125 | + |
| 126 | + if p.IsVerbosityDebug() { |
| 127 | + modelStr, err := print.BuildDebugStrFromInputModel(model) |
| 128 | + if err != nil { |
| 129 | + p.Debug(print.ErrorLevel, "convert model to string for debugging: %v", err) |
| 130 | + } else { |
| 131 | + p.Debug(print.ErrorLevel, "parsed input values: %s", modelStr) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + return &model, nil |
| 136 | +} |
| 137 | + |
| 138 | +type kmsKeyClient interface { |
| 139 | + CreateKey(ctx context.Context, projectId string, regionId string, keyRingId string) kms.ApiCreateKeyRequest |
| 140 | +} |
| 141 | + |
| 142 | +func buildRequest(ctx context.Context, model *inputModel, apiClient kmsKeyClient) (kms.ApiCreateKeyRequest, error) { |
| 143 | + req := apiClient.CreateKey(ctx, model.ProjectId, model.Region, model.KeyRingId) |
| 144 | + |
| 145 | + // Question: Should there be additional checks here? |
| 146 | + req = req.CreateKeyPayload(kms.CreateKeyPayload{ |
| 147 | + DisplayName: model.Name, |
| 148 | + Description: model.Description, |
| 149 | + Algorithm: kms.CreateKeyPayloadGetAlgorithmAttributeType(model.Algorithm), |
| 150 | + Backend: kms.CreateKeyPayloadGetBackendAttributeType(&model.Backend), |
| 151 | + Purpose: kms.CreateKeyPayloadGetPurposeAttributeType(model.Purpose), |
| 152 | + ImportOnly: model.ImportOnly, |
| 153 | + }) |
| 154 | + return req, nil |
| 155 | +} |
| 156 | + |
| 157 | +func outputResult(p *print.Printer, outputFormat, projectLabel string, resp *kms.Key) error { |
| 158 | + if resp == nil { |
| 159 | + return fmt.Errorf("response is nil") |
| 160 | + } |
| 161 | + |
| 162 | + switch outputFormat { |
| 163 | + case print.JSONOutputFormat: |
| 164 | + details, err := json.MarshalIndent(resp, "", " ") |
| 165 | + if err != nil { |
| 166 | + return fmt.Errorf("marshal KMS Key: %w", err) |
| 167 | + } |
| 168 | + p.Outputln(string(details)) |
| 169 | + return nil |
| 170 | + |
| 171 | + case print.YAMLOutputFormat: |
| 172 | + details, err := yaml.MarshalWithOptions(resp, yaml.IndentSequence(true), yaml.UseJSONMarshaler()) |
| 173 | + if err != nil { |
| 174 | + return fmt.Errorf("marshal KMS Key: %w", err) |
| 175 | + } |
| 176 | + p.Outputln(string(details)) |
| 177 | + return nil |
| 178 | + |
| 179 | + default: |
| 180 | + p.Outputf("Created Key for project %q. Key ID: %s\n", projectLabel, utils.PtrString(resp.Id)) |
| 181 | + return nil |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +func configureFlags(cmd *cobra.Command) { |
| 186 | + cmd.Flags().Var(flags.UUIDFlag(), keyRingIdFlag, "ID of the KMS Key Ring") |
| 187 | + cmd.Flags().String(algorithmFlag, "", "En-/Decryption / signing algorithm") |
| 188 | + cmd.Flags().String(backendFlag, "software", "The backend that is responsible for maintaining this key") |
| 189 | + cmd.Flags().String(displayNameFlag, "", "The display name to distinguish multiple keys") |
| 190 | + cmd.Flags().String(descriptionFlag, "", "Optinal description of the Key") |
| 191 | + cmd.Flags().Bool(importOnlyFlag, false, "States whether versions can be created or only imported") |
| 192 | + cmd.Flags().String(purposeFlag, "", "Purpose of the Key. Enum: 'symmetric_encrypt_decrypt', 'asymmetric_encrypt_decrypt', 'message_authentication_code', 'asymmetric_sign_verify' ") |
| 193 | + |
| 194 | + err := flags.MarkFlagsRequired(cmd, keyRingIdFlag, algorithmFlag, purposeFlag, displayNameFlag) |
| 195 | + cobra.CheckErr(err) |
| 196 | +} |
0 commit comments