sanitize.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package config
  2. import (
  3. "fmt"
  4. "strings"
  5. "text/template"
  6. "github.com/OliveTin/OliveTin/internal/env"
  7. "github.com/google/uuid"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. // Sanitize will look for common configuration issues, and fix them. For example,
  11. // populating undefined fields - name -> title, etc.
  12. func (cfg *Config) Sanitize() {
  13. cfg.sanitizeLogLevel()
  14. cfg.sanitizeAuthRequireGuestsToLogin()
  15. cfg.sanitizeLogHistoryPageSize()
  16. cfg.sanitizeLocalUsers()
  17. cfg.sanitizeSecurityHeaders()
  18. // log.Infof("cfg %p", cfg)
  19. for idx := range cfg.Actions {
  20. cfg.Actions[idx].sanitize(cfg)
  21. }
  22. cfg.sanitizeDashboardsForInlineActions()
  23. }
  24. func (cfg *Config) sanitizeDashboardsForInlineActions() {
  25. for _, dashboard := range cfg.Dashboards {
  26. cfg.sanitizeDashboardComponentForInlineActions(dashboard)
  27. }
  28. }
  29. func (cfg *Config) sanitizeDashboardComponentForInlineActions(component *DashboardComponent) {
  30. visited := make(map[*DashboardComponent]bool)
  31. cfg.sanitizeDashboardComponentForInlineActionsHelper(component, visited)
  32. }
  33. func (cfg *Config) sanitizeDashboardComponentForInlineActionsHelper(component *DashboardComponent, visited map[*DashboardComponent]bool) {
  34. if component == nil {
  35. return
  36. }
  37. if visited[component] {
  38. return
  39. }
  40. visited[component] = true
  41. cfg.sanitizeInlineAction(component)
  42. cfg.sanitizeChildDashboardComponents(component, visited)
  43. }
  44. func (cfg *Config) sanitizeInlineAction(component *DashboardComponent) {
  45. if component.InlineAction == nil {
  46. return
  47. }
  48. sanitizeInlineActionTitles(component)
  49. if component.Entity != "" && component.InlineAction.Entity == "" {
  50. component.InlineAction.Entity = component.Entity
  51. }
  52. component.InlineAction.sanitize(cfg)
  53. cfg.addInlineActionIfNotExists(component.InlineAction)
  54. }
  55. func (cfg *Config) addInlineActionIfNotExists(action *Action) {
  56. if cfg.inlineActionExists(action) {
  57. return
  58. }
  59. cfg.Actions = append(cfg.Actions, action)
  60. }
  61. func sanitizeInlineActionTitles(component *DashboardComponent) {
  62. if component.InlineAction.Title == "" {
  63. component.InlineAction.Title = component.Title
  64. }
  65. if component.Title == "" {
  66. component.Title = component.InlineAction.Title
  67. }
  68. }
  69. func (cfg *Config) inlineActionExists(action *Action) bool {
  70. if cfg.inlineActionPointerExists(action) {
  71. return true
  72. }
  73. if cfg.inlineActionIDExists(action) {
  74. return true
  75. }
  76. return false
  77. }
  78. func (cfg *Config) inlineActionPointerExists(action *Action) bool {
  79. for _, existingAction := range cfg.Actions {
  80. if existingAction == action {
  81. return true
  82. }
  83. }
  84. return false
  85. }
  86. func (cfg *Config) inlineActionIDExists(action *Action) bool {
  87. if action.ID == "" {
  88. return false
  89. }
  90. for _, existingAction := range cfg.Actions {
  91. if existingAction.ID == action.ID {
  92. return true
  93. }
  94. }
  95. return false
  96. }
  97. func (cfg *Config) sanitizeChildDashboardComponents(component *DashboardComponent, visited map[*DashboardComponent]bool) {
  98. for _, child := range component.Contents {
  99. if child.Entity == "" {
  100. child.Entity = component.Entity
  101. }
  102. cfg.sanitizeDashboardComponentForInlineActionsHelper(child, visited)
  103. }
  104. }
  105. func (cfg *Config) sanitizeLogLevel() {
  106. if logLevel, err := log.ParseLevel(cfg.LogLevel); err == nil {
  107. log.Info("Setting log level to ", logLevel)
  108. log.SetLevel(logLevel)
  109. }
  110. }
  111. func (action *Action) sanitize(cfg *Config) {
  112. if action.Timeout < 3 {
  113. action.Timeout = 3
  114. }
  115. action.ID = getActionID(action)
  116. action.Icon = lookupHTMLIcon(action.Icon, cfg.DefaultIconForActions)
  117. action.PopupOnStart = sanitizePopupOnStart(action.PopupOnStart, cfg)
  118. if action.MaxConcurrent < 1 {
  119. action.MaxConcurrent = 1
  120. }
  121. for idx := range action.Arguments {
  122. action.Arguments[idx].sanitize()
  123. }
  124. }
  125. func (cfg *Config) sanitizeAuthRequireGuestsToLogin() {
  126. if cfg.AuthRequireGuestsToLogin {
  127. log.Infof("AuthRequireGuestsToLogin is enabled. All defaultPermissions will be set to false")
  128. cfg.DefaultPermissions.View = false
  129. cfg.DefaultPermissions.Exec = false
  130. cfg.DefaultPermissions.Logs = false
  131. cfg.DefaultPermissions.Kill = false
  132. }
  133. }
  134. func (cfg *Config) sanitizeLogHistoryPageSize() {
  135. if cfg.LogHistoryPageSize < 10 {
  136. log.Warnf("LogsHistoryLimit is too low, setting it to 10")
  137. cfg.LogHistoryPageSize = 10
  138. } else if cfg.LogHistoryPageSize > 100 {
  139. log.Warnf("LogsHistoryLimit is high, you can do this, but expect browser lag.")
  140. }
  141. }
  142. func (cfg *Config) sanitizeLocalUsers() {
  143. for _, user := range cfg.AuthLocalUsers.Users {
  144. expandLocalUserEnvTemplates(user)
  145. }
  146. if err := validateUniqueLocalUserAPIKeys(cfg.AuthLocalUsers.Users); err != nil {
  147. log.Fatalf("%v", err)
  148. }
  149. }
  150. func expandLocalUserEnvTemplates(user *LocalUser) {
  151. if user == nil {
  152. return
  153. }
  154. if user.Password != "" {
  155. user.Password = expandEnvTemplate(user.Password)
  156. }
  157. if user.ApiKey != "" {
  158. user.ApiKey = expandEnvTemplate(user.ApiKey)
  159. }
  160. }
  161. // validateUniqueLocalUserAPIKeys returns an error when two local users share the same non-empty apiKey.
  162. func validateUniqueLocalUserAPIKeys(users []*LocalUser) error {
  163. seen := make(map[string]string)
  164. for _, user := range users {
  165. if err := recordUniqueLocalUserAPIKey(seen, user); err != nil {
  166. return err
  167. }
  168. }
  169. return nil
  170. }
  171. func recordUniqueLocalUserAPIKey(seen map[string]string, user *LocalUser) error {
  172. if user == nil || user.ApiKey == "" {
  173. return nil
  174. }
  175. if prior, ok := seen[user.ApiKey]; ok {
  176. return fmt.Errorf("duplicate authLocalUsers apiKey for users %q and %q", prior, user.Username)
  177. }
  178. seen[user.ApiKey] = user.Username
  179. return nil
  180. }
  181. func (cfg *Config) sanitizeSecurityHeaders() {
  182. cfg.sanitizeSecurityHeadersCSP()
  183. cfg.sanitizeSecurityHeadersXFrameOptions()
  184. }
  185. func (cfg *Config) sanitizeSecurityHeadersCSP() {
  186. if !cfg.Security.HeaderContentSecurityPolicy || cfg.Security.ContentSecurityPolicy != "" {
  187. return
  188. }
  189. cfg.Security.ContentSecurityPolicy = ContentSecurityPolicyDefault
  190. }
  191. func (cfg *Config) sanitizeSecurityHeadersXFrameOptions() {
  192. if !cfg.Security.HeaderXFrameOptions || cfg.Security.XFrameOptions != "" {
  193. return
  194. }
  195. cfg.Security.XFrameOptions = "DENY"
  196. }
  197. // expandEnvTemplate expands {{ .Env.VAR }} in config strings using the process environment.
  198. func expandEnvTemplate(source string) string {
  199. t, err := template.New("envTemplate").Option("missingkey=error").Parse(source)
  200. if err != nil {
  201. log.WithFields(log.Fields{"error": err}).Debug("Env template parse failed, using literal")
  202. return source
  203. }
  204. var b strings.Builder
  205. if err := t.Execute(&b, map[string]interface{}{"Env": env.BuildEnvMap()}); err != nil {
  206. log.WithFields(log.Fields{"error": err}).Debug("Env template execute failed, using literal")
  207. return source
  208. }
  209. return b.String()
  210. }
  211. func getActionID(action *Action) string {
  212. if action.ID == "" {
  213. return uuid.NewString()
  214. }
  215. if strings.Contains(action.ID, "{{") {
  216. log.Fatalf("Action IDs cannot contain variables")
  217. }
  218. return action.ID
  219. }
  220. //gocyclo:ignore
  221. func sanitizePopupOnStart(raw string, cfg *Config) string {
  222. switch raw {
  223. case "execution-dialog":
  224. return raw
  225. case "execution-dialog-output-html":
  226. return raw
  227. case "execution-dialog-stdout-only":
  228. return raw
  229. case "execution-button":
  230. return raw
  231. case "history":
  232. return raw
  233. default:
  234. return cfg.DefaultPopupOnStart
  235. }
  236. }
  237. func (arg *ActionArgument) sanitize() {
  238. if arg.Title == "" {
  239. arg.Title = arg.Name
  240. }
  241. for idx, choice := range arg.Choices {
  242. if choice.Title == "" {
  243. arg.Choices[idx].Title = choice.Value
  244. }
  245. }
  246. arg.sanitizeNoType()
  247. // Default value validation runs in executor at config load (validateArgumentDefaults).
  248. }
  249. func (arg *ActionArgument) sanitizeNoType() {
  250. if len(arg.Choices) == 0 && arg.Type == "" {
  251. log.WithFields(log.Fields{
  252. "arg": arg.Name,
  253. }).Warn("Argument type isn't set, will default to 'ascii' but this may not be safe. You should set a type specifically.")
  254. arg.Type = "ascii"
  255. }
  256. }