arguments.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. package executor
  2. import (
  3. config "github.com/OliveTin/OliveTin/internal/config"
  4. "github.com/OliveTin/OliveTin/internal/entities"
  5. "github.com/OliveTin/OliveTin/internal/tpl"
  6. log "github.com/sirupsen/logrus"
  7. "fmt"
  8. "net/mail"
  9. "net/url"
  10. "regexp"
  11. "strings"
  12. "time"
  13. )
  14. var (
  15. typecheckRegex = map[string]string{
  16. "very_dangerous_raw_string": "",
  17. "int": `^\d+$`,
  18. "unicode_identifier": `^[\w\-\.\_\d]+$`,
  19. "ascii": `^[a-zA-Z0-9]+$`,
  20. "ascii_identifier": `^[a-zA-Z0-9\-\._]+$`,
  21. "shell_safe_identifier": `^[a-zA-Z0-9@\.\_\+\-]+$`,
  22. "ascii_sentence": `^[a-zA-Z0-9\-\._, ]+$`,
  23. }
  24. )
  25. // parseExecArray parses all exec arguments in the action.
  26. func parseExecArray(action *config.Action, values map[string]string, entity *entities.Entity) ([]string, error) {
  27. parsed := make([]string, len(action.Exec))
  28. for i, segment := range action.Exec {
  29. out, err := parseExecSegment(segment, values, entity)
  30. if err != nil {
  31. return nil, err
  32. }
  33. parsed[i] = out
  34. }
  35. return parsed, nil
  36. }
  37. func parseActionExec(values map[string]string, action *config.Action, entity *entities.Entity) ([]string, error) {
  38. if action == nil {
  39. return nil, fmt.Errorf("action is nil")
  40. }
  41. if err := validateArguments(values, action); err != nil {
  42. return nil, err
  43. }
  44. parsed, err := parseExecArray(action, values, entity)
  45. if err != nil {
  46. return nil, err
  47. }
  48. logParsedExec(action, parsed, values)
  49. return parsed, nil
  50. }
  51. func parseExecSegment(arg string, values map[string]string, entity *entities.Entity) (string, error) {
  52. return tpl.ParseTemplateWithActionContext(arg, entity, values)
  53. }
  54. func validateArguments(values map[string]string, action *config.Action) error {
  55. for _, arg := range action.Arguments {
  56. if err := typecheckActionArgument(&arg, values[arg.Name], action); err != nil {
  57. return err
  58. }
  59. log.WithFields(log.Fields{"name": arg.Name, "value": values[arg.Name]}).Debugf("Arg assigned")
  60. }
  61. return nil
  62. }
  63. func logParsedExec(action *config.Action, parsed []string, values map[string]string) {
  64. redacted := redactExecArgs(parsed, action.Arguments, values)
  65. log.WithFields(log.Fields{"actionTitle": action.Title, "cmd": redacted}).Infof("Action parse args - After (Exec)")
  66. }
  67. func parseActionArguments(req *ExecutionRequest) (string, error) {
  68. log.WithFields(log.Fields{
  69. "actionTitle": req.Binding.Action.Title,
  70. "cmd": req.Binding.Action.Shell,
  71. }).Infof("Action parse args - Before")
  72. for _, arg := range req.Binding.Action.Arguments {
  73. argName := arg.Name
  74. argValue := req.Arguments[argName]
  75. err := typecheckActionArgument(&arg, argValue, req.Binding.Action)
  76. if err != nil {
  77. return "", err
  78. }
  79. log.WithFields(log.Fields{
  80. "name": argName,
  81. "value": argValue,
  82. }).Debugf("Arg assigned")
  83. }
  84. parsedShellCommand, err := tpl.ParseTemplateWithActionContext(req.Binding.Action.Shell, req.Binding.Entity, req.Arguments)
  85. if err != nil {
  86. return "", err
  87. }
  88. redactedShellCommand := redactShellCommand(parsedShellCommand, req.Binding.Action.Arguments, req.Arguments)
  89. log.WithFields(log.Fields{
  90. "actionTitle": req.Binding.Action.Title,
  91. "cmd": redactedShellCommand,
  92. }).Infof("Action parse args - After")
  93. return parsedShellCommand, nil
  94. }
  95. //gocyclo:ignore
  96. func redactShellCommand(shellCommand string, arguments []config.ActionArgument, argumentValues map[string]string) string {
  97. for _, arg := range arguments {
  98. if arg.Type == "password" {
  99. argValue, exists := argumentValues[arg.Name]
  100. if !exists {
  101. log.Warnf("Redact shell command: Argument %s not found in values", arg.Name)
  102. continue
  103. }
  104. if argValue == "" {
  105. continue
  106. }
  107. shellCommand = strings.ReplaceAll(shellCommand, argValue, "<redacted>")
  108. }
  109. }
  110. return shellCommand
  111. }
  112. //gocyclo:ignore
  113. func redactExecArgs(execArgs []string, arguments []config.ActionArgument, argumentValues map[string]string) []string {
  114. redacted := make([]string, len(execArgs))
  115. for i, arg := range execArgs {
  116. redacted[i] = redactShellCommand(arg, arguments, argumentValues)
  117. }
  118. return redacted
  119. }
  120. func typecheckActionArgument(arg *config.ActionArgument, value string, action *config.Action) error {
  121. if arg.Type == "confirmation" {
  122. return nil
  123. }
  124. if arg.Name == "" {
  125. return fmt.Errorf("argument name cannot be empty")
  126. }
  127. return typecheckActionArgumentFound(value, arg)
  128. }
  129. // ValidateArgument validates a single argument value using the same logic as the executor.
  130. // It applies mangling transformations and performs full validation including null checks,
  131. // choice validation, and type safety checks.
  132. func ValidateArgument(arg *config.ActionArgument, value string, action *config.Action) error {
  133. if arg == nil {
  134. return fmt.Errorf("ValidateArgument: arg is nil")
  135. }
  136. if action == nil {
  137. return fmt.Errorf("ValidateArgument: action is nil")
  138. }
  139. // Apply mangling transformations
  140. mangledValue := MangleArgumentValue(arg, value, action.Title)
  141. // Use the same validation path as the executor
  142. return typecheckActionArgument(arg, mangledValue, action)
  143. }
  144. func typecheckActionArgumentFound(value string, arg *config.ActionArgument) error {
  145. if value == "" {
  146. return typecheckNull(arg)
  147. }
  148. if len(arg.Choices) > 0 {
  149. return typecheckChoice(value, arg)
  150. }
  151. return TypeSafetyCheck(arg.Name, value, arg.Type)
  152. }
  153. // TypeSafetyCheck checks argument values match a specific type. The types are
  154. // defined in typecheckRegex, and, you guessed it, uses regex to check for allowed
  155. // characters.
  156. //
  157. //gocyclo:ignore
  158. func TypeSafetyCheck(name string, value string, argumentType string) error {
  159. switch argumentType {
  160. case "password":
  161. return nil
  162. case "raw_string_multiline":
  163. return nil
  164. case "checkbox":
  165. return nil
  166. case "email":
  167. return typeSafetyCheckEmail(value)
  168. case "url":
  169. return typeSafetyCheckUrl(value)
  170. case "datetime":
  171. return typeSafetyCheckDatetime(value)
  172. }
  173. return typeSafetyCheckRegex(name, value, argumentType)
  174. }
  175. func typecheckNull(arg *config.ActionArgument) error {
  176. if arg.RejectNull {
  177. return fmt.Errorf("null values are not allowed")
  178. }
  179. return nil
  180. }
  181. func typecheckChoice(value string, arg *config.ActionArgument) error {
  182. if arg.Entity != "" {
  183. return typecheckChoiceEntity(value, arg)
  184. }
  185. for _, choice := range arg.Choices {
  186. if value == choice.Value {
  187. return nil
  188. }
  189. }
  190. return fmt.Errorf("argument value is not one of the predefined choices")
  191. }
  192. func typecheckChoiceEntity(value string, arg *config.ActionArgument) error {
  193. templateChoice := arg.Choices[0].Value
  194. for _, ent := range entities.GetEntityInstances(arg.Entity) {
  195. choice := tpl.ParseTemplateOfActionBeforeExec(templateChoice, ent)
  196. if value == choice {
  197. return nil
  198. }
  199. }
  200. return fmt.Errorf("argument value cannot be found in entities")
  201. }
  202. func typeSafetyCheckEmail(value string) error {
  203. _, err := mail.ParseAddress(value)
  204. if err != nil {
  205. log.WithField("type", "email").Debugf("Email argument type check failed")
  206. return err
  207. }
  208. return nil
  209. }
  210. func typeSafetyCheckDatetime(value string) error {
  211. _, err := time.Parse("2006-01-02T15:04:05", value)
  212. if err != nil {
  213. return err
  214. }
  215. return nil
  216. }
  217. func typeSafetyCheckRegex(name string, value string, argumentType string) error {
  218. pattern := ""
  219. if strings.HasPrefix(argumentType, "regex:") {
  220. pattern = strings.Replace(argumentType, "regex:", "", 1)
  221. } else {
  222. found := false
  223. pattern, found = typecheckRegex[argumentType]
  224. if !found {
  225. return fmt.Errorf("argument type not implemented %v for arg: %v", argumentType, name)
  226. }
  227. }
  228. matches, _ := regexp.MatchString(pattern, value)
  229. if !matches {
  230. log.WithFields(log.Fields{
  231. "name": name,
  232. "value": value,
  233. "type": argumentType,
  234. "pattern": pattern,
  235. }).Warn("Arg type check safety failure")
  236. return fmt.Errorf("invalid argument %v, doesn't match %v", name, argumentType)
  237. }
  238. return nil
  239. }
  240. func typeSafetyCheckUrl(value string) error {
  241. _, err := url.ParseRequestURI(value)
  242. return err
  243. }
  244. func checkShellArgumentSafety(action *config.Action) error {
  245. if action.Shell == "" {
  246. return nil
  247. }
  248. unsafe := map[string]struct{}{"url": {}, "email": {}, "raw_string_multiline": {}, "very_dangerous_raw_string": {}, "password": {}}
  249. for _, arg := range action.Arguments {
  250. if _, bad := unsafe[arg.Type]; bad {
  251. return fmt.Errorf("unsafe argument type '%s' cannot be used with Shell execution. Use 'exec' instead. See https://docs.olivetin.app/action_execution/shellvsexec.html", arg.Type)
  252. }
  253. }
  254. return nil
  255. }
  256. func mangleInvalidArgumentValues(req *ExecutionRequest) {
  257. for _, arg := range req.Binding.Action.Arguments {
  258. if arg.Type == "datetime" {
  259. mangleInvalidDatetimeValues(req, &arg)
  260. }
  261. mangleCheckboxValues(req, &arg)
  262. }
  263. }
  264. func mangleCheckboxValues(req *ExecutionRequest, arg *config.ActionArgument) {
  265. if arg.Type != "checkbox" {
  266. return
  267. }
  268. log.Infof("Checking checkbox values for argument %s in action %s", arg.Name, req.Binding.Action.Title)
  269. for i, v := range arg.Choices {
  270. choice := &arg.Choices[i]
  271. if req.Arguments[arg.Name] == choice.Title {
  272. log.WithFields(log.Fields{
  273. "arg": arg.Name,
  274. "choice": v,
  275. "oldValue": req.Arguments[arg.Name],
  276. "newValue": choice.Value,
  277. "actionTitle": req.Binding.Action.Title,
  278. }).Infof("Mangled checkbox value")
  279. req.Arguments[arg.Name] = choice.Value
  280. }
  281. }
  282. }
  283. func mangleInvalidDatetimeValues(req *ExecutionRequest, arg *config.ActionArgument) {
  284. value, exists := req.Arguments[arg.Name]
  285. if !exists || value == "" {
  286. return
  287. }
  288. timestamp, err := time.Parse("2006-01-02T15:04", value)
  289. if err == nil {
  290. log.WithFields(log.Fields{
  291. "arg": arg.Name,
  292. "value": value,
  293. "actionTitle": req.Binding.Action.Title,
  294. }).Warnf("Mangled invalid datetime value without seconds to :00 seconds, this issue is commonly caused by Android browsers.")
  295. req.Arguments[arg.Name] = timestamp.Format("2006-01-02T15:04:05")
  296. }
  297. }
  298. // MangleArgumentValue applies mangling transformations to a single argument value.
  299. // This is used by the validation API to ensure the value matches what would be
  300. // used during actual execution.
  301. func MangleArgumentValue(arg *config.ActionArgument, value string, actionTitle string) string {
  302. if arg == nil {
  303. log.Debugf("MangleArgumentValue called with nil arg, returning value unchanged")
  304. return value
  305. }
  306. if arg.Type == "datetime" {
  307. return mangleDatetimeValue(arg, value, actionTitle)
  308. }
  309. if arg.Type == "checkbox" {
  310. return mangleCheckboxValue(arg, value, actionTitle)
  311. }
  312. return value
  313. }
  314. func mangleDatetimeValue(arg *config.ActionArgument, value string, actionTitle string) string {
  315. if arg == nil {
  316. log.Debugf("mangleDatetimeValue called with nil arg, returning value unchanged")
  317. return value
  318. }
  319. if value == "" {
  320. return value
  321. }
  322. timestamp, err := time.Parse("2006-01-02T15:04", value)
  323. if err != nil {
  324. return value
  325. }
  326. log.WithFields(log.Fields{
  327. "arg": arg.Name,
  328. "value": value,
  329. "actionTitle": actionTitle,
  330. }).Warnf("Mangled invalid datetime value without seconds to :00 seconds, this issue is commonly caused by Android browsers.")
  331. return timestamp.Format("2006-01-02T15:04:05")
  332. }
  333. func mangleCheckboxValue(arg *config.ActionArgument, value string, actionTitle string) string {
  334. if arg == nil {
  335. log.Debugf("mangleCheckboxValue called with nil arg, returning value unchanged")
  336. return value
  337. }
  338. for _, choice := range arg.Choices {
  339. if value == choice.Title {
  340. log.WithFields(log.Fields{
  341. "arg": arg.Name,
  342. "oldValue": value,
  343. "newValue": choice.Value,
  344. "actionTitle": actionTitle,
  345. }).Infof("Mangled checkbox value")
  346. return choice.Value
  347. }
  348. }
  349. return value
  350. }