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

[A2-572] Add 'viewer' and 'editor' users to local-dev and dev/acceptance envs, add --skip-policy-migration to upgrade-to-v2 #403

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
fd53817
automate-cli/dev: add cmd to create IAM dev users (viewer, editor)
srenatus May 22, 2019
5d928c9
start_all_services: create IAM v2 dev users
srenatus May 22, 2019
e66dde3
terraform: create iam dev users in test envs
srenatus May 22, 2019
d448ad2
automate-cli/dev: mention that the command can be run many times
srenatus May 22, 2019
6f084f7
inspec/a2-iam-v2-only-integration: rely on automate-cli for user crea…
srenatus May 22, 2019
7230d15
automate-cli/iam: add --skip-legacy-upgrade flag (hidden)
srenatus May 22, 2019
35e1d6e
automate-gateway/api: add migrate_v1_policies to UpdateToV2Req
srenatus May 22, 2019
a3f140b
automate-gateway/api: add migrate_v1_policies to UpdateToV2Req [proto…
srenatus May 22, 2019
1fee8f2
automate-cli/iam: set migrate_v1_policies according to provided flag
srenatus May 22, 2019
2861676
api/interservice/authz: add migrate_v1_policies to MigrateToV2Req
srenatus May 22, 2019
d0bedb7
api/interservice/authz: add migrate_v1_policies to MigrateToV2Req [pr…
srenatus May 22, 2019
a94090c
automate-gateway/authz: pass migrate_v1_policies along
srenatus May 22, 2019
5cbf498
authz-service/migration: nitpicks
srenatus May 22, 2019
1ce7045
authz-service/upgrade-to-v2: respect migrate_v1_policies flag
srenatus May 22, 2019
2501bfe
authz-service/upgrade-to-v2: report number of skipped policies, not IDs
srenatus May 22, 2019
f745c68
integration/tests/iam_v2p1_only: rely on skip flag to skip legacy pol…
srenatus May 22, 2019
c65a147
studio: upgrade to IAM v2 in start_all_services
srenatus May 22, 2019
a2add7b
terraform: add --skip-legacy-upgrade to iam upgrade-to-v2 command
srenatus May 22, 2019
613f37f
api: flip migrate_v1_policies -> skip_v1_policies
srenatus May 22, 2019
7fa7955
api: flip migrate_v1_policies -> skip_v1_policies [protobuf]
srenatus May 22, 2019
49ce217
api: flip migrate_v1_policies -> skip_v1_policies (adapt code)
srenatus May 22, 2019
aeeed92
authz-service/migration: add test case
srenatus May 22, 2019
8c2849f
studiorc: free a cat
srenatus May 22, 2019
61ccc53
rename flag: --skip-policy-migration
srenatus May 23, 2019
922ebd0
automate-cli/iam: unhide upgrade-to-v2 flags in dev mode
srenatus May 23, 2019
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
5 changes: 4 additions & 1 deletion .studiorc
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ GETTING_STARTED

# Memory check. Because we all always forget to change the docker preferences
# when we re-install it
total_memory_kb=$(cat /proc/meminfo | grep MemTotal | grep -o -E '[[:digit:]]+')
total_memory_kb=$(grep MemTotal /proc/meminfo | grep -o -E '[[:digit:]]+')
# 8 gigs == 8164340kb, subtract a few kb so we can just do a less than comp
if (( $total_memory_kb < 8164000 )); then
warn "!!!"
Expand All @@ -128,13 +128,16 @@ fi

document "start_all_services" <<DOC
Simple wrapper for 'start_deployment_service' and 'chef-automate dev deployinate'.
Also applies a license (if present), creates IAM v2 dev users, and upgrades IAM to v2.
DOC
function start_all_services() {
start_deployment_service
chef-automate dev deployinate
if [[ -f "/src/dev/license.jwt" ]]; then
chef-automate license apply "/src/dev/license.jwt"
fi
chef-automate dev create-iam-dev-users
chef-automate iam upgrade-to-v2 --skip-policy-migration
}

document "get_admin_token" <<DOC
Expand Down
288 changes: 149 additions & 139 deletions api/interservice/authz/v2/policy.pb.go

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions api/interservice/authz/v2/policy.pb.validate.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions api/interservice/authz/v2/policy.proto
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ enum Flag {

message MigrateToV2Req {
Flag flag = 1;
bool skip_v1_policies = 2;
}
message MigrateToV2Resp {
repeated string reports = 1;
Expand Down
6 changes: 2 additions & 4 deletions components/authz-service/server/v2/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package v2
import (
"context"
"fmt"
"regexp"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -54,7 +53,7 @@ func (s *policyServer) migrateV1Policies(ctx context.Context) ([]error, error) {
if err := s.addTokenToAdminPolicy(ctx, adminTokenPolicy.Subjects[0]); err != nil {
errs = append(errs, errors.Wrapf(err, "adding members %q for admin policy %q", pol.Subjects, pol.ID.String()))
}
continue //don't migrate admin policies with single token
continue // don't migrate admin policies with single token
}
storagePol, err := migrateV1Policy(pol)
if err != nil {
Expand Down Expand Up @@ -100,8 +99,7 @@ func (s *policyServer) addTokenToAdminPolicy(ctx context.Context, tok string) er
}

func checkForAdminTokenPolicy(pol *storage_v1.Policy) (*storage_v1.Policy, error) {
var tokenRE = regexp.MustCompile(`^token`)
if pol.Action == "*" && pol.Resource == "*" && len(pol.Subjects) == 1 && tokenRE.MatchString(pol.Subjects[0]) {
if pol.Action == "*" && pol.Resource == "*" && len(pol.Subjects) == 1 && strings.HasPrefix(pol.Subjects[0], "token:") {
return pol, nil
}
return nil, nil
Expand Down
30 changes: 22 additions & 8 deletions components/authz-service/server/v2/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package v2

import (
"context"
"fmt"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -556,14 +557,27 @@ func (s *policyServer) MigrateToV2(ctx context.Context,
}
}

errs, err := s.migrateV1Policies(ctx)
if err != nil {
recordFailure()
return nil, status.Errorf(codes.Internal, "migrate v1 policies: %s", err.Error())
}
reports := make([]string, len(errs))
for i, e := range errs {
reports[i] = e.Error()
var reports []string
if !req.SkipV1Policies {
errs, err := s.migrateV1Policies(ctx)
if err != nil {
recordFailure()
return nil, status.Errorf(codes.Internal, "migrate v1 policies: %s", err.Error())
}
for _, e := range errs {
reports = append(reports, e.Error())
}
} else {
// Note 2019/05/22 (sr): policies without subjects are silently ignored -- this
// is to be in line with the migration case, that does the same. However, this
// could be worth revisiting?
pols, err := s.v1.ListPoliciesWithSubjects(ctx)
if err != nil {
recordFailure()
return nil, status.Errorf(codes.Internal, "list v1 policies: %s", err.Error())
}
reports = append(reports, fmt.Sprintf("%d v1 policies", len(pols)))
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider "%d v1 policies found -- skipping"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The output, in the end, will be

[79][default:/src:0]# chef-automate iam upgrade-to-v2 --beta2.1 --skip-policy-migration

Enabling IAM v2.1

Skipped policies:
  28 v1 policies

(see PR message) -- I'd rather not use skipped twice there

Copy link
Contributor

@susanev susanev May 23, 2019

Choose a reason for hiding this comment

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

@srenatus do you mind if we have a single line with Skipped: %d v1 policies, then a newline before the teams output?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Right now, that's shared between a migration and no migration (see https://github.com/chef/a2/pull/4120#issuecomment-433389839), so it's a little more work than just the formatting. But yeah, we can do that.

Copy link
Contributor

@susanev susanev May 23, 2019

Choose a reason for hiding this comment

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

oh i see.... nah, just leave it as is for now.


}

err = s.store.ApplyV2DataMigrations(ctx)
Expand Down
17 changes: 17 additions & 0 deletions components/authz-service/server/v2/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2226,6 +2226,23 @@ func TestMigrateToV2(t *testing.T) {
pol := getPolicyFromStore(t, policyStore, constants_v2.ComplianceTokenPolicyID)
assert.Equal(t, "[Legacy] Compliance Profile Access", pol.Name)
},
"legacy default and custom v1 policies are skipped when asked to skip them": func(t *testing.T) {
polID := genUUID(t)
v1List = v1Lister{pols: []*storage_v1.Policy{
wellknown(t, constants_v1.ComplianceTokenReadProfilesPolicyID),
{
ID: polID,
Subjects: []string{"user:ldap:bob", "team:ldap:ops"},
Action: "create",
Resource: "ingest:nodes",
},
}}

resp, err := cl.MigrateToV2(ctx, &api_v2.MigrateToV2Req{SkipV1Policies: true})
require.NoError(t, err)
assert.NotNil(t, resp)
assert.Equal(t, defaultPolicyCount, policyStore.ItemCount()) // nothing extra
},
// --------- migration status related tests ---------
"when no migration has been run, migration status is set to v1": func(t *testing.T) {
s, err := status.MigrationStatus(ctx)
Expand Down
44 changes: 44 additions & 0 deletions components/automate-cli/cmd/chef-automate/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
dc "github.com/chef/automate/api/config/deployment"
w "github.com/chef/automate/api/config/shared/wrappers"
api "github.com/chef/automate/api/interservice/deployment"
"github.com/chef/automate/components/automate-cli/pkg/adminmgmt"
"github.com/chef/automate/components/automate-cli/pkg/client/apiclient"
"github.com/chef/automate/components/automate-cli/pkg/dev/hab"
"github.com/chef/automate/components/automate-cli/pkg/docs"
"github.com/chef/automate/components/automate-cli/pkg/status"
Expand Down Expand Up @@ -81,6 +83,7 @@ func init() {
devCmd.AddCommand(newVerifyPackagesCmd())
devCmd.AddCommand(newEnablePrometheusCmd())
devCmd.AddCommand(newDisablePrometheusCmd())
devCmd.AddCommand(newCreateIAMDevUsersCmd())
RootCmd.AddCommand(devCmd)
}

Expand Down Expand Up @@ -940,6 +943,15 @@ func newDisablePrometheusCmd() *cobra.Command {
}
}

func newCreateIAMDevUsersCmd() *cobra.Command {
return &cobra.Command{
Use: "create-iam-dev-users",
RunE: runCreateIAMDevUsersCmd,
Short: `Create IAM v2 dev users ("viewer" and "editor") idempotently`,
Args: cobra.NoArgs,
}
}

// Equivalent to patching the config with the following toml:
// [deployment.v1.svc]
// enable_dev_monitoring = true
Expand Down Expand Up @@ -974,3 +986,35 @@ func runDisablePrometheusCmd(*cobra.Command, []string) error {
}
return nil
}

func runCreateIAMDevUsersCmd(*cobra.Command, []string) error {
ctx := context.TODO()
apiClient, err := apiclient.OpenConnection(ctx)
if err != nil {
return err
}
for username, data := range map[string]struct {
displayName, password, team string
}{
"viewer": {"Viewer User", "chefautomate", "viewers"},
"editor": {"Editor User", "chefautomate", "editors"},
} {
userID, _, err := adminmgmt.CreateUserOrUpdatePassword(ctx,
apiClient, username, data.displayName, data.password, false /* dry run */)
Copy link
Contributor

Choose a reason for hiding this comment

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

Personal style thing for sure, but just my 2 cents:
false /* dry run */ suggests to me that "setting this param false here and that means it is a dry run".
Whereas:
/* dry run */ false suggests to me that "this is supplying a value of false for 'dry run' and that means it is not a dry run.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

hehe I didn't mean to convey that much -- I really just meant "this bool is the dry run parameter". But yeah, you're not wrong with that connotation πŸ˜‰

if err != nil {
return err
}
// Note: the teams SHOULD exist. But since you never know what happens in a
// long running acceptance env, we'll better ensure them:
Copy link
Contributor

Choose a reason for hiding this comment

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

s/we'll/we'd/

teamID, _, err := adminmgmt.EnsureTeam(ctx, data.team, data.team /* description */, apiClient, false /* dry run */)
if err != nil {
return err
}
_, err = adminmgmt.AddUserToTeam(ctx, apiClient, teamID, userID, false /* dry run */)
if err != nil {
return err
}
}

return nil
}
52 changes: 29 additions & 23 deletions components/automate-cli/cmd/chef-automate/iam.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc/codes"
grpc_status "google.golang.org/grpc/status"

Expand All @@ -20,10 +21,11 @@ import (
)

var iamCmdFlags = struct {
dryRun bool
adminToken bool
tokenID string
betaVersion bool
dryRun bool
adminToken bool
tokenID string
betaVersion bool
skipLegacyUpgrade bool
}{}

func newIAMCommand() *cobra.Command {
Expand Down Expand Up @@ -93,17 +95,20 @@ func newIAMUpgradeToV2Cmd() *cobra.Command {
RunE: runIAMUpgradeToV2Cmd,
Args: cobra.ExactArgs(0),
}
cmd.PersistentFlags().BoolVar(
&iamCmdFlags.skipLegacyUpgrade,
"skip-policy-migration",
false,
"Do not migrate policies from IAM v1.")
cmd.PersistentFlags().BoolVar(
&iamCmdFlags.betaVersion,
"beta2.1",
false,
"Upgrade to version 2.1 with beta project authorization.")
err := cmd.PersistentFlags().MarkHidden("beta2.1")
// we could also ignore the lint error :shrug:
if err != nil {
fmt.Printf("failed configuring cobra: %s\n", err.Error())
panic(err.Error())
}

// all flags are hidden right now
cmd.PersistentFlags().VisitAll(func(f *pflag.Flag) { f.Hidden = !isDevMode() })
Copy link
Contributor

Choose a reason for hiding this comment

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

I thought the team consensus was that skip-policy-migration was for public consumption as well...?

Copy link
Contributor

Choose a reason for hiding this comment

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

i believe that consensus convo happened last friday during subtasking and i wasnt there. if we do make it public we should have a corresponding docs update, so id like to do that in a separate pr if possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm all in favour of not adding anything here πŸ˜‰


return cmd
}

Expand Down Expand Up @@ -153,18 +158,27 @@ const alreadyMigratedMessage = `You have already upgraded to IAM %s.
Then re-run this command.`

func runIAMUpgradeToV2Cmd(cmd *cobra.Command, args []string) error {
label := map[bool]string{
true: "v2.1",
false: "v2",
}

upgradeReq := &policies_req.UpgradeToV2Req{
Flag: policies_common.Flag_VERSION_2_0,
Flag: policies_common.Flag_VERSION_2_0,
SkipV1Policies: iamCmdFlags.skipLegacyUpgrade,
}
isBetaVersion := iamCmdFlags.betaVersion

isBetaVersion := iamCmdFlags.betaVersion
if isBetaVersion {
upgradeReq.Flag = policies_common.Flag_VERSION_2_1
writer.Title("Enabling IAM v2.1")
} else {
writer.Title("Upgrading to IAM v2")
}
writer.Println("Migrating v1 policies...")

if !iamCmdFlags.skipLegacyUpgrade {
writer.Println("Migrating v1 policies...")
}

ctx := context.Background()
apiClient, err := apiclient.OpenConnection(ctx)
Expand All @@ -188,11 +202,7 @@ func runIAMUpgradeToV2Cmd(cmd *cobra.Command, args []string) error {
return status.Wrap(err, status.IAMUpgradeV2DatabaseError,
"Migration to IAM v2 already in progress")
case codes.AlreadyExists:
if isBetaVersion {
writer.Failf(alreadyMigratedMessage, "v2.1")
} else {
writer.Failf(alreadyMigratedMessage, "v2")
}
writer.Failf(alreadyMigratedMessage, label[isBetaVersion])
return nil
default: // something else: fail
return status.Wrap(err, status.IAMUpgradeV2DatabaseError,
Expand Down Expand Up @@ -222,10 +232,6 @@ func runIAMUpgradeToV2Cmd(cmd *cobra.Command, args []string) error {
"Failed to migrate teams service")
}

label := map[bool]string{
true: "v2.1",
false: "v2",
}
writer.Successf("Enabled IAM %s", label[isBetaVersion])
return nil
}
Expand All @@ -234,7 +240,7 @@ func outputReport(report string) {
// if it's got ":" in it, split on the first
parts := strings.SplitN(report, ":", 2)
writer.Body(parts[0])
if parts[1] != "" {
if len(parts) >= 2 {
writer.Body(strings.TrimSpace(parts[1]))
}
}
Expand Down
Loading