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

Vault 28310 hvs integrations poc #125

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
6 changes: 6 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: "2024-06-24"
type: "mongodb"
name: "climongo"
details:
private_key: "{mongodb_private_key}"
public_key: "{mongodb_public_key}"
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/hashicorp/go-multierror v1.1.1
github.com/hashicorp/go-version v1.6.0
github.com/hashicorp/hcl/v2 v2.19.1
github.com/hashicorp/hcp-sdk-go v0.96.0
github.com/hashicorp/hcp-sdk-go v0.99.0
github.com/lithammer/dedent v1.1.0
github.com/manifoldco/promptui v0.9.0
github.com/mitchellh/cli v1.1.5
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ github.com/hashicorp/hcl/v2 v2.19.1 h1://i05Jqznmb2EXqa39Nsvyan2o5XyMowW5fnCKW5R
github.com/hashicorp/hcl/v2 v2.19.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE=
github.com/hashicorp/hcp-sdk-go v0.96.0 h1:7oI993ZN7HG7TiFg00r2Po1N5mZZryOtSX0Ec/8cCQ4=
github.com/hashicorp/hcp-sdk-go v0.96.0/go.mod h1:vQ4fzdL1AmhIAbCw+4zmFe5Hbpajj3NvRWkJoVuxmAk=
github.com/hashicorp/hcp-sdk-go v0.99.0 h1:qW915thxFMIyHFLFyHuTqN1AJqZYsu+YL+IVRrpP2Ck=
github.com/hashicorp/hcp-sdk-go v0.99.0/go.mod h1:vQ4fzdL1AmhIAbCw+4zmFe5Hbpajj3NvRWkJoVuxmAk=
github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
Expand Down
10 changes: 4 additions & 6 deletions internal/commands/projects/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,10 @@ func addToBillingAccount(opts *CreateOpts, projectID string) error {
updateReq := billing_account_service.NewBillingAccountServiceUpdateParams()
updateReq.OrganizationID = ba.OrganizationID
updateReq.ID = ba.ID
updateReq.Body = &billingModels.Billing20201105UpdateBillingAccountRequest{
OrganizationID: opts.Profile.OrganizationID,
ID: ba.ID,
ProjectIds: ba.ProjectIds,
Name: ba.Name,
Country: ba.Country,
updateReq.Body = &billingModels.BillingAccountServiceUpdateBody{
ProjectIds: ba.ProjectIds,
Name: ba.Name,
Country: ba.Country,
}

updateReq.Body.ProjectIds = append(updateReq.Body.ProjectIds, projectID)
Expand Down
119 changes: 119 additions & 0 deletions internal/commands/vaultsecrets/integrations/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package integrations

import (
"context"
"fmt"
"os"

preview_secret_service "github.com/hashicorp/hcp-sdk-go/clients/cloud-vault-secrets/preview/2023-11-28/client/secret_service"
"github.com/hashicorp/hcp-sdk-go/clients/cloud-vault-secrets/stable/2023-06-13/client/secret_service"
"github.com/hashicorp/hcp/internal/pkg/cmd"
"github.com/hashicorp/hcp/internal/pkg/flagvalue"
"github.com/hashicorp/hcp/internal/pkg/format"
"github.com/hashicorp/hcp/internal/pkg/heredoc"
"github.com/hashicorp/hcp/internal/pkg/iostreams"
"github.com/hashicorp/hcp/internal/pkg/profile"
"github.com/posener/complete"
"gopkg.in/yaml.v3"
)

type CreateOpts struct {
Ctx context.Context
Profile *profile.Profile
Output *format.Outputter
IO iostreams.IOStreams

ConfigFilePath string
Client secret_service.ClientService
PreviewClient preview_secret_service.ClientService
}

func NewCmdCreate(ctx *cmd.Context, runF func(*CreateOpts) error) *cmd.Command {
opts := &CreateOpts{
Ctx: ctx.ShutdownCtx,
Profile: ctx.Profile,
Output: ctx.Output,
IO: ctx.IO,
Client: secret_service.New(ctx.HCP, nil),
PreviewClient: preview_secret_service.New(ctx.HCP, nil),
}

cmd := &cmd.Command{
Name: "create",
ShortHelp: "help",
LongHelp: heredoc.New(ctx.IO).Must(`help`),
Flags: cmd.Flags{
Local: []*cmd.Flag{
{
Name: "config-file",
DisplayValue: "PATH",
Description: "The path to a file containing an integration config.",
Value: flagvalue.Simple("", &opts.ConfigFilePath),
Required: true,
Autocomplete: complete.PredictFiles("*.json"),
},
},
},
RunF: func(c *cmd.Command, args []string) error {

if runF != nil {
return runF(opts)
}

return createIntegration(opts)
},
PersistentPreRun: func(c *cmd.Command, args []string) error {
return cmd.RequireOrgAndProject(ctx)
},
}

return cmd
}

type IntegrationConfig struct {
Version string
Type string
Name string
Details map[string]interface{}
}

func createIntegration(opts *CreateOpts) error {
// Open the file
f, err := os.ReadFile(opts.ConfigFilePath)
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}

var i IntegrationConfig
err = yaml.Unmarshal(f, &i)
if err != nil {
return fmt.Errorf("failed to unmarshal policy file: %w", err)
}

if i.Type == "mongodb" {
privkey := i.Details["private_key"].(string)
pubKey := i.Details["public_key"].(string)
body := preview_secret_service.CreateMongoDBAtlasIntegrationBody{
IntegrationName: i.Name,
MongodbAPIPrivateKey: privkey,
MongodbAPIPublicKey: pubKey,
}
resp, err := opts.PreviewClient.CreateMongoDBAtlasIntegration(&preview_secret_service.CreateMongoDBAtlasIntegrationParams{
Context: opts.Ctx,
ProjectID: opts.Profile.ProjectID,
OrganizationID: opts.Profile.OrganizationID,
Body: body,
}, nil)

if err != nil {
return fmt.Errorf("failed to create integration: %w", err)
}

fmt.Fprintln(opts.IO.Err())
fmt.Fprintf(opts.IO.Err(), "%s Successfully created integration with name %q\n", opts.IO.ColorScheme().SuccessIcon(), resp.Payload.Integration.IntegrationName)
} else {
fmt.Errorf("invalid type given")
}

return nil
}
26 changes: 26 additions & 0 deletions internal/commands/vaultsecrets/integrations/integrations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package integrations

import (
"github.com/hashicorp/hcp/internal/pkg/cmd"
"github.com/hashicorp/hcp/internal/pkg/heredoc"
)

func NewCmdIntegrations(ctx *cmd.Context) *cmd.Command {
cmd := &cmd.Command{
Name: "integrations",
ShortHelp: "Manage Vault Secrets integrations.",
LongHelp: heredoc.New(ctx.IO).Must(`
The {{ template "mdCodeOrBold" "hcp vault-secrets integrations" }} command group lets you
manage Vault Secrets integrations.
`),
PersistentPreRun: func(c *cmd.Command, args []string) error {
return cmd.RequireOrgAndProject(ctx)
},
}

cmd.AddChild(NewCmdCreate(ctx, nil))
return cmd
}
146 changes: 146 additions & 0 deletions internal/commands/vaultsecrets/secrets/create-rotating.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package secrets

import (
"context"
"fmt"
"os"

preview_secret_service "github.com/hashicorp/hcp-sdk-go/clients/cloud-vault-secrets/preview/2023-11-28/client/secret_service"
"github.com/hashicorp/hcp-sdk-go/clients/cloud-vault-secrets/preview/2023-11-28/models"
"github.com/hashicorp/hcp-sdk-go/clients/cloud-vault-secrets/stable/2023-06-13/client/secret_service"
"github.com/hashicorp/hcp/internal/commands/vaultsecrets/secrets/appname"
"github.com/hashicorp/hcp/internal/pkg/cmd"
"github.com/hashicorp/hcp/internal/pkg/flagvalue"
"github.com/hashicorp/hcp/internal/pkg/format"
"github.com/hashicorp/hcp/internal/pkg/heredoc"
"github.com/hashicorp/hcp/internal/pkg/iostreams"
"github.com/hashicorp/hcp/internal/pkg/profile"
"github.com/mitchellh/mapstructure"
"github.com/posener/complete"
"gopkg.in/yaml.v3"
)

func NewCmdCreateRotating(ctx *cmd.Context, runF func(*CreateRotatingOpts) error) *cmd.Command {
opts := &CreateRotatingOpts{
Ctx: ctx.ShutdownCtx,
Profile: ctx.Profile,
IO: ctx.IO,
Output: ctx.Output,
PreviewClient: preview_secret_service.New(ctx.HCP, nil),
Client: secret_service.New(ctx.HCP, nil),
}

cmd := &cmd.Command{
Name: "create-rotating",
ShortHelp: "Create a new rotating secret.",
LongHelp: heredoc.New(ctx.IO).Must(`
The {{ template "mdCodeOrBold" "hcp vault-secrets secrets create-rotating" }} command creates a new rotating secret under a Vault Secrets application.
`),
Flags: cmd.Flags{
Local: []*cmd.Flag{
{
Name: "config-file",
DisplayValue: "CONFIG_FILE_PATH",
Description: "File path to a secret config",
Value: flagvalue.Simple("", &opts.SecretConfigFile),
Autocomplete: complete.PredictOr(
complete.PredictFiles("*"),
complete.PredictSet("-"),
),
},
},
},
RunF: func(c *cmd.Command, args []string) error {
opts.AppName = appname.Get()

if runF != nil {
return runF(opts)
}
return createRotatingRun(opts)
},
}

return cmd
}

type CreateRotatingOpts struct {
Ctx context.Context
Profile *profile.Profile
IO iostreams.IOStreams
Output *format.Outputter

AppName string
SecretConfigFile string
PreviewClient preview_secret_service.ClientService
Client secret_service.ClientService
}

type RotatingSecretConfig struct {
Version string
SecretName string `yaml:"secret_name"`
RotationIntegrationType string `yaml:"rotation_integration_type"`
RotationIntegrationName string `yaml:"rotation_integration_name"`
RotationPolicyName string `yaml:"rotation_policy_name"`
Details map[string]interface{}
}

type MongoDBRole struct {
RoleName string `mapstructure:"role_name"`
DatabaseName string `mapstructure:"database_name"`
CollectionName string `mapstructure:"collection_name"`
}

func createRotatingRun(opts *CreateRotatingOpts) error {
fmt.Fprintf(opts.IO.Err(), "starting")
f, err := os.ReadFile(opts.SecretConfigFile)
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}

var rsc RotatingSecretConfig
err = yaml.Unmarshal(f, &rsc)
if err != nil {
return fmt.Errorf("failed to unmarshal policy file: %w", err)
}
fmt.Fprintf(opts.IO.Err(), "read config %+v\n", rsc)
if rsc.RotationIntegrationType == "mongodb" {
roles := rsc.Details["roles"].([]interface{})
req := preview_secret_service.NewCreateMongoDBAtlasRotatingSecretParamsWithContext(opts.Ctx)
req.OrganizationID = opts.Profile.OrganizationID
req.ProjectID = opts.Profile.ProjectID
req.AppName = opts.AppName

var reqRoles []*models.Secrets20231128MongoDBRole
for _, r := range roles {
var castRole MongoDBRole
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{WeaklyTypedInput: true, Result: &castRole})
if err := decoder.Decode(r); err != nil {
return fmt.Errorf("invalid decoding to mongodbrole")
}

reqRole := &models.Secrets20231128MongoDBRole{
CollectionName: castRole.CollectionName,
RoleName: castRole.RoleName,
DatabaseName: castRole.DatabaseName,
}
reqRoles = append(reqRoles, reqRole)
}
req.Body = preview_secret_service.CreateMongoDBAtlasRotatingSecretBody{
SecretName: rsc.SecretName,
RotationIntegrationName: rsc.RotationIntegrationName,
RotationPolicyName: rsc.RotationPolicyName,
MongodbGroupID: rsc.Details["group_id"].(string),
MongodbRoles: reqRoles,
}
_, err := opts.PreviewClient.CreateMongoDBAtlasRotatingSecret(req, nil)
if err != nil {
return fmt.Errorf("failed to create secret with name %q: %w", rsc.SecretName, err)
}

fmt.Fprintln(opts.IO.Err())
fmt.Fprintf(opts.IO.Err(), "%s Successfully created secret with name %q\n", opts.IO.ColorScheme().SuccessIcon(), rsc.SecretName)
} else {
return fmt.Errorf("invalid type")
}
return nil
}
1 change: 1 addition & 0 deletions internal/commands/vaultsecrets/secrets/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ func NewCmdSecrets(ctx *cmd.Context) *cmd.Command {
}

cmd.AddChild(NewCmdCreate(ctx, nil))
cmd.AddChild(NewCmdCreateRotating(ctx, nil))
cmd.AddChild(NewCmdRead(ctx, nil))
cmd.AddChild(NewCmdDelete(ctx, nil))
cmd.AddChild(NewCmdList(ctx, nil))
Expand Down
2 changes: 2 additions & 0 deletions internal/commands/vaultsecrets/vault_secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package vaultsecrets

import (
"github.com/hashicorp/hcp/internal/commands/vaultsecrets/apps"
"github.com/hashicorp/hcp/internal/commands/vaultsecrets/integrations"
"github.com/hashicorp/hcp/internal/commands/vaultsecrets/run"
"github.com/hashicorp/hcp/internal/commands/vaultsecrets/secrets"
"github.com/hashicorp/hcp/internal/pkg/cmd"
Expand All @@ -26,6 +27,7 @@ func NewCmdVaultSecrets(ctx *cmd.Context) *cmd.Command {

cmd.AddChild(apps.NewCmdApps(ctx))
cmd.AddChild(secrets.NewCmdSecrets(ctx))
cmd.AddChild(integrations.NewCmdIntegrations(ctx))
cmd.AddChild(run.NewCmdRun(ctx, nil))
return cmd
}
Loading
Loading