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

feat: allow multiple webhook body sources #1606

Merged
merged 7 commits into from
Jul 30, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 7 additions & 1 deletion driver/config/.schema/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,13 @@
},
"body": {
"type": "string",
"description": "Path to the jsonnet template used for payload generation. Only used for those HTTP methods, which support HTTP body payloads"
"description": "URI pointing to the jsonnet template used for payload generation. Only used for those HTTP methods, which support HTTP body payloads",
"examples": [
"file:///path/to/body.jsonnet",
"/path/to/body.jsonnet",
"./body.jsonnet",
"base64://ZnVuY3Rpb24oY3R4KSB7CiAgaWRlbnRpdHlfaWQ6IGlmIGN0eFsiaWRlbnRpdHkiXSAhPSBudWxsIHRoZW4gY3R4LmlkZW50aXR5LmlkLAp9="
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we allow loading from http too?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, if the loader is registered.

]
},
"auth": {
"type": "object",
Expand Down
41 changes: 27 additions & 14 deletions selfservice/hook/web_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"io"
"net/http"

"github.com/pkg/errors"

"github.com/ory/jsonschema/v3"
"github.com/ory/kratos/selfservice/flow"

"github.com/ory/kratos/identity"
Expand Down Expand Up @@ -49,10 +52,10 @@ type (
}

webHookConfig struct {
method string
url string
templatePath string
auth AuthStrategy
method string
url string
templateURI string
auth AuthStrategy
}

webHookDependencies interface {
Expand Down Expand Up @@ -166,10 +169,10 @@ func newWebHookConfig(r json.RawMessage) (*webHookConfig, error) {
}

return &webHookConfig{
method: rc.Method,
url: rc.Url,
templatePath: rc.Body,
auth: as,
method: rc.Method,
url: rc.Url,
templateURI: rc.Body,
auth: as,
}, nil
}

Expand Down Expand Up @@ -257,7 +260,7 @@ func (e *WebHook) execute(data *templateContext) error {
// According to the HTTP spec any request method, but TRACE is allowed to
// have a body. Even this is a really bad practice for some of them, like for
// GET
body, err = createBody(conf.templatePath, data)
body, err = createBody(conf.templateURI, data)
if err != nil {
return fmt.Errorf("failed to create web hook body: %w", err)
}
Expand All @@ -269,10 +272,20 @@ func (e *WebHook) execute(data *templateContext) error {
return nil
}

func createBody(templatePath string, data *templateContext) (io.Reader, error) {
var body io.Reader
if len(templatePath) == 0 {
return body, nil
func createBody(templateURI string, data *templateContext) (*bytes.Reader, error) {
if len(templateURI) == 0 {
return nil, nil
}

r, err := jsonschema.LoadURL(templateURI)
if err != nil {
return nil, errors.WithStack(err)
}
defer r.Close()

template, err := io.ReadAll(r)
if err != nil {
return nil, errors.WithStack(err)
}

vm := jsonnet.MakeVM()
Expand All @@ -287,7 +300,7 @@ func createBody(templatePath string, data *templateContext) (io.Reader, error) {
}
vm.TLACode("ctx", buf.String())

if res, err := vm.EvaluateFile(templatePath); err != nil {
if res, err := vm.EvaluateAnonymousSnippet(templateURI, string(template)); err != nil {
return nil, err
} else {
return bytes.NewReader([]byte(res)), nil
Expand Down
107 changes: 69 additions & 38 deletions selfservice/hook/web_hook_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hook

import (
_ "embed"
"encoding/base64"
"encoding/json"
"fmt"
Expand All @@ -9,7 +10,6 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"

"github.com/ory/kratos/selfservice/flow/recovery"
Expand Down Expand Up @@ -91,47 +91,78 @@ func TestApiKeyInCookieStrategy(t *testing.T) {
assert.Equal(t, "my-api-key-value", cookies[0].Value)
}

//go:embed stub/test_body.jsonnet
var testBodyJSONNet []byte

func TestJsonNetSupport(t *testing.T) {
f := login.Flow{ID: x.NewUUID()}
f := &login.Flow{ID: x.NewUUID()}
i := identity.NewIdentity("")

headers := http.Header{}
headers.Add("Some-Header", "Some-Value")
headers.Add("Cookie", "c1=v1")
headers.Add("Cookie", "c2=v2")
data := &templateContext{
Flow: &f,
RequestHeaders: headers,
RequestMethod: "POST",
RequestUrl: "https://test.kratos.ory.sh/some-test-path",
Identity: i,
}

b, err := createBody("./stub/test_body.jsonnet", data)
assert.NoError(t, err)

buf := new(strings.Builder)
io.Copy(buf, b)

expected := fmt.Sprintf(`
for _, tc := range []struct {
desc, template string
data *templateContext
}{
{
desc: "simple file URI",
template: "file://./stub/test_body.jsonnet",
data: &templateContext{
Flow: f,
RequestHeaders: http.Header{
"Cookie": []string{"c1=v1", "c2=v2"},
"Some-Header": []string{"Some-Value"},
},
RequestMethod: "POST",
RequestUrl: "https://test.kratos.ory.sh/some-test-path",
Identity: i,
},
},
{
desc: "filepath without scheme",
template: "./stub/test_body.jsonnet",
aeneasr marked this conversation as resolved.
Show resolved Hide resolved
data: &templateContext{
Flow: f,
RequestHeaders: http.Header{
"Cookie": []string{"c1=v1", "c2=v2"},
"Some-Header": []string{"Some-Value"},
},
RequestMethod: "POST",
RequestUrl: "https://test.kratos.ory.sh/some-test-path",
Identity: i,
},
},
{
"flow_id": "%s",
"identity_id": "%s",
"headers": {
"Cookie": ["%s", "%s"],
"Some-Header": ["%s"]
desc: "base64 encoded template URI",
template: "base64://" + base64.StdEncoding.EncodeToString(testBodyJSONNet),
data: &templateContext{
Flow: f,
RequestHeaders: http.Header{
"Cookie": []string{"foo=bar"},
"My-Custom-Header": []string{"Cumstom-Value"},
},
RequestMethod: "PUT",
RequestUrl: "https://test.kratos.ory.sh/other-test-path",
Identity: i,
},
"method": "%s",
"url": "%s"
}`,
f.ID, i.ID,
data.RequestHeaders.Values("Cookie")[0],
data.RequestHeaders.Values("Cookie")[1],
data.RequestHeaders.Get("Some-Header"),
data.RequestMethod,
data.RequestUrl)

assert.JSONEq(t, expected, buf.String())
},
} {
t.Run("case="+tc.desc, func(t *testing.T) {
b, err := createBody(tc.template, tc.data)
require.NoError(t, err)
body, err := io.ReadAll(b)
require.NoError(t, err)

expected, err := json.Marshal(map[string]interface{}{
"flow_id": tc.data.Flow.GetID(),
"identity_id": tc.data.Identity.ID,
"headers": tc.data.RequestHeaders,
"method": tc.data.RequestMethod,
"url": tc.data.RequestUrl,
})
require.NoError(t, err)

assert.JSONEq(t, string(expected), string(body))
})
}
}

func TestWebHookConfig(t *testing.T) {
Expand Down Expand Up @@ -221,7 +252,7 @@ func TestWebHookConfig(t *testing.T) {

assert.Equal(t, tc.url, conf.url)
assert.Equal(t, tc.method, conf.method)
assert.Equal(t, tc.body, conf.templatePath)
assert.Equal(t, tc.body, conf.templateURI)
assert.NotNil(t, conf.auth)
assert.IsTypef(t, tc.authStrategy, conf.auth, "Auth should be of the expected type")
})
Expand Down