Browse Source

Add jsonpath filter support to webhook (#1940)

* Add jsonpath filter support to webhook

Signed-off-by: Thibault Cohen <47721+titilambert@users.noreply.github.com>

* Fix tests

Signed-off-by: Thibault Cohen <47721+titilambert@users.noreply.github.com>

Signed-off-by: Thibault Cohen <47721+titilambert@users.noreply.github.com>
Thibault Cohen 3 years ago
parent
commit
ff88395c09
2 changed files with 32 additions and 2 deletions
  1. 8 1
      pkg/provider/webhook/webhook.go
  2. 24 1
      pkg/provider/webhook/webhook_test.go

+ 8 - 1
pkg/provider/webhook/webhook.go

@@ -160,7 +160,14 @@ func (w *WebHook) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDat
 		}
 		jsonvalue, ok := jsondata.(string)
 		if !ok {
-			return nil, fmt.Errorf("failed to get response (wrong type: %T)", jsondata)
+			jsonvalues, ok := jsondata.([]interface{})
+			if !ok {
+				return nil, fmt.Errorf("failed to get response (wrong type: %T)", jsondata)
+			}
+			if len(jsonvalues) == 0 {
+				return nil, fmt.Errorf("filter worked but didn't get any result")
+			}
+			jsonvalue = jsonvalues[0].(string)
 		}
 		return []byte(jsonvalue), nil
 	}

+ 24 - 1
pkg/provider/webhook/webhook_test.go

@@ -220,7 +220,19 @@ want:
   err: ''
   result: secret-value
 ---
-case: good json with bad temlated jsonpath
+case: good json with jsonpath filter
+args:
+  url: /api/getsecret?id={{ .remoteRef.key }}&version={{ .remoteRef.version }}
+  key: testkey
+  version: 1
+  jsonpath: $.secrets[?@.name=="thesecret"].value
+  response: '{"secrets": [{"name": "thesecret", "value": "secret-value"}, {"name": "alsosecret", "value": "another-value"}]}'
+want:
+  path: /api/getsecret?id=testkey&version=1
+  err: ''
+  result: secret-value
+---
+case: good json with bad templated jsonpath
 args:
   url: /api/getsecret?id={{ .remoteRef.key }}&version={{ .remoteRef.version }}
   key: testkey
@@ -231,6 +243,17 @@ args:
 want:
   path: /api/getsecret?id=testkey&version=1
   err: 'template: webhooktemplate:1: unexpected "}" in operand'
+---
+case: error with jsonpath filter empty results
+args:
+  url: /api/getsecret?id={{ .remoteRef.key }}&version={{ .remoteRef.version }}
+  key: testkey
+  version: 1
+  jsonpath: $.secrets[?@.name=="thebadsecret"].value
+  response: '{"secrets": [{"name": "thesecret", "value": "secret-value"}, {"name": "alsosecret", "value": "another-value"}]}'
+want:
+  path: /api/getsecret?id=testkey&version=1
+  err: "filter worked but didn't get any result"
 `
 
 func TestWebhookGetSecret(t *testing.T) {