Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add datetime functions #991

Merged
merged 4 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions pkg/scanners/azure/functions/date_time_add.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package functions

import (
"fmt"
"regexp"
"strconv"
"time"
)

var pattern = regexp.MustCompile(`^P((?P<year>\d+)Y)?((?P<month>\d+)M)?((?P<week>\d+)W)?((?P<day>\d+)D)?(T((?P<hour>\d+)H)?((?P<minute>\d+)M)?((?P<second>\d+)S)?)?$`)

func DateTimeAdd(args ...interface{}) interface{} {
if len(args) < 2 {
return nil
}

base, ok := args[0].(string)
if !ok {
return nil
}

baseTime, err := time.Parse(time.RFC3339, base)
if err != nil {
return nil
}

duration, err := parseISO8601(args[1].(string))
if err != nil {
return nil
}

timeDuration := duration.timeDuration()
baseTime = baseTime.Add(timeDuration)

if len(args) == 3 {
format, ok := args[2].(string)
if ok {
return baseTime.Format(format)
}
}

return baseTime.Format(time.RFC3339)
}

type ISO8601Duration struct {
Y int
M int
W int
D int
// Time Component
TH int
TM int
TS int
}

func parseISO8601(from string) (ISO8601Duration, error) {
var match []string
var d ISO8601Duration

if pattern.MatchString(from) {
match = pattern.FindStringSubmatch(from)
} else {
return d, fmt.Errorf("could not parse duration string")
}

for i, name := range pattern.SubexpNames() {
part := match[i]
if i == 0 || name == "" || part == "" {
continue
}

val, err := strconv.Atoi(part)
if err != nil {
return d, err
}
switch name {
case "year":
d.Y = val
case "month":
d.M = val
case "week":
d.W = val
case "day":
d.D = val
case "hour":
d.TH = val
case "minute":
d.TM = val
case "second":
d.TS = val
default:
return d, fmt.Errorf("unknown field %s", name)
}
}

return d, nil
}

func (d ISO8601Duration) timeDuration() time.Duration {
var dur time.Duration
dur += time.Duration(d.TH) * time.Hour
dur += time.Duration(d.TM) * time.Minute
dur += time.Duration(d.TS) * time.Second
dur += time.Duration(d.D) * 24 * time.Hour
dur += time.Duration(d.W) * 7 * 24 * time.Hour
dur += time.Duration(d.M) * 30 * 24 * time.Hour
dur += time.Duration(d.Y) * 365 * 24 * time.Hour

return dur
}
38 changes: 38 additions & 0 deletions pkg/scanners/azure/functions/date_time_epoch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package functions

import (
"time"

smithyTime "github.com/aws/smithy-go/time"
)

func DateTimeFromEpoch(args ...interface{}) interface{} {
if len(args) != 1 {
return nil
}

epoch, ok := args[0].(int)
if !ok {
return nil
}

return smithyTime.ParseEpochSeconds(float64(epoch)).Format(time.RFC3339)
}

func DateTimeToEpoch(args ...interface{}) interface{} {
if len(args) != 1 {
return nil
}

dateTime, ok := args[0].(string)
if !ok {
return nil
}

parsed, err := time.Parse(time.RFC3339, dateTime)
if err != nil {
return nil
}

return int(parsed.Unix())
}
51 changes: 51 additions & 0 deletions pkg/scanners/azure/functions/date_time_epoch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package functions

import (
"testing"

"github.com/stretchr/testify/assert"
)

func Test_DateTimeFromEpoch(t *testing.T) {
tests := []struct {
name string
args []interface{}
expected interface{}
}{
{
name: "datetime from epoch",
args: []interface{}{
1683040573,
},
expected: "2023-05-02T15:16:13Z",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual := DateTimeFromEpoch(tt.args...)
assert.Equal(t, tt.expected, actual)
})
}
}

func Test_DateTimeToEpoch(t *testing.T) {
tests := []struct {
name string
args []interface{}
expected interface{}
}{
{
name: "datetime to epoch",
args: []interface{}{
"2023-05-02T15:16:13Z",
},
expected: 1683040573,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual := DateTimeToEpoch(tt.args...)
assert.Equal(t, tt.expected, actual)
})
}
}
72 changes: 72 additions & 0 deletions pkg/scanners/azure/functions/datetime_add_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package functions

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func Test_DateTimeAdd(t *testing.T) {
tests := []struct {
name string
args []interface{}
expected interface{}
}{

{
name: "datetime add 1 years",
args: []interface{}{
"2010-01-01T00:00:00Z",
"P1Y",
},
expected: "2011-01-01T00:00:00Z",
},
{
name: "datetime add 3 months",
args: []interface{}{
"2010-01-01T00:00:00Z",
"P3M",
},
expected: "2010-04-01T00:00:00Z",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual := DateTimeAdd(tt.args...)
assert.Equal(t, tt.expected, actual)
})
}
}

func Test_ISO8601DurationParse(t *testing.T) {
tests := []struct {
name string
args string
expected ISO8601Duration
}{

{
name: "parse 1 year",
args: "P1Y",
expected: ISO8601Duration{Y: 1},
},
{
name: "parse 3 months",
args: "P3M",
expected: ISO8601Duration{M: 3},
},
{
name: "parse 12 hours",
args: "PT12H",
expected: ISO8601Duration{TH: 12},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual, err := parseISO8601(tt.args)
require.NoError(t, err)
assert.Equal(t, tt.expected, actual)
})
}
}
86 changes: 45 additions & 41 deletions pkg/scanners/azure/functions/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,47 +8,51 @@ var deploymentFuncs = map[string]func(dp DeploymentData, args ...interface{}) in
}
var generalFuncs = map[string]func(...interface{}) interface{}{

"array": Array,
"base64": Base64,
"base64ToJson": Base64ToJson,
"concat": Concat,
"contains": Contains,
"createArray": CreateArray,
"dataUri": DataUri,
"dataUriToString": DataUriToString,
"empty": Empty,
"endsWith": EndsWith,
"format": Format,
"guid": Guid,
"indexOf": IndexOf,
"intersection": Intersection,
"join": Join,
"lastIndexOf": LastIndexOf,
"length": Length,
"max": Max,
"min": Min,
"newGuid": NewGuid,
"padLeft": PadLeft,
"range": Range,
"replace": Replace,
"skip": Skip,
"split": Split,
"startsWith": StartsWith,
"string": String,
"substring": SubString,
"toLower": ToLower,
"toUpper": ToUpper,
"trim": Trim,
"union": Union,
"union:": Union,
"uniqueString": UniqueString,
"uri": Uri,
"coalesce": Coalesce,
"equals": Equals,
"greater": Greater,
"greaterOrEquals": GreaterOrEquals,
"less": Less,
"lessOrEquals": LessOrEquals,
"array": Array,
"base64": Base64,
"base64ToJson": Base64ToJson,
"coalesce": Coalesce,
"concat": Concat,
"contains": Contains,
"createArray": CreateArray,
"dataUri": DataUri,
"dataUriToString": DataUriToString,
"dateTimeAdd": DateTimeAdd,
"dateTimeFromEpoch": DateTimeFromEpoch,
"dateTimeToEpoch": DateTimeToEpoch,
"empty": Empty,
"endsWith": EndsWith,
"equals": Equals,
"format": Format,
"greater": Greater,
"greaterOrEquals": GreaterOrEquals,
"guid": Guid,
"indexOf": IndexOf,
"intersection": Intersection,
"join": Join,
"lastIndexOf": LastIndexOf,
"length": Length,
"less": Less,
"lessOrEquals": LessOrEquals,
"max": Max,
"min": Min,
"newGuid": NewGuid,
"padLeft": PadLeft,
"range": Range,
"replace": Replace,
"skip": Skip,
"split": Split,
"startsWith": StartsWith,
"string": String,
"substring": SubString,
"toLower": ToLower,
"toUpper": ToUpper,
"trim": Trim,
"union": Union,
"union:": Union,
"uniqueString": UniqueString,
"uri": Uri,
"utcNow": UTCNow,
}

func Evaluate(deploymentProvider DeploymentData, name string, args ...interface{}) interface{} {
Expand Down
18 changes: 18 additions & 0 deletions pkg/scanners/azure/functions/utc_now.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package functions

import "time"

func UTCNow(args ...interface{}) interface{} {
if len(args) > 1 {
return nil
}

if len(args) == 1 {
format, ok := args[0].(string)
if ok {
return time.Now().UTC().Format(format)
}
}

return time.Now().UTC().Format(time.RFC3339)
}