templates.go 6.7 KB

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