decoding.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright © The ESO Authors
  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. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package decoding provides helpers for decoding ExternalSecret values.
  14. package decoding
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  19. )
  20. // DecodeMap decodes values from a secretMap.
  21. func DecodeMap(strategy esv1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  22. out := make(map[string][]byte, len(in))
  23. for k, v := range in {
  24. val, err := Decode(strategy, v)
  25. if err != nil {
  26. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  27. }
  28. out[k] = val
  29. }
  30. return out, nil
  31. }
  32. // Decode decodes the input byte slice according to the provided decoding strategy.
  33. func Decode(strategy esv1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  34. switch strategy {
  35. case esv1.ExternalSecretDecodeBase64:
  36. out, err := base64.StdEncoding.DecodeString(string(in))
  37. if err != nil {
  38. return nil, err
  39. }
  40. return out, nil
  41. case esv1.ExternalSecretDecodeBase64URL:
  42. out, err := base64.URLEncoding.DecodeString(string(in))
  43. if err != nil {
  44. return nil, err
  45. }
  46. return out, nil
  47. case esv1.ExternalSecretDecodeNone:
  48. return in, nil
  49. // default when stored version is v1alpha1
  50. case "":
  51. return in, nil
  52. case esv1.ExternalSecretDecodeAuto:
  53. out, err := Decode(esv1.ExternalSecretDecodeBase64, in)
  54. if err != nil {
  55. out, err := Decode(esv1.ExternalSecretDecodeBase64URL, in)
  56. if err != nil {
  57. return Decode(esv1.ExternalSecretDecodeNone, in)
  58. }
  59. return out, nil
  60. }
  61. return out, nil
  62. default:
  63. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  64. }
  65. }