github.com/zntrio/harp/v2@v2.0.9/pkg/vault/kv/builder.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 kv 19 20 import ( 21 "context" 22 "fmt" 23 24 "github.com/hashicorp/vault/api" 25 26 vpath "github.com/zntrio/harp/v2/pkg/vault/path" 27 ) 28 29 // Option defines the functional option pattern. 30 type Option func(opts *Options) 31 32 // Options defiens the default option value. 33 type Options struct { 34 useCustomMetadata bool 35 ctx context.Context 36 } 37 38 // WithContext adds given context to all queries. 39 func WithContext(ctx context.Context) Option { 40 return func(opts *Options) { 41 opts.ctx = ctx 42 } 43 } 44 45 // WithVaultMetatadata enable/disable the custom metadata storage strategy (requires Vault >=1.9). 46 func WithVaultMetatadata(value bool) Option { 47 return func(opts *Options) { 48 opts.useCustomMetadata = value 49 } 50 } 51 52 // New build a KV service according to mountPath version. 53 func New(client *api.Client, path string, opts ...Option) (Service, error) { 54 // Sanitize path 55 secretPath := vpath.SanitizePath(path) 56 57 // Defines default flag. 58 dopts := &Options{ 59 useCustomMetadata: false, 60 ctx: context.Background(), 61 } 62 63 // Apply option function. 64 for _, o := range opts { 65 o(dopts) 66 } 67 68 // Detect mount path 69 mountPath, v2, err := isKVv2(dopts.ctx, secretPath, client) 70 if err != nil { 71 return nil, fmt.Errorf("vault: unable to detect k/v backend version: %w", err) 72 } 73 74 // Build the service according to mountPath version 75 var s Service 76 if v2 { 77 s = V2(client.Logical(), mountPath, dopts.useCustomMetadata) 78 } else { 79 s = V1(client.Logical(), mountPath) 80 } 81 82 // No error 83 return s, nil 84 }