options.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package sshutil
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "io/ioutil"
  6. "text/template"
  7. "github.com/Masterminds/sprig/v3"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/cli/config"
  10. )
  11. func getFuncMap(failMessage *string) template.FuncMap {
  12. m := sprig.TxtFuncMap()
  13. m["fail"] = func(msg string) (string, error) {
  14. *failMessage = msg
  15. return "", errors.New(msg)
  16. }
  17. return m
  18. }
  19. // Options are the options that can be passed to NewCertificate.
  20. type Options struct {
  21. CertBuffer *bytes.Buffer
  22. }
  23. func (o *Options) apply(cr CertificateRequest, opts []Option) (*Options, error) {
  24. for _, fn := range opts {
  25. if err := fn(cr, o); err != nil {
  26. return o, err
  27. }
  28. }
  29. return o, nil
  30. }
  31. // Option is the type used as a variadic argument in NewCertificate.
  32. type Option func(cr CertificateRequest, o *Options) error
  33. // WithTemplate is an options that executes the given template text with the
  34. // given data.
  35. func WithTemplate(text string, data TemplateData) Option {
  36. return func(cr CertificateRequest, o *Options) error {
  37. terr := new(TemplateError)
  38. funcMap := getFuncMap(&terr.Message)
  39. tmpl, err := template.New("template").Funcs(funcMap).Parse(text)
  40. if err != nil {
  41. return errors.Wrapf(err, "error parsing template")
  42. }
  43. buf := new(bytes.Buffer)
  44. data.SetCertificateRequest(cr)
  45. if err := tmpl.Execute(buf, data); err != nil {
  46. if terr.Message != "" {
  47. return terr
  48. }
  49. return errors.Wrapf(err, "error executing template")
  50. }
  51. o.CertBuffer = buf
  52. return nil
  53. }
  54. }
  55. // WithTemplateBase64 is an options that executes the given template base64
  56. // string with the given data.
  57. func WithTemplateBase64(s string, data TemplateData) Option {
  58. return func(cr CertificateRequest, o *Options) error {
  59. b, err := base64.StdEncoding.DecodeString(s)
  60. if err != nil {
  61. return errors.Wrap(err, "error decoding template")
  62. }
  63. fn := WithTemplate(string(b), data)
  64. return fn(cr, o)
  65. }
  66. }
  67. // WithTemplateFile is an options that reads the template file and executes it
  68. // with the given data.
  69. func WithTemplateFile(path string, data TemplateData) Option {
  70. return func(cr CertificateRequest, o *Options) error {
  71. filename := config.StepAbs(path)
  72. b, err := ioutil.ReadFile(filename)
  73. if err != nil {
  74. return errors.Wrapf(err, "error reading %s", path)
  75. }
  76. fn := WithTemplate(string(b), data)
  77. return fn(cr, o)
  78. }
  79. }