github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/gitlab/yaml/secret.go (about)

     1  // Copyright 2022 Harness, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package yaml
    16  
    17  import (
    18  	"errors"
    19  	"strings"
    20  )
    21  
    22  type Secret struct {
    23  	Vault *Vault `yaml:"vault,omitempty"`
    24  	File  *bool  `yaml:"file,omitempty"`
    25  	Token string `yaml:"token,omitempty"`
    26  }
    27  
    28  type Vault struct {
    29  	Engine *VaultEngine `yaml:"engine,omitempty"`
    30  	Path   string       `yaml:"path,omitempty"`
    31  	Field  string       `yaml:"field,omitempty"`
    32  }
    33  
    34  type VaultEngine struct {
    35  	Name string `yaml:"name,omitempty"`
    36  	Path string `yaml:"path,omitempty"`
    37  }
    38  
    39  // UnmarshalYAML implements the unmarshal interface.
    40  func (v *Vault) UnmarshalYAML(unmarshal func(interface{}) error) error {
    41  	var out1 string
    42  	var out2 = struct {
    43  		Engine *VaultEngine `yaml:"engine,omitempty"`
    44  		Path   string       `yaml:"path,omitempty"`
    45  		Field  string       `yaml:"field,omitempty"`
    46  	}{}
    47  
    48  	if err := unmarshal(&out1); err == nil {
    49  		parts := strings.SplitN(out1, "/", 3)
    50  		if len(parts) == 3 {
    51  			v.Path = parts[0] + "/" + parts[1]
    52  			v.Field = parts[2]
    53  			engineParts := strings.SplitN(parts[2], "@", 2)
    54  			if len(engineParts) == 2 {
    55  				v.Field = engineParts[0]
    56  				v.Engine = &VaultEngine{
    57  					Path: engineParts[1],
    58  					Name: "kv-v2",
    59  				}
    60  			}
    61  		} else {
    62  			v.Path = out1
    63  		}
    64  		return nil
    65  	}
    66  
    67  	if err := unmarshal(&out2); err == nil {
    68  		v.Path = out2.Path
    69  		v.Field = out2.Field
    70  		v.Engine = out2.Engine
    71  		return nil
    72  	}
    73  
    74  	return errors.New("failed to unmarshal vault")
    75  }