github.com/zntrio/harp/v2@v2.0.9/pkg/tasks/share/get.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 share
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  
    24  	"github.com/hashicorp/vault/api"
    25  
    26  	"github.com/zntrio/harp/v2/pkg/tasks"
    27  	"github.com/zntrio/harp/v2/pkg/vault"
    28  )
    29  
    30  // GetTask implements secret sharing via Vault Cubbyhole.
    31  type GetTask struct {
    32  	OutputWriter   tasks.WriterProvider
    33  	BackendPrefix  string
    34  	VaultNamespace string
    35  	Token          string
    36  }
    37  
    38  // Run the task.
    39  func (t *GetTask) Run(ctx context.Context) error {
    40  	// Initialize vault connection
    41  	client, err := api.NewClient(api.DefaultConfig())
    42  	if err != nil {
    43  		return fmt.Errorf("unable to initialize Vault connection: %w", err)
    44  	}
    45  
    46  	// If a namespace is specified
    47  	if t.VaultNamespace != "" {
    48  		client.SetNamespace(t.VaultNamespace)
    49  	}
    50  
    51  	// Verify vault connection
    52  	if _, errAuth := vault.CheckAuthentication(ctx, client); errAuth != nil {
    53  		return fmt.Errorf("vault connection verification failed: %w", errAuth)
    54  	}
    55  
    56  	// Create cubbyhole service
    57  	sf, errFactory := vault.FromVaultClient(client)
    58  	if err != nil {
    59  		return fmt.Errorf("unable to initialize service factory: %w", errFactory)
    60  	}
    61  	s, errService := sf.Cubbyhole(t.BackendPrefix)
    62  	if errService != nil {
    63  		return fmt.Errorf("unable to initialize service factory: %w", errFactory)
    64  	}
    65  
    66  	// Create output writer
    67  	writer, err := t.OutputWriter(ctx)
    68  	if err != nil {
    69  		return fmt.Errorf("unable to open output writer: %w", err)
    70  	}
    71  
    72  	// Retrieve secret
    73  	if err := s.Get(ctx, t.Token, writer); err != nil {
    74  		return fmt.Errorf("unable to retrieve secret: %w", err)
    75  	}
    76  
    77  	// No error
    78  	return nil
    79  }