templates.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package templates
  2. import (
  3. "bytes"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "sync"
  8. "text/template"
  9. "github.com/Masterminds/sprig/v3"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/cli-utils/fileutil"
  12. "github.com/smallstep/cli-utils/step"
  13. )
  14. // TemplateType defines how a template will be written in disk.
  15. type TemplateType string
  16. const (
  17. // Snippet will mark a template as a part of a file.
  18. Snippet TemplateType = "snippet"
  19. // PrependLine is a template for prepending a single line to a file. If the
  20. // line already exists in the file it will be removed first.
  21. PrependLine TemplateType = "prepend-line"
  22. // File will mark a templates as a full file.
  23. File TemplateType = "file"
  24. // Directory will mark a template as a directory.
  25. Directory TemplateType = "directory"
  26. )
  27. var (
  28. stepFuncMap template.FuncMap
  29. stepFuncOnce sync.Once
  30. )
  31. // StepFuncMap returns sprig.TxtFuncMap but removing the "env" and "expandenv"
  32. // functions to avoid any leak of information.
  33. func StepFuncMap() template.FuncMap {
  34. stepFuncOnce.Do(func() {
  35. stepFuncMap = sprig.TxtFuncMap()
  36. delete(stepFuncMap, "env")
  37. delete(stepFuncMap, "expandenv")
  38. })
  39. return stepFuncMap
  40. }
  41. // Templates is a collection of templates and variables.
  42. type Templates struct {
  43. SSH *SSHTemplates `json:"ssh,omitempty"`
  44. Data map[string]any `json:"data,omitempty"`
  45. }
  46. // Validate returns an error if a template is not valid.
  47. func (t *Templates) Validate() (err error) {
  48. if t == nil {
  49. return nil
  50. }
  51. // Validate members
  52. if err = t.SSH.Validate(); err != nil {
  53. return
  54. }
  55. // Do not allow "Step" and "User"
  56. if t.Data != nil {
  57. if _, ok := t.Data["Step"]; ok {
  58. return errors.New("templates variables cannot contain 'Step' as a property")
  59. }
  60. if _, ok := t.Data["User"]; ok {
  61. return errors.New("templates variables cannot contain 'User' as a property")
  62. }
  63. }
  64. return nil
  65. }
  66. // LoadAll preloads all templates in memory. It returns an error if an error is
  67. // found parsing at least one template.
  68. func LoadAll(t *Templates) (err error) {
  69. if t != nil {
  70. if t.SSH != nil {
  71. for _, tt := range t.SSH.User {
  72. if err = tt.Load(); err != nil {
  73. return
  74. }
  75. }
  76. for _, tt := range t.SSH.Host {
  77. if err = tt.Load(); err != nil {
  78. return
  79. }
  80. }
  81. }
  82. }
  83. return
  84. }
  85. // SSHTemplates contains the templates defining ssh configuration files.
  86. type SSHTemplates struct {
  87. User []Template `json:"user"`
  88. Host []Template `json:"host"`
  89. }
  90. // Validate returns an error if a template is not valid.
  91. func (t *SSHTemplates) Validate() (err error) {
  92. if t == nil {
  93. return nil
  94. }
  95. for _, tt := range t.User {
  96. if err = tt.Validate(); err != nil {
  97. return
  98. }
  99. }
  100. for _, tt := range t.Host {
  101. if err = tt.Validate(); err != nil {
  102. return
  103. }
  104. }
  105. return
  106. }
  107. // Template represents a template file.
  108. type Template struct {
  109. *template.Template
  110. Name string `json:"name"`
  111. Type TemplateType `json:"type"`
  112. TemplatePath string `json:"template"`
  113. Path string `json:"path"`
  114. Comment string `json:"comment"`
  115. RequiredData []string `json:"requires,omitempty"`
  116. Content []byte `json:"-"`
  117. }
  118. // Validate returns an error if the template is not valid.
  119. func (t *Template) Validate() error {
  120. switch {
  121. case t == nil:
  122. return nil
  123. case t.Name == "":
  124. return errors.New("template name cannot be empty")
  125. case t.Type != Snippet && t.Type != File && t.Type != Directory && t.Type != PrependLine:
  126. return errors.Errorf("invalid template type %s, it must be %s, %s, %s, or %s", t.Type, Snippet, PrependLine, File, Directory)
  127. case t.TemplatePath == "" && t.Type != Directory && len(t.Content) == 0:
  128. return errors.New("template template cannot be empty")
  129. case t.TemplatePath != "" && t.Type == Directory:
  130. return errors.New("template template must be empty with directory type")
  131. case t.TemplatePath != "" && len(t.Content) > 0:
  132. return errors.New("template template must be empty with content")
  133. case t.Path == "":
  134. return errors.New("template path cannot be empty")
  135. }
  136. if t.TemplatePath != "" {
  137. // Check for file
  138. st, err := os.Stat(step.Abs(t.TemplatePath))
  139. if err != nil {
  140. return errors.Wrapf(err, "error reading %s", t.TemplatePath)
  141. }
  142. if st.IsDir() {
  143. return errors.Errorf("error reading %s: is not a file", t.TemplatePath)
  144. }
  145. // Defaults
  146. if t.Comment == "" {
  147. t.Comment = "#"
  148. }
  149. }
  150. return nil
  151. }
  152. // ValidateRequiredData checks that the given data contains all the keys
  153. // required.
  154. func (t *Template) ValidateRequiredData(data map[string]string) error {
  155. for _, key := range t.RequiredData {
  156. if _, ok := data[key]; !ok {
  157. return errors.Errorf("required variable '%s' is missing", key)
  158. }
  159. }
  160. return nil
  161. }
  162. // Load loads the template in memory, returns an error if the parsing of the
  163. // template fails.
  164. func (t *Template) Load() error {
  165. if t.Template == nil && t.Type != Directory {
  166. switch {
  167. case t.TemplatePath != "":
  168. filename := step.Abs(t.TemplatePath)
  169. b, err := os.ReadFile(filename)
  170. if err != nil {
  171. return errors.Wrapf(err, "error reading %s", filename)
  172. }
  173. return t.LoadBytes(b)
  174. default:
  175. return t.LoadBytes(t.Content)
  176. }
  177. }
  178. return nil
  179. }
  180. // LoadBytes loads the template in memory, returns an error if the parsing of
  181. // the template fails.
  182. func (t *Template) LoadBytes(b []byte) error {
  183. t.backfill(b)
  184. tmpl, err := template.New(t.Name).Funcs(StepFuncMap()).Parse(string(b))
  185. if err != nil {
  186. return errors.Wrapf(err, "error parsing template %s", t.Name)
  187. }
  188. t.Template = tmpl
  189. return nil
  190. }
  191. // Render executes the template with the given data and returns the rendered
  192. // version.
  193. func (t *Template) Render(data any) ([]byte, error) {
  194. if t.Type == Directory {
  195. return nil, nil
  196. }
  197. if err := t.Load(); err != nil {
  198. return nil, err
  199. }
  200. buf := new(bytes.Buffer)
  201. if err := t.Execute(buf, data); err != nil {
  202. return nil, errors.Wrapf(err, "error executing %s", t.TemplatePath)
  203. }
  204. return buf.Bytes(), nil
  205. }
  206. // Output renders the template and returns a template.Output struct or an error.
  207. func (t *Template) Output(data any) (Output, error) {
  208. b, err := t.Render(data)
  209. if err != nil {
  210. return Output{}, err
  211. }
  212. return Output{
  213. Name: t.Name,
  214. Type: t.Type,
  215. Path: t.Path,
  216. Comment: t.Comment,
  217. Content: b,
  218. }, nil
  219. }
  220. // backfill updates old templates with the required data.
  221. func (t *Template) backfill(b []byte) {
  222. if strings.EqualFold(t.Name, "sshd_config.tpl") && len(t.RequiredData) == 0 {
  223. a := bytes.TrimSpace(b)
  224. b := bytes.TrimSpace([]byte(DefaultSSHTemplateData[t.Name]))
  225. if bytes.Equal(a, b) {
  226. t.RequiredData = []string{"Certificate", "Key"}
  227. }
  228. }
  229. }
  230. // Output represents the text representation of a rendered template.
  231. type Output struct {
  232. Name string `json:"name"`
  233. Type TemplateType `json:"type"`
  234. Path string `json:"path"`
  235. Comment string `json:"comment"`
  236. Content []byte `json:"content"`
  237. }
  238. // Write writes the Output to the filesystem as a directory, file or snippet.
  239. func (o *Output) Write() error {
  240. // Replace ${STEPPATH} with the base step path.
  241. o.Path = strings.ReplaceAll(o.Path, "${STEPPATH}", step.BasePath())
  242. path := step.Abs(o.Path)
  243. if o.Type == Directory {
  244. return mkdir(path, 0700)
  245. }
  246. dir := filepath.Dir(path)
  247. if err := mkdir(dir, 0700); err != nil {
  248. return err
  249. }
  250. switch o.Type {
  251. case File:
  252. return fileutil.WriteFile(path, o.Content, 0600)
  253. case Snippet:
  254. return fileutil.WriteSnippet(path, o.Content, 0600)
  255. case PrependLine:
  256. return fileutil.PrependLine(path, o.Content, 0600)
  257. default:
  258. // Default to using a Snippet type if the type is not known.
  259. return fileutil.WriteSnippet(path, o.Content, 0600)
  260. }
  261. }
  262. func mkdir(path string, perm os.FileMode) error {
  263. if err := os.MkdirAll(path, perm); err != nil {
  264. return errors.Wrapf(err, "error creating %s", path)
  265. }
  266. return nil
  267. }