templates.go 7.5 KB

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