arguments.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. dnsNameLabelPattern = regexp.MustCompile(`^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`)
  25. dnsNameAllNumericPattern = regexp.MustCompile(`^[0-9]+$`)
  26. )
  27. // parseExecArray parses all exec arguments in the action.
  28. func parseExecArray(action *config.Action, values map[string]string, entity *entities.Entity) ([]string, error) {
  29. parsed := make([]string, len(action.Exec))
  30. for i, segment := range action.Exec {
  31. out, err := parseExecSegment(segment, values, entity)
  32. if err != nil {
  33. return nil, err
  34. }
  35. parsed[i] = out
  36. }
  37. return parsed, nil
  38. }
  39. func parseActionExec(values map[string]string, action *config.Action, entity *entities.Entity) ([]string, error) {
  40. if action == nil {
  41. return nil, fmt.Errorf("action is nil")
  42. }
  43. if err := validateArguments(values, action); err != nil {
  44. return nil, err
  45. }
  46. parsed, err := parseExecArray(action, values, entity)
  47. if err != nil {
  48. return nil, err
  49. }
  50. logParsedExec(action, parsed, values)
  51. return parsed, nil
  52. }
  53. func parseExecSegment(arg string, values map[string]string, entity *entities.Entity) (string, error) {
  54. return tpl.ParseTemplateWithActionContext(arg, entity, values)
  55. }
  56. func validateArguments(values map[string]string, action *config.Action) error {
  57. for _, arg := range action.Arguments {
  58. if err := typecheckActionArgument(&arg, values[arg.Name], action); err != nil {
  59. return err
  60. }
  61. log.WithFields(log.Fields{"name": arg.Name, "value": values[arg.Name]}).Debugf("Arg assigned")
  62. }
  63. return nil
  64. }
  65. func logParsedExec(action *config.Action, parsed []string, values map[string]string) {
  66. redacted := redactExecArgs(parsed, action.Arguments, values)
  67. log.WithFields(log.Fields{"actionTitle": action.Title, "cmd": redacted}).Infof("Action parse args - After (Exec)")
  68. }
  69. func parseActionArguments(req *ExecutionRequest) (string, error) {
  70. log.WithFields(log.Fields{
  71. "actionTitle": req.Binding.Action.Title,
  72. "cmd": req.Binding.Action.Shell,
  73. }).Infof("Action parse args - Before")
  74. for _, arg := range req.Binding.Action.Arguments {
  75. argName := arg.Name
  76. argValue := req.Arguments[argName]
  77. err := typecheckActionArgument(&arg, argValue, req.Binding.Action)
  78. if err != nil {
  79. return "", err
  80. }
  81. log.WithFields(log.Fields{
  82. "name": argName,
  83. "value": argValue,
  84. }).Debugf("Arg assigned")
  85. }
  86. parsedShellCommand, err := tpl.ParseTemplateWithActionContext(req.Binding.Action.Shell, req.Binding.Entity, req.Arguments)
  87. if err != nil {
  88. return "", err
  89. }
  90. redactedShellCommand := redactShellCommand(parsedShellCommand, req.Binding.Action.Arguments, req.Arguments)
  91. log.WithFields(log.Fields{
  92. "actionTitle": req.Binding.Action.Title,
  93. "cmd": redactedShellCommand,
  94. }).Infof("Action parse args - After")
  95. return parsedShellCommand, nil
  96. }
  97. //gocyclo:ignore
  98. func redactShellCommand(shellCommand string, arguments []config.ActionArgument, argumentValues map[string]string) string {
  99. for _, arg := range arguments {
  100. if arg.Type == "password" {
  101. argValue, exists := argumentValues[arg.Name]
  102. if !exists {
  103. log.Warnf("Redact shell command: Argument %s not found in values", arg.Name)
  104. continue
  105. }
  106. if argValue == "" {
  107. continue
  108. }
  109. shellCommand = strings.ReplaceAll(shellCommand, argValue, "<redacted>")
  110. }
  111. }
  112. return shellCommand
  113. }
  114. //gocyclo:ignore
  115. func redactExecArgs(execArgs []string, arguments []config.ActionArgument, argumentValues map[string]string) []string {
  116. redacted := make([]string, len(execArgs))
  117. for i, arg := range execArgs {
  118. redacted[i] = redactShellCommand(arg, arguments, argumentValues)
  119. }
  120. return redacted
  121. }
  122. func argumentSkipsValidation(arg *config.ActionArgument) bool {
  123. switch arg.Type {
  124. case "confirmation", "html":
  125. return true
  126. default:
  127. return false
  128. }
  129. }
  130. func typecheckActionArgument(arg *config.ActionArgument, value string, action *config.Action) error {
  131. if argumentSkipsValidation(arg) {
  132. return nil
  133. }
  134. if arg.Name == "" {
  135. return fmt.Errorf("argument name cannot be empty")
  136. }
  137. return typecheckActionArgumentFound(value, arg)
  138. }
  139. // ValidateArgument validates a single argument value using the same logic as the executor.
  140. // It applies mangling transformations and performs full validation including null checks,
  141. // choice validation, and type safety checks.
  142. func ValidateArgument(arg *config.ActionArgument, value string, action *config.Action) error {
  143. if arg == nil {
  144. return fmt.Errorf("ValidateArgument: arg is nil")
  145. }
  146. if action == nil {
  147. return fmt.Errorf("ValidateArgument: action is nil")
  148. }
  149. // Apply mangling transformations
  150. mangledValue := MangleArgumentValue(arg, value, action.Title)
  151. // Use the same validation path as the executor
  152. return typecheckActionArgument(arg, mangledValue, action)
  153. }
  154. func typecheckActionArgumentFound(value string, arg *config.ActionArgument) error {
  155. if value == "" {
  156. return typecheckNull(arg)
  157. }
  158. if arg.Type == "checklist" {
  159. return typecheckChecklist(value, arg)
  160. }
  161. if len(arg.Choices) > 0 {
  162. return typecheckChoice(value, arg)
  163. }
  164. return TypeSafetyCheck(arg.Name, value, arg.Type)
  165. }
  166. // TypeSafetyCheck checks argument values match a specific type. The types are
  167. // defined in typecheckRegex, and, you guessed it, uses regex to check for allowed
  168. // characters.
  169. //
  170. //gocyclo:ignore
  171. func TypeSafetyCheck(name string, value string, argumentType string) error {
  172. switch argumentType {
  173. case "password":
  174. return nil
  175. case "raw_string_multiline":
  176. return nil
  177. case "checkbox":
  178. return nil
  179. case "checklist":
  180. return nil
  181. case "email":
  182. return typeSafetyCheckEmail(value)
  183. case "url":
  184. return typeSafetyCheckUrl(value)
  185. case "datetime":
  186. return typeSafetyCheckDatetime(value)
  187. case "dnsname":
  188. return typeSafetyCheckDnsName(value)
  189. }
  190. return typeSafetyCheckRegex(name, value, argumentType)
  191. }
  192. func typecheckNull(arg *config.ActionArgument) error {
  193. if arg.RejectNull {
  194. return fmt.Errorf("null values are not allowed")
  195. }
  196. return nil
  197. }
  198. func typecheckChecklist(value string, arg *config.ActionArgument) error {
  199. if len(arg.Choices) == 0 {
  200. return fmt.Errorf("checklist argument %q requires choices", arg.Name)
  201. }
  202. segments, err := config.ParseChecklistValue(value)
  203. if err != nil {
  204. return err
  205. }
  206. return typecheckChecklistSegments(segments, arg)
  207. }
  208. func typecheckChecklistSegments(segments []string, arg *config.ActionArgument) error {
  209. for _, segment := range segments {
  210. if err := typecheckChecklistSegment(segment, arg); err != nil {
  211. return err
  212. }
  213. }
  214. return nil
  215. }
  216. func typecheckChecklistSegment(segment string, arg *config.ActionArgument) error {
  217. if segment == "" {
  218. return fmt.Errorf("checklist argument %q contains an empty segment", arg.Name)
  219. }
  220. return typecheckChoice(segment, arg)
  221. }
  222. func typecheckChoice(value string, arg *config.ActionArgument) error {
  223. if arg.Entity != "" {
  224. return typecheckChoiceEntity(value, arg)
  225. }
  226. for _, choice := range arg.Choices {
  227. if value == choice.Value {
  228. return nil
  229. }
  230. }
  231. return fmt.Errorf("argument value is not one of the predefined choices")
  232. }
  233. func typecheckChoiceEntity(value string, arg *config.ActionArgument) error {
  234. templateChoice := arg.Choices[0].Value
  235. for _, ent := range entities.GetEntityInstances(arg.Entity) {
  236. choice := tpl.ParseTemplateOfActionBeforeExec(templateChoice, ent)
  237. if value == choice {
  238. return nil
  239. }
  240. }
  241. return fmt.Errorf("argument value cannot be found in entities")
  242. }
  243. func typeSafetyCheckEmail(value string) error {
  244. _, err := mail.ParseAddress(value)
  245. if err != nil {
  246. log.WithField("type", "email").Debugf("Email argument type check failed")
  247. return err
  248. }
  249. return nil
  250. }
  251. // typeSafetyCheckDnsName validates a DNS hostname (RFC 1123 LDH labels).
  252. // Accepts short names (e.g. webserver) and FQDNs (e.g. webserver.example.com).
  253. // An optional trailing dot is allowed.
  254. func typeSafetyCheckDnsName(value string) error {
  255. hostname := strings.TrimSuffix(value, ".")
  256. if hostname == "" || len(hostname) > 253 {
  257. return fmt.Errorf("invalid dnsname length")
  258. }
  259. return typeSafetyCheckDnsNameLabels(strings.Split(hostname, "."))
  260. }
  261. func typeSafetyCheckDnsNameLabels(labels []string) error {
  262. for _, label := range labels {
  263. if !dnsNameLabelPattern.MatchString(label) {
  264. return fmt.Errorf("invalid dnsname label %q", label)
  265. }
  266. }
  267. tld := labels[len(labels)-1]
  268. if dnsNameAllNumericPattern.MatchString(tld) {
  269. return fmt.Errorf("dnsname top-level label must not be all-numeric")
  270. }
  271. return nil
  272. }
  273. func typeSafetyCheckDatetime(value string) error {
  274. _, err := time.Parse("2006-01-02T15:04:05", value)
  275. if err != nil {
  276. return err
  277. }
  278. return nil
  279. }
  280. func anchorCustomRegexPattern(pattern string) string {
  281. return "^(?:" + pattern + ")$"
  282. }
  283. func typeSafetyCheckRegex(name string, value string, argumentType string) error {
  284. pattern := ""
  285. isCustomRegex := strings.HasPrefix(argumentType, "regex:")
  286. if isCustomRegex {
  287. pattern = strings.TrimPrefix(argumentType, "regex:")
  288. pattern = anchorCustomRegexPattern(pattern)
  289. } else {
  290. found := false
  291. pattern, found = typecheckRegex[argumentType]
  292. if !found {
  293. return fmt.Errorf("argument type not implemented %v for arg: %v", argumentType, name)
  294. }
  295. }
  296. matches, _ := regexp.MatchString(pattern, value)
  297. if !matches {
  298. log.WithFields(log.Fields{
  299. "name": name,
  300. "value": value,
  301. "type": argumentType,
  302. "pattern": pattern,
  303. }).Warn("Arg type check safety failure")
  304. return fmt.Errorf("invalid argument %v, doesn't match %v", name, argumentType)
  305. }
  306. return nil
  307. }
  308. func typeSafetyCheckUrl(value string) error {
  309. parsed, err := url.ParseRequestURI(value)
  310. if err != nil {
  311. return err
  312. }
  313. scheme := strings.ToLower(parsed.Scheme)
  314. if scheme != "http" && scheme != "https" {
  315. return fmt.Errorf("url scheme %q is not allowed; only http and https are permitted", parsed.Scheme)
  316. }
  317. return nil
  318. }
  319. var shellUnsafeArgumentTypes = map[string]struct{}{
  320. "url": {},
  321. "email": {},
  322. "raw_string_multiline": {},
  323. "very_dangerous_raw_string": {},
  324. "password": {},
  325. "html": {},
  326. "confirmation": {},
  327. }
  328. func isUnsafeShellArgumentType(arg *config.ActionArgument) bool {
  329. if strings.HasPrefix(arg.Type, "regex:") {
  330. return true
  331. }
  332. _, inMap := shellUnsafeArgumentTypes[arg.Type]
  333. return inMap || (arg.Type == "checkbox" && len(arg.Choices) == 0)
  334. }
  335. func checkShellArgumentSafety(action *config.Action) error {
  336. if action.Shell == "" {
  337. return nil
  338. }
  339. for i := range action.Arguments {
  340. arg := &action.Arguments[i]
  341. if isUnsafeShellArgumentType(arg) {
  342. 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)
  343. }
  344. }
  345. return nil
  346. }
  347. func mangleInvalidArgumentValues(req *ExecutionRequest) {
  348. for _, arg := range req.Binding.Action.Arguments {
  349. if arg.Type == "datetime" {
  350. mangleInvalidDatetimeValues(req, &arg)
  351. }
  352. mangleCheckboxValues(req, &arg)
  353. mangleChecklistValues(req, &arg)
  354. }
  355. }
  356. func mangleCheckboxValues(req *ExecutionRequest, arg *config.ActionArgument) {
  357. if arg.Type != "checkbox" {
  358. return
  359. }
  360. log.Infof("Checking checkbox values for argument %s in action %s", arg.Name, req.Binding.Action.Title)
  361. for i, v := range arg.Choices {
  362. choice := &arg.Choices[i]
  363. if req.Arguments[arg.Name] == choice.Title {
  364. log.WithFields(log.Fields{
  365. "arg": arg.Name,
  366. "choice": v,
  367. "oldValue": req.Arguments[arg.Name],
  368. "newValue": choice.Value,
  369. "actionTitle": req.Binding.Action.Title,
  370. }).Infof("Mangled checkbox value")
  371. req.Arguments[arg.Name] = choice.Value
  372. }
  373. }
  374. }
  375. func mangleInvalidDatetimeValues(req *ExecutionRequest, arg *config.ActionArgument) {
  376. value, exists := req.Arguments[arg.Name]
  377. if !exists || value == "" {
  378. return
  379. }
  380. timestamp, err := time.Parse("2006-01-02T15:04", value)
  381. if err == nil {
  382. log.WithFields(log.Fields{
  383. "arg": arg.Name,
  384. "value": value,
  385. "actionTitle": req.Binding.Action.Title,
  386. }).Warnf("Mangled invalid datetime value without seconds to :00 seconds, this issue is commonly caused by Android browsers.")
  387. req.Arguments[arg.Name] = timestamp.Format("2006-01-02T15:04:05")
  388. }
  389. }
  390. // MangleArgumentValue applies mangling transformations to a single argument value.
  391. // This is used by the validation API to ensure the value matches what would be
  392. // used during actual execution.
  393. func MangleArgumentValue(arg *config.ActionArgument, value string, actionTitle string) string {
  394. if arg == nil {
  395. log.Debugf("MangleArgumentValue called with nil arg, returning value unchanged")
  396. return value
  397. }
  398. return mangleArgumentValueByType(arg, value, actionTitle)
  399. }
  400. func mangleArgumentValueByType(arg *config.ActionArgument, value string, actionTitle string) string {
  401. switch arg.Type {
  402. case "datetime":
  403. return mangleDatetimeValue(arg, value, actionTitle)
  404. case "checkbox":
  405. return mangleCheckboxValue(arg, value, actionTitle)
  406. case "checklist":
  407. return mangleChecklistValue(arg, value, actionTitle)
  408. default:
  409. return value
  410. }
  411. }
  412. func mangleDatetimeValue(arg *config.ActionArgument, value string, actionTitle string) string {
  413. if arg == nil {
  414. log.Debugf("mangleDatetimeValue called with nil arg, returning value unchanged")
  415. return value
  416. }
  417. if value == "" {
  418. return value
  419. }
  420. timestamp, err := time.Parse("2006-01-02T15:04", value)
  421. if err != nil {
  422. return value
  423. }
  424. log.WithFields(log.Fields{
  425. "arg": arg.Name,
  426. "value": value,
  427. "actionTitle": actionTitle,
  428. }).Warnf("Mangled invalid datetime value without seconds to :00 seconds, this issue is commonly caused by Android browsers.")
  429. return timestamp.Format("2006-01-02T15:04:05")
  430. }
  431. func mangleCheckboxValue(arg *config.ActionArgument, value string, actionTitle string) string {
  432. if arg == nil {
  433. log.Debugf("mangleCheckboxValue called with nil arg, returning value unchanged")
  434. return value
  435. }
  436. return mangleChoiceSegment(arg, value, actionTitle)
  437. }
  438. func mangleChecklistValues(req *ExecutionRequest, arg *config.ActionArgument) {
  439. if arg.Type != "checklist" {
  440. return
  441. }
  442. value, exists := req.Arguments[arg.Name]
  443. if !exists || value == "" {
  444. return
  445. }
  446. req.Arguments[arg.Name] = mangleChecklistValue(arg, value, req.Binding.Action.Title)
  447. }
  448. func mangleChecklistValue(arg *config.ActionArgument, value string, actionTitle string) string {
  449. if arg == nil || value == "" {
  450. return value
  451. }
  452. segments, err := config.ParseChecklistValue(value)
  453. if err != nil {
  454. return value
  455. }
  456. return mangleChecklistSegments(arg, segments, value, actionTitle)
  457. }
  458. func mangleChecklistSegments(arg *config.ActionArgument, segments []string, fallback string, actionTitle string) string {
  459. mangled := make([]string, len(segments))
  460. for i, segment := range segments {
  461. mangled[i] = mangleChecklistSegment(arg, segment, actionTitle)
  462. }
  463. formatted, err := config.FormatChecklistValue(mangled)
  464. if err != nil {
  465. return fallback
  466. }
  467. return formatted
  468. }
  469. func mangleChecklistSegment(arg *config.ActionArgument, segment string, actionTitle string) string {
  470. trimmed := strings.TrimSpace(segment)
  471. if trimmed == "" {
  472. return ""
  473. }
  474. return mangleChoiceSegment(arg, trimmed, actionTitle)
  475. }
  476. func mangleChoiceSegment(arg *config.ActionArgument, value string, actionTitle string) string {
  477. if mapped, ok := mangleChoiceSegmentEntity(arg, value, actionTitle); ok {
  478. return mapped
  479. }
  480. return mangleChoiceSegmentStatic(arg, value, actionTitle)
  481. }
  482. func mangleChoiceSegmentEntity(arg *config.ActionArgument, value string, actionTitle string) (string, bool) {
  483. if arg.Entity == "" || len(arg.Choices) == 0 {
  484. return value, false
  485. }
  486. return mangleEntityTemplateChoiceSegment(arg.Choices[0], arg.Entity, arg.Name, value, actionTitle)
  487. }
  488. func mangleEntityTemplateChoiceSegment(templateChoice config.ActionArgumentChoice, entityName string, argName string, value string, actionTitle string) (string, bool) {
  489. for _, ent := range entities.GetEntityInstancesOrdered(entityName) {
  490. expandedTitle := tpl.ParseTemplateOfActionBeforeExec(templateChoice.Title, ent)
  491. if value != expandedTitle {
  492. continue
  493. }
  494. expandedValue := tpl.ParseTemplateOfActionBeforeExec(templateChoice.Value, ent)
  495. log.WithFields(log.Fields{
  496. "arg": argName,
  497. "oldValue": value,
  498. "newValue": expandedValue,
  499. "actionTitle": actionTitle,
  500. }).Infof("Mangled entity choice segment")
  501. return expandedValue, true
  502. }
  503. return value, false
  504. }
  505. func mangleChoiceSegmentStatic(arg *config.ActionArgument, value string, actionTitle string) string {
  506. for _, choice := range arg.Choices {
  507. if value == choice.Title {
  508. log.WithFields(log.Fields{
  509. "arg": arg.Name,
  510. "oldValue": value,
  511. "newValue": choice.Value,
  512. "actionTitle": actionTitle,
  513. }).Infof("Mangled choice segment")
  514. return choice.Value
  515. }
  516. }
  517. return value
  518. }