options.go 2.3 KB

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