From 5f8520075eba3f5430895132b07ce6711a80dc8b Mon Sep 17 00:00:00 2001 From: Chen Bojun Date: Thu, 8 Sep 2022 16:05:04 +0800 Subject: [PATCH] postreceive: fix the problem that getEnvVar may panic The input passed to the getEnvVar() is not controllable. For example, when the input env string is "foo" and the value of key is also "foo", then getEnvVar() will cause panic exception because the parsed array is out of range. When the array length of the parsed env string is less than 2 then it is skipped directly because incorrect KV format should be considered invaild. Also added unit test for getEnvVar(). Changelog: fixed Signed-off-by: Chen Bojun --- internal/gitaly/hook/postreceive.go | 3 ++ internal/gitaly/hook/postreceive_test.go | 54 ++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/internal/gitaly/hook/postreceive.go b/internal/gitaly/hook/postreceive.go index 2063b1adf99..36faa08d13f 100644 --- a/internal/gitaly/hook/postreceive.go +++ b/internal/gitaly/hook/postreceive.go @@ -34,6 +34,9 @@ const ( func getEnvVar(key string, vars []string) string { for _, varPair := range vars { kv := strings.SplitN(varPair, "=", 2) + if len(kv) < 2 { + continue + } if kv[0] == key { return kv[1] } diff --git a/internal/gitaly/hook/postreceive_test.go b/internal/gitaly/hook/postreceive_test.go index 5fb125ad044..e9abedb5385 100644 --- a/internal/gitaly/hook/postreceive_test.go +++ b/internal/gitaly/hook/postreceive_test.go @@ -410,3 +410,57 @@ func TestPostReceive_quarantine(t *testing.T) { }) } } + +func Test_getEnvVar(t *testing.T) { + type args struct { + key string + vars []string + } + tests := []struct { + desc string + args args + want string + }{ + { + desc: "success found key from key-value pairs", + args: args{ + key: "key", + vars: []string{ + "key1=value1", + "key=value", + "key2=value2", + }, + }, + want: "value", + }, + { + desc: "invalid key-value format, only key name", + args: args{ + key: "key", + vars: []string{ + "key", + "key=value", + "key2=value2", + }, + }, + want: "value", + }, + { + desc: "key not found", + args: args{ + key: "key", + vars: []string{ + "key", + "key1=value1", + "key2=value2", + }, + }, + want: "", + }, + } + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + assert.Equalf(t, tt.want, getEnvVar(tt.args.key, tt.args.vars), "getEnvVar(%v, %v)", tt.args.key, tt.args.vars) + }) + } +} -- GitLab