From ac4d723e52940938635889cf43c759c320dbc73a Mon Sep 17 00:00:00 2001 From: Kyle Carberry Date: Wed, 13 Sep 2023 09:48:40 -0500 Subject: [PATCH] fix: add validation to cron (#159) --- go.mod | 1 + go.sum | 2 ++ provider/script.go | 15 +++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/go.mod b/go.mod index da846746..af666bdd 100644 --- a/go.mod +++ b/go.mod @@ -46,6 +46,7 @@ require ( github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/oklog/run v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/robfig/cron/v3 v3.0.1 // indirect github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect diff --git a/go.sum b/go.sum index d98eda60..0ef602a8 100644 --- a/go.sum +++ b/go.sum @@ -143,6 +143,8 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= diff --git a/provider/script.go b/provider/script.go index fd02d4cc..8281d57d 100644 --- a/provider/script.go +++ b/provider/script.go @@ -2,13 +2,17 @@ package provider import ( "context" + "fmt" "github.com/google/uuid" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/robfig/cron/v3" ) +var ScriptCRONParser = cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor) + func scriptResource() *schema.Resource { return &schema.Resource{ Description: "Use this resource to run a script from an agent.", @@ -56,6 +60,17 @@ func scriptResource() *schema.Resource { Type: schema.TypeString, Optional: true, Description: "The cron schedule to run the script on. This is a cron expression.", + ValidateFunc: func(i interface{}, s string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return []string{}, []error{fmt.Errorf("got type %T instead of string", i)} + } + _, err := ScriptCRONParser.Parse(v) + if err != nil { + return []string{}, []error{fmt.Errorf("%s is not a valid cron expression: %w", v, err)} + } + return nil, nil + }, }, "start_blocks_login": { Type: schema.TypeBool,