| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240 |
- package executor
- import (
- "fmt"
- "strings"
- config "github.com/OliveTin/OliveTin/internal/config"
- "github.com/OliveTin/OliveTin/internal/entities"
- "github.com/OliveTin/OliveTin/internal/tpl"
- log "github.com/sirupsen/logrus"
- "testing"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- )
- func TestSanitizeUnsafe(t *testing.T) {
- require.NoError(t, TypeSafetyCheck("", "_zomg_ c:/ haxxor ' bobby tables && rm -rf ", "very_dangerous_raw_string"))
- }
- func TestSanitizeUnimplemented(t *testing.T) {
- err := TypeSafetyCheck("", "I am a happy little argument", "greeting_type")
- require.Error(t, err, "Test an argument type that does not exist")
- }
- func TestValidateArgumentCheckboxDefaultValues(t *testing.T) {
- arg := config.ActionArgument{
- Name: "confirm",
- Type: "checkbox",
- }
- action := config.Action{
- Title: "Test checkbox default values",
- }
- // Default checkbox values without choices should accept "1" and "0"
- err := ValidateArgument(&arg, "1", &action)
- require.NoError(t, err, "Expected checkbox value \"1\" to be accepted without choices")
- err = ValidateArgument(&arg, "0", &action)
- require.NoError(t, err, "Expected checkbox value \"0\" to be accepted without choices")
- }
- func TestMangleCheckboxValueWithChoices(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := config.ActionArgument{
- Name: "confirm",
- Type: "checkbox",
- Choices: []config.ActionArgumentChoice{
- {Title: "Enabled", Value: "on"},
- {Title: "Disabled", Value: "off"},
- },
- }
- // When the incoming value matches a choice title, it should be mapped to the choice value
- out := mangleCheckboxValue(&arg, "Enabled", "Test action")
- assert.Equal(t, "on", out, "Expected checkbox title to be mangled to its value")
- out = mangleCheckboxValue(&arg, "Disabled", "Test action")
- assert.Equal(t, "off", out, "Expected checkbox title to be mangled to its value")
- // When there is no matching title, the value should be returned unchanged
- out = mangleCheckboxValue(&arg, "something-else", "Test action")
- assert.Equal(t, "something-else", out, "Expected non-matching value to be returned unchanged")
- }
- func TestMangleArgumentValueCheckbox(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := config.ActionArgument{
- Name: "confirm",
- Type: "checkbox",
- Choices: []config.ActionArgumentChoice{
- {Title: "Yes", Value: "true-value"},
- {Title: "No", Value: "false-value"},
- },
- }
- out := MangleArgumentValue(&arg, "Yes", "Test action")
- assert.Equal(t, "true-value", out, "Expected MangleArgumentValue to delegate to mangleCheckboxValue for checkbox types")
- out = MangleArgumentValue(&arg, "No", "Test action")
- assert.Equal(t, "false-value", out)
- // For non-matching values, it should return the original value
- out = MangleArgumentValue(&arg, "maybe", "Test action")
- assert.Equal(t, "maybe", out)
- }
- func TestValidateArgumentCheckboxWithChoices(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := config.ActionArgument{
- Name: "confirm",
- Type: "checkbox",
- Choices: []config.ActionArgumentChoice{
- {Title: "Enabled", Value: "on"},
- {Title: "Disabled", Value: "off"},
- },
- }
- action := config.Action{
- Title: "Test checkbox with choices",
- }
- // Titles should be accepted once mangled to their values
- err := ValidateArgument(&arg, "Enabled", &action)
- require.NoError(t, err, "Expected checkbox title \"Enabled\" to be accepted after mangling to choice value")
- err = ValidateArgument(&arg, "Disabled", &action)
- require.NoError(t, err, "Expected checkbox title \"Disabled\" to be accepted after mangling to choice value")
- // Unknown titles should be rejected because they do not match any choice value
- err = ValidateArgument(&arg, "Maybe", &action)
- require.Error(t, err, "Expected unknown checkbox title to be rejected against choices")
- }
- func checklistTestArg() config.ActionArgument {
- return config.ActionArgument{
- Name: "directories",
- Type: "checklist",
- Choices: []config.ActionArgumentChoice{
- {Title: "Documents", Value: "documents"},
- {Title: "Photos", Value: "photos"},
- {Title: "Music", Value: "music"},
- },
- }
- }
- func TestValidateArgumentChecklistSelections(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := checklistTestArg()
- action := config.Action{Title: "Test checklist"}
- err := ValidateArgument(&arg, "documents", &action)
- require.NoError(t, err)
- err = ValidateArgument(&arg, `["documents","photos"]`, &action)
- require.NoError(t, err)
- err = ValidateArgument(&arg, `["documents","unknown"]`, &action)
- require.Error(t, err)
- }
- func TestValidateArgumentChecklistTitleMangling(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := checklistTestArg()
- action := config.Action{Title: "Test checklist title mangling"}
- err := ValidateArgument(&arg, `["Documents","Photos"]`, &action)
- require.NoError(t, err)
- }
- func TestValidateArgumentChecklistEmptySelection(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := checklistTestArg()
- action := config.Action{Title: "Test checklist empty"}
- err := ValidateArgument(&arg, "", &action)
- require.NoError(t, err)
- arg.RejectNull = true
- err = ValidateArgument(&arg, "", &action)
- require.Error(t, err)
- }
- func TestValidateArgumentChecklistWithoutChoices(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := config.ActionArgument{
- Name: "directories",
- Type: "checklist",
- }
- action := config.Action{Title: "Test checklist without choices"}
- err := ValidateArgument(&arg, "documents", &action)
- require.Error(t, err)
- }
- func TestValidateArgumentChecklistRejectsEmptySegment(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := checklistTestArg()
- action := config.Action{Title: "Test checklist empty segment"}
- err := ValidateArgument(&arg, `["documents","","photos"]`, &action)
- require.Error(t, err)
- }
- func TestMangleArgumentValueChecklist(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- arg := checklistTestArg()
- out := MangleArgumentValue(&arg, `["Documents","Music"]`, "Test action")
- assert.Equal(t, `["documents","music"]`, out)
- out = MangleArgumentValue(&arg, `["documents","photos"]`, "Test action")
- assert.Equal(t, `["documents","photos"]`, out)
- }
- func checklistEntityTestArg() config.ActionArgument {
- return config.ActionArgument{
- Name: "rooms",
- Type: "checklist",
- Entity: "room",
- Choices: []config.ActionArgumentChoice{
- {Title: "{{ room.hostname }}", Value: "{{ room.hostname }}"},
- },
- }
- }
- func TestValidateArgumentChecklistEntitySelections(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
- entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
- arg := checklistEntityTestArg()
- action := config.Action{Title: "Test checklist entity"}
- err := ValidateArgument(&arg, "attic", &action)
- require.NoError(t, err)
- err = ValidateArgument(&arg, `["attic","basement"]`, &action)
- require.NoError(t, err)
- err = ValidateArgument(&arg, `["attic","unknown"]`, &action)
- require.Error(t, err)
- }
- func TestMangleArgumentValueChecklistEntityTitles(t *testing.T) {
- log.SetLevel(log.PanicLevel)
- entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
- entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
- arg := config.ActionArgument{
- Name: "rooms",
- Type: "checklist",
- Entity: "room",
- Choices: []config.ActionArgumentChoice{
- {Title: "{{ room.hostname }} room", Value: "{{ room.hostname }}"},
- },
- }
- out := MangleArgumentValue(&arg, `["attic room","basement room"]`, "Test checklist entity titles")
- assert.Equal(t, `["attic","basement"]`, out)
- }
- func TestParseActionArgumentsChecklistEmptySelection(t *testing.T) {
- req := newExecRequest()
- req.Binding.Action = &config.Action{
- Title: "Test checklist empty selection",
- Shell: "echo 'Selected segments: {{ segments }}'",
- Arguments: []config.ActionArgument{
- {
- Name: "segments",
- Type: "checklist",
- Choices: []config.ActionArgumentChoice{
- {Value: "kitchen"},
- {Value: "bedroom"},
- },
- },
- },
- }
- req.Arguments = map[string]string{
- "segments": "",
- }
- mangleInvalidArgumentValues(req)
- out, err := parseActionArguments(req)
- require.NoError(t, err)
- assert.Equal(t, "echo 'Selected segments: '", out)
- }
- func newExecRequest() *ExecutionRequest {
- return &ExecutionRequest{
- Arguments: make(map[string]string),
- Binding: &ActionBinding{
- Action: &config.Action{},
- },
- }
- }
- func TestArgumentValueNullable(t *testing.T) {
- req := newExecRequest()
- req.Binding.Action = &config.Action{
- Title: "Release the hounds",
- Shell: "echo 'Releasing {{ count }} hounds'",
- Arguments: []config.ActionArgument{
- {
- Name: "count",
- Type: "int",
- RejectNull: false,
- },
- },
- }
- req.Arguments = map[string]string{
- "count": "",
- }
- out, err := parseActionArguments(req)
- assert.Equal(t, "echo 'Releasing hounds'", out)
- require.NoError(t, err)
- req.Binding.Action.Arguments[0].RejectNull = true
- _, err = parseActionArguments(req)
- require.Error(t, err)
- }
- func TestArgumentNameNumbers(t *testing.T) {
- req := newExecRequest()
- req.Binding.Action = &config.Action{
- Title: "Do some tickles",
- Shell: "echo 'Tickling {{ person1name }}'",
- Arguments: []config.ActionArgument{
- {
- Name: "person1name",
- Type: "ascii",
- },
- },
- }
- req.Arguments = map[string]string{
- "person1name": "Fred",
- }
- out, err := parseActionArguments(req)
- assert.Equal(t, "echo 'Tickling Fred'", out)
- require.NoError(t, err)
- }
- func TestArgumentNotProvided(t *testing.T) {
- req := newExecRequest()
- req.Binding.Action = &config.Action{
- Title: "Do some tickles",
- Shell: "echo 'Tickling {{ personName }}'",
- Arguments: []config.ActionArgument{
- {
- Name: "person",
- Type: "ascii",
- },
- },
- }
- req.Arguments = map[string]string{}
- out, err := parseActionArguments(req)
- assert.Empty(t, out)
- require.EqualError(t, err, "required arg not provided: personName")
- }
- func TestExecArrayParsing(t *testing.T) {
- req := newExecRequest()
- req.Binding.Action = &config.Action{
- Title: "List files",
- Exec: []string{"ls", "-alh"},
- Arguments: []config.ActionArgument{},
- }
- req.Arguments = map[string]string{}
- out, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
- require.NoError(t, err)
- assert.Equal(t, []string{"ls", "-alh"}, out)
- }
- func TestExecArrayWithTemplateReplacement(t *testing.T) {
- a1 := config.Action{
- Title: "List specific path",
- Exec: []string{"ls", "-alh", "{{path}}"},
- Arguments: []config.ActionArgument{
- {
- Name: "path",
- Type: "ascii_identifier",
- },
- },
- }
- values := map[string]string{
- "path": "tmp",
- }
- out, err := parseActionExec(values, &a1, nil)
- require.NoError(t, err)
- assert.Equal(t, []string{"ls", "-alh", "tmp"}, out)
- }
- func TestCheckShellArgumentSafetyWithURL(t *testing.T) {
- a1 := config.Action{
- Title: "Download file",
- Shell: "curl {{url}}",
- Arguments: []config.ActionArgument{
- {
- Name: "url",
- Type: "url",
- },
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.Error(t, err)
- assert.Contains(t, err.Error(), "unsafe argument type 'url' cannot be used with Shell execution")
- assert.Contains(t, err.Error(), "https://docs.olivetin.app/action_execution/shellvsexec.html")
- }
- func TestCheckShellArgumentSafetyWithEmail(t *testing.T) {
- a1 := config.Action{
- Title: "Send email",
- Shell: "sendmail {{email}}",
- Arguments: []config.ActionArgument{
- {
- Name: "email",
- Type: "email",
- },
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.Error(t, err)
- assert.Contains(t, err.Error(), "unsafe argument type 'email' cannot be used with Shell execution")
- }
- func TestCheckShellArgumentSafetyWithExec(t *testing.T) {
- a1 := config.Action{
- Title: "Download file",
- Exec: []string{"curl", "{{url}}"},
- Arguments: []config.ActionArgument{
- {
- Name: "url",
- Type: "url",
- },
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.NoError(t, err)
- }
- func TestCheckShellArgumentSafetyWithSafeTypes(t *testing.T) {
- a1 := config.Action{
- Title: "List files",
- Shell: "ls {{path}}",
- Arguments: []config.ActionArgument{
- {
- Name: "path",
- Type: "ascii_identifier",
- },
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.NoError(t, err)
- }
- func TestCheckShellArgumentSafetyWithPassword(t *testing.T) {
- a1 := config.Action{
- Title: "Auth with password",
- Shell: "somecommand --password '{{password}}'",
- Arguments: []config.ActionArgument{
- {
- Name: "password",
- Type: "password",
- },
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.Error(t, err)
- assert.Contains(t, err.Error(), "unsafe argument type 'password' cannot be used with Shell execution")
- assert.Contains(t, err.Error(), "https://docs.olivetin.app/action_execution/shellvsexec.html")
- }
- func TestCheckShellArgumentSafetyWithPasswordAndExec(t *testing.T) {
- a1 := config.Action{
- Title: "Auth with password via exec",
- Exec: []string{"somecommand", "--password", "{{password}}"},
- Arguments: []config.ActionArgument{
- {
- Name: "password",
- Type: "password",
- },
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.NoError(t, err)
- }
- func TestCheckShellArgumentSafetyWithHTML(t *testing.T) {
- a1 := config.Action{
- Title: "HTML shell",
- Shell: "echo {{ body }}",
- Arguments: []config.ActionArgument{
- {Name: "body", Type: "html"},
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.Error(t, err)
- assert.Contains(t, err.Error(), "unsafe argument type 'html'")
- }
- func TestCheckShellArgumentSafetyWithConfirmation(t *testing.T) {
- a1 := config.Action{
- Title: "Confirm shell",
- Shell: "echo ok",
- Arguments: []config.ActionArgument{
- {Name: "agree", Type: "confirmation"},
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.NoError(t, err, "confirmation is constrained to 0/1 and is safe with shell")
- }
- func TestCheckShellArgumentSafetyWithUnnamedConfirmation(t *testing.T) {
- a1 := config.Action{
- Title: "Confirm shell unnamed",
- Shell: "echo ok",
- Arguments: []config.ActionArgument{
- {Type: "confirmation", Title: "Are you sure?!"},
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.NoError(t, err)
- }
- func TestCheckShellArgumentSafetyWithChoicelessCheckbox(t *testing.T) {
- a1 := config.Action{
- Title: "Checkbox shell",
- Shell: "echo {{ flag }}",
- Arguments: []config.ActionArgument{
- {Name: "flag", Type: "checkbox"},
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.Error(t, err)
- assert.Contains(t, err.Error(), "unsafe argument type 'checkbox'")
- }
- func TestCheckShellArgumentSafetyWithCustomRegex(t *testing.T) {
- a1 := config.Action{
- Title: "Regex shell",
- Shell: "curl {{ host }}",
- Arguments: []config.ActionArgument{
- {Name: "host", Type: "regex:[a-zA-Z0-9.-]+"},
- },
- }
- err := checkShellArgumentSafety(&a1)
- require.Error(t, err)
- assert.Contains(t, err.Error(), "unsafe argument type 'regex:[a-zA-Z0-9.-]+'")
- }
- func TestTypeSafetyCheckUrl(t *testing.T) {
- require.NoError(t, TypeSafetyCheck("test1", "http://google.com", "url"), "Test URL: google.com")
- require.NoError(t, TypeSafetyCheck("test2", "http://technowax.net:80?foo=bar", "url"), "Test URL: technowax.net with query arguments")
- require.NoError(t, TypeSafetyCheck("test3", "http://localhost:80?foo=bar", "url"), "Test URL: localhost with query arguments")
- require.NoError(t, TypeSafetyCheck("test7", "https://example.com/path", "url"), "Test URL: https scheme")
- require.Error(t, TypeSafetyCheck("test4", "http://lo host:80", "url"), "Test a badly formed URL")
- require.Error(t, TypeSafetyCheck("test5", "12345", "url"), "Test a badly formed URL")
- require.Error(t, TypeSafetyCheck("test6", "_!23;", "url"), "Test a badly formed URL")
- require.Error(t, TypeSafetyCheck("test8", "file:///etc/passwd", "url"), "file:// scheme must be rejected")
- require.Error(t, TypeSafetyCheck("test9", "gopher://example.com", "url"), "gopher:// scheme must be rejected")
- }
- func TestTypeSafetyCheckRegex(t *testing.T) {
- tests := []struct {
- name string
- field string
- pattern string
- value string
- hasError bool
- }{
- {
- name: "Issue #578 - Domain",
- field: "domain",
- pattern: "regex:^(?:[a-zA-Z0-9-]{1,63}.)+[a-zA-Z]{2,63}$",
- value: "immich.example.dev",
- hasError: false,
- },
- {
- name: "Don't allow numbers in username",
- field: "Username",
- pattern: "regex:^[a-zA-Z]$",
- value: "James1234",
- hasError: true,
- },
- {
- name: "GHSA-gvxq - reject partial regex match",
- field: "host",
- pattern: "regex:[a-zA-Z0-9.-]+",
- value: "example.com; id",
- hasError: true,
- },
- {
- name: "reject alternation bypass when pattern looks anchored",
- field: "host",
- pattern: "regex:^safe$|bad",
- value: "xxxbad",
- hasError: true,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := typeSafetyCheckRegex(tt.field, tt.value, tt.pattern)
- if tt.hasError {
- require.Error(t, err, "Expected error for value %s with pattern %s, but got no error", tt.value, tt.pattern)
- } else {
- require.NoError(t, err, "Expected no error for value %s with pattern %s, but got error: %v", tt.value, tt.pattern, err)
- }
- })
- }
- }
- func TestRedactShellCommand(t *testing.T) {
- cmd := "echo 'The password for Fred is toomanysecrets'"
- args := []config.ActionArgument{
- {
- Name: "personName",
- Type: "ascii",
- },
- {
- Name: "password",
- Type: "password",
- },
- }
- values := map[string]string{
- "personName": "Fred",
- "password": "toomanysecrets",
- }
- res := redactShellCommand(cmd, args, values)
- assert.Equal(t, "echo 'The password for Fred is <redacted>'", res, "Redacted shell command should mask the password argument")
- // Test with empty password
- values["password"] = ""
- res = redactShellCommand(cmd, args, values)
- assert.Equal(t, cmd, res, "Empty password should not change the command")
- // Test with missing password argument
- delete(values, "password")
- res = redactShellCommand(cmd, args, values)
- assert.Equal(t, cmd, res, "Missing password argument should not change the command")
- }
- func TestTypeSafetyCheckEmail(t *testing.T) {
- tests := []struct {
- name string
- field string
- value string
- hasError bool
- }{
- {"Valid simple email", "email", "user@example.com", false},
- {"Valid email with subdomain", "email", "user@mail.example.com", false},
- {"Valid email with plus", "email", "user+test@example.com", false},
- {"Valid email with dash", "email", "user-name@example.com", false},
- {"Valid email with numbers", "email", "user123@example123.com", false},
- {"Invalid email no @", "email", "userexample.com", true},
- {"Invalid email no domain", "email", "user@", true},
- {"Invalid email no user", "email", "@example.com", true},
- {"Invalid email spaces", "email", "user name@example.com", true},
- {"Invalid email double @", "email", "user@@example.com", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck(tt.field, tt.value, "email")
- if tt.hasError {
- require.Error(t, err, "Expected error for value '%s'", tt.value)
- } else {
- require.NoError(t, err, "Expected no error for value '%s', but got: %v", tt.value, err)
- }
- })
- }
- }
- func TestTypeSafetyCheckDatetime(t *testing.T) {
- tests := []struct {
- name string
- field string
- value string
- hasError bool
- }{
- {"Valid datetime", "datetime", "2023-12-25T15:30:45", false},
- {"Valid datetime morning", "datetime", "2023-01-01T00:00:00", false},
- {"Valid datetime evening", "datetime", "2023-12-31T23:59:59", false},
- {"Invalid format missing T", "datetime", "2023-12-25 15:30:45", true},
- {"Invalid format missing seconds", "datetime", "2023-12-25T15:30", true},
- {"Invalid date", "datetime", "2023-13-25T15:30:45", true},
- {"Invalid time", "datetime", "2023-12-25T25:30:45", true},
- {"Random string", "datetime", "not-a-date", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck(tt.field, tt.value, "datetime")
- if tt.hasError {
- require.Error(t, err, "Expected error for value '%s'", tt.value)
- } else {
- require.NoError(t, err, "Expected no error for value '%s', but got: %v", tt.value, err)
- }
- })
- }
- }
- func TestTypeSafetyCheckRawStringMultiline(t *testing.T) {
- tests := []struct {
- name string
- field string
- value string
- }{
- {"Simple string", "content", "hello world"},
- {"Multiline string", "content", "line1\nline2\nline3"},
- {"String with special chars", "content", "!@#$%^&*()"},
- {"Unicode string", "content", "héllo wörld 🌍"},
- {"Very long string", "content", strings.Repeat("a", 1000)},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck(tt.field, tt.value, "raw_string_multiline")
- require.NoError(t, err, "raw_string_multiline should accept any value")
- })
- }
- }
- func TestTypeSafetyCheckUnicodeIdentifier(t *testing.T) {
- tests := []struct {
- name string
- field string
- value string
- expectsError bool
- }{
- {"Valid unicode identifier", "name", "hello_world", false},
- {"Valid with numbers", "name", "test123", false},
- {"Valid with dots", "name", "file.txt", false},
- {"Valid with underscores", "name", "my_file_name", false},
- {"Invalid with special chars", "name", "hello@world", true},
- {"Invalid with brackets", "name", "hello[world]", true},
- {"Invalid with spaces", "name", "hello world", true},
- {"Invalid with path separators", "name", "path/to/file", true},
- {"Invalid with backslashes", "name", "path\\to\\file", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck(tt.field, tt.value, "unicode_identifier")
- validateTypeSafetyResult(t, tt.value, tt.expectsError, err)
- })
- }
- }
- func validateTypeSafetyResult(t *testing.T, value string, expectsError bool, err error) {
- t.Helper()
- if expectsError {
- assertErrorExpected(t, value, err)
- } else {
- assertNoErrorExpected(t, value, err)
- }
- }
- func assertErrorExpected(t *testing.T, value string, err error) {
- t.Helper()
- if err == nil {
- t.Errorf("Expected error for value '%s', but got none", value)
- } else {
- t.Logf("Received expected error for value '%s': %v", value, err)
- }
- }
- func assertNoErrorExpected(t *testing.T, value string, err error) {
- t.Helper()
- if err != nil {
- t.Errorf("Expected no error for value '%s', but got: %v", value, err)
- } else {
- t.Logf("No error for valid value '%s' as expected", value)
- }
- }
- func TestTypeSafetyCheckAsciiIdentifier(t *testing.T) {
- tests := []struct {
- name string
- field string
- value string
- hasError bool
- }{
- {"Valid identifier", "name", "hello_world", false},
- {"Valid with numbers", "name", "test123", false},
- {"Valid with dots", "name", "file.txt", false},
- {"Valid with dashes", "name", "my-file", false},
- {"Valid with underscores", "name", "my_file", false},
- {"Invalid with spaces", "name", "hello world", true},
- {"Invalid with special chars", "name", "hello@world", true},
- {"Invalid unicode", "name", "héllo", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck(tt.field, tt.value, "ascii_identifier")
- if tt.hasError {
- require.Error(t, err, "Expected error for value '%s'", tt.value)
- } else {
- require.NoError(t, err, "Expected no error for value '%s', but got: %v", tt.value, err)
- }
- })
- }
- }
- func TestTypeSafetyCheckDnsName(t *testing.T) {
- tests := []struct {
- name string
- value string
- hasError bool
- }{
- {"Short name", "webserver", false},
- {"Localhost", "localhost", false},
- {"Simple domain", "example.com", false},
- {"Host with subdomain", "webserver.example.com", false},
- {"Deep subdomain", "a.b.c.example.co.uk", false},
- {"Label starting with digit", "1host.example.com", false},
- {"Trailing dot", "example.com.", false},
- {"Punycode IDN", "xn--bcher-kva.example", false},
- {"Underscore", "my_host.example.com", true},
- {"Space", "example .com", true},
- {"Leading hyphen label", "-host.example.com", true},
- {"Trailing hyphen label", "host-.example.com", true},
- {"Empty label", "example..com", true},
- {"IP address", "192.168.1.1", true},
- {"All numeric TLD", "example.123", true},
- {"All numeric short name", "12345", true},
- {"Special chars", "exam!ple.com", true},
- {"Unicode label", "bücher.example.com", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck("host", tt.value, "dnsname")
- if tt.hasError {
- require.Error(t, err, "Expected error for value '%s'", tt.value)
- } else {
- require.NoError(t, err, "Expected no error for value '%s', but got: %v", tt.value, err)
- }
- })
- }
- }
- func TestTypeSafetyCheckShellSafeIdentifier(t *testing.T) {
- tests := []struct {
- name string
- value string
- hasError bool
- }{
- {"Simple username", "alice123", false},
- {"Email username", "alice@example.com", false},
- {"Plus addressing", "alice+test@example.com", false},
- {"Hyphen underscore dot", "alice-test_user.example", false},
- {"Invalid space", "alice example", true},
- {"Invalid shell substitution", "$(whoami)", true},
- {"Invalid backtick", "`whoami`", true},
- {"Invalid semicolon", "alice;id", true},
- {"Invalid ampersand", "alice&id", true},
- {"Invalid pipe", "alice|id", true},
- {"Invalid quote", "alice'example", true},
- {"Invalid slash", "alice/example", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck("username", tt.value, "shell_safe_identifier")
- if tt.hasError {
- require.Error(t, err, "Expected error for value '%s'", tt.value)
- } else {
- require.NoError(t, err, "Expected no error for value '%s', but got: %v", tt.value, err)
- }
- })
- }
- }
- func TestTypeSafetyCheckAsciiSentence(t *testing.T) {
- tests := []struct {
- name string
- field string
- value string
- hasError bool
- }{
- {"Valid sentence", "text", "Hello world", false},
- {"Valid with numbers", "text", "Test 123", false},
- {"Valid with commas", "text", "Hello, world", false},
- {"Valid with periods", "text", "Hello world.", false},
- {"Valid with multiple spaces", "text", "Hello world", false},
- {"Invalid with special chars", "text", "Hello@world", true},
- {"Invalid with parentheses", "text", "Hello (world)", true},
- {"Invalid unicode", "text", "Héllo world", true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := TypeSafetyCheck(tt.field, tt.value, "ascii_sentence")
- if tt.hasError {
- require.Error(t, err, "Expected error for value '%s'", tt.value)
- } else {
- require.NoError(t, err, "Expected no error for value '%s', but got: %v", tt.value, err)
- }
- })
- }
- }
- func TestTypecheckActionArgumentEmptyName(t *testing.T) {
- arg := config.ActionArgument{
- Name: "",
- Type: "ascii",
- }
- err := typecheckActionArgument(&arg, "test")
- require.Error(t, err)
- assert.Contains(t, err.Error(), "argument name cannot be empty")
- }
- func TestTypecheckActionArgumentConfirmation(t *testing.T) {
- arg := config.ActionArgument{
- Name: "confirm",
- Type: "confirmation",
- }
- require.NoError(t, typecheckActionArgument(&arg, "0"))
- require.NoError(t, typecheckActionArgument(&arg, "1"))
- err := typecheckActionArgument(&arg, "any_value")
- require.Error(t, err)
- assert.Contains(t, err.Error(), "must be \"0\" or \"1\"")
- err = typecheckActionArgument(&arg, "")
- require.Error(t, err)
- assert.Contains(t, err.Error(), "must be \"0\" or \"1\"")
- }
- func TestTypecheckActionArgumentUnnamedConfirmation(t *testing.T) {
- arg := config.ActionArgument{
- Type: "confirmation",
- Title: "Are you sure?!",
- }
- require.NoError(t, typecheckActionArgument(&arg, ""))
- require.NoError(t, typecheckActionArgument(&arg, "ignored"))
- }
- func TestTypecheckActionArgumentHtmlWithoutName(t *testing.T) {
- action := config.Action{
- Title: "Delete old backups",
- Shell: "rm -rf /opt/oliveTinOldBackups/ && sleep 5",
- Arguments: []config.ActionArgument{
- {Type: "html", Title: "Description"},
- {Type: "confirmation", Title: "Are you sure?!"},
- },
- }
- err := validateArguments(map[string]string{}, &action)
- require.NoError(t, err)
- }
- func TestParseCommandForReplacements(t *testing.T) {
- tests := []struct {
- values map[string]string
- name string
- shellCommand string
- expectedOutput string
- errorContains string
- expectError bool
- }{
- {
- name: "Simple replacement",
- shellCommand: "echo {{ name }}",
- values: map[string]string{"name": "John"},
- expectedOutput: "echo John",
- expectError: false,
- },
- {
- name: "Multiple replacements",
- shellCommand: "echo {{ first }} {{ last }}",
- values: map[string]string{"first": "John", "last": "Doe"},
- expectedOutput: "echo John Doe",
- expectError: false,
- },
- {
- name: "Replacement with spaces in template",
- shellCommand: "echo {{ name }}",
- values: map[string]string{"name": "John"},
- expectedOutput: "echo John",
- expectError: false,
- },
- {
- name: "Missing argument",
- shellCommand: "echo {{ missing }}",
- values: map[string]string{},
- expectedOutput: "",
- expectError: true,
- errorContains: "required arg not provided: missing",
- },
- {
- name: "No replacements needed",
- shellCommand: "echo hello",
- values: map[string]string{},
- expectedOutput: "echo hello",
- expectError: false,
- },
- {
- name: "Multiple same argument",
- shellCommand: "echo {{ name }} says hello {{ name }}",
- values: map[string]string{"name": "Alice"},
- expectedOutput: "echo Alice says hello Alice",
- expectError: false,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- output, err := tpl.ParseTemplateWithActionContext(tt.shellCommand, nil, tt.values)
- if tt.expectError {
- require.Error(t, err, "Expected error but got none")
- if tt.errorContains != "" {
- assert.Contains(t, err.Error(), tt.errorContains)
- }
- } else {
- require.NoError(t, err, "Expected no error but got: %v", err)
- assert.Equal(t, tt.expectedOutput, output)
- }
- })
- }
- }
- func TestArgumentChoicesValidation(t *testing.T) {
- tests := []struct {
- req *ExecutionRequest
- name string
- description string
- expectError bool
- }{
- {
- name: "Valid choice",
- req: &ExecutionRequest{
- Binding: &ActionBinding{
- Action: &config.Action{
- Title: "Test choices",
- Shell: "echo {{ option }}",
- Arguments: []config.ActionArgument{
- {
- Name: "option",
- Type: "ascii",
- Choices: []config.ActionArgumentChoice{
- {Value: "option1", Title: "Option 1"},
- {Value: "option2", Title: "Option 2"},
- },
- },
- },
- },
- },
- Arguments: map[string]string{"option": "option1"},
- },
- expectError: false,
- description: "Should accept valid choice",
- },
- {
- name: "Invalid choice",
- req: &ExecutionRequest{
- Binding: &ActionBinding{
- Action: &config.Action{
- Title: "Test choices",
- Shell: "echo {{ option }}",
- Arguments: []config.ActionArgument{
- {
- Name: "option",
- Type: "ascii",
- Choices: []config.ActionArgumentChoice{
- {Value: "option1", Title: "Option 1"},
- {Value: "option2", Title: "Option 2"},
- },
- },
- },
- },
- },
- Arguments: map[string]string{"option": "invalid_option"},
- },
- expectError: true,
- description: "Should reject invalid choice",
- },
- {
- name: "Invalid choice",
- req: &ExecutionRequest{
- Binding: &ActionBinding{
- Action: &config.Action{
- Title: "Test choices",
- Shell: "echo {{ option }}",
- Arguments: []config.ActionArgument{
- {
- Name: "option",
- Type: "ascii",
- Choices: []config.ActionArgumentChoice{
- {Value: "option1", Title: "Option 1"},
- {Value: "option2", Title: "Option 2"},
- },
- },
- },
- },
- },
- Arguments: map[string]string{"option": "option1"},
- },
- expectError: false,
- description: "Should accept valid choice",
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- _, err := parseActionArguments(tt.req)
- if tt.expectError {
- require.Error(t, err, tt.description)
- assert.Contains(t, err.Error(), "predefined choices")
- } else {
- require.NoError(t, err, tt.description)
- }
- })
- }
- }
- func TestTypeSafetyCheckVeryDangerousRawString(t *testing.T) {
- // This type should allow anything without validation
- tests := []string{
- "normal text",
- "_zomg_ c:/ haxxor ' bobby tables && rm -rf /",
- "$(rm -rf /)",
- "; DROP TABLE users; --",
- "../../../../etc/passwd",
- "",
- "unicode: 你好世界",
- "emojis: 🔥💀☠️",
- }
- for _, value := range tests {
- t.Run(fmt.Sprintf("Value: %s", value), func(t *testing.T) {
- err := TypeSafetyCheck("test", value, "very_dangerous_raw_string")
- require.NoError(t, err, "very_dangerous_raw_string should accept any value including: %s", value)
- })
- }
- }
- func TestParseActionArgumentsWithEntityPrefix(t *testing.T) {
- req := newExecRequest()
- req.Binding.Action = &config.Action{
- Title: "Test entity prefix",
- Shell: "echo 'Processing {{ name }} for entity'",
- Arguments: []config.ActionArgument{
- {Name: "name", Type: "ascii"},
- },
- }
- req.Arguments = map[string]string{
- "name": "testuser",
- }
- req.Binding.Entity = &entities.Entity{
- Title: "entity_123",
- }
- // Test with entity prefix
- output, err := parseActionArguments(req)
- require.NoError(t, err)
- assert.Contains(t, output, "testuser")
- }
- func TestComplexRegexPatterns(t *testing.T) {
- tests := []struct {
- name string
- pattern string
- value string
- hasError bool
- }{
- {
- name: "Phone number pattern",
- pattern: "regex:^\\+?[1-9]\\d{1,14}$",
- value: "+1234567890",
- hasError: false,
- },
- {
- name: "Invalid phone number",
- pattern: "regex:^\\+?[1-9]\\d{1,14}$",
- value: "123abc",
- hasError: true,
- },
- {
- name: "Semantic version pattern",
- pattern: "regex:^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$",
- value: "1.2.3",
- hasError: false,
- },
- {
- name: "Invalid semantic version",
- pattern: "regex:^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$",
- value: "1.2",
- hasError: true,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := typeSafetyCheckRegex("test", tt.value, tt.pattern)
- if tt.hasError {
- require.Error(t, err)
- } else {
- require.NoError(t, err)
- }
- })
- }
- }
|