From 282177afc28a5bd83d8c92f00e8fc3d5c0db3b89 Mon Sep 17 00:00:00 2001 From: Jeff Mitchell Date: Mon, 17 Aug 2020 15:38:41 -0400 Subject: [PATCH] Remove the default org (#270) --- api/authmethods/account_test.go | 21 +-- api/groups/group_test.go | 34 ++--- api/hosts/host_catalog_test.go | 23 +--- api/roles/role_test.go | 70 +++------- api/scopes/project_test.go | 26 ++-- api/users/user_test.go | 12 +- internal/cmd/base/base.go | 43 +++--- internal/cmd/base/servers.go | 126 ++++++------------ .../cmd/commands/controller/controller.go | 15 --- internal/cmd/commands/dev/dev.go | 15 --- internal/cmd/config/config.go | 1 - internal/cmd/main.go | 9 +- internal/db/domains_test.go | 14 -- internal/db/migrations/postgres.gen.go | 33 +---- internal/db/migrations/postgres/06_iam.up.sql | 33 +---- internal/iam/testing.go | 18 +++ internal/servers/controller/cors_test.go | 7 +- internal/servers/controller/handler_test.go | 6 +- internal/servers/controller/handler_ui.go | 14 +- .../controller/index_response_writer.go | 50 ------- internal/servers/controller/multi_test.go | 12 +- internal/servers/controller/testing.go | 24 ++-- .../cluster/multi_controller_worker_test.go | 2 - testing/controller/controller.go | 13 -- 24 files changed, 190 insertions(+), 431 deletions(-) delete mode 100644 internal/servers/controller/index_response_writer.go diff --git a/api/authmethods/account_test.go b/api/authmethods/account_test.go index f9069771b..a5b0b8403 100644 --- a/api/authmethods/account_test.go +++ b/api/authmethods/account_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api/authmethods" "github.com/hashicorp/boundary/internal/auth/password" + "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/servers/controller" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -15,11 +16,9 @@ import ( func TestAccounts_List(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -27,6 +26,9 @@ func TestAccounts_List(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + accountClient := authmethods.NewAccountsClient(client) expected, apiErr, err := accountClient.List(tc.Context(), amId) @@ -76,11 +78,9 @@ func comparableSlice(in []*authmethods.Account) []authmethods.Account { func TestAccount_Crud(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -88,6 +88,9 @@ func TestAccount_Crud(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + accountClient := authmethods.NewAccountsClient(client) checkAccount := func(step string, u *authmethods.Account, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) { @@ -129,11 +132,9 @@ func TestAccount_Crud(t *testing.T) { func TestAccount_CustomMethods(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -141,6 +142,9 @@ func TestAccount_CustomMethods(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + accountClient := authmethods.NewAccountsClient(client) al, apiErr, err := accountClient.List(tc.Context(), amId) @@ -165,11 +169,9 @@ func TestAccount_CustomMethods(t *testing.T) { func TestAccount_Errors(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -177,6 +179,9 @@ func TestAccount_Errors(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + accountClient := authmethods.NewAccountsClient(client) u, apiErr, err := accountClient.Create(tc.Context(), amId, authmethods.WithType("password"), authmethods.WithPasswordAccountLoginName("first")) diff --git a/api/groups/group_test.go b/api/groups/group_test.go index dc211d168..8b999220e 100644 --- a/api/groups/group_test.go +++ b/api/groups/group_test.go @@ -7,7 +7,6 @@ import ( "github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api/groups" - "github.com/hashicorp/boundary/api/scopes" "github.com/hashicorp/boundary/api/users" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/servers/controller" @@ -17,11 +16,9 @@ import ( func TestGroup_List(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -29,13 +26,10 @@ func TestGroup_List(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) cases := []struct { name string @@ -92,11 +86,9 @@ func comparableSlice(in []*groups.Group) []groups.Group { func TestGroup_Crud(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -104,13 +96,10 @@ func TestGroup_Crud(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) checkGroup := func(step string, g *groups.Group, apiErr *api.Error, err error, wantedName string, wantedVersion uint32, expectedUserIds []string) { require.NoError(err, step) @@ -189,11 +178,9 @@ func TestGroup_Crud(t *testing.T) { func TestGroup_Errors(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -201,13 +188,10 @@ func TestGroup_Errors(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) cases := []struct { name string diff --git a/api/hosts/host_catalog_test.go b/api/hosts/host_catalog_test.go index f872dcdf9..0051bd59e 100644 --- a/api/hosts/host_catalog_test.go +++ b/api/hosts/host_catalog_test.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api/hosts" - "github.com/hashicorp/boundary/api/scopes" "github.com/hashicorp/boundary/internal/host/static" + "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/servers/controller" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -15,11 +15,9 @@ import ( func TestCatalogs_Crud(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -27,13 +25,10 @@ func TestCatalogs_Crud(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) checkCatalog := func(step string, hc *hosts.HostCatalog, apiErr *api.Error, err error, wantedName string, wantVersion uint32) { require.NoError(err, step) @@ -75,11 +70,9 @@ func TestCatalogs_Crud(t *testing.T) { // TODO: Get better coverage for expected errors and error formats. func TestCatalogs_Errors(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -87,12 +80,8 @@ func TestCatalogs_Errors(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - - client.SetScopeId(proj.Id) + _, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(proj.GetPublicId()) pc := hosts.NewHostCatalogsClient(client) hc, apiErr, err := pc.Create(tc.Context(), hosts.WithType("static")) diff --git a/api/roles/role_test.go b/api/roles/role_test.go index 87cdf02f4..f87364cf3 100644 --- a/api/roles/role_test.go +++ b/api/roles/role_test.go @@ -7,9 +7,7 @@ import ( "github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api/groups" - "github.com/hashicorp/boundary/api/internal/strutil" "github.com/hashicorp/boundary/api/roles" - "github.com/hashicorp/boundary/api/scopes" "github.com/hashicorp/boundary/api/users" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/servers/controller" @@ -20,11 +18,9 @@ import ( func TestCustom(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -32,13 +28,10 @@ func TestCustom(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) cases := []struct { name string @@ -138,11 +131,9 @@ func TestCustom(t *testing.T) { func TestRole_List(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -150,13 +141,10 @@ func TestRole_List(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) cases := []struct { name string @@ -178,13 +166,7 @@ func TestRole_List(t *testing.T) { p1, apiErr, err := roleClient.List(tc.Context()) require.NoError(err) assert.Nil(apiErr) - var defaultRoleIds []string - if tt.name == "org" { - require.True(len(p1) == 2) - defaultRoleIds = []string{p1[0].Id, p1[1].Id} - } else { - require.Len(p1, 0) - } + require.Len(p1, 0) var expected []*roles.Role for i := 0; i < 10; i++ { @@ -198,13 +180,7 @@ func TestRole_List(t *testing.T) { p2, apiErr, err := roleClient.List(tc.Context()) assert.NoError(err) assert.Nil(apiErr) - var p2ForComparison []*roles.Role - for _, v := range p2 { - if !strutil.StrListContains(defaultRoleIds, v.Id) { - p2ForComparison = append(p2ForComparison, v) - } - } - assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(p2ForComparison)) + assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(p2)) for i := 1; i < 10; i++ { expected[i], apiErr, err = roleClient.Create(tc.Context(), roles.WithName(expected[i].Name)) @@ -214,13 +190,7 @@ func TestRole_List(t *testing.T) { p3, apiErr, err := roleClient.List(tc.Context()) require.NoError(err) assert.Nil(apiErr) - var p3ForComparison []*roles.Role - for _, v := range p3 { - if !strutil.StrListContains(defaultRoleIds, v.Id) { - p3ForComparison = append(p3ForComparison, v) - } - } - assert.ElementsMatch(comparableSlice(expected), comparableSlice(p3ForComparison)) + assert.ElementsMatch(comparableSlice(expected), comparableSlice(p3)) }) } } @@ -242,11 +212,9 @@ func comparableSlice(in []*roles.Role) []roles.Role { func TestRole_Crud(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -254,13 +222,10 @@ func TestRole_Crud(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) cases := []struct { name string @@ -320,11 +285,9 @@ func TestRole_Crud(t *testing.T) { func TestRole_Errors(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -332,13 +295,10 @@ func TestRole_Errors(t *testing.T) { defer tc.Shutdown() client := tc.Client() - - proj, apiErr, err := scopes.NewScopesClient(client).Create(tc.Context(), orgId) - require.NoError(err) - require.Nil(apiErr) - + org, proj := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) projClient := client.Clone() - projClient.SetScopeId(proj.Id) + projClient.SetScopeId(proj.GetPublicId()) cases := []struct { name string diff --git a/api/scopes/project_test.go b/api/scopes/project_test.go index 6d7c48148..c41bf88ff 100644 --- a/api/scopes/project_test.go +++ b/api/scopes/project_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api/scopes" + "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/servers/controller" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -14,11 +15,9 @@ import ( func TestProjects_List(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -26,20 +25,23 @@ func TestProjects_List(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + scps := scopes.NewScopesClient(client) - pl, apiErr, err := scps.List(tc.Context(), orgId) + pl, apiErr, err := scps.List(tc.Context(), org.GetPublicId()) require.NoError(err) assert.Nil(apiErr) assert.Empty(pl) expected := make([]*scopes.Scope, 10) for i := 0; i < 10; i++ { - expected[i], apiErr, err = scps.Create(tc.Context(), orgId, scopes.WithName(fmt.Sprintf("%d", i))) + expected[i], apiErr, err = scps.Create(tc.Context(), org.GetPublicId(), scopes.WithName(fmt.Sprintf("%d", i))) require.NoError(err) assert.Nil(apiErr) } - pl, apiErr, err = scps.List(tc.Context(), orgId) + pl, apiErr, err = scps.List(tc.Context(), org.GetPublicId()) require.NoError(err) assert.Nil(apiErr) assert.ElementsMatch(comparableSlice(expected), comparableSlice(pl)) @@ -62,11 +64,9 @@ func comparableSlice(in []*scopes.Scope) []scopes.Scope { func TestProjects_Crud(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -74,6 +74,9 @@ func TestProjects_Crud(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org, _ := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + scps := scopes.NewScopesClient(client) checkProject := func(step string, s *scopes.Scope, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) { @@ -88,7 +91,7 @@ func TestProjects_Crud(t *testing.T) { assert.Equal(wantedVersion, s.Version) } - s, apiErr, err := scps.Create(tc.Context(), orgId, scopes.WithName("foo")) + s, apiErr, err := scps.Create(tc.Context(), org.GetPublicId(), scopes.WithName("foo")) checkProject("create", s, apiErr, err, "foo", 1) s, apiErr, err = scps.Read(tc.Context(), s.Id) @@ -114,11 +117,9 @@ func TestProjects_Crud(t *testing.T) { // TODO: Get better coverage for expected errors and error formats. func TestProject_Errors(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -126,9 +127,12 @@ func TestProject_Errors(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org, _ := iam.TestScopes(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) + scps := scopes.NewScopesClient(client) - createdProj, apiErr, err := scps.Create(tc.Context(), orgId) + createdProj, apiErr, err := scps.Create(tc.Context(), org.GetPublicId()) require.NoError(err) assert.NotNil(createdProj) assert.Nil(apiErr) diff --git a/api/users/user_test.go b/api/users/user_test.go index d4d1e39df..cfb4845d1 100644 --- a/api/users/user_test.go +++ b/api/users/user_test.go @@ -15,11 +15,9 @@ import ( func TestUsers_List(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -27,6 +25,8 @@ func TestUsers_List(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) userClient := users.NewUsersClient(client) ul, apiErr, err := userClient.List(tc.Context()) @@ -76,11 +76,9 @@ func comparableSlice(in []*users.User) []users.User { func TestUser_Crud(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -88,6 +86,8 @@ func TestUser_Crud(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) userClient := users.NewUsersClient(client) checkUser := func(step string, u *users.User, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) { @@ -129,11 +129,9 @@ func TestUser_Crud(t *testing.T) { func TestUser_Errors(t *testing.T) { assert, require := assert.New(t), require.New(t) - orgId := "o_1234567890" amId := "paum_1234567890" tc := controller.NewTestController(t, &controller.TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: "user", DefaultPassword: "passpass", @@ -141,6 +139,8 @@ func TestUser_Errors(t *testing.T) { defer tc.Shutdown() client := tc.Client() + org := iam.TestOrg(t, tc.DbConn()) + client.SetScopeId(org.GetPublicId()) userClient := users.NewUsersClient(client) u, apiErr, err := userClient.Create(tc.Context(), users.WithName("first")) diff --git a/internal/cmd/base/base.go b/internal/cmd/base/base.go index 7df8a7815..1e0c73d3a 100644 --- a/internal/cmd/base/base.go +++ b/internal/cmd/base/base.go @@ -46,8 +46,9 @@ type Command struct { flags *FlagSets flagsOnce sync.Once - flagAddr string - flagScope string + flagAddr string + flagScope string + flagVerbose bool flagTLSCACert string flagTLSCAPath string @@ -168,8 +169,8 @@ func (c *Command) Client() (*api.Client, error) { c.client.SetMaxRetries(0) } + tokenName := "default" if c.client.Token() == "" { - tokenName := "default" if c.FlagTokenName != "" { tokenName = c.FlagTokenName } @@ -203,10 +204,25 @@ func (c *Command) Client() (*api.Client, error) { // We do this here so we override the stored token info if it's set above if c.flagScope != NotSetValue { c.client.SetScopeId(c.flagScope) + if c.flagFormat == "table" && c.flagVerbose { + if c.flagScope == os.Getenv("BOUNDARY_TOKEN") { + c.UI.Info(fmt.Sprintf("Scope of %q set from BOUNDARY_TOKEN env var", c.flagScope)) + } else { + c.UI.Info(fmt.Sprintf("Scope of %q set from -scope command flag", c.flagScope)) + } + } + } else if c.client.ScopeId() != "" { + // If it didn't come from env or a flag but isn't empty, it must have come from the token + if c.flagFormat == "table" && c.flagVerbose { + c.UI.Info(fmt.Sprintf("Scope of %q set from saved token with name %q", c.client.ScopeId(), tokenName)) + } } // At this point if we haven't figured out the scope, default to "global" if c.client.ScopeId() == "" { c.client.SetScopeId("global") + if c.flagFormat == "table" && c.flagVerbose { + c.UI.Info(`Scope of "global" set by default`) + } } return c.client, nil @@ -218,7 +234,6 @@ const ( FlagSetNone FlagSetBit = 1 << iota FlagSetHTTP FlagSetClient - FlagSetOutputField FlagSetOutputFormat ) @@ -334,21 +349,15 @@ func (c *Command) FlagSet(bit FlagSetBit) *FlagSets { }) } - if bit&(FlagSetOutputField|FlagSetOutputFormat) != 0 { + if bit&FlagSetOutputFormat != 0 { f := set.NewFlagSet("Output Options") - if bit&FlagSetOutputField != 0 { - f.StringVar(&StringVar{ - Name: "field", - Target: &c.flagField, - Default: "", - Completion: complete.PredictAnything, - Usage: "Print only the field with the given name. Specifying " + - "this option will take precedence over other formatting " + - "directives. The result will not have a trailing newline " + - "making it ideal for piping to other processes.", - }) - } + f.BoolVar(&BoolVar{ + Name: "verbose", + Target: &c.flagVerbose, + Completion: complete.PredictAnything, + Usage: "Turns on some extra verbosity in the command output.", + }) if bit&FlagSetOutputFormat != 0 { f.StringVar(&StringVar{ diff --git a/internal/cmd/base/servers.go b/internal/cmd/base/servers.go index 7b186147a..b54b56fb9 100644 --- a/internal/cmd/base/servers.go +++ b/internal/cmd/base/servers.go @@ -18,6 +18,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/types/scope" "github.com/hashicorp/boundary/version" "github.com/hashicorp/errwrap" "github.com/hashicorp/go-hclog" @@ -62,7 +63,6 @@ type Server struct { Listeners []*ServerListener - DefaultOrgId string DevAuthMethodId string DevLoginName string DevPassword string @@ -444,52 +444,57 @@ func (b *Server) CreateDevDatabase(dialect string) error { cancel() }() - var orgScope *iam.Scope - if b.DefaultOrgId != "" { - orgScope, err = repo.LookupScope(ctx, b.DefaultOrgId) - if err != nil { - return fmt.Errorf("error looking up existing scope with org ID %q: %w", b.DefaultOrgId, err) - } - } - - if orgScope == nil { - orgScope, err = iam.NewOrg() - if err != nil { - return fmt.Errorf("error creating new org scope: %w", err) - } - orgScope, err = repo.CreateScope(ctx, orgScope, "", iam.WithPublicId(b.DefaultOrgId)) - if err != nil { - return fmt.Errorf("error persisting new org scope: %w", err) - } - if b.DefaultOrgId != "" { - if orgScope.GetPublicId() != b.DefaultOrgId { - return fmt.Errorf("expected org ID %q, got %q after persisting", b.DefaultOrgId, orgScope.GetPublicId()) - } - } else { - b.DefaultOrgId = orgScope.GetPublicId() - } - } - - ar, err := iam.NewRole(orgScope.PublicId) + // Create the dev auth method + pwRepo, err := password.NewRepository(rw, rw, b.ControllerKMS) if err != nil { - return fmt.Errorf("error creating in memory role for anon authen: %w", err) + return fmt.Errorf("error creating password repo: %w", err) } - authenRole, err := repo.CreateRole(ctx, ar, iam.WithDescription("role for authentication by the anonymous user")) + authMethod, err := password.NewAuthMethod(scope.Global.String()) if err != nil { - return fmt.Errorf("error creating role for anon authen: %w", err) + return fmt.Errorf("error creating new in memory auth method: %w", err) } - if _, err := repo.AddRoleGrants(ctx, authenRole.PublicId, authenRole.Version, []string{"type=auth-method;actions=list,authenticate"}); err != nil { - return fmt.Errorf("error creating grant for anon authen: %w", err) + amId := b.DevAuthMethodId + if amId == "" { + amId = "paum_1234567890" } - if _, err := repo.AddPrincipalRoles(ctx, authenRole.PublicId, authenRole.Version+1, []string{"u_anon"}, nil); err != nil { - return fmt.Errorf("error adding principal to role for anon authen: %w", err) + _, err = pwRepo.CreateAuthMethod(ctx, authMethod, password.WithPublicId(amId)) + if err != nil { + return fmt.Errorf("error saving auth method to the db: %w", err) } - pr, err := iam.NewRole(orgScope.PublicId) + // Create the dev user + acctLoginName := b.DevLoginName + if acctLoginName == "" { + acctLoginName, err = base62.Random(10) + if err != nil { + return fmt.Errorf("unable to generate dev login name: %w", err) + } + acctLoginName = strings.ToLower(acctLoginName) + } + pw := b.DevPassword + if pw == "" { + pw, err = base62.Random(20) + if err != nil { + return fmt.Errorf("unable to generate dev password: %w", err) + } + } + acct, err := password.NewAccount(amId, password.WithLoginName(acctLoginName)) + if err != nil { + return fmt.Errorf("error creating new in memory auth account: %w", err) + } + acct, err = pwRepo.CreateAccount(ctx, acct, password.WithPassword(pw)) + if err != nil { + return fmt.Errorf("error saving auth account to the db: %w", err) + } + + // Create a role tying them together + pr, err := iam.NewRole(scope.Global.String()) if err != nil { return fmt.Errorf("error creating in memory role for default dev grants: %w", err) } - defPermsRole, err := repo.CreateRole(ctx, pr, iam.WithDescription("role for admin grants to authenticated users")) + pr.Name = "Dev Mode Global Scope Admin Role" + pr.Description = `Provides admin grants to all authenticated users within the "global" scope` + defPermsRole, err := repo.CreateRole(ctx, pr) if err != nil { return fmt.Errorf("error creating role for default dev grants: %w", err) } @@ -500,52 +505,7 @@ func (b *Server) CreateDevDatabase(dialect string) error { return fmt.Errorf("error adding principal to role for default dev grants: %w", err) } - pwRepo, err := password.NewRepository(rw, rw, b.ControllerKMS) - if err != nil { - return fmt.Errorf("error creating password repo: %w", err) - } - authMethod, err := password.NewAuthMethod(orgScope.GetPublicId()) - if err != nil { - return fmt.Errorf("error creating new in memory auth method: %w", err) - } - - amId := b.DevAuthMethodId - if amId == "" { - amId = "paum_1234567890" - } - _, err = pwRepo.CreateAuthMethod(ctx, authMethod, password.WithPublicId(amId)) - if err != nil { - return fmt.Errorf("error saving auth method to the db: %w", err) - } - - acctLoginName := b.DevLoginName - if acctLoginName == "" { - acctLoginName, err = base62.Random(10) - if err != nil { - return fmt.Errorf("unable to generate dev login name: %w", err) - } - acctLoginName = strings.ToLower(acctLoginName) - } - - pw := b.DevPassword - if pw == "" { - pw, err = base62.Random(20) - if err != nil { - return fmt.Errorf("unable to generate dev password: %w", err) - } - } - - acct, err := password.NewAccount(amId, password.WithLoginName(acctLoginName)) - if err != nil { - return fmt.Errorf("error creating new in memory auth account: %w", err) - } - acct, err = pwRepo.CreateAccount(ctx, acct, password.WithPassword(pw)) - if err != nil { - return fmt.Errorf("error saving auth account to the db: %w", err) - } - - b.InfoKeys = append(b.InfoKeys, "dev org id", "dev auth method id", "dev login name", "dev password") - b.Info["dev org id"] = b.DefaultOrgId + b.InfoKeys = append(b.InfoKeys, "dev auth method id", "dev login name", "dev password") b.Info["dev auth method id"] = amId b.Info["dev login name"] = acct.GetLoginName() b.Info["dev password"] = pw diff --git a/internal/cmd/commands/controller/controller.go b/internal/cmd/commands/controller/controller.go index 777ff0914..7822cef43 100644 --- a/internal/cmd/commands/controller/controller.go +++ b/internal/cmd/commands/controller/controller.go @@ -363,9 +363,6 @@ func (c *Command) ParseFlagsAndConfig(args []string) int { return 1 } - if c.flagDevOrgId != "" { - c.Config.DefaultOrgId = c.flagDevOrgId - } if c.flagDevAuthMethodId != "" { prefix := password.AuthMethodPrefix + "_" if !strings.HasPrefix(c.flagDevAuthMethodId, prefix) { @@ -405,18 +402,6 @@ func (c *Command) ParseFlagsAndConfig(args []string) int { } } - if c.Config.DefaultOrgId != "" { - if !strings.HasPrefix(c.Config.DefaultOrgId, "o_") { - c.UI.Error(fmt.Sprintf("Invalid default org ID, must start with %q", "o_")) - return 1 - } - if len(c.Config.DefaultOrgId) != 12 { - c.UI.Error(fmt.Sprintf("Invalid default org ID, must be 10 base62 characters after %q", "o_")) - return 1 - } - c.DefaultOrgId = c.Config.DefaultOrgId - } - return 0 } diff --git a/internal/cmd/commands/dev/dev.go b/internal/cmd/commands/dev/dev.go index 1d18dd69a..dd9adddb5 100644 --- a/internal/cmd/commands/dev/dev.go +++ b/internal/cmd/commands/dev/dev.go @@ -171,9 +171,6 @@ func (c *Command) Run(args []string) int { c.UI.Error(fmt.Errorf("Error creating controller dev config: %w", err).Error()) return 1 } - if c.flagDevOrgId != "" { - devConfig.DefaultOrgId = c.flagDevOrgId - } if c.flagDevAuthMethodId != "" { prefix := password.AuthMethodPrefix + "_" if !strings.HasPrefix(c.flagDevAuthMethodId, prefix) { @@ -212,18 +209,6 @@ func (c *Command) Run(args []string) int { } } - if devConfig.DefaultOrgId != "" { - if !strings.HasPrefix(devConfig.DefaultOrgId, "o_") { - c.UI.Error(fmt.Sprintf("Invalid default org ID, must start with %q", "o_")) - return 1 - } - if len(devConfig.DefaultOrgId) != 12 { - c.UI.Error(fmt.Sprintf("Invalid default org ID, must be 10 base62 characters after %q", "o_")) - return 1 - } - c.DefaultOrgId = devConfig.DefaultOrgId - } - if err := c.SetupLogging(c.flagLogLevel, c.flagLogFormat, "", ""); err != nil { c.UI.Error(err.Error()) return 1 diff --git a/internal/cmd/config/config.go b/internal/cmd/config/config.go index 21299c7f7..1a1676ed3 100644 --- a/internal/cmd/config/config.go +++ b/internal/cmd/config/config.go @@ -79,7 +79,6 @@ type Config struct { *configutil.SharedConfig `hcl:"-"` DevController bool `hcl:"-"` - DefaultOrgId string `hcl:"default_org_id"` PassthroughDirectory string `hcl:"-"` Worker *Worker `hcl:"worker"` Controller *Controller `hcl:"controller"` diff --git a/internal/cmd/main.go b/internal/cmd/main.go index 9abf0e545..e65b574db 100644 --- a/internal/cmd/main.go +++ b/internal/cmd/main.go @@ -34,7 +34,7 @@ func setupEnv(args []string) (retArgs []string, format string, outputCurlString break } - if len(args) == 1 && (arg == "-v" || arg == "-version" || arg == "--version") { + if len(args) == 1 && arg == "-version" { args = []string{"version"} break } @@ -45,14 +45,11 @@ func setupEnv(args []string) (retArgs []string, format string, outputCurlString } // Parse a given flag here, which overrides the env var - if strings.HasPrefix(arg, "--format=") { - format = strings.TrimPrefix(arg, "--format=") - } if strings.HasPrefix(arg, "-format=") { format = strings.TrimPrefix(arg, "-format=") } - // For backwards compat, it could be specified without an equal sign - if arg == "-format" || arg == "--format" { + // Handle the case where it is specified without an equal sign + if arg == "-format" { nextArgFormat = true } } diff --git a/internal/db/domains_test.go b/internal/db/domains_test.go index b697e9439..8a66eb8a8 100644 --- a/internal/db/domains_test.go +++ b/internal/db/domains_test.go @@ -285,20 +285,6 @@ returning public_id; assert.Equal(3, v) } -func TestDomain_DisallowDefaultRoleModification(t *testing.T) { - conn, _ := TestSetup(t, "postgres") - db := conn.DB() - - _, err := db.Exec(`delete from iam_role where public_id = $1`, "r_default") - require.Error(t, err) - assert.Equal(t, `pq: deletion of default role not allowed`, err.Error()) - - // This actually tests not just default, but all roles - _, err = db.Exec(`update iam_role set public_id = $1 where public_id = $2`, "r_something", "r_default") - require.Error(t, err) - assert.Equal(t, `pq: immutable column: iam_role.public_id`, err.Error()) -} - func TestDomain_DefaultUsersExist(t *testing.T) { conn, _ := TestSetup(t, "postgres") db := conn.DB() diff --git a/internal/db/migrations/postgres.gen.go b/internal/db/migrations/postgres.gen.go index 015937611..a9f894c95 100644 --- a/internal/db/migrations/postgres.gen.go +++ b/internal/db/migrations/postgres.gen.go @@ -923,26 +923,6 @@ before insert or update on iam_role for each row execute procedure grant_scope_id_valid(); --- disallow_default_role_deletion prevents the default role (r_default) from --- being deleted -create or replace function - disallow_default_role_deletion() - returns trigger -as $$ -begin - if old.public_id = 'r_default' then - raise exception 'deletion of default role not allowed'; - end if; - return old; -end; -$$ language plpgsql; - -create trigger - disallow_default_role_deletion -before -delete on iam_role - for each row execute procedure disallow_default_role_deletion(); - -- define the immutable fields for iam_role (started trigger name with "a_" so -- it will run first) create trigger @@ -951,12 +931,6 @@ before update on iam_role for each row execute procedure immutable_columns('public_id', 'create_time', 'scope_id'); -insert into iam_role (public_id, name, description, scope_id) - values('r_default', 'default', 'default role', 'global'); - -insert into iam_role_grant (role_id, canonical_grant, raw_grant) - values('r_default', 'type=scope;actions=list', 'type=scope;actions=list'); - create table iam_group ( public_id wt_public_id not null primary key, create_time wt_timestamp, @@ -1043,12 +1017,17 @@ begin end; $$ language plpgsql; +insert into iam_role (public_id, name, description, scope_id) + values('r_default', 'default', 'Default role created on first instantiation of Boundary. It is meant to provide enough permissions for users to successfully authenticate via various clients types.', 'global'); +insert into iam_role_grant (role_id, canonical_grant, raw_grant) + values + ('r_default', 'type=scope;actions=list', 'type=scope;actions=list'), + ('r_default', 'type=auth-method;actions=authenticate,list', 'type=auth-method;actions=authenticate'); insert into iam_user_role (role_id, principal_id) values ('r_default', 'u_anon'), ('r_default', 'u_auth'); - -- iam_principle_role provides a consolidated view all principal roles assigned -- (user and group roles). create view iam_principal_role as diff --git a/internal/db/migrations/postgres/06_iam.up.sql b/internal/db/migrations/postgres/06_iam.up.sql index 6b2b48a2d..db94a95dd 100644 --- a/internal/db/migrations/postgres/06_iam.up.sql +++ b/internal/db/migrations/postgres/06_iam.up.sql @@ -417,26 +417,6 @@ before insert or update on iam_role for each row execute procedure grant_scope_id_valid(); --- disallow_default_role_deletion prevents the default role (r_default) from --- being deleted -create or replace function - disallow_default_role_deletion() - returns trigger -as $$ -begin - if old.public_id = 'r_default' then - raise exception 'deletion of default role not allowed'; - end if; - return old; -end; -$$ language plpgsql; - -create trigger - disallow_default_role_deletion -before -delete on iam_role - for each row execute procedure disallow_default_role_deletion(); - -- define the immutable fields for iam_role (started trigger name with "a_" so -- it will run first) create trigger @@ -445,12 +425,6 @@ before update on iam_role for each row execute procedure immutable_columns('public_id', 'create_time', 'scope_id'); -insert into iam_role (public_id, name, description, scope_id) - values('r_default', 'default', 'default role', 'global'); - -insert into iam_role_grant (role_id, canonical_grant, raw_grant) - values('r_default', 'type=scope;actions=list', 'type=scope;actions=list'); - create table iam_group ( public_id wt_public_id not null primary key, create_time wt_timestamp, @@ -537,12 +511,17 @@ begin end; $$ language plpgsql; +insert into iam_role (public_id, name, description, scope_id) + values('r_default', 'default', 'Default role created on first instantiation of Boundary. It is meant to provide enough permissions for users to successfully authenticate via various clients types.', 'global'); +insert into iam_role_grant (role_id, canonical_grant, raw_grant) + values + ('r_default', 'type=scope;actions=list', 'type=scope;actions=list'), + ('r_default', 'type=auth-method;actions=authenticate,list', 'type=auth-method;actions=authenticate'); insert into iam_user_role (role_id, principal_id) values ('r_default', 'u_anon'), ('r_default', 'u_auth'); - -- iam_principle_role provides a consolidated view all principal roles assigned -- (user and group roles). create view iam_principal_role as diff --git a/internal/iam/testing.go b/internal/iam/testing.go index a176601ef..f20bde222 100644 --- a/internal/iam/testing.go +++ b/internal/iam/testing.go @@ -39,6 +39,24 @@ func TestScopes(t *testing.T, conn *gorm.DB) (org *Scope, prj *Scope) { return } +func TestOrg(t *testing.T, conn *gorm.DB) (org *Scope) { + t.Helper() + require := require.New(t) + rw := db.New(conn) + wrapper := db.TestWrapper(t) + repo, err := NewRepository(rw, rw, wrapper) + require.NoError(err) + + org, err = NewOrg() + require.NoError(err) + org, err = repo.CreateScope(context.Background(), org, "") + require.NoError(err) + require.NotNil(org) + require.NotEmpty(org.GetPublicId()) + + return +} + func testOrg(t *testing.T, conn *gorm.DB, name, description string) (org *Scope) { t.Helper() require := require.New(t) diff --git a/internal/servers/controller/cors_test.go b/internal/servers/controller/cors_test.go index 2cbc5a72b..fe7f9cc6d 100644 --- a/internal/servers/controller/cors_test.go +++ b/internal/servers/controller/cors_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/hashicorp/boundary/internal/cmd/config" + "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/go-retryablehttp" ) @@ -69,11 +70,12 @@ func TestHandler_CORS(t *testing.T) { } tc := NewTestController(t, &TestControllerOpts{ Config: cfg, - DefaultOrgId: "o_1234567890", DisableAuthorizationFailures: true, }) defer tc.Shutdown() + org := iam.TestOrg(t, tc.DbConn()) + cases := []struct { name string method string @@ -183,7 +185,6 @@ func TestHandler_CORS(t *testing.T) { client := tc.Client() err := client.SetAddr(tc.ApiAddrs()[c.listenerNum-1]) require.NoError(t, err) - client.SetScopeId("o_1234567890") client.SetToken("fo_o_bar") // Create the request @@ -193,7 +194,7 @@ func TestHandler_CORS(t *testing.T) { var body interface{} scopeId := "global" if c.provideScopeId { - scopeId = "o_1234567890" + scopeId = org.GetPublicId() if c.method == http.MethodPost { body = map[string]interface{}{} } diff --git a/internal/servers/controller/handler_test.go b/internal/servers/controller/handler_test.go index 73d1c6d03..6b3c11562 100644 --- a/internal/servers/controller/handler_test.go +++ b/internal/servers/controller/handler_test.go @@ -8,20 +8,22 @@ import ( "strings" "testing" + "github.com/hashicorp/boundary/internal/iam" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAuthenticationHandler(t *testing.T) { c := NewTestController(t, &TestControllerOpts{ - DefaultOrgId: "o_1234567890", DisableAuthorizationFailures: true, DefaultLoginName: "admin", DefaultPassword: "password123", }) defer c.Shutdown() - resp, err := http.Post(fmt.Sprintf("%s/v1/scopes/o_1234567890/auth-methods/paum_1234567890:authenticate", c.ApiAddrs()[0]), "application/json", + org := iam.TestOrg(t, c.DbConn()) + + resp, err := http.Post(fmt.Sprintf("%s/v1/scopes/%s/auth-methods/paum_1234567890:authenticate", c.ApiAddrs()[0], org.GetPublicId()), "application/json", strings.NewReader(`{"token_type": null, "credentials": {"login_name":"admin", "password": "password123"}}`)) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode, "Got response: %v", resp) diff --git a/internal/servers/controller/handler_ui.go b/internal/servers/controller/handler_ui.go index cf66c924a..b28d47c01 100644 --- a/internal/servers/controller/handler_ui.go +++ b/internal/servers/controller/handler_ui.go @@ -21,18 +21,6 @@ func handleUiWithAssets(c *Controller) http.Handler { nextHandler = http.FileServer(ui.AssetFile()) } - rootHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/": - irw := newIndexResponseWriter(c.conf.DefaultOrgId) - nextHandler.ServeHTTP(irw, r) - irw.writeToWriter(w) - - default: - nextHandler.ServeHTTP(w, r) - } - }) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) @@ -66,6 +54,6 @@ func handleUiWithAssets(c *Controller) http.Handler { } // Fall through to the next handler - rootHandler.ServeHTTP(w, r) + nextHandler.ServeHTTP(w, r) }) } diff --git a/internal/servers/controller/index_response_writer.go b/internal/servers/controller/index_response_writer.go deleted file mode 100644 index 44b927970..000000000 --- a/internal/servers/controller/index_response_writer.go +++ /dev/null @@ -1,50 +0,0 @@ -package controller - -import ( - "bytes" - "fmt" - "net/http" - "strings" -) - -const magicValue = `{{DEFAULT_ORG_ID}}` - -type indexResponseWriter struct { - statusCode int - header http.Header - body *bytes.Buffer - defaultOrgId string -} - -// newindexResponseWriter returns an initialized indexResponseWriter -func newIndexResponseWriter(defaultOrgId string) *indexResponseWriter { - return &indexResponseWriter{ - header: make(http.Header), - body: new(bytes.Buffer), - defaultOrgId: defaultOrgId, - } -} - -func (i *indexResponseWriter) Header() http.Header { - return i.header -} - -func (i *indexResponseWriter) Write(buf []byte) (int, error) { - return i.body.Write(buf) -} - -func (i *indexResponseWriter) WriteHeader(code int) { - i.statusCode = code -} - -func (i *indexResponseWriter) writeToWriter(w http.ResponseWriter) { - for k, v := range i.header { - for _, h := range v { - w.Header().Add(k, h) - } - } - newBody := []byte(strings.Replace(i.body.String(), magicValue, i.defaultOrgId, 1)) - w.Header().Set("content-length", fmt.Sprintf("%d", len(newBody))) - w.WriteHeader(i.statusCode) - w.Write(newBody) -} diff --git a/internal/servers/controller/multi_test.go b/internal/servers/controller/multi_test.go index 91ca7057c..ef2ff42ec 100644 --- a/internal/servers/controller/multi_test.go +++ b/internal/servers/controller/multi_test.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/boundary/api/authmethods" "github.com/hashicorp/boundary/api/scopes" "github.com/hashicorp/boundary/internal/servers/controller" + "github.com/hashicorp/boundary/internal/types/scope" "github.com/hashicorp/go-hclog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -17,13 +18,11 @@ func TestAuthenticationMulti(t *testing.T) { amId := "paum_1234567890" user := "user" password := "passpass" - orgId := "o_1234567890" logger := hclog.New(&hclog.LoggerOptions{ Level: hclog.Trace, }) c1 := controller.NewTestController(t, &controller.TestControllerOpts{ - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: user, DefaultPassword: password, @@ -52,16 +51,17 @@ func TestAuthenticationMulti(t *testing.T) { assert.NotEqual(token1.Token, token2.Token) c1.Client().SetToken(token1.Token) + c1.Client().SetScopeId(scope.Global.String()) c2.Client().SetToken(token1.Token) // Same token, as it should work on both + c2.Client().SetScopeId(scope.Global.String()) // Create a project, read from the other - proj, apiErr, err := scopes.NewScopesClient(c1.Client()).Create(c1.Context(), orgId) + org, apiErr, err := scopes.NewScopesClient(c1.Client()).Create(c1.Context(), scope.Global.String()) require.NoError(err) require.Nil(apiErr) - require.NotNil(proj) - projId := proj.Id + require.NotNil(org) - proj, apiErr, err = scopes.NewScopesClient(c2.Client()).Read(c2.Context(), projId) + proj, apiErr, err := scopes.NewScopesClient(c2.Client()).Read(c2.Context(), org.Id) require.NoError(err) require.Nil(apiErr) require.NotNil(proj) diff --git a/internal/servers/controller/testing.go b/internal/servers/controller/testing.go index dc73ee00c..0ecececda 100644 --- a/internal/servers/controller/testing.go +++ b/internal/servers/controller/testing.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/go-hclog" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/vault/sdk/helper/base62" + "github.com/jinzhu/gorm" ) // TestController wraps a base.Server and Controller to provide a @@ -62,6 +63,10 @@ func (tc *TestController) ClusterAddrs() []string { return tc.addrs("cluster") } +func (tc *TestController) DbConn() *gorm.DB { + return tc.b.Database +} + func (tc *TestController) addrs(purpose string) []string { var prefix string switch purpose { @@ -110,9 +115,10 @@ func (tc *TestController) buildClient() { if err := client.SetAddr(apiAddrs[0]); err != nil { tc.t.Fatal(fmt.Errorf("error setting client address: %w", err)) } - if tc.b.DefaultOrgId != "" { - client.SetScopeId(tc.b.DefaultOrgId) - } + // Because this is using the real lib it can pick up from stored locations + // like the system keychain. Explicitly clear the token to ensure we + // understand the client state at the start of each test. + client.SetToken("") tc.client = client } @@ -147,10 +153,6 @@ type TestControllerOpts struct { // Config; if not provided a dev one will be created Config *config.Config - // DefaultOrgId is the default org ID to use, if set. Can also be provided - // in the normal config. - DefaultOrgId string - // DefaultAuthMethodId is the default auth method ID to use, if set. DefaultAuthMethodId string @@ -219,13 +221,6 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController { opts.Config.Controller.Name = opts.Name } - // Set default org ID, preferring one passed in from opts over config - if opts.Config.DefaultOrgId != "" { - tc.b.DefaultOrgId = opts.Config.DefaultOrgId - } - if opts.DefaultOrgId != "" { - tc.b.DefaultOrgId = opts.DefaultOrgId - } if opts.DefaultAuthMethodId != "" { tc.b.DevAuthMethodId = opts.DefaultAuthMethodId } @@ -319,7 +314,6 @@ func (tc *TestController) AddClusterControllerMember(t *testing.T, opts *TestCon nextOpts := &TestControllerOpts{ DatabaseUrl: tc.c.conf.DatabaseUrl, DefaultAuthMethodId: tc.c.conf.DevAuthMethodId, - DefaultOrgId: tc.c.conf.DefaultOrgId, ControllerKMS: tc.c.conf.ControllerKMS, WorkerAuthKMS: tc.c.conf.WorkerAuthKMS, Name: opts.Name, diff --git a/internal/tests/cluster/multi_controller_worker_test.go b/internal/tests/cluster/multi_controller_worker_test.go index 6e6c46b17..7e9ac1c01 100644 --- a/internal/tests/cluster/multi_controller_worker_test.go +++ b/internal/tests/cluster/multi_controller_worker_test.go @@ -16,13 +16,11 @@ func TestMultiControllerMultiWorkerConnections(t *testing.T) { amId := "paum_1234567890" user := "user" password := "passpass" - orgId := "o_1234567890" logger := hclog.New(&hclog.LoggerOptions{ Level: hclog.Trace, }) c1 := controller.NewTestController(t, &controller.TestControllerOpts{ - DefaultOrgId: orgId, DefaultAuthMethodId: amId, DefaultLoginName: user, DefaultPassword: password, diff --git a/testing/controller/controller.go b/testing/controller/controller.go index af3177212..50c84774d 100644 --- a/testing/controller/controller.go +++ b/testing/controller/controller.go @@ -28,7 +28,6 @@ type option struct { setWithConfigFile bool setWithConfigText bool setDisableDatabaseCreation bool - setDefaultOrgId bool setDefaultAuthMethodId bool setDefaultLoginName bool setDefaultPassword bool @@ -83,18 +82,6 @@ func DisableDatabaseCreation() Option { } } -// WithDefaultOrgId sets the org id to the one provided here. -func WithDefaultOrgId(id string) Option { - return func(c *option) error { - if c.setDefaultOrgId { - return fmt.Errorf("WithDefaultOrgId provided more than once.") - } - c.setDefaultOrgId = true - c.tcOptions.DefaultOrgId = id - return nil - } -} - func WithDefaultAuthMethodId(id string) Option { return func(c *option) error { if c.setDefaultAuthMethodId {