github.com/zntrio/harp/v2@v2.0.9/pkg/tasks/to/vault.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package to 19 20 import ( 21 "context" 22 "fmt" 23 24 "github.com/hashicorp/vault/api" 25 26 "github.com/zntrio/harp/v2/pkg/bundle" 27 bundlevault "github.com/zntrio/harp/v2/pkg/bundle/vault" 28 "github.com/zntrio/harp/v2/pkg/tasks" 29 "github.com/zntrio/harp/v2/pkg/vault" 30 ) 31 32 // VaultTask implements secret-container publication process to Vault. 33 type VaultTask struct { 34 ContainerReader tasks.ReaderProvider 35 BackendPrefix string 36 PushMetadata bool 37 AsVaultMetadata bool 38 VaultNamespace string 39 MaxWorkerCount int64 40 } 41 42 // Run the task. 43 func (t *VaultTask) Run(ctx context.Context) error { 44 // Initialize vault connection 45 client, err := api.NewClient(api.DefaultConfig()) 46 if err != nil { 47 return fmt.Errorf("unable to initialize Vault connection: %w", err) 48 } 49 50 // If a namespace is specified 51 if t.VaultNamespace != "" { 52 client.SetNamespace(t.VaultNamespace) 53 } 54 55 // Verify vault connection 56 if _, errAuth := vault.CheckAuthentication(ctx, client); errAuth != nil { 57 return fmt.Errorf("vault connection verification failed: %w", errAuth) 58 } 59 60 // Create the reader 61 reader, err := t.ContainerReader(ctx) 62 if err != nil { 63 return fmt.Errorf("unable to open input bundle reader: %w", err) 64 } 65 66 // Extract bundle from container 67 b, err := bundle.FromContainerReader(reader) 68 if err != nil { 69 return fmt.Errorf("unable to load bundle: %w", err) 70 } 71 72 // Process push operation 73 if err := bundlevault.Push(ctx, b, client, 74 bundlevault.WithPrefix(t.BackendPrefix), 75 bundlevault.WithSecretMetadata(t.PushMetadata), 76 bundlevault.WithVaultMetadata(t.AsVaultMetadata), 77 bundlevault.WithMaxWorkerCount(t.MaxWorkerCount), 78 ); err != nil { 79 return fmt.Errorf("error occurs during vault export (prefix: %q): %w", t.BackendPrefix, err) 80 } 81 82 // No error 83 return nil 84 }