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: transient_payload lost in API flow with session token exchange code (PS-482) #4112

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
38 changes: 38 additions & 0 deletions selfservice/flow/transient_payload.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package flow

import (
"github.com/ory/x/sqlxx"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)

const internalContextTransientPayloadPath = "transient_payload"

func SetTransientPayloadIntoInternalContext(flow InternalContexter, transientPayload sqlxx.JSONRawMessage) error {
if flow.GetInternalContext() == nil {
flow.EnsureInternalContext()
}
bytes, err := sjson.SetBytes(
flow.GetInternalContext(),
internalContextTransientPayloadPath,
transientPayload,
)
if err != nil {
return err
}
flow.SetInternalContext(bytes)

return nil
}

func GetTransientPayloadFromInternalContext(flow InternalContexter) (sqlxx.JSONRawMessage, error) {
if flow.GetInternalContext() == nil {
flow.EnsureInternalContext()
}
raw := gjson.GetBytes(flow.GetInternalContext(), internalContextTransientPayloadPath)
if !raw.IsObject() {
return nil, nil
Copy link
Member

Choose a reason for hiding this comment

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

Error is always nil, remove it?

}

return sqlxx.JSONRawMessage(raw.Raw), nil
}
8 changes: 8 additions & 0 deletions selfservice/strategy/oidc/strategy.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,14 @@ func (s *Strategy) ValidateCallback(w http.ResponseWriter, r *http.Request) (flo
}
cntnr.State = stateParam
cntnr.FlowID = state.FlowID
internalContexter, ok := f.(flow.InternalContexter)
if ok {
transientPayload, err := flow.GetTransientPayloadFromInternalContext(internalContexter)
if err != nil {
return nil, &cntnr, err
}
cntnr.TransientPayload = json.RawMessage(transientPayload)
}
}

if errorParam != "" {
Expand Down
7 changes: 7 additions & 0 deletions selfservice/strategy/oidc/strategy_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package oidc
import (
"bytes"
"encoding/json"
"github.com/ory/x/sqlxx"
"net/http"
"strings"
"time"
Expand Down Expand Up @@ -201,6 +202,12 @@ func (s *Strategy) Login(w http.ResponseWriter, r *http.Request, f *login.Flow,
f.IDToken = p.IDToken
f.RawIDTokenNonce = p.IDTokenNonce
f.TransientPayload = p.TransientPayload
if err := flow.SetTransientPayloadIntoInternalContext(f, sqlxx.JSONRawMessage(p.TransientPayload)); err != nil {
return nil, err
}
if err := s.d.LoginFlowPersister().UpdateLoginFlow(ctx, f); err != nil {
return nil, err
}

pid := p.Provider // this can come from both url query and post body
if pid == "" {
Expand Down
6 changes: 6 additions & 0 deletions selfservice/strategy/oidc/strategy_registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ func (s *Strategy) Register(w http.ResponseWriter, r *http.Request, f *registrat
f.TransientPayload = p.TransientPayload
f.IDToken = p.IDToken
f.RawIDTokenNonce = p.IDTokenNonce
if err := flow.SetTransientPayloadIntoInternalContext(f, sqlxx.JSONRawMessage(p.TransientPayload)); err != nil {
return s.handleError(w, r, f, pid, nil, err)
}
if err := s.d.RegistrationFlowPersister().UpdateRegistrationFlow(ctx, f); err != nil {
Copy link
Member

Choose a reason for hiding this comment

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

Is this database write really needed?

return s.handleError(w, r, f, pid, nil, err)
}

if !strings.EqualFold(strings.ToLower(p.Method), s.SettingsStrategyID()) && p.Method != "" {
// the user is sending a method that is not oidc, but the payload includes a provider
Expand Down
45 changes: 35 additions & 10 deletions selfservice/strategy/oidc/strategy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,13 @@ func TestStrategy(t *testing.T) {
return res, body
}

makeAPICodeFlowRequest := func(t *testing.T, provider, action string) (returnToURL *url.URL) {
res, err := testhelpers.NewDebugClient(t).Post(action, "application/json", strings.NewReader(fmt.Sprintf(`{
"method": "oidc",
"provider": %q
}`, provider)))
makeAPICodeFlowRequest := func(t *testing.T, provider, action string, transientPayload string) (returnToURL *url.URL) {
res, err := testhelpers.NewDebugClient(t).Post(action, "application/json",
strings.NewReader(fmt.Sprintf(`{
"method": "oidc",
"provider": %q,
"transient_payload": %q
}`, provider, transientPayload)))
require.NoError(t, err)
require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode)
var changeLocation flow.BrowserLocationChangeRequiredError
Expand Down Expand Up @@ -650,14 +652,25 @@ func TestStrategy(t *testing.T) {
})

t.Run("suite=API with session token exchange code", func(t *testing.T) {
postRegistrationWebhook := hooktest.NewServer()
t.Cleanup(postRegistrationWebhook.Close)
postRegistrationWebhook.SetConfig(t, conf.GetProvider(ctx),
config.HookStrategyKey(config.ViperKeySelfServiceRegistrationAfter, identity.CredentialsTypeOIDC.String()))

postLoginWebhook := hooktest.NewServer()
t.Cleanup(postLoginWebhook.Close)
postLoginWebhook.SetConfig(t, conf.GetProvider(ctx),
config.HookStrategyKey(config.ViperKeySelfServiceLoginAfter, config.HookGlobal))

scope = []string{"openid"}
transientPayload := `{"data": "registration"}`

loginOrRegister := func(t *testing.T, flowID uuid.UUID, code string) {
_, err := exchangeCodeForToken(t, sessiontokenexchange.Codes{InitCode: code})
require.Error(t, err)

action := assertFormValues(t, flowID, "valid")
returnToURL := makeAPICodeFlowRequest(t, "valid", action)
returnToURL := makeAPICodeFlowRequest(t, "valid", action, transientPayload)
returnToCode := returnToURL.Query().Get("code")
assert.NotEmpty(t, code, "code query param was empty in the return_to URL")

Expand All @@ -673,27 +686,39 @@ func TestStrategy(t *testing.T) {
performRegistration := func(t *testing.T) {
f := newAPIRegistrationFlow(t, returnTS.URL+"?return_session_token_exchange_code=true&return_to=/app_code", 1*time.Minute)
loginOrRegister(t, f.ID, f.SessionTokenExchangeCode)
postRegistrationWebhook.AssertTransientPayload(t, transientPayload)
}
startRegistrationButLogin := func(t *testing.T) {
f := newAPIRegistrationFlow(t, returnTS.URL+"?return_session_token_exchange_code=true&return_to=/app_code", 1*time.Minute)
loginOrRegister(t, f.ID, f.SessionTokenExchangeCode)
postLoginWebhook.AssertTransientPayload(t, transientPayload)
}
performLogin := func(t *testing.T) {
f := newAPILoginFlow(t, returnTS.URL+"?return_session_token_exchange_code=true&return_to=/app_code", 1*time.Minute)
loginOrRegister(t, f.ID, f.SessionTokenExchangeCode)
postLoginWebhook.AssertTransientPayload(t, transientPayload)
}
startLoginButRegister := func(t *testing.T) {
f := newAPILoginFlow(t, returnTS.URL+"?return_session_token_exchange_code=true&return_to=/app_code", 1*time.Minute)
loginOrRegister(t, f.ID, f.SessionTokenExchangeCode)
postRegistrationWebhook.AssertTransientPayload(t, transientPayload)
}

for _, tc := range []struct {
name string
first, then func(*testing.T)
}{{
name: "login-twice",
first: performLogin, then: performLogin,
first: startLoginButRegister, then: performLogin,
}, {
name: "login-then-register",
first: performLogin, then: performRegistration,
first: startLoginButRegister, then: startRegistrationButLogin,
}, {
name: "register-then-login",
first: performRegistration, then: performLogin,
}, {
name: "register-twice",
first: performRegistration, then: performRegistration,
first: performRegistration, then: startRegistrationButLogin,
}} {
t.Run("case="+tc.name, func(t *testing.T) {
subject = tc.name + "[email protected]"
Expand All @@ -718,7 +743,7 @@ func TestStrategy(t *testing.T) {
require.Error(t, err)

action := assertFormValues(t, f.ID, "valid")
returnToURL := makeAPICodeFlowRequest(t, "valid", action)
returnToURL := makeAPICodeFlowRequest(t, "valid", action, "{}")
returnedFlow := returnToURL.Query().Get("flow")

require.NotEmpty(t, returnedFlow, "flow query param was empty in the return_to URL")
Expand Down
Loading