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

test: always use OAuth2 token instead of session token #364

Merged
merged 3 commits into from
Jul 16, 2024
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
19 changes: 11 additions & 8 deletions cmd/cloudx/accountexperience/accountexperience_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import (
"strings"
"testing"

cloud "github.com/ory/client-go"
"github.com/ory/x/cmdx"

"github.com/stretchr/testify/assert"

"github.com/stretchr/testify/require"
Expand All @@ -16,22 +19,22 @@ import (
"github.com/ory/cli/cmd/cloudx/testhelpers"
)

var (
ctx context.Context
project *cloud.Project
cmd *cmdx.CommandExecuter
)

func TestMain(m *testing.M) {
ctx, _, _, project, cmd = testhelpers.CreateDefaultAssetsBrowser()
testhelpers.UseStaging()
m.Run()
}

func TestOpenAXPages(t *testing.T) {
_, _, _, sessionToken := testhelpers.RegisterAccount(context.Background(), t)
ctx := client.ContextWithOptions(context.Background(),
client.WithConfigLocation(testhelpers.NewConfigFile(t)),
client.WithSessionToken(t, sessionToken))
project := testhelpers.CreateProject(ctx, t, nil)
cmd := testhelpers.Cmd(ctx)

t.Run("is able to open all pages", func(t *testing.T) {
for _, flowType := range []string{"login", "registration", "recovery", "verification", "settings"} {
testhelpers.Cmd(client.ContextWithOptions(ctx, client.WithOpenBrowserHook(func(uri string) error {
cmd := testhelpers.Cmd(client.ContextWithOptions(ctx, client.WithOpenBrowserHook(func(uri string) error {
assert.Truef(t, strings.HasPrefix(uri, "https://"+project.Slug), "expected %q to have prefix %q", uri, "https://"+project.Slug)
assert.Contains(t, uri, flowType)
return nil
Expand Down
2 changes: 1 addition & 1 deletion cmd/cloudx/client/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func (h *CommandHelper) oAuth2DanceWithServer(ctx context.Context, client *oauth
l net.Listener
state = randx.MustString(32, randx.AlphaNum)
pkceVerifier = oauth2.GenerateVerifier()
ports = []int{12345, 34525, 49763, 51238, 59724, 60582, 62125}
ports = []int{12345, 15793, 17628, 19834, 23730, 27462, 34525, 36209, 42827, 46718, 49763, 51238, 52213, 57923, 59724, 60582, 62125, 65321, 49876, 54321, 59876, 60987, 62345, 63456, 64567, 65123, 65234, 65432, 65500, 65510, 65520, 65530}
)
rand.Shuffle(len(ports), func(i, j int) { ports[i], ports[j] = ports[j], ports[i] })
for _, port := range ports {
Expand Down
14 changes: 2 additions & 12 deletions cmd/cloudx/client/command_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,9 @@ import (
"os"
"os/user"
"strings"
"testing"

"github.com/pkg/browser"

"github.com/ory/x/pointerx"

"github.com/gofrs/uuid"
"github.com/pkg/browser"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/tidwall/gjson"
Expand All @@ -28,6 +24,7 @@ import (
"github.com/ory/x/cmdx"
"github.com/ory/x/flagx"
"github.com/ory/x/jsonx"
"github.com/ory/x/pointerx"
)

const (
Expand All @@ -53,7 +50,6 @@ type (
openBrowserHook func(string) error
projectAPIKey *string
workspaceAPIKey *string
sessionToken *string
}
helperOptionsContextKey struct{}
CommandHelperOption func(*CommandHelper)
Expand Down Expand Up @@ -121,12 +117,6 @@ func WithWorkspaceAPIKey(apiKey string) CommandHelperOption {
}
}

func WithSessionToken(_ testing.TB, sessionToken string) CommandHelperOption {
return func(h *CommandHelper) {
h.sessionToken = &sessionToken
}
}

func WithOpenBrowserHook(openBrowser func(string) error) CommandHelperOption {
return func(h *CommandHelper) {
h.openBrowserHook = openBrowser
Expand Down
50 changes: 30 additions & 20 deletions cmd/cloudx/client/command_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ func TestMain(m *testing.M) {
}

func TestCommandHelper(t *testing.T) {
defaultConfigFile := testhelpers.NewConfigFile(t)
ctx := client.ContextWithOptions(
context.Background(),
client.WithConfigLocation(testhelpers.NewConfigFile(t)),
client.WithConfigLocation(defaultConfigFile),
client.WithNoConfirm(true),
client.WithQuiet(true),
client.WithVerboseErrWriter(io.Discard),
Expand All @@ -55,9 +56,16 @@ func TestCommandHelper(t *testing.T) {
}))

email, password, name, sessionToken := testhelpers.RegisterAccount(ctx, t)
defaultConfigFile := testhelpers.NewConfigFile(t)
authenticated, err := client.NewCommandHelper(ctx, client.WithConfigLocation(defaultConfigFile), client.WithSessionToken(t, sessionToken))

browser, page, cleanup := testhelpers.SetupPlaywright(t)
t.Cleanup(cleanup)
authenticated, err := client.NewCommandHelper(
ctx,
client.WithQuiet(false),
client.WithOpenBrowserHook(testhelpers.PlaywrightAcceptConsentBrowserHook(t, page, email, password)),
)
require.NoError(t, err)
require.NoError(t, authenticated.Authenticate(ctx))

defaultWorkspace, err := authenticated.CreateWorkspace(ctx, randx.MustString(6, randx.AlphaNum))
require.NoError(t, err)
Expand All @@ -79,14 +87,14 @@ func TestCommandHelper(t *testing.T) {

t.Run("func=SelectProjectWorkspace", func(t *testing.T) {
t.Parallel()
h, err := client.NewCommandHelper(ctx, client.WithSessionToken(t, sessionToken), client.WithConfigLocation(defaultConfigFile))
h, err := client.NewCommandHelper(ctx)
require.NoError(t, err)
otherProject, err := h.CreateProject(ctx, "other project", "dev", &defaultWorkspace.Id, false)
require.NoError(t, err)

t.Run("can change the selected project and workspace", func(t *testing.T) {
// create new helper to ensure clean internal state
h, err := client.NewCommandHelper(ctx, client.WithSessionToken(t, sessionToken), client.WithConfigLocation(defaultConfigFile))
h, err := client.NewCommandHelper(ctx)
require.NoError(t, err)

current, err := h.ProjectID()
Expand All @@ -105,7 +113,7 @@ func TestCommandHelper(t *testing.T) {
assert.Equal(t, defaultWorkspace.Id, *actualWorkspace)

// check if persistent across instances
h, err = client.NewCommandHelper(ctx, client.WithSessionToken(t, sessionToken), client.WithConfigLocation(defaultConfigFile))
h, err = client.NewCommandHelper(ctx)
require.NoError(t, err)

current, err = h.ProjectID()
Expand All @@ -117,10 +125,19 @@ func TestCommandHelper(t *testing.T) {
t.Run("func=ListProjects", func(t *testing.T) {
t.Parallel()

configFile := testhelpers.NewConfigFile(t)
_, _, _, sessionToken := testhelpers.RegisterAccount(ctx, t)
ctx := client.ContextWithOptions(ctx, client.WithConfigLocation(testhelpers.NewConfigFile(t)))
email, password, _, _ := testhelpers.RegisterAccount(ctx, t)
page, err := browser.NewPage()
require.NoError(t, err)
authenticated, err := client.NewCommandHelper(
ctx,
client.WithQuiet(false),
client.WithOpenBrowserHook(testhelpers.PlaywrightAcceptConsentBrowserHook(t, page, email, password)),
)
require.NoError(t, err)
require.NoError(t, authenticated.Authenticate(ctx))

h, err := client.NewCommandHelper(ctx, client.WithSessionToken(t, sessionToken), client.WithConfigLocation(configFile))
h, err := client.NewCommandHelper(ctx)
require.NoError(t, err)

t.Run("empty list", func(t *testing.T) {
Expand Down Expand Up @@ -161,9 +178,9 @@ func TestCommandHelper(t *testing.T) {

t.Run("func=CreateProject", func(t *testing.T) {
t.Parallel()
configPath := testhelpers.NewConfigFile(t)
ctx := testhelpers.WithDuplicatedConfigFile(ctx, t, defaultConfigFile)

h, err := client.NewCommandHelper(ctx, client.WithSessionToken(t, sessionToken), client.WithConfigLocation(configPath))
h, err := client.NewCommandHelper(ctx)
require.NoError(t, err)
workspace, err := h.CreateWorkspace(ctx, t.Name())
require.NoError(t, err)
Expand Down Expand Up @@ -196,19 +213,12 @@ func TestCommandHelper(t *testing.T) {
t.Run("func=Authenticate", func(t *testing.T) {
t.Parallel()

_, page, cleanup := testhelpers.SetupPlaywright(t)
t.Cleanup(cleanup)

// ensure the browser has a valid session cookie
testhelpers.BrowserLogin(t, page, email, password)
t.Logf("browser login successful")

// set up the command helper
ctx := client.ContextWithOptions(ctx, client.WithConfigLocation(testhelpers.NewConfigFile(t)))
h, err := client.NewCommandHelper(
ctx,
client.WithQuiet(false),
client.WithOpenBrowserHook(testhelpers.PlaywrightAcceptConsentBrowserHook(t, page, password)),
client.WithOpenBrowserHook(testhelpers.PlaywrightAcceptConsentBrowserHook(t, page, email, password)),
)
require.NoError(t, err)

Expand Down Expand Up @@ -312,7 +322,7 @@ func TestCommandHelper(t *testing.T) {
t.Run("is not able to get project if not authenticated and quiet flag "+name, func(t *testing.T) {
t.Parallel()

h, err := client.NewCommandHelper(ctx, client.WithQuiet(true))
h, err := client.NewCommandHelper(ctx, client.WithConfigLocation(testhelpers.NewConfigFile(t)), client.WithQuiet(true))
require.NoError(t, err)
_, err = h.GetProject(ctx, p.Id, p.WorkspaceId.Get())
assert.ErrorIs(t, err, client.ErrNoConfigQuiet)
Expand Down
10 changes: 0 additions & 10 deletions cmd/cloudx/client/sdks.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,6 @@ func NewPublicOryProjectClient() *cloud.APIClient {
return cloud.NewAPIClient(conf)
}

func NewConsoleAPIClient(sessionToken string) *cloud.APIClient {
conf := newSDKConfiguration(CloudConsoleURL("api").String())
conf.HTTPClient = newOAuth2TokenClient(oauth2.StaticTokenSource(&oauth2.Token{AccessToken: sessionToken}))
return cloud.NewAPIClient(conf)
}

func (h *CommandHelper) newConsoleAPIClient(ctx context.Context) (_ *cloud.APIClient, err error) {
conf := newSDKConfiguration(CloudConsoleURL("api").String())
conf.HTTPClient, err = h.newConsoleHTTPClient(ctx)
Expand All @@ -87,8 +81,6 @@ func (h *CommandHelper) newConsoleHTTPClient(ctx context.Context) (*http.Client,
// use the workspace API key if set
if h.workspaceAPIKey != nil {
return newOAuth2TokenClient(oauth2.StaticTokenSource(&oauth2.Token{AccessToken: *h.workspaceAPIKey})), nil
} else if h.sessionToken != nil {
return newOAuth2TokenClient(oauth2.StaticTokenSource(&oauth2.Token{AccessToken: *h.sessionToken})), nil
}

// fall back to interactive OAuth2 flow
Expand All @@ -103,8 +95,6 @@ func (h *CommandHelper) newConsoleHTTPClient(ctx context.Context) (*http.Client,
func (h *CommandHelper) ProjectAuthToken(ctx context.Context) (oauth2.TokenSource, func(string) *url.URL, error) {
if h.projectAPIKey != nil {
return oauth2.StaticTokenSource(&oauth2.Token{AccessToken: *h.projectAPIKey}), CloudAPIsURL, nil
} else if h.sessionToken != nil {
return oauth2.StaticTokenSource(&oauth2.Token{AccessToken: *h.sessionToken}), CloudConsoleURL, nil
}

config, err := h.GetAuthenticatedConfig(ctx)
Expand Down
2 changes: 1 addition & 1 deletion cmd/cloudx/identity/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ var (
)

func TestMain(m *testing.M) {
ctx, _, _, defaultProject, defaultCmd = testhelpers.CreateDefaultAssets()
ctx, _, _, defaultProject, defaultCmd = testhelpers.CreateDefaultAssetsBrowser()
m.Run()
}
2 changes: 1 addition & 1 deletion cmd/cloudx/oauth2/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ var (
)

func TestMain(m *testing.M) {
ctx, _, _, defaultProject, defaultCmd = testhelpers.CreateDefaultAssets()
ctx, _, _, defaultProject, defaultCmd = testhelpers.CreateDefaultAssetsBrowser()
m.Run()
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/cloudx/organizations/organizations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var (
)

func TestMain(m *testing.M) {
_, _, _, defaultProject, defaultCmd = testhelpers.CreateDefaultAssets()
_, _, _, defaultProject, defaultCmd = testhelpers.CreateDefaultAssetsBrowser()
m.Run()
}

Expand Down
15 changes: 13 additions & 2 deletions cmd/cloudx/project/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,21 @@ func TestListProject(t *testing.T) {
t.Parallel()

// this test needs a separate account to properly list projects
_, _, _, sessionToken := testhelpers.RegisterAccount(context.Background(), t)
ctx := client.ContextWithOptions(ctx,
client.WithSessionToken(t, sessionToken),
client.WithConfigLocation(testhelpers.NewConfigFile(t)))

email, password, _, _ := testhelpers.RegisterAccount(context.Background(), t)
_, page, cleanup := testhelpers.SetupPlaywright(t)
t.Cleanup(cleanup)
h, err := client.NewCommandHelper(
ctx,
client.WithQuiet(false),
client.WithOpenBrowserHook(testhelpers.PlaywrightAcceptConsentBrowserHook(t, page, email, password)),
)
require.NoError(t, err)
require.NoError(t, h.Authenticate(ctx))
cleanup()

cmd := testhelpers.Cmd(ctx)

projects := make([]*cloud.Project, 3)
Expand Down
2 changes: 1 addition & 1 deletion cmd/cloudx/project/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ var (
)

func TestMain(m *testing.M) {
ctx, defaultConfig, extraProject, defaultProject, defaultCmd = testhelpers.CreateDefaultAssets()
ctx, defaultConfig, extraProject, defaultProject, defaultCmd = testhelpers.CreateDefaultAssetsBrowser()
m.Run()
}
30 changes: 14 additions & 16 deletions cmd/cloudx/project/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,54 +21,54 @@ func TestPatchProject(t *testing.T) {
{
name: "is able to replace a key",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json", "--replace", `/services/identity/config/selfservice/methods/password/enabled=false`)
require.NoError(t, err)
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json", "--replace", `/services/identity/config/selfservice/methods/password/enabled=false`)
require.NoError(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
assert.False(t, gjson.Get(stdout, "services.identity.config.selfservice.methods.password.enabled").Bool())
},
},
{
name: "is able to add a key",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json", "--add", `/services/identity/config/selfservice/methods/password/enabled=false`)
require.NoError(t, err)
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json", "--add", `/services/identity/config/selfservice/methods/password/enabled=false`)
require.NoError(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
assert.False(t, gjson.Get(stdout, "services.identity.config.selfservice.methods.password.enabled").Bool())
},
},
{
name: "is able to add a key with string",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json", "--replace", "/services/identity/config/selfservice/flows/error/ui_url=\"https://example.com/error-ui\"")
require.NoError(t, err)
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json", "--replace", "/services/identity/config/selfservice/flows/error/ui_url=\"https://example.com/error-ui\"")
require.NoError(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
assert.Equal(t, "https://example.com/error-ui", gjson.Get(stdout, "services.identity.config.selfservice.flows.error.ui_url").String())
},
},
{
name: "is able to add a key with raw json",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json", "--replace", `/services/identity/config/selfservice/flows/error={"ui_url":"https://example.org/error-ui"}`)
require.NoError(t, err)
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json", "--replace", `/services/identity/config/selfservice/flows/error={"ui_url":"https://example.org/error-ui"}`)
require.NoErrorf(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
assert.Equal(t, "https://example.org/error-ui", gjson.Get(stdout, "services.identity.config.selfservice.flows.error.ui_url").String())
},
},
{
name: "is able to remove a key",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json", "--remove", `/services/identity/config/selfservice/methods/password/enabled`)
require.NoError(t, err)
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json", "--remove", `/services/identity/config/selfservice/methods/password/enabled`)
require.NoErrorf(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
assert.True(t, gjson.Get(stdout, "services.identity.config.selfservice.methods.password.enabled").Bool())
},
},
{
name: "fails if no opts are given",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json")
require.Error(t, err, stdout)
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json")
require.Errorf(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
},
},
{
name: "is able to update several keys",
doPatch: func(t *testing.T, exec execFunc) {
stdout, _, err := exec(nil, "patch", "project", "--format", "json",
stdout, stderr, err := exec(nil, "patch", "project", "--format", "json",
"--replace", `/services/identity/config/selfservice/methods/link/enabled=true`,
"--replace", `/services/identity/config/selfservice/methods/oidc/enabled=true`,
"--remove", `/services/identity/config/selfservice/methods/profile/enabled`,
Expand All @@ -78,7 +78,7 @@ func TestPatchProject(t *testing.T) {
"-f", "fixtures/patch/1.json",
"-f", "fixtures/patch/2.json",
)
require.NoError(t, err)
require.NoErrorf(t, err, "stdout: %s\nstderr: %s", stdout, stderr)
assert.True(t, gjson.Get(stdout, "services.identity.config.selfservice.methods.password.enabled").Bool())
assert.True(t, gjson.Get(stdout, "services.identity.config.selfservice.methods.profile.enabled").Bool())
assert.True(t, gjson.Get(stdout, "services.identity.config.selfservice.methods.link.enabled").Bool())
Expand All @@ -92,8 +92,6 @@ func TestPatchProject(t *testing.T) {
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

runWithProjectAsDefault(ctx, t, defaultProject.Id, tc.doPatch)
runWithProjectAsArgument(ctx, t, extraProject.Id, tc.doPatch)
})
Expand Down
Loading
Loading