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

fix: Allow use of relative URLs in config #1754

Merged
merged 6 commits into from
Oct 29, 2021
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
29 changes: 17 additions & 12 deletions driver/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,7 @@ func (p *Config) SecretsCipher() [][32]byte {
}

func (p *Config) SelfServiceBrowserDefaultReturnTo() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceBrowserDefaultReturnTo)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceBrowserDefaultReturnTo)
}

func (p *Config) guessBaseURL(keyHost, keyPort string, defaultPort int) *url.URL {
Expand Down Expand Up @@ -758,23 +758,23 @@ func (p *Config) CourierSMTPURL() *url.URL {
}

func (p *Config) SelfServiceFlowLoginUI() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceLoginUI)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceLoginUI)
}

func (p *Config) SelfServiceFlowSettingsUI() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceSettingsURL)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceSettingsURL)
}

func (p *Config) SelfServiceFlowErrorURL() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceErrorUI)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceErrorUI)
}

func (p *Config) SelfServiceFlowRegistrationUI() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceRegistrationUI)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceRegistrationUI)
}

func (p *Config) SelfServiceFlowRecoveryUI() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceRecoveryUI)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceRecoveryUI)
}

// SessionLifespan returns nil when the value is not set.
Expand Down Expand Up @@ -845,24 +845,29 @@ func splitUrlAndFragment(s string) (string, string) {
return s[:i], s[i+1:]
}

func (p *Config) ParseURIOrFail(key string) *url.URL {
func (p *Config) ParseAbsoluteOrRelativeURIOrFail(key string) *url.URL {
u, frag := splitUrlAndFragment(p.p.String(key))
parsed, err := url.ParseRequestURI(u)
if err != nil {
p.l.WithError(errors.WithStack(err)).
Fatalf("Configuration value from key %s is not a valid URL: %s", key, p.p.String(key))
}
if parsed.Scheme == "" {
chlasch marked this conversation as resolved.
Show resolved Hide resolved
p.l.WithField("reason", "expected scheme to be set").
Fatalf("Configuration value from key %s is not a valid URL: %s", key, p.p.String(key))
}

if frag != "" {
parsed.Fragment = frag
}
return parsed
}

func (p *Config) ParseURIOrFail(key string) *url.URL {
parsed := p.ParseAbsoluteOrRelativeURIOrFail(key)
if parsed.Scheme == "" {
p.l.WithField("reason", "expected scheme to be set").
Fatalf("Configuration value from key %s is not a valid URL: %s", key, p.p.String(key))
}
return parsed
}

func (p *Config) Tracing() *tracing.Config {
return p.p.TracingConfig("Ory Kratos")
}
Expand All @@ -884,7 +889,7 @@ func (p *Config) MetricsListenOn() string {
}

func (p *Config) SelfServiceFlowVerificationUI() *url.URL {
return p.ParseURIOrFail(ViperKeySelfServiceVerificationUI)
return p.ParseAbsoluteOrRelativeURIOrFail(ViperKeySelfServiceVerificationUI)
}

func (p *Config) SelfServiceFlowVerificationRequestLifespan() time.Duration {
Expand Down
19 changes: 17 additions & 2 deletions driver/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func TestViperProvider(t *testing.T) {
assert.Equal(t, []string{
"http://return-to-1-test.ory.sh/",
"http://return-to-2-test.ory.sh/",
"/return-to-relative-test/",
}, ds)

pWithFragments := config.MustNew(t, logrusx.New("", ""),
Expand All @@ -81,10 +82,24 @@ func TestViperProvider(t *testing.T) {
assert.Equal(t, "http://test.kratos.ory.sh/#/register", pWithFragments.SelfServiceFlowRegistrationUI().String())
assert.Equal(t, "http://test.kratos.ory.sh/#/error", pWithFragments.SelfServiceFlowErrorURL().String())

pWithRelativeFragments := config.MustNew(t, logrusx.New("", ""),
os.Stderr,
configx.WithValues(map[string]interface{}{
config.ViperKeySelfServiceLoginUI: "/login",
config.ViperKeySelfServiceSettingsURL: "/settings",
config.ViperKeySelfServiceRegistrationUI: "/register",
config.ViperKeySelfServiceErrorUI: "/error",
}),
configx.SkipValidation(),
)

assert.Equal(t, "/login", pWithRelativeFragments.SelfServiceFlowLoginUI().String())
assert.Equal(t, "/settings", pWithRelativeFragments.SelfServiceFlowSettingsUI().String())
assert.Equal(t, "/register", pWithRelativeFragments.SelfServiceFlowRegistrationUI().String())
assert.Equal(t, "/error", pWithRelativeFragments.SelfServiceFlowErrorURL().String())

for _, v := range []string{
"#/login",
"/login",
"/",
"test.kratos.ory.sh/login",
} {

Expand Down
1 change: 1 addition & 0 deletions driver/config/stub/.kratos.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ selfservice:
whitelisted_return_urls:
- http://return-to-1-test.ory.sh/
- http://return-to-2-test.ory.sh/
- /return-to-relative-test/
methods:
totp:
enabled: true
Expand Down
11 changes: 11 additions & 0 deletions internal/testhelpers/handler_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ func NewClientWithCookies(t *testing.T) *http.Client {
return &http.Client{Jar: cj}
}

func NewNoRedirectClientWithCookies(t *testing.T) *http.Client {
cj, err := cookiejar.New(&cookiejar.Options{})
require.NoError(t, err)
return &http.Client{
Jar: cj,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}

func MockHydrateCookieClient(t *testing.T, c *http.Client, u string) {
res, err := c.Get(u)
require.NoError(t, err)
Expand Down
14 changes: 14 additions & 0 deletions internal/testhelpers/selfservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,17 @@ func SelfServiceMakeHookRequest(t *testing.T, ts *httptest.Server, suffix string
require.NoError(t, err)
return res, string(body)
}

func GetSelfServiceRedirectLocation(t *testing.T, url string) string {
Copy link
Member

Choose a reason for hiding this comment

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

Perfect 👍

c := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req, err := http.NewRequest("GET", url, nil)
require.NoError(t, err)
res, err := c.Do(req)
require.NoError(t, err)
defer res.Body.Close()
return res.Header.Get("Location")
}
26 changes: 26 additions & 0 deletions internal/testhelpers/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ func NewHTTPClientWithSessionCookie(t *testing.T, reg *driver.RegistryDefault, s
return c
}

func NewNoRedirectHTTPClientWithSessionCookie(t *testing.T, reg *driver.RegistryDefault, sess *session.Session) *http.Client {
maybePersistSession(t, reg, sess)

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.NoError(t, reg.SessionManager().IssueCookie(context.Background(), w, r, sess))
}))
defer ts.Close()

c := NewNoRedirectClientWithCookies(t)

MockHydrateCookieClient(t, c, ts.URL)
return c
}

func NewTransportWithLogger(parent http.RoundTripper, t *testing.T) *TransportWithLogger {
return &TransportWithLogger{
RoundTripper: parent,
Expand Down Expand Up @@ -118,6 +132,18 @@ func NewHTTPClientWithArbitrarySessionCookie(t *testing.T, reg *driver.RegistryD
return NewHTTPClientWithSessionCookie(t, reg, s)
}

func NewNoRedirectHTTPClientWithArbitrarySessionCookie(t *testing.T, reg *driver.RegistryDefault) *http.Client {
s, err := session.NewActiveSession(
&identity.Identity{ID: x.NewUUID(), State: identity.StateActive},
NewSessionLifespanProvider(time.Hour),
time.Now(),
identity.CredentialsTypePassword,
)
require.NoError(t, err, "Could not initialize session from identity.")

return NewNoRedirectHTTPClientWithSessionCookie(t, reg, s)
}

func NewHTTPClientWithIdentitySessionCookie(t *testing.T, reg *driver.RegistryDefault, id *identity.Identity) *http.Client {
s, err := session.NewActiveSession(id, NewSessionLifespanProvider(time.Hour), time.Now(), identity.CredentialsTypePassword)
require.NoError(t, err, "Could not initialize session from identity.")
Expand Down
14 changes: 14 additions & 0 deletions selfservice/flow/login/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (

"github.com/ory/herodot"

"github.com/ory/kratos/driver/config"
"github.com/ory/kratos/internal"
"github.com/ory/kratos/internal/testhelpers"
"github.com/ory/kratos/schema"
Expand Down Expand Up @@ -98,6 +99,19 @@ func TestHandleError(t *testing.T) {
assertx.EqualAsJSON(t, flowError, sse)
})

t.Run("case=relative error", func(t *testing.T) {
t.Cleanup(reset)
reg.Config(context.Background()).MustSet(config.ViperKeySelfServiceErrorUI, "/login-ts")
flowError = herodot.ErrInternalServerError.WithReason("system error")
ct = node.PasswordGroup
assert.Regexp(
t,
"^/login-ts.*$",
testhelpers.GetSelfServiceRedirectLocation(t, ts.URL+"/error"),
)

})

t.Run("case=error with nil flow detects application/json", func(t *testing.T) {
t.Cleanup(reset)

Expand Down
8 changes: 8 additions & 0 deletions selfservice/flow/login/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,14 @@ func TestFlowLifecycle(t *testing.T) {
assert.Contains(t, res.Request.URL.String(), loginTS.URL)
})
})
t.Run("case=relative redirect when self-service login ui is a relative URL", func(t *testing.T) {
reg.Config(context.Background()).MustSet(config.ViperKeySelfServiceLoginUI, "/login-ts")
assert.Regexp(
t,
"^/login-ts.*$",
testhelpers.GetSelfServiceRedirectLocation(t, ts.URL+login.RouteInitBrowserFlow),
)
})
})
}

Expand Down
9 changes: 9 additions & 0 deletions selfservice/flow/recovery/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,15 @@ func TestInitFlow(t *testing.T) {
res, _ := initAuthenticatedFlow(t, false, false)
assert.Contains(t, res.Request.URL.String(), "https://www.ory.sh")
})
t.Run("case=relative redirect when self-service recovery ui is a relative URL", func(t *testing.T) {
reg.Config(context.Background()).MustSet(config.ViperKeySelfServiceRecoveryUI, "/recovery-ts")
assert.Regexp(
t,
"^/recovery-ts.*$",
testhelpers.GetSelfServiceRedirectLocation(t, publicTS.URL+recovery.RouteInitBrowserFlow),
)
})

})
}

Expand Down
8 changes: 8 additions & 0 deletions selfservice/flow/registration/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ func TestInitFlow(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, res.StatusCode)
assertx.EqualAsJSON(t, registration.ErrAlreadyLoggedIn, json.RawMessage(gjson.GetBytes(body, "error").Raw), "%s", body)
})
t.Run("case=relative redirect when self-service registration ui is a relative URL", func(t *testing.T) {
reg.Config(context.Background()).MustSet(config.ViperKeySelfServiceRegistrationUI, "/registration-ts")
assert.Regexp(
t,
"^/registration-ts.*$",
testhelpers.GetSelfServiceRedirectLocation(t, publicTS.URL+registration.RouteInitBrowserFlow),
)
})
})
}

Expand Down
10 changes: 10 additions & 0 deletions selfservice/flow/settings/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,14 @@ func TestHandler(t *testing.T) {
})
})
})
t.Run("case=relative redirect when self-service settings ui is a relative url", func(t *testing.T) {
reg.Config(context.Background()).MustSet(config.ViperKeySelfServiceSettingsURL, "/settings-ts")
user1 := testhelpers.NewNoRedirectHTTPClientWithArbitrarySessionCookie(t, reg)
res, _ := initFlow(t, user1, false)
assert.Regexp(
t,
"^/settings-ts.*$",
res.Header.Get("Location"),
)
})
}
10 changes: 10 additions & 0 deletions selfservice/flow/verification/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,14 @@ func TestGetFlow(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, public.URL+verification.RouteInitBrowserFlow+"?return_to=https://www.ory.sh", f.RequestURL)
})
t.Run("case=relative redirect when self-service verification ui is a relative URL", func(t *testing.T) {
router := x.NewRouterPublic()
ts, _ := testhelpers.NewKratosServerWithRouters(t, reg, router, x.NewRouterAdmin())
reg.Config(context.Background()).MustSet(config.ViperKeySelfServiceVerificationUI, "/verification-ts")
assert.Regexp(
t,
"^/verification-ts.*$",
testhelpers.GetSelfServiceRedirectLocation(t, ts.URL+verification.RouteInitBrowserFlow),
)
})
}