| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591 |
- package config
- import (
- "fmt"
- "slices"
- "strings"
- "text/template"
- "github.com/OliveTin/OliveTin/internal/configissues"
- "github.com/OliveTin/OliveTin/internal/env"
- "github.com/google/uuid"
- log "github.com/sirupsen/logrus"
- )
- // Sanitize will look for common configuration issues, and fix them. For example,
- // populating undefined fields - name -> title, etc.
- func (cfg *Config) Sanitize() {
- cfg.sanitizeLogLevel()
- cfg.sanitizeAuthRequireGuestsToLogin()
- cfg.sanitizeLogHistoryPageSize()
- cfg.sanitizeLocalUsers()
- cfg.sanitizeSecurityHeaders()
- cfg.sanitizeOnClickDefaults()
- // log.Infof("cfg %p", cfg)
- for idx := range cfg.Actions {
- cfg.Actions[idx].sanitize(cfg)
- }
- cfg.sanitizeDashboardsForInlineActions()
- cfg.sanitizeActionGroups()
- cfg.sanitizeEntities()
- if err := cfg.validateReservedActionArgumentNames(); err != nil {
- log.Fatalf("%v", err)
- }
- if err := cfg.validateChecklistChoiceValues(); err != nil {
- log.Fatalf("%v", err)
- }
- if err := cfg.validateEntityArgumentChoices(); err != nil {
- log.Fatalf("%v", err)
- }
- }
- func (cfg *Config) validateReservedActionArgumentNames() error {
- for _, action := range cfg.Actions {
- if err := action.validateReservedArgumentNames(); err != nil {
- return err
- }
- }
- return nil
- }
- func (action *Action) validateReservedArgumentNames() error {
- if action == nil {
- return nil
- }
- for _, arg := range action.Arguments {
- if strings.HasPrefix(arg.Name, ReservedArgumentNamePrefix) {
- return fmt.Errorf("action %q argument %q uses reserved prefix %q", action.Title, arg.Name, ReservedArgumentNamePrefix)
- }
- }
- return nil
- }
- func (cfg *Config) validateChecklistChoiceValues() error {
- for _, action := range cfg.Actions {
- if err := action.validateChecklistChoiceValues(); err != nil {
- return err
- }
- }
- return nil
- }
- func (action *Action) validateChecklistChoiceValues() error {
- if action == nil {
- return nil
- }
- for _, arg := range action.Arguments {
- if err := validateChecklistChoicesForArgument(action.Title, arg); err != nil {
- return err
- }
- }
- return nil
- }
- func validateChecklistChoicesForArgument(actionTitle string, arg ActionArgument) error {
- if arg.Type != "checklist" {
- return nil
- }
- for _, choice := range arg.Choices {
- if strings.TrimSpace(choice.Value) == "" {
- return fmt.Errorf(
- `action %q argument %q choice value must not be empty`,
- actionTitle,
- arg.Name,
- )
- }
- }
- return nil
- }
- func (cfg *Config) validateEntityArgumentChoices() error {
- for _, action := range cfg.Actions {
- if err := action.validateEntityArgumentChoices(); err != nil {
- return err
- }
- }
- return nil
- }
- func (action *Action) validateEntityArgumentChoices() error {
- if action == nil {
- return nil
- }
- for _, arg := range action.Arguments {
- if err := validateEntityArgumentChoicesForArgument(action.Title, arg); err != nil {
- return err
- }
- }
- return nil
- }
- func validateEntityArgumentChoicesForArgument(actionTitle string, arg ActionArgument) error {
- if arg.Entity == "" || len(arg.Choices) == 1 {
- return nil
- }
- return fmt.Errorf(
- `action %q argument %q with entity must define exactly one choice template`,
- actionTitle,
- arg.Name,
- )
- }
- func (cfg *Config) sanitizeDashboardsForInlineActions() {
- for _, dashboard := range cfg.Dashboards {
- cfg.sanitizeDashboardComponentForInlineActions(dashboard)
- }
- }
- func (cfg *Config) sanitizeDashboardComponentForInlineActions(component *DashboardComponent) {
- visited := make(map[*DashboardComponent]bool)
- cfg.sanitizeDashboardComponentForInlineActionsHelper(component, visited)
- }
- func (cfg *Config) sanitizeDashboardComponentForInlineActionsHelper(component *DashboardComponent, visited map[*DashboardComponent]bool) {
- if component == nil {
- return
- }
- if visited[component] {
- return
- }
- visited[component] = true
- cfg.sanitizeInlineAction(component)
- cfg.sanitizeChildDashboardComponents(component, visited)
- }
- func (cfg *Config) sanitizeInlineAction(component *DashboardComponent) {
- if component.InlineAction == nil {
- return
- }
- sanitizeInlineActionTitles(component)
- if component.Entity != "" && component.InlineAction.Entity == "" {
- component.InlineAction.Entity = component.Entity
- }
- component.InlineAction.sanitize(cfg)
- cfg.addInlineActionIfNotExists(component.InlineAction)
- }
- func (cfg *Config) addInlineActionIfNotExists(action *Action) {
- if cfg.inlineActionExists(action) {
- return
- }
- cfg.Actions = append(cfg.Actions, action)
- }
- func sanitizeInlineActionTitles(component *DashboardComponent) {
- if component.InlineAction.Title == "" {
- component.InlineAction.Title = component.Title
- }
- if component.Title == "" {
- component.Title = component.InlineAction.Title
- }
- }
- func (cfg *Config) inlineActionExists(action *Action) bool {
- if cfg.inlineActionPointerExists(action) {
- return true
- }
- if cfg.inlineActionIDExists(action) {
- return true
- }
- return false
- }
- func (cfg *Config) inlineActionPointerExists(action *Action) bool {
- return slices.Contains(cfg.Actions, action)
- }
- func (cfg *Config) inlineActionIDExists(action *Action) bool {
- if action.ID == "" {
- return false
- }
- for _, existingAction := range cfg.Actions {
- if existingAction.ID == action.ID {
- return true
- }
- }
- return false
- }
- func (cfg *Config) sanitizeChildDashboardComponents(component *DashboardComponent, visited map[*DashboardComponent]bool) {
- for _, child := range component.Contents {
- if child.Entity == "" {
- child.Entity = component.Entity
- }
- cfg.sanitizeDashboardComponentForInlineActionsHelper(child, visited)
- }
- }
- func (cfg *Config) sanitizeLogLevel() {
- if logLevel, err := log.ParseLevel(cfg.LogLevel); err == nil {
- log.Info("Setting log level to ", logLevel)
- log.SetLevel(logLevel)
- }
- }
- func (action *Action) sanitize(cfg *Config) {
- if action.Timeout < 3 {
- action.Timeout = 3
- }
- action.ID = getActionID(action)
- action.Icon = lookupHTMLIcon(action.Icon, cfg.DefaultIconForActions)
- migrateActionOnClick(action)
- action.sanitizeJustification()
- action.reportUnknownOnClick(cfg)
- action.OnClick = sanitizeOnClick(action.OnClick, cfg)
- action.PopupOnStart = action.OnClick
- if action.MaxConcurrent < 1 {
- action.MaxConcurrent = 1
- }
- action.Groups = dedupeStrings(action.Groups)
- for idx := range action.Arguments {
- action.Arguments[idx].sanitize(action)
- }
- }
- func dedupeStrings(values []string) []string {
- seen := make(map[string]struct{}, len(values))
- out := make([]string, 0, len(values))
- for _, value := range values {
- out = appendUniqueString(out, seen, value)
- }
- return out
- }
- func appendUniqueString(out []string, seen map[string]struct{}, value string) []string {
- if value == "" {
- return out
- }
- if _, found := seen[value]; found {
- return out
- }
- seen[value] = struct{}{}
- return append(out, value)
- }
- const defaultActionGroupQueueSize = 5
- func (cfg *Config) sanitizeActionGroups() {
- for _, group := range cfg.ActionGroups {
- if group == nil {
- continue
- }
- if group.QueueSize <= 0 {
- group.QueueSize = defaultActionGroupQueueSize
- }
- group.Icon = lookupHTMLIcon(group.Icon, cfg.DefaultIconForActions)
- }
- }
- func (cfg *Config) sanitizeEntities() {
- for _, entityFile := range cfg.Entities {
- if entityFile == nil {
- continue
- }
- entityFile.Icon = lookupHTMLIcon(entityFile.Icon, "")
- sanitizeEntityProperties(entityFile)
- }
- }
- func sanitizeEntityProperties(entityFile *EntityFile) {
- for idx := range entityFile.Properties {
- if entityFile.Properties[idx].Title == "" {
- entityFile.Properties[idx].Title = entityFile.Properties[idx].Name
- }
- }
- }
- func (cfg *Config) sanitizeAuthRequireGuestsToLogin() {
- if cfg.AuthRequireGuestsToLogin {
- log.Infof("AuthRequireGuestsToLogin is enabled. All defaultPermissions will be set to false")
- cfg.DefaultPermissions.View = false
- cfg.DefaultPermissions.Exec = false
- cfg.DefaultPermissions.Logs = false
- cfg.DefaultPermissions.Kill = false
- }
- }
- func (cfg *Config) sanitizeLogHistoryPageSize() {
- if cfg.LogHistoryPageSize < 10 {
- log.Warnf("LogsHistoryLimit is too low, setting it to 10")
- cfg.LogHistoryPageSize = 10
- } else if cfg.LogHistoryPageSize > 100 {
- log.Warnf("LogsHistoryLimit is high, you can do this, but expect browser lag.")
- }
- }
- func (cfg *Config) sanitizeLocalUsers() {
- for _, user := range cfg.AuthLocalUsers.Users {
- expandLocalUserEnvTemplates(user)
- }
- if err := validateUniqueLocalUserAPIKeys(cfg.AuthLocalUsers.Users); err != nil {
- log.Fatalf("%v", err)
- }
- }
- func expandLocalUserEnvTemplates(user *LocalUser) {
- if user == nil {
- return
- }
- if user.Password != "" {
- user.Password = expandEnvTemplate(user.Password)
- }
- if user.ApiKey != "" {
- user.ApiKey = expandEnvTemplate(user.ApiKey)
- }
- }
- // validateUniqueLocalUserAPIKeys returns an error when two local users share the same non-empty apiKey.
- func validateUniqueLocalUserAPIKeys(users []*LocalUser) error {
- seen := make(map[string]string)
- for _, user := range users {
- if err := recordUniqueLocalUserAPIKey(seen, user); err != nil {
- return err
- }
- }
- return nil
- }
- func recordUniqueLocalUserAPIKey(seen map[string]string, user *LocalUser) error {
- if user == nil || user.ApiKey == "" {
- return nil
- }
- if prior, ok := seen[user.ApiKey]; ok {
- return fmt.Errorf("duplicate authLocalUsers apiKey for users %q and %q", prior, user.Username)
- }
- seen[user.ApiKey] = user.Username
- return nil
- }
- func (cfg *Config) sanitizeSecurityHeaders() {
- cfg.sanitizeSecurityHeadersCSP()
- cfg.sanitizeSecurityHeadersXFrameOptions()
- }
- func (cfg *Config) sanitizeSecurityHeadersCSP() {
- if !cfg.Security.HeaderContentSecurityPolicy || cfg.Security.ContentSecurityPolicy != "" {
- return
- }
- cfg.Security.ContentSecurityPolicy = ContentSecurityPolicyDefault
- }
- func (cfg *Config) sanitizeSecurityHeadersXFrameOptions() {
- if !cfg.Security.HeaderXFrameOptions || cfg.Security.XFrameOptions != "" {
- return
- }
- cfg.Security.XFrameOptions = "DENY"
- }
- // expandEnvTemplate expands {{ .Env.VAR }} in config strings using the process environment.
- func expandEnvTemplate(source string) string {
- t, err := template.New("envTemplate").Option("missingkey=error").Parse(source)
- if err != nil {
- log.WithFields(log.Fields{"error": err}).Debug("Env template parse failed, using literal")
- return source
- }
- var b strings.Builder
- if err := t.Execute(&b, map[string]any{"Env": env.BuildEnvMap()}); err != nil {
- log.WithFields(log.Fields{"error": err}).Debug("Env template execute failed, using literal")
- return source
- }
- return b.String()
- }
- func getActionID(action *Action) string {
- if action.ID == "" {
- return uuid.NewString()
- }
- if strings.Contains(action.ID, "{{") {
- log.Fatalf("Action IDs cannot contain variables")
- }
- return action.ID
- }
- // onClickModes are the onclick values that change how an action behaves.
- var onClickModes = []string{
- "execution-dialog",
- "execution-dialog-output-html",
- "execution-dialog-stdout-only",
- "execution-button",
- "history",
- }
- // onClickDefaultAliases are accepted values that mean "use the default behaviour".
- var onClickDefaultAliases = []string{
- "",
- "default",
- "nothing",
- }
- func isKnownOnClick(value string) bool {
- return slices.Contains(onClickModes, value) || slices.Contains(onClickDefaultAliases, value)
- }
- func sanitizeOnClick(raw string, cfg *Config) string {
- if slices.Contains(onClickModes, raw) {
- return raw
- }
- return cfg.DefaultOnClick
- }
- func (action *Action) reportUnknownOnClick(cfg *Config) {
- // On a second sanitize pass, an action's onclick may already hold the
- // (separately reported) defaultOnClick value.
- if isKnownOnClick(action.OnClick) || action.OnClick == cfg.DefaultOnClick {
- return
- }
- configissues.ReportSticky(configissues.Issue{
- Severity: configissues.SeverityWarning,
- Code: configissues.CodeOnClickUnknown,
- Message: fmt.Sprintf("Unknown onclick value %q, using defaultOnClick (%q) instead", action.OnClick, cfg.DefaultOnClick),
- ActionID: action.ID,
- ActionTitle: action.Title,
- Source: action.OnClick,
- ConfigFile: action.SourceFile,
- })
- }
- func (cfg *Config) reportUnknownDefaultOnClick() {
- if isKnownOnClick(cfg.DefaultOnClick) {
- return
- }
- configissues.ReportSticky(configissues.Issue{
- Severity: configissues.SeverityWarning,
- Code: configissues.CodeOnClickUnknown,
- Message: fmt.Sprintf("Unknown defaultOnClick value %q, actions will behave as if it were \"nothing\"", cfg.DefaultOnClick),
- Source: cfg.DefaultOnClick,
- })
- }
- func migrateActionOnClick(action *Action) {
- if action.OnClick == "" && action.PopupOnStart != "" {
- action.OnClick = action.PopupOnStart
- }
- }
- func (action *Action) sanitizeJustification() {
- switch action.Justification {
- case "false":
- action.Justification = ""
- case "true":
- action.Justification = JustificationRequiredNoTemplate
- }
- }
- func shouldMigrateDefaultOnClickFromPopup(onClick, popupOnStart string) bool {
- if popupOnStart == "" {
- return false
- }
- if onClick == "" {
- return true
- }
- return onClick == "nothing" && popupOnStart != "nothing"
- }
- func (cfg *Config) migrateDefaultOnClickFromLegacyPopup() {
- if !shouldMigrateDefaultOnClickFromPopup(cfg.DefaultOnClick, cfg.DefaultPopupOnStart) {
- return
- }
- cfg.DefaultOnClick = cfg.DefaultPopupOnStart
- }
- func (cfg *Config) sanitizeOnClickDefaults() {
- cfg.migrateDefaultOnClickFromLegacyPopup()
- if cfg.DefaultOnClick == "" {
- cfg.DefaultOnClick = "nothing"
- }
- cfg.reportUnknownDefaultOnClick()
- cfg.DefaultPopupOnStart = cfg.DefaultOnClick
- }
- func (arg *ActionArgument) sanitize(action *Action) {
- if arg.Title == "" {
- arg.Title = arg.Name
- }
- for idx, choice := range arg.Choices {
- if choice.Title == "" {
- arg.Choices[idx].Title = choice.Value
- }
- }
- arg.sanitizeNoType(action)
- // Checklist configuration problems are reported by configcheck.
- }
- func (arg *ActionArgument) sanitizeNoType(action *Action) {
- if len(arg.Choices) == 0 && arg.Type == "" {
- issue := configissues.Issue{
- Severity: configissues.SeverityWarning,
- Code: configissues.CodeArgTypeUnset,
- Message: "Argument type isn't set, will default to 'ascii' but this may not be safe",
- ArgumentName: arg.Name,
- }
- if action != nil {
- issue.ActionID = action.ID
- issue.ActionTitle = action.Title
- issue.ConfigFile = action.SourceFile
- }
- configissues.ReportSticky(issue)
- arg.Type = "ascii"
- }
- }
|