sanitize.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. package config
  2. import (
  3. "fmt"
  4. "slices"
  5. "strings"
  6. "text/template"
  7. "github.com/OliveTin/OliveTin/internal/configissues"
  8. "github.com/OliveTin/OliveTin/internal/env"
  9. "github.com/google/uuid"
  10. log "github.com/sirupsen/logrus"
  11. )
  12. // Sanitize will look for common configuration issues, and fix them. For example,
  13. // populating undefined fields - name -> title, etc.
  14. func (cfg *Config) Sanitize() {
  15. cfg.sanitizeLogLevel()
  16. cfg.sanitizeAuthRequireGuestsToLogin()
  17. cfg.sanitizeLogHistoryPageSize()
  18. cfg.sanitizeLocalUsers()
  19. cfg.sanitizeSecurityHeaders()
  20. cfg.sanitizeOnClickDefaults()
  21. // log.Infof("cfg %p", cfg)
  22. for idx := range cfg.Actions {
  23. cfg.Actions[idx].sanitize(cfg)
  24. }
  25. cfg.sanitizeDashboardsForInlineActions()
  26. cfg.sanitizeActionGroups()
  27. cfg.sanitizeEntities()
  28. if err := cfg.validateReservedActionArgumentNames(); err != nil {
  29. log.Fatalf("%v", err)
  30. }
  31. if err := cfg.validateChecklistChoiceValues(); err != nil {
  32. log.Fatalf("%v", err)
  33. }
  34. if err := cfg.validateEntityArgumentChoices(); err != nil {
  35. log.Fatalf("%v", err)
  36. }
  37. }
  38. func (cfg *Config) validateReservedActionArgumentNames() error {
  39. for _, action := range cfg.Actions {
  40. if err := action.validateReservedArgumentNames(); err != nil {
  41. return err
  42. }
  43. }
  44. return nil
  45. }
  46. func (action *Action) validateReservedArgumentNames() error {
  47. if action == nil {
  48. return nil
  49. }
  50. for _, arg := range action.Arguments {
  51. if strings.HasPrefix(arg.Name, ReservedArgumentNamePrefix) {
  52. return fmt.Errorf("action %q argument %q uses reserved prefix %q", action.Title, arg.Name, ReservedArgumentNamePrefix)
  53. }
  54. }
  55. return nil
  56. }
  57. func (cfg *Config) validateChecklistChoiceValues() error {
  58. for _, action := range cfg.Actions {
  59. if err := action.validateChecklistChoiceValues(); err != nil {
  60. return err
  61. }
  62. }
  63. return nil
  64. }
  65. func (action *Action) validateChecklistChoiceValues() error {
  66. if action == nil {
  67. return nil
  68. }
  69. for _, arg := range action.Arguments {
  70. if err := validateChecklistChoicesForArgument(action.Title, arg); err != nil {
  71. return err
  72. }
  73. }
  74. return nil
  75. }
  76. func validateChecklistChoicesForArgument(actionTitle string, arg ActionArgument) error {
  77. if arg.Type != "checklist" {
  78. return nil
  79. }
  80. for _, choice := range arg.Choices {
  81. if strings.TrimSpace(choice.Value) == "" {
  82. return fmt.Errorf(
  83. `action %q argument %q choice value must not be empty`,
  84. actionTitle,
  85. arg.Name,
  86. )
  87. }
  88. }
  89. return nil
  90. }
  91. func (cfg *Config) validateEntityArgumentChoices() error {
  92. for _, action := range cfg.Actions {
  93. if err := action.validateEntityArgumentChoices(); err != nil {
  94. return err
  95. }
  96. }
  97. return nil
  98. }
  99. func (action *Action) validateEntityArgumentChoices() error {
  100. if action == nil {
  101. return nil
  102. }
  103. for _, arg := range action.Arguments {
  104. if err := validateEntityArgumentChoicesForArgument(action.Title, arg); err != nil {
  105. return err
  106. }
  107. }
  108. return nil
  109. }
  110. func validateEntityArgumentChoicesForArgument(actionTitle string, arg ActionArgument) error {
  111. if arg.Entity == "" || len(arg.Choices) == 1 {
  112. return nil
  113. }
  114. return fmt.Errorf(
  115. `action %q argument %q with entity must define exactly one choice template`,
  116. actionTitle,
  117. arg.Name,
  118. )
  119. }
  120. func (cfg *Config) sanitizeDashboardsForInlineActions() {
  121. for _, dashboard := range cfg.Dashboards {
  122. cfg.sanitizeDashboardComponentForInlineActions(dashboard)
  123. }
  124. }
  125. func (cfg *Config) sanitizeDashboardComponentForInlineActions(component *DashboardComponent) {
  126. visited := make(map[*DashboardComponent]bool)
  127. cfg.sanitizeDashboardComponentForInlineActionsHelper(component, visited)
  128. }
  129. func (cfg *Config) sanitizeDashboardComponentForInlineActionsHelper(component *DashboardComponent, visited map[*DashboardComponent]bool) {
  130. if component == nil {
  131. return
  132. }
  133. if visited[component] {
  134. return
  135. }
  136. visited[component] = true
  137. cfg.sanitizeInlineAction(component)
  138. cfg.sanitizeChildDashboardComponents(component, visited)
  139. }
  140. func (cfg *Config) sanitizeInlineAction(component *DashboardComponent) {
  141. if component.InlineAction == nil {
  142. return
  143. }
  144. sanitizeInlineActionTitles(component)
  145. if component.Entity != "" && component.InlineAction.Entity == "" {
  146. component.InlineAction.Entity = component.Entity
  147. }
  148. component.InlineAction.sanitize(cfg)
  149. cfg.addInlineActionIfNotExists(component.InlineAction)
  150. }
  151. func (cfg *Config) addInlineActionIfNotExists(action *Action) {
  152. if cfg.inlineActionExists(action) {
  153. return
  154. }
  155. cfg.Actions = append(cfg.Actions, action)
  156. }
  157. func sanitizeInlineActionTitles(component *DashboardComponent) {
  158. if component.InlineAction.Title == "" {
  159. component.InlineAction.Title = component.Title
  160. }
  161. if component.Title == "" {
  162. component.Title = component.InlineAction.Title
  163. }
  164. }
  165. func (cfg *Config) inlineActionExists(action *Action) bool {
  166. if cfg.inlineActionPointerExists(action) {
  167. return true
  168. }
  169. if cfg.inlineActionIDExists(action) {
  170. return true
  171. }
  172. return false
  173. }
  174. func (cfg *Config) inlineActionPointerExists(action *Action) bool {
  175. return slices.Contains(cfg.Actions, action)
  176. }
  177. func (cfg *Config) inlineActionIDExists(action *Action) bool {
  178. if action.ID == "" {
  179. return false
  180. }
  181. for _, existingAction := range cfg.Actions {
  182. if existingAction.ID == action.ID {
  183. return true
  184. }
  185. }
  186. return false
  187. }
  188. func (cfg *Config) sanitizeChildDashboardComponents(component *DashboardComponent, visited map[*DashboardComponent]bool) {
  189. for _, child := range component.Contents {
  190. if child.Entity == "" {
  191. child.Entity = component.Entity
  192. }
  193. cfg.sanitizeDashboardComponentForInlineActionsHelper(child, visited)
  194. }
  195. }
  196. func (cfg *Config) sanitizeLogLevel() {
  197. if logLevel, err := log.ParseLevel(cfg.LogLevel); err == nil {
  198. log.Info("Setting log level to ", logLevel)
  199. log.SetLevel(logLevel)
  200. }
  201. }
  202. func (action *Action) sanitize(cfg *Config) {
  203. if action.Timeout < 3 {
  204. action.Timeout = 3
  205. }
  206. action.ID = getActionID(action)
  207. action.Icon = lookupHTMLIcon(action.Icon, cfg.DefaultIconForActions)
  208. migrateActionOnClick(action)
  209. action.sanitizeJustification()
  210. action.reportUnknownOnClick(cfg)
  211. action.OnClick = sanitizeOnClick(action.OnClick, cfg)
  212. action.PopupOnStart = action.OnClick
  213. if action.MaxConcurrent < 1 {
  214. action.MaxConcurrent = 1
  215. }
  216. action.Groups = dedupeStrings(action.Groups)
  217. for idx := range action.Arguments {
  218. action.Arguments[idx].sanitize(action)
  219. }
  220. }
  221. func dedupeStrings(values []string) []string {
  222. seen := make(map[string]struct{}, len(values))
  223. out := make([]string, 0, len(values))
  224. for _, value := range values {
  225. out = appendUniqueString(out, seen, value)
  226. }
  227. return out
  228. }
  229. func appendUniqueString(out []string, seen map[string]struct{}, value string) []string {
  230. if value == "" {
  231. return out
  232. }
  233. if _, found := seen[value]; found {
  234. return out
  235. }
  236. seen[value] = struct{}{}
  237. return append(out, value)
  238. }
  239. const defaultActionGroupQueueSize = 5
  240. func (cfg *Config) sanitizeActionGroups() {
  241. for _, group := range cfg.ActionGroups {
  242. if group == nil {
  243. continue
  244. }
  245. if group.QueueSize <= 0 {
  246. group.QueueSize = defaultActionGroupQueueSize
  247. }
  248. group.Icon = lookupHTMLIcon(group.Icon, cfg.DefaultIconForActions)
  249. }
  250. }
  251. func (cfg *Config) sanitizeEntities() {
  252. for _, entityFile := range cfg.Entities {
  253. if entityFile == nil {
  254. continue
  255. }
  256. entityFile.Icon = lookupHTMLIcon(entityFile.Icon, "")
  257. sanitizeEntityProperties(entityFile)
  258. }
  259. }
  260. func sanitizeEntityProperties(entityFile *EntityFile) {
  261. for idx := range entityFile.Properties {
  262. if entityFile.Properties[idx].Title == "" {
  263. entityFile.Properties[idx].Title = entityFile.Properties[idx].Name
  264. }
  265. }
  266. }
  267. func (cfg *Config) sanitizeAuthRequireGuestsToLogin() {
  268. if cfg.AuthRequireGuestsToLogin {
  269. log.Infof("AuthRequireGuestsToLogin is enabled. All defaultPermissions will be set to false")
  270. cfg.DefaultPermissions.View = false
  271. cfg.DefaultPermissions.Exec = false
  272. cfg.DefaultPermissions.Logs = false
  273. cfg.DefaultPermissions.Kill = false
  274. }
  275. }
  276. func (cfg *Config) sanitizeLogHistoryPageSize() {
  277. if cfg.LogHistoryPageSize < 10 {
  278. log.Warnf("LogsHistoryLimit is too low, setting it to 10")
  279. cfg.LogHistoryPageSize = 10
  280. } else if cfg.LogHistoryPageSize > 100 {
  281. log.Warnf("LogsHistoryLimit is high, you can do this, but expect browser lag.")
  282. }
  283. }
  284. func (cfg *Config) sanitizeLocalUsers() {
  285. for _, user := range cfg.AuthLocalUsers.Users {
  286. expandLocalUserEnvTemplates(user)
  287. }
  288. if err := validateUniqueLocalUserAPIKeys(cfg.AuthLocalUsers.Users); err != nil {
  289. log.Fatalf("%v", err)
  290. }
  291. }
  292. func expandLocalUserEnvTemplates(user *LocalUser) {
  293. if user == nil {
  294. return
  295. }
  296. if user.Password != "" {
  297. user.Password = expandEnvTemplate(user.Password)
  298. }
  299. if user.ApiKey != "" {
  300. user.ApiKey = expandEnvTemplate(user.ApiKey)
  301. }
  302. }
  303. // validateUniqueLocalUserAPIKeys returns an error when two local users share the same non-empty apiKey.
  304. func validateUniqueLocalUserAPIKeys(users []*LocalUser) error {
  305. seen := make(map[string]string)
  306. for _, user := range users {
  307. if err := recordUniqueLocalUserAPIKey(seen, user); err != nil {
  308. return err
  309. }
  310. }
  311. return nil
  312. }
  313. func recordUniqueLocalUserAPIKey(seen map[string]string, user *LocalUser) error {
  314. if user == nil || user.ApiKey == "" {
  315. return nil
  316. }
  317. if prior, ok := seen[user.ApiKey]; ok {
  318. return fmt.Errorf("duplicate authLocalUsers apiKey for users %q and %q", prior, user.Username)
  319. }
  320. seen[user.ApiKey] = user.Username
  321. return nil
  322. }
  323. func (cfg *Config) sanitizeSecurityHeaders() {
  324. cfg.sanitizeSecurityHeadersCSP()
  325. cfg.sanitizeSecurityHeadersXFrameOptions()
  326. }
  327. func (cfg *Config) sanitizeSecurityHeadersCSP() {
  328. if !cfg.Security.HeaderContentSecurityPolicy || cfg.Security.ContentSecurityPolicy != "" {
  329. return
  330. }
  331. cfg.Security.ContentSecurityPolicy = ContentSecurityPolicyDefault
  332. }
  333. func (cfg *Config) sanitizeSecurityHeadersXFrameOptions() {
  334. if !cfg.Security.HeaderXFrameOptions || cfg.Security.XFrameOptions != "" {
  335. return
  336. }
  337. cfg.Security.XFrameOptions = "DENY"
  338. }
  339. // expandEnvTemplate expands {{ .Env.VAR }} in config strings using the process environment.
  340. func expandEnvTemplate(source string) string {
  341. t, err := template.New("envTemplate").Option("missingkey=error").Parse(source)
  342. if err != nil {
  343. log.WithFields(log.Fields{"error": err}).Debug("Env template parse failed, using literal")
  344. return source
  345. }
  346. var b strings.Builder
  347. if err := t.Execute(&b, map[string]any{"Env": env.BuildEnvMap()}); err != nil {
  348. log.WithFields(log.Fields{"error": err}).Debug("Env template execute failed, using literal")
  349. return source
  350. }
  351. return b.String()
  352. }
  353. func getActionID(action *Action) string {
  354. if action.ID == "" {
  355. return uuid.NewString()
  356. }
  357. if strings.Contains(action.ID, "{{") {
  358. log.Fatalf("Action IDs cannot contain variables")
  359. }
  360. return action.ID
  361. }
  362. // onClickModes are the onclick values that change how an action behaves.
  363. var onClickModes = []string{
  364. "execution-dialog",
  365. "execution-dialog-output-html",
  366. "execution-dialog-stdout-only",
  367. "execution-button",
  368. "history",
  369. }
  370. // onClickDefaultAliases are accepted values that mean "use the default behaviour".
  371. var onClickDefaultAliases = []string{
  372. "",
  373. "default",
  374. "nothing",
  375. }
  376. func isKnownOnClick(value string) bool {
  377. return slices.Contains(onClickModes, value) || slices.Contains(onClickDefaultAliases, value)
  378. }
  379. func sanitizeOnClick(raw string, cfg *Config) string {
  380. if slices.Contains(onClickModes, raw) {
  381. return raw
  382. }
  383. return cfg.DefaultOnClick
  384. }
  385. func (action *Action) reportUnknownOnClick(cfg *Config) {
  386. // On a second sanitize pass, an action's onclick may already hold the
  387. // (separately reported) defaultOnClick value.
  388. if isKnownOnClick(action.OnClick) || action.OnClick == cfg.DefaultOnClick {
  389. return
  390. }
  391. configissues.ReportSticky(configissues.Issue{
  392. Severity: configissues.SeverityWarning,
  393. Code: configissues.CodeOnClickUnknown,
  394. Message: fmt.Sprintf("Unknown onclick value %q, using defaultOnClick (%q) instead", action.OnClick, cfg.DefaultOnClick),
  395. ActionID: action.ID,
  396. ActionTitle: action.Title,
  397. Source: action.OnClick,
  398. ConfigFile: action.SourceFile,
  399. })
  400. }
  401. func (cfg *Config) reportUnknownDefaultOnClick() {
  402. if isKnownOnClick(cfg.DefaultOnClick) {
  403. return
  404. }
  405. configissues.ReportSticky(configissues.Issue{
  406. Severity: configissues.SeverityWarning,
  407. Code: configissues.CodeOnClickUnknown,
  408. Message: fmt.Sprintf("Unknown defaultOnClick value %q, actions will behave as if it were \"nothing\"", cfg.DefaultOnClick),
  409. Source: cfg.DefaultOnClick,
  410. })
  411. }
  412. func migrateActionOnClick(action *Action) {
  413. if action.OnClick == "" && action.PopupOnStart != "" {
  414. action.OnClick = action.PopupOnStart
  415. }
  416. }
  417. func (action *Action) sanitizeJustification() {
  418. switch action.Justification {
  419. case "false":
  420. action.Justification = ""
  421. case "true":
  422. action.Justification = JustificationRequiredNoTemplate
  423. }
  424. }
  425. func shouldMigrateDefaultOnClickFromPopup(onClick, popupOnStart string) bool {
  426. if popupOnStart == "" {
  427. return false
  428. }
  429. if onClick == "" {
  430. return true
  431. }
  432. return onClick == "nothing" && popupOnStart != "nothing"
  433. }
  434. func (cfg *Config) migrateDefaultOnClickFromLegacyPopup() {
  435. if !shouldMigrateDefaultOnClickFromPopup(cfg.DefaultOnClick, cfg.DefaultPopupOnStart) {
  436. return
  437. }
  438. cfg.DefaultOnClick = cfg.DefaultPopupOnStart
  439. }
  440. func (cfg *Config) sanitizeOnClickDefaults() {
  441. cfg.migrateDefaultOnClickFromLegacyPopup()
  442. if cfg.DefaultOnClick == "" {
  443. cfg.DefaultOnClick = "nothing"
  444. }
  445. cfg.reportUnknownDefaultOnClick()
  446. cfg.DefaultPopupOnStart = cfg.DefaultOnClick
  447. }
  448. func (arg *ActionArgument) sanitize(action *Action) {
  449. if arg.Title == "" {
  450. arg.Title = arg.Name
  451. }
  452. for idx, choice := range arg.Choices {
  453. if choice.Title == "" {
  454. arg.Choices[idx].Title = choice.Value
  455. }
  456. }
  457. arg.sanitizeNoType(action)
  458. // Checklist configuration problems are reported by configcheck.
  459. }
  460. func (arg *ActionArgument) sanitizeNoType(action *Action) {
  461. if len(arg.Choices) == 0 && arg.Type == "" {
  462. issue := configissues.Issue{
  463. Severity: configissues.SeverityWarning,
  464. Code: configissues.CodeArgTypeUnset,
  465. Message: "Argument type isn't set, will default to 'ascii' but this may not be safe",
  466. ArgumentName: arg.Name,
  467. }
  468. if action != nil {
  469. issue.ActionID = action.ID
  470. issue.ActionTitle = action.Title
  471. issue.ConfigFile = action.SourceFile
  472. }
  473. configissues.ReportSticky(issue)
  474. arg.Type = "ascii"
  475. }
  476. }