diff --git a/CHANGELOG.md b/CHANGELOG.md index bb2048c1b..d7a2e027c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,27 @@ Canonical reference for changes, improvements, and bugfixes for Boundary. ## Next +### Deprecations/Changes + +* `password` account IDs: When the `oidc` auth method came out, accounts were + given the prefix `acctoidc`. Unfortunately, accounts in the `password` method + were using `apw`...oops. We're standardizing on `acct` and have updated the + `password` method to generate new IDs with `acctpw` prefixes. + Previously-generated prefixes will continue to work. + ### New and Improved -* mlock: Add a Docker entrypoint script and modify Dockerfiles to mimic Vault +* oidc: The new Managed Groups feature allows groups of accounts to be created + based on an authenticating user's JWT or User Info data. This data uses the + same filtering syntax found elsewhere in Boundary to provide a rich way to + specify the criteria for group membership. Once defined, authenticated users + are added to or removed from these groups as appropriateds each time they + authenticate. These groups are treated like other role principals and can be + added to roles to provide grants to users. +* dev: Predictable IDs in `boundary dev` mode now extend to the accounts created + in the default `password` and `oidc` auth methods. +* mlock: Add a Docker entrypoint script and modify Dockerfiles to handle mlock + in a fashion similar to Vault ([PR](https://github.com/hashicorp/boundary/pull/1269)) ## 0.2.3 (2021/05/21) diff --git a/api/accounts/account.gen.go b/api/accounts/account.gen.go index 47e70bd0b..bcad294d8 100644 --- a/api/accounts/account.gen.go +++ b/api/accounts/account.gen.go @@ -23,6 +23,7 @@ type Account struct { Type string `json:"type,omitempty"` AuthMethodId string `json:"auth_method_id,omitempty"` Attributes map[string]interface{} `json:"attributes,omitempty"` + ManagedGroupIds []string `json:"managed_group_ids,omitempty"` AuthorizedActions []string `json:"authorized_actions,omitempty"` response *api.Response diff --git a/api/managedgroups/managedgroups.gen.go b/api/managedgroups/managedgroups.gen.go new file mode 100644 index 000000000..94741999b --- /dev/null +++ b/api/managedgroups/managedgroups.gen.go @@ -0,0 +1,323 @@ +// Code generated by "make api"; DO NOT EDIT. +package managedgroups + +import ( + "context" + "errors" + "fmt" + "net/url" + "time" + + "github.com/hashicorp/boundary/api" + "github.com/hashicorp/boundary/api/scopes" +) + +type ManagedGroup struct { + Id string `json:"id,omitempty"` + Scope *scopes.ScopeInfo `json:"scope,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + CreatedTime time.Time `json:"created_time,omitempty"` + UpdatedTime time.Time `json:"updated_time,omitempty"` + Version uint32 `json:"version,omitempty"` + Type string `json:"type,omitempty"` + AuthMethodId string `json:"auth_method_id,omitempty"` + Attributes map[string]interface{} `json:"attributes,omitempty"` + MemberIds []string `json:"member_ids,omitempty"` + AuthorizedActions []string `json:"authorized_actions,omitempty"` + + response *api.Response +} + +type ManagedGroupReadResult struct { + Item *ManagedGroup + response *api.Response +} + +func (n ManagedGroupReadResult) GetItem() interface{} { + return n.Item +} + +func (n ManagedGroupReadResult) GetResponse() *api.Response { + return n.response +} + +type ( + ManagedGroupCreateResult = ManagedGroupReadResult + ManagedGroupUpdateResult = ManagedGroupReadResult +) + +type ManagedGroupDeleteResult struct { + response *api.Response +} + +// GetItem will always be nil for ManagedGroupDeleteResult +func (n ManagedGroupDeleteResult) GetItem() interface{} { + return nil +} + +func (n ManagedGroupDeleteResult) GetResponse() *api.Response { + return n.response +} + +type ManagedGroupListResult struct { + Items []*ManagedGroup + response *api.Response +} + +func (n ManagedGroupListResult) GetItems() interface{} { + return n.Items +} + +func (n ManagedGroupListResult) GetResponse() *api.Response { + return n.response +} + +// Client is a client for this collection +type Client struct { + client *api.Client +} + +// Creates a new client for this collection. The submitted API client is cloned; +// modifications to it after generating this client will not have effect. If you +// need to make changes to the underlying API client, use ApiClient() to access +// it. +func NewClient(c *api.Client) *Client { + return &Client{client: c.Clone()} +} + +// ApiClient returns the underlying API client +func (c *Client) ApiClient() *api.Client { + return c.client +} + +func (c *Client) Create(ctx context.Context, authMethodId string, opt ...Option) (*ManagedGroupCreateResult, error) { + if authMethodId == "" { + return nil, fmt.Errorf("empty authMethodId value passed into Create request") + } + + opts, apiOpts := getOpts(opt...) + + if c.client == nil { + return nil, fmt.Errorf("nil client") + } + + opts.postMap["auth_method_id"] = authMethodId + + req, err := c.client.NewRequest(ctx, "POST", "managed-groups", opts.postMap, apiOpts...) + if err != nil { + return nil, fmt.Errorf("error creating Create request: %w", err) + } + + if len(opts.queryMap) > 0 { + q := url.Values{} + for k, v := range opts.queryMap { + q.Add(k, v) + } + req.URL.RawQuery = q.Encode() + } + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error performing client request during Create call: %w", err) + } + + target := new(ManagedGroupCreateResult) + target.Item = new(ManagedGroup) + apiErr, err := resp.Decode(target.Item) + if err != nil { + return nil, fmt.Errorf("error decoding Create response: %w", err) + } + if apiErr != nil { + return nil, apiErr + } + target.response = resp + return target, nil +} + +func (c *Client) Read(ctx context.Context, managedGroupId string, opt ...Option) (*ManagedGroupReadResult, error) { + if managedGroupId == "" { + return nil, fmt.Errorf("empty managedGroupId value passed into Read request") + } + if c.client == nil { + return nil, fmt.Errorf("nil client") + } + + opts, apiOpts := getOpts(opt...) + + req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("managed-groups/%s", managedGroupId), nil, apiOpts...) + if err != nil { + return nil, fmt.Errorf("error creating Read request: %w", err) + } + + if len(opts.queryMap) > 0 { + q := url.Values{} + for k, v := range opts.queryMap { + q.Add(k, v) + } + req.URL.RawQuery = q.Encode() + } + + resp, err := c.client.Do(req, apiOpts...) + if err != nil { + return nil, fmt.Errorf("error performing client request during Read call: %w", err) + } + + target := new(ManagedGroupReadResult) + target.Item = new(ManagedGroup) + apiErr, err := resp.Decode(target.Item) + if err != nil { + return nil, fmt.Errorf("error decoding Read response: %w", err) + } + if apiErr != nil { + return nil, apiErr + } + target.response = resp + return target, nil +} + +func (c *Client) Update(ctx context.Context, managedGroupId string, version uint32, opt ...Option) (*ManagedGroupUpdateResult, error) { + if managedGroupId == "" { + return nil, fmt.Errorf("empty managedGroupId value passed into Update request") + } + if c.client == nil { + return nil, fmt.Errorf("nil client") + } + + opts, apiOpts := getOpts(opt...) + + if version == 0 { + if !opts.withAutomaticVersioning { + return nil, errors.New("zero version number passed into Update request and automatic versioning not specified") + } + existingTarget, existingErr := c.Read(ctx, managedGroupId, append([]Option{WithSkipCurlOutput(true)}, opt...)...) + if existingErr != nil { + if api.AsServerError(existingErr) != nil { + return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr) + } + return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr) + } + if existingTarget == nil { + return nil, errors.New("nil resource response found when performing initial check-and-set read") + } + if existingTarget.Item == nil { + return nil, errors.New("nil resource found when performing initial check-and-set read") + } + version = existingTarget.Item.Version + } + + opts.postMap["version"] = version + + req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("managed-groups/%s", managedGroupId), opts.postMap, apiOpts...) + if err != nil { + return nil, fmt.Errorf("error creating Update request: %w", err) + } + + if len(opts.queryMap) > 0 { + q := url.Values{} + for k, v := range opts.queryMap { + q.Add(k, v) + } + req.URL.RawQuery = q.Encode() + } + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error performing client request during Update call: %w", err) + } + + target := new(ManagedGroupUpdateResult) + target.Item = new(ManagedGroup) + apiErr, err := resp.Decode(target.Item) + if err != nil { + return nil, fmt.Errorf("error decoding Update response: %w", err) + } + if apiErr != nil { + return nil, apiErr + } + target.response = resp + return target, nil +} + +func (c *Client) Delete(ctx context.Context, managedGroupId string, opt ...Option) (*ManagedGroupDeleteResult, error) { + if managedGroupId == "" { + return nil, fmt.Errorf("empty managedGroupId value passed into Delete request") + } + if c.client == nil { + return nil, fmt.Errorf("nil client") + } + + opts, apiOpts := getOpts(opt...) + + req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("managed-groups/%s", managedGroupId), nil, apiOpts...) + if err != nil { + return nil, fmt.Errorf("error creating Delete request: %w", err) + } + + if len(opts.queryMap) > 0 { + q := url.Values{} + for k, v := range opts.queryMap { + q.Add(k, v) + } + req.URL.RawQuery = q.Encode() + } + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error performing client request during Delete call: %w", err) + } + + apiErr, err := resp.Decode(nil) + if err != nil { + return nil, fmt.Errorf("error decoding Delete response: %w", err) + } + if apiErr != nil { + return nil, apiErr + } + + target := &ManagedGroupDeleteResult{ + response: resp, + } + return target, nil +} + +func (c *Client) List(ctx context.Context, authMethodId string, opt ...Option) (*ManagedGroupListResult, error) { + if authMethodId == "" { + return nil, fmt.Errorf("empty authMethodId value passed into List request") + } + if c.client == nil { + return nil, fmt.Errorf("nil client") + } + + opts, apiOpts := getOpts(opt...) + opts.queryMap["auth_method_id"] = authMethodId + + req, err := c.client.NewRequest(ctx, "GET", "managed-groups", nil, apiOpts...) + if err != nil { + return nil, fmt.Errorf("error creating List request: %w", err) + } + + if len(opts.queryMap) > 0 { + q := url.Values{} + for k, v := range opts.queryMap { + q.Add(k, v) + } + req.URL.RawQuery = q.Encode() + } + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error performing client request during List call: %w", err) + } + + target := new(ManagedGroupListResult) + apiErr, err := resp.Decode(target) + if err != nil { + return nil, fmt.Errorf("error decoding List response: %w", err) + } + if apiErr != nil { + return nil, apiErr + } + target.response = resp + return target, nil +} diff --git a/api/managedgroups/oidc_managed_group_attributes.gen.go b/api/managedgroups/oidc_managed_group_attributes.gen.go new file mode 100644 index 000000000..73eba7540 --- /dev/null +++ b/api/managedgroups/oidc_managed_group_attributes.gen.go @@ -0,0 +1,6 @@ +// Code generated by "make api"; DO NOT EDIT. +package managedgroups + +type OidcManagedGroupAttributes struct { + Filter string `json:"filter,omitempty"` +} diff --git a/api/managedgroups/option.gen.go b/api/managedgroups/option.gen.go new file mode 100644 index 000000000..1a65ba439 --- /dev/null +++ b/api/managedgroups/option.gen.go @@ -0,0 +1,123 @@ +package managedgroups + +import ( + "strings" + + "github.com/hashicorp/boundary/api" +) + +// Option is a func that sets optional attributes for a call. This does not need +// to be used directly, but instead option arguments are built from the +// functions in this package. WithX options set a value to that given in the +// argument; DefaultX options indicate that the value should be set to its +// default. When an API call is made options are processed in ther order they +// appear in the function call, so for a given argument X, a succession of WithX +// or DefaultX calls will result in the last call taking effect. +type Option func(*options) + +type options struct { + postMap map[string]interface{} + queryMap map[string]string + withAutomaticVersioning bool + withSkipCurlOutput bool + withFilter string +} + +func getDefaultOptions() options { + return options{ + postMap: make(map[string]interface{}), + queryMap: make(map[string]string), + } +} + +func getOpts(opt ...Option) (options, []api.Option) { + opts := getDefaultOptions() + for _, o := range opt { + if o != nil { + o(&opts) + } + } + var apiOpts []api.Option + if opts.withSkipCurlOutput { + apiOpts = append(apiOpts, api.WithSkipCurlOutput(true)) + } + if opts.withFilter != "" { + opts.queryMap["filter"] = opts.withFilter + } + return opts, apiOpts +} + +// If set, and if the version is zero during an update, the API will perform a +// fetch to get the current version of the resource and populate it during the +// update call. This is convenient but opens up the possibility for subtle +// order-of-modification issues, so use carefully. +func WithAutomaticVersioning(enable bool) Option { + return func(o *options) { + o.withAutomaticVersioning = enable + } +} + +// WithSkipCurlOutput tells the API to not use the current call for cURL output. +// Useful for when we need to look up versions. +func WithSkipCurlOutput(skip bool) Option { + return func(o *options) { + o.withSkipCurlOutput = true + } +} + +// WithFilter tells the API to filter the items returned using the provided +// filter term. The filter should be in a format supported by +// hashicorp/go-bexpr. +func WithFilter(filter string) Option { + return func(o *options) { + o.withFilter = strings.TrimSpace(filter) + } +} + +func WithAttributes(inAttributes map[string]interface{}) Option { + return func(o *options) { + o.postMap["attributes"] = inAttributes + } +} + +func DefaultAttributes() Option { + return func(o *options) { + o.postMap["attributes"] = nil + } +} + +func WithDescription(inDescription string) Option { + return func(o *options) { + o.postMap["description"] = inDescription + } +} + +func DefaultDescription() Option { + return func(o *options) { + o.postMap["description"] = nil + } +} + +func WithOidcManagedGroupFilter(inFilter string) Option { + return func(o *options) { + raw, ok := o.postMap["attributes"] + if !ok { + raw = interface{}(map[string]interface{}{}) + } + val := raw.(map[string]interface{}) + val["filter"] = inFilter + o.postMap["attributes"] = val + } +} + +func WithName(inName string) Option { + return func(o *options) { + o.postMap["name"] = inName + } +} + +func DefaultName() Option { + return func(o *options) { + o.postMap["name"] = nil + } +} diff --git a/globals/doc.go b/globals/doc.go new file mode 100644 index 000000000..3b9c5beb2 --- /dev/null +++ b/globals/doc.go @@ -0,0 +1,16 @@ +/* +Globals, in the traditional sense, are usually bad. But there are some +situations where we want either consts or known values that are constant per +invocation but invocation may be in various places, such as a test or via CLI, +and placing such a value in any given package leads to import issues. So think +of this package as "freeing us from circular dependency hell". + +This package provides _exported_ globals that might reasonably be used by API +users, Terraform, etc. A separate package, under internal/intglobals, provides +globals that perform a similar function but are only meant for internal use. + +There is no race checking; these values should only ever be set at startup of +Boundary or a test, but available to reference from anywhere. +*/ + +package globals diff --git a/globals/fields.go b/globals/fields.go index 56d8fd652..5a0cb1bfa 100644 --- a/globals/fields.go +++ b/globals/fields.go @@ -1,9 +1,5 @@ package globals -// This set of consts is intended to be a place to collect commonly-used field -// names. Since these might be used outside of the internal code (e.g. by SDK or -// CLI), it's outside internal/ here in globals. Some of these are already const -// elsewhere in the code but we should migrate to using a single source. const ( IdField = "id" VersionField = "version" @@ -53,4 +49,6 @@ const ( FullNameField = "full_name" PrimaryAccountIdField = "primary_account_id" EmailField = "email" + ManagedGroupIdsField = "managed_group_ids" + FilterField = "filter" ) diff --git a/globals/globals.go b/globals/globals.go index b73da4cee..087e5497c 100644 --- a/globals/globals.go +++ b/globals/globals.go @@ -2,13 +2,6 @@ package globals import "time" -// NOTE: Globals, in the traditional sense, are bad. But there are some -// situations where we want a value that is constant per invocation but -// invocation may be in various places, such as a test or via CLI, and placing -// such a value in any given package leads to import issues. So think of this -// package as "freeing us from circular dependency hell". These values should -// only ever be set at startup, but simply available to reference from anywhere. - const ( TcpProxyV1 = "boundary-tcp-proxy-v1" ServiceTokenV1 = "s1" diff --git a/go.mod b/go.mod index 0d69d56ce..b04e58aa0 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/hashicorp/dbassert v0.0.0-20200930125617-6218396928df github.com/hashicorp/errwrap v1.1.0 github.com/hashicorp/eventlogger v0.0.0-20210523164657-c216620e1746 - github.com/hashicorp/go-bexpr v0.1.7 + github.com/hashicorp/go-bexpr v0.1.8 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/hashicorp/go-hclog v0.16.1 github.com/hashicorp/go-kms-wrapping v0.6.1 diff --git a/go.sum b/go.sum index 4f699ec05..bc24a2ede 100644 --- a/go.sum +++ b/go.sum @@ -452,8 +452,8 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/eventlogger v0.0.0-20210523164657-c216620e1746 h1:uFLAYWBCufq4idhqjltAWb4s2JuJt1oE1hDRixwWqwY= github.com/hashicorp/eventlogger v0.0.0-20210523164657-c216620e1746/go.mod h1:LG0lqGlYKC9FD5m5Umh7FW8SeJlciNUZv400J4+j094= -github.com/hashicorp/go-bexpr v0.1.7 h1:z48qzCgJkvdnMO/LDy3XHNyCyxnHiFGx9uTKLv0jW2Y= -github.com/hashicorp/go-bexpr v0.1.7/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0= +github.com/hashicorp/go-bexpr v0.1.8 h1:ETfuLF1bBAuHW/Qg6l1xCdV8WJ7lfatLtJ1N1w0IsfE= +github.com/hashicorp/go-bexpr v0.1.8/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= diff --git a/internal/api/genapi/input.go b/internal/api/genapi/input.go index 0c3821a19..060c9c6e4 100644 --- a/internal/api/genapi/input.go +++ b/internal/api/genapi/input.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/boundary/internal/gen/controller/api/resources/hostcatalogs" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/hosts" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/hostsets" + "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/roles" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/sessions" @@ -87,6 +88,10 @@ type structInfo struct { // conveyed within the item itself extraOptions []fieldInfo + // fieldOverrides allows overriding some field behavior without making them + // "new" fields like with extraOptions + fieldOverrides []fieldInfo + // createResponseTypes controls for which structs response types are created createResponseTypes bool @@ -298,6 +303,34 @@ var inputStructs = []*structInfo{ versionEnabled: true, createResponseTypes: true, }, + // Managed Groups + { + inProto: &managedgroups.OidcManagedGroupAttributes{}, + outFile: "managedgroups/oidc_managed_group_attributes.gen.go", + subtypeName: "OidcManagedGroup", + fieldOverrides: []fieldInfo{ + { + Name: "Filter", + SkipDefault: true, + }, + }, + }, + { + inProto: &managedgroups.ManagedGroup{}, + outFile: "managedgroups/managedgroups.gen.go", + templates: []*template.Template{ + clientTemplate, + createTemplate, + readTemplate, + updateTemplate, + deleteTemplate, + listTemplate, + }, + pathArgs: []string{"managed-group"}, + parentTypeName: "auth-method", + versionEnabled: true, + createResponseTypes: true, + }, // Auth Tokens { inProto: &authtokens.AuthToken{}, diff --git a/internal/api/genapi/templates.go b/internal/api/genapi/templates.go index 5277e9ea7..2429ff6ea 100644 --- a/internal/api/genapi/templates.go +++ b/internal/api/genapi/templates.go @@ -123,6 +123,19 @@ func fillTemplates() { } optionsMap[input.Package] = optionMap } + // Override some defined options + if len(in.fieldOverrides) > 0 && optionsMap != nil { + for _, override := range in.fieldOverrides { + inOpts := optionsMap[input.Package] + if inOpts != nil { + if override.SkipDefault { + fieldInfo := inOpts[override.Name] + fieldInfo.SkipDefault = true + inOpts[override.Name] = fieldInfo + } + } + } + } outFile, err := filepath.Abs(fmt.Sprintf("%s/%s", os.Getenv("API_GEN_BASEPATH"), in.outFile)) if err != nil { diff --git a/internal/auth/additional_verification_test.go b/internal/auth/additional_verification_test.go index afc6c8cce..eae6f4c24 100644 --- a/internal/auth/additional_verification_test.go +++ b/internal/auth/additional_verification_test.go @@ -116,7 +116,10 @@ func TestFetchActionSetForId(t *testing.T) { func TestRecursiveListingDifferentOutputFields(t *testing.T) { require, assert := require.New(t), assert.New(t) - tc := controller.NewTestController(t, nil) + tc := controller.NewTestController(t, &controller.TestControllerOpts{ + // Disable this to avoid having to deal with sorting them in the test + DisableOidcAuthMethodCreation: true, + }) defer tc.Shutdown() conn := tc.DbConn() diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 1f0661b13..e6d6dbc84 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -494,20 +494,20 @@ func (v verifier) performAuthCheck() (aclResults perms.ACLResults, userId string } var parsedGrants []perms.Grant - var grantPairs []perms.GrantPair + var grantTuples []perms.GrantTuple // Fetch and parse grants for this user ID (which may include grants for // u_anon and u_auth) - grantPairs, err = iamRepo.GrantsForUser(v.ctx, userId) + grantTuples, err = iamRepo.GrantsForUser(v.ctx, userId) if err != nil { retErr = errors.Wrap(err, op) return } - parsedGrants = make([]perms.Grant, 0, len(grantPairs)) + parsedGrants = make([]perms.Grant, 0, len(grantTuples)) // Note: Below, we always skip validation so that we don't error on formats // that we've since restricted, e.g. "id=foo;actions=create,read". These // will simply not have an effect. - for _, pair := range grantPairs { + for _, pair := range grantTuples { parsed, err := perms.Parse( pair.ScopeId, pair.Grant, diff --git a/internal/auth/oidc/ids.go b/internal/auth/oidc/ids.go index 05ef04464..5b30027b8 100644 --- a/internal/auth/oidc/ids.go +++ b/internal/auth/oidc/ids.go @@ -3,6 +3,7 @@ package oidc import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/intglobals" ) const ( @@ -38,3 +39,12 @@ func newAccountId(authMethodId, issuer, sub string) (string, error) { } return id, nil } + +func newManagedGroupId() (string, error) { + const op = "oidc.newManagedGroupId" + id, err := db.NewPublicId(intglobals.OidcManagedGroupPrefix) + if err != nil { + return "", errors.Wrap(err, op) + } + return id, nil +} diff --git a/internal/auth/oidc/managed_group.go b/internal/auth/oidc/managed_group.go new file mode 100644 index 000000000..ff74c5733 --- /dev/null +++ b/internal/auth/oidc/managed_group.go @@ -0,0 +1,98 @@ +package oidc + +import ( + "github.com/hashicorp/boundary/internal/auth/oidc/store" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/oplog" + "github.com/hashicorp/go-bexpr" + "google.golang.org/protobuf/proto" +) + +// defaultManagedGroupTableName defines the default table name for a Managed Group +const defaultManagedGroupTableName = "auth_oidc_managed_group" + +// ManagedGroup contains an OIDC managed group. It is assigned to an OIDC AuthMethod +// and updates/deletes to that AuthMethod are cascaded to its Managed Groups. +type ManagedGroup struct { + *store.ManagedGroup + tableName string +} + +// NewManagedGroup creates a new in memory ManagedGroup assigned to OIDC +// AuthMethod. Supported options are withName and withDescription. +func NewManagedGroup(authMethodId string, filter string, opt ...Option) (*ManagedGroup, error) { + const op = "oidc.NewManagedGroup" + opts := getOpts(opt...) + mg := &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethodId, + Name: opts.withName, + Description: opts.withDescription, + Filter: filter, + }, + } + if err := mg.validate(op); err != nil { + return nil, err // intentionally not wrapped. + } + + return mg, nil +} + +// validate the Managed Group. On success, it will return nil. +func (mg *ManagedGroup) validate(caller errors.Op) error { + if mg.AuthMethodId == "" { + return errors.New(errors.InvalidParameter, caller, "missing auth method id") + } + if mg.Filter == "" { + return errors.New(errors.InvalidParameter, caller, "missing filter") + } + if _, err := bexpr.CreateEvaluator(mg.Filter); err != nil { + return errors.New(errors.InvalidParameter, caller, "error evaluating filter expression", errors.WithWrap(err)) + } + + return nil +} + +// AllocManagedGroup makes an empty one in memory +func AllocManagedGroup() *ManagedGroup { + return &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{}, + } +} + +// Clone a ManagedGroup. +func (mg *ManagedGroup) Clone() *ManagedGroup { + cp := proto.Clone(mg.ManagedGroup) + return &ManagedGroup{ + ManagedGroup: cp.(*store.ManagedGroup), + } +} + +// TableName returns the table name. +func (mg *ManagedGroup) TableName() string { + if mg.tableName != "" { + return mg.tableName + } + return defaultManagedGroupTableName +} + +// SetTableName sets the table name. +func (mg *ManagedGroup) SetTableName(n string) { + mg.tableName = n +} + +// oplog will create oplog metadata for the ManagedGroup. +func (mg *ManagedGroup) oplog(op oplog.OpType, authMethodScopeId string) oplog.Metadata { + metadata := oplog.Metadata{ + "resource-public-id": []string{mg.GetPublicId()}, + "resource-type": []string{"oidc managed group"}, + "op-type": []string{op.String()}, + } + if mg.AuthMethodId != "" { + metadata["auth-method-id"] = []string{mg.AuthMethodId} + } + if authMethodScopeId != "" { + metadata["scope-id"] = []string{authMethodScopeId} + } + return metadata +} diff --git a/internal/auth/oidc/managed_group_member_account.go b/internal/auth/oidc/managed_group_member_account.go new file mode 100644 index 000000000..0f4719d3a --- /dev/null +++ b/internal/auth/oidc/managed_group_member_account.go @@ -0,0 +1,75 @@ +package oidc + +import ( + "github.com/hashicorp/boundary/internal/auth/oidc/store" + "github.com/hashicorp/boundary/internal/errors" + "google.golang.org/protobuf/proto" +) + +// defaultManagedGroupMemberAccountTableName defines the default table name for a Managed Group +const defaultManagedGroupMemberAccountTableName = "auth_oidc_managed_group_member_account" + +// ManagedGroupMemberAccount contains a mapping between a managed group and a +// member account +type ManagedGroupMemberAccount struct { + *store.ManagedGroupMemberAccount + tableName string +} + +// NewManagedGroupMemberAccount creates a new in memory +// ManagedGroupMemberAccount assigned to a managed group within an OIDC +// AuthMethod. Supported options are withName and withDescription. +func NewManagedGroupMemberAccount(managedGroupId string, memberId string, opt ...Option) (*ManagedGroupMemberAccount, error) { + const op = "oidc.NewManagedGroupMemberAccount" + mg := &ManagedGroupMemberAccount{ + ManagedGroupMemberAccount: &store.ManagedGroupMemberAccount{ + ManagedGroupId: managedGroupId, + MemberId: memberId, + }, + } + if err := mg.validate(op); err != nil { + return nil, err // intentionally not wrapped. + } + + return mg, nil +} + +// validate the ManagedGroupMemberAccount. On success, it will return nil. +func (mg *ManagedGroupMemberAccount) validate(caller errors.Op) error { + if mg.ManagedGroupId == "" { + return errors.New(errors.InvalidParameter, caller, "missing managed group id") + } + if mg.MemberId == "" { + return errors.New(errors.InvalidParameter, caller, "missing member id") + } + + return nil +} + +// AllocManagedGroupMemberAccount makes an empty one in memory +func AllocManagedGroupMemberAccount() *ManagedGroupMemberAccount { + return &ManagedGroupMemberAccount{ + ManagedGroupMemberAccount: &store.ManagedGroupMemberAccount{}, + } +} + +// Clone a ManagedGroupMemberAccount. +func (mg *ManagedGroupMemberAccount) Clone() *ManagedGroupMemberAccount { + cp := proto.Clone(mg.ManagedGroupMemberAccount) + return &ManagedGroupMemberAccount{ + ManagedGroupMemberAccount: cp.(*store.ManagedGroupMemberAccount), + } +} + +// TableName returns the table name. +func (mg *ManagedGroupMemberAccount) TableName() string { + if mg.tableName != "" { + return mg.tableName + } + return defaultManagedGroupMemberAccountTableName +} + +// SetTableName sets the table name. +func (mg *ManagedGroupMemberAccount) SetTableName(n string) { + mg.tableName = n +} diff --git a/internal/auth/oidc/managed_group_test.go b/internal/auth/oidc/managed_group_test.go new file mode 100644 index 000000000..178524668 --- /dev/null +++ b/internal/auth/oidc/managed_group_test.go @@ -0,0 +1,32 @@ +package oidc + +import ( + "testing" + + "github.com/hashicorp/boundary/internal/errors" + "github.com/stretchr/testify/assert" +) + +func Test_ManagedGroups_RepoValidate(t *testing.T) { + t.Parallel() + assert := assert.New(t) + const op = "test" + mg := AllocManagedGroup() + t.Run("empty auth method", func(t *testing.T) { + assert.Contains(mg.validate(op).Error(), errors.New(errors.InvalidParameter, op, "missing auth method id").Error()) + }) + t.Run("empty filter", func(t *testing.T) { + mg.AuthMethodId = "amoidc_1234567890" + assert.Contains(mg.validate(op).Error(), errors.New(errors.InvalidParameter, op, "missing filter").Error()) + }) + t.Run("bad filter", func(t *testing.T) { + mg.AuthMethodId = "amoidc_1234567890" + mg.Filter = "foobar" + assert.Contains(mg.validate(op).Error(), errors.New(errors.InvalidParameter, op, "error evaluating filter expression").Error()) + }) + t.Run("valid", func(t *testing.T) { + mg.AuthMethodId = "amoidc_1234567890" + mg.Filter = TestFakeManagedGroupFilter + assert.NoError(mg.validate(op)) + }) +} diff --git a/internal/auth/oidc/options.go b/internal/auth/oidc/options.go index 87dd578e7..7c2cfb484 100644 --- a/internal/auth/oidc/options.go +++ b/internal/auth/oidc/options.go @@ -3,6 +3,8 @@ package oidc import ( "crypto/x509" "net/url" + + "github.com/hashicorp/boundary/internal/db" ) // getOpts - iterate the inbound Options and return a struct. @@ -42,6 +44,7 @@ type options struct { withIssuer *url.URL withOperationalState AuthMethodState withAccountClaimMap map[string]AccountToClaim + withReader db.Reader } func getDefaultOptions() options { @@ -218,3 +221,11 @@ func WithAccountClaimMap(acm map[string]AccountToClaim) Option { o.withAccountClaimMap = acm } } + +// WithReader provides an option for specifying a reader to use for the +// operation. +func WithReader(reader db.Reader) Option { + return func(o *options) { + o.withReader = reader + } +} diff --git a/internal/auth/oidc/options_test.go b/internal/auth/oidc/options_test.go index 5ea8fbe1c..5dd89eb62 100644 --- a/internal/auth/oidc/options_test.go +++ b/internal/auth/oidc/options_test.go @@ -5,6 +5,7 @@ import ( "net/url" "testing" + "github.com/hashicorp/boundary/internal/db" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -194,4 +195,12 @@ func Test_GetOpts(t *testing.T) { testOpts.withAccountClaimMap = acm assert.Equal(opts, testOpts) }) + t.Run("WithReader", func(t *testing.T) { + assert := assert.New(t) + testOpts := getDefaultOptions() + assert.Nil(testOpts.withReader) + var r db.Reader + opts := getOpts(WithReader(r)) + assert.Equal(r, opts.withReader) + }) } diff --git a/internal/auth/oidc/query.go b/internal/auth/oidc/query.go index 725b6e583..845717c7c 100644 --- a/internal/auth/oidc/query.go +++ b/internal/auth/oidc/query.go @@ -2,14 +2,14 @@ package oidc const ( acctUpsertQuery = ` - insert into auth_oidc_account + insert into auth_oidc_account (%s) - values + values (%s) - on conflict on constraint + on conflict on constraint auth_oidc_account_auth_method_id_issuer_subject_uq - do update set + do update set %s - returning public_id, version - ` + returning public_id, version + ` ) diff --git a/internal/auth/oidc/repository_account.go b/internal/auth/oidc/repository_account.go index 70ea38cce..ec9fc011b 100644 --- a/internal/auth/oidc/repository_account.go +++ b/internal/auth/oidc/repository_account.go @@ -24,6 +24,8 @@ import ( // // Both a.Name and a.Description are optional. If a.Name is set, it must be // unique within a.AuthMethodId. +// +// WithPublicId is currently the only valid option. func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Account, opt ...Option) (*Account, error) { const op = "oidc.(Repository).CreateAccount" if a == nil { @@ -67,11 +69,20 @@ func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Accou if a.Issuer == "" { return nil, errors.New(errors.InvalidParameter, op, "no issuer provided or defined in auth method") } - id, err := newAccountId(a.AuthMethodId, a.Issuer, a.Subject) - if err != nil { - return nil, errors.Wrap(err, op) + + opts := getOpts(opt...) + if opts.withPublicId != "" { + if !strings.HasPrefix(opts.withPublicId, AccountPrefix+"_") { + return nil, errors.New(errors.InvalidParameter, op, "chosen account id does not have a valid prefix") + } + a.PublicId = opts.withPublicId + } else { + id, err := newAccountId(a.AuthMethodId, a.Issuer, a.Subject) + if err != nil { + return nil, errors.Wrap(err, op) + } + a.PublicId = id } - a.PublicId = id oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) if err != nil { diff --git a/internal/auth/oidc/repository_account_test.go b/internal/auth/oidc/repository_account_test.go index 8cda9fed3..f2121b70b 100644 --- a/internal/auth/oidc/repository_account_test.go +++ b/internal/auth/oidc/repository_account_test.go @@ -67,7 +67,7 @@ func TestRepository_CreateAccount(t *testing.T) { wantErrMsg: "oidc.(Repository).CreateAccount: missing embedded Account: parameter violation: error #100", }, { - name: "invalid-no-scope-id", + name: "invalid-no-auth-method-id", in: &Account{ Account: &store.Account{}, }, diff --git a/internal/auth/oidc/repository_auth_method_update.go b/internal/auth/oidc/repository_auth_method_update.go index 11309cd19..b514a55d5 100644 --- a/internal/auth/oidc/repository_auth_method_update.go +++ b/internal/auth/oidc/repository_auth_method_update.go @@ -21,6 +21,7 @@ const ( VersionField = "Version" NameField = "Name" DescriptionField = "Description" + FilterField = "Filter" IssuerField = "Issuer" ClientIdField = "ClientId" ClientSecretField = "ClientSecret" diff --git a/internal/auth/oidc/repository_managed_group.go b/internal/auth/oidc/repository_managed_group.go new file mode 100644 index 000000000..e5193586d --- /dev/null +++ b/internal/auth/oidc/repository_managed_group.go @@ -0,0 +1,251 @@ +package oidc + +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/boundary/internal/db" + dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/oplog" +) + +// CreateManagedGroup inserts an ManagedGroup, mg, into the repository and +// returns a new ManagedGroup containing its PublicId. mg is not changed. mg +// must contain a valid AuthMethodId. mg must not contain a PublicId. The +// PublicId is generated and assigned by this method. +// +// Both mg.Name and mg.Description are optional. If mg.Name is set, it must be +// unique within mg.AuthMethodId. +func (r *Repository) CreateManagedGroup(ctx context.Context, scopeId string, mg *ManagedGroup, opt ...Option) (*ManagedGroup, error) { + const op = "oidc.(Repository).CreateManagedGroup" + if mg == nil { + return nil, errors.New(errors.InvalidParameter, op, "missing ManagedGroup") + } + if mg.ManagedGroup == nil { + return nil, errors.New(errors.InvalidParameter, op, "missing embedded ManagedGroup") + } + if mg.AuthMethodId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing auth method id") + } + if mg.Filter == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing filter") + } + if mg.PublicId != "" { + return nil, errors.New(errors.InvalidParameter, op, "public id must be empty") + } + if scopeId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing scope id") + } + + mg = mg.Clone() + + id, err := newManagedGroupId() + if err != nil { + return nil, errors.Wrap(err, op) + } + mg.PublicId = id + + oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) + if err != nil { + return nil, errors.Wrap(err, op, errors.WithMsg("unable to get oplog wrapper"), errors.WithCode(errors.Encrypt)) + } + + var newManagedGroup *ManagedGroup + _, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, + func(_ db.Reader, w db.Writer) error { + newManagedGroup = mg.Clone() + if err := w.Create(ctx, newManagedGroup, db.WithOplog(oplogWrapper, mg.oplog(oplog.OpType_OP_TYPE_CREATE, scopeId))); err != nil { + return errors.Wrap(err, op) + } + return nil + }, + ) + + if err != nil { + if errors.IsUniqueError(err) { + return nil, errors.New(errors.NotUnique, op, fmt.Sprintf( + "in auth method %s: name %q already exists", + mg.AuthMethodId, mg.Name)) + } + return nil, errors.Wrap(err, op, errors.WithMsg(mg.AuthMethodId)) + } + return newManagedGroup, nil +} + +// LookupManagedGroup will look up a managed group in the repository. If the managed group is not +// found, it will return nil, nil. All options are ignored. +func (r *Repository) LookupManagedGroup(ctx context.Context, withPublicId string, opt ...Option) (*ManagedGroup, error) { + const op = "oidc.(Repository).LookupManagedGroup" + if withPublicId == "" { + return nil, errors.New(errors.InvalidPublicId, op, "missing public id") + } + a := AllocManagedGroup() + a.PublicId = withPublicId + if err := r.reader.LookupByPublicId(ctx, a); err != nil { + if errors.IsNotFoundError(err) { + return nil, nil + } + return nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", withPublicId))) + } + return a, nil +} + +// ListManagedGroups in an auth method and supports WithLimit option. +func (r *Repository) ListManagedGroups(ctx context.Context, withAuthMethodId string, opt ...Option) ([]*ManagedGroup, error) { + const op = "oidc.(Repository).ListManagedGroups" + if withAuthMethodId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing auth method id") + } + opts := getOpts(opt...) + limit := r.defaultLimit + if opts.withLimit != 0 { + // non-zero signals an override of the default limit for the repo. + limit = opts.withLimit + } + var mgs []*ManagedGroup + err := r.reader.SearchWhere(ctx, &mgs, "auth_method_id = ?", []interface{}{withAuthMethodId}, db.WithLimit(limit)) + if err != nil { + return nil, errors.Wrap(err, op) + } + return mgs, nil +} + +// DeleteManagedGroup deletes the managed group for the provided id from the +// repository returning a count of the number of records deleted. All options +// are ignored. +func (r *Repository) DeleteManagedGroup(ctx context.Context, scopeId, withPublicId string, opt ...Option) (int, error) { + const op = "oidc.(Repository).DeleteManagedGroup" + if withPublicId == "" { + return db.NoRowsAffected, errors.New(errors.InvalidPublicId, op, "missing public id") + } + if scopeId == "" { + return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing scope id") + } + mg := AllocManagedGroup() + mg.PublicId = withPublicId + + oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) + if err != nil { + return db.NoRowsAffected, errors.Wrap(err, op, errors.WithCode(errors.Encrypt), errors.WithMsg("unable to get oplog wrapper")) + } + + var rowsDeleted int + _, err = r.writer.DoTx( + ctx, + db.StdRetryCnt, + db.ExpBackoff{}, + func(_ db.Reader, w db.Writer) (err error) { + metadata := mg.oplog(oplog.OpType_OP_TYPE_DELETE, scopeId) + dMg := mg.Clone() + rowsDeleted, err = w.Delete(ctx, dMg, db.WithOplog(oplogWrapper, metadata)) + if err != nil { + return errors.Wrap(err, op) + } + if rowsDeleted > 1 { + return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted") + } + return nil + }, + ) + + if err != nil { + return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(withPublicId)) + } + + return rowsDeleted, nil +} + +// UpdateManagedGroup updates the repository entry for mg.PublicId with the +// values in mg for the fields listed in fieldMaskPaths. It returns a new +// ManagedGroup containing the updated values and a count of the number of +// records updated. mg is not changed. +// +// mg must contain a valid PublicId. Only mg.Name, mg.Description, and mg.Filter +// can be updated. If mg.Name is set to a non-empty string, it must be unique +// within mg.AuthMethodId. +// +// An attribute of a will be set to NULL in the database if the attribute in a +// is the zero value and it is included in fieldMaskPaths. +func (r *Repository) UpdateManagedGroup(ctx context.Context, scopeId string, mg *ManagedGroup, version uint32, fieldMaskPaths []string, opt ...Option) (*ManagedGroup, int, error) { + const op = "oidc.(Repository).UpdateManagedGroup" + if mg == nil { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing ManagedGroup") + } + if mg.ManagedGroup == nil { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing embedded ManagedGroup") + } + if mg.PublicId == "" { + return nil, db.NoRowsAffected, errors.New(errors.InvalidPublicId, op, "missing public id") + } + if version == 0 { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing version") + } + if scopeId == "" { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing scope id") + } + + for _, f := range fieldMaskPaths { + switch { + case strings.EqualFold(NameField, f): + case strings.EqualFold(DescriptionField, f): + case strings.EqualFold(FilterField, f): + default: + return nil, db.NoRowsAffected, errors.New(errors.InvalidFieldMask, op, f) + } + } + var dbMask, nullFields []string + dbMask, nullFields = dbcommon.BuildUpdatePaths( + map[string]interface{}{ + NameField: mg.Name, + DescriptionField: mg.Description, + FilterField: mg.Filter, + }, + fieldMaskPaths, + nil, + ) + if len(dbMask) == 0 && len(nullFields) == 0 { + return nil, db.NoRowsAffected, errors.New(errors.EmptyFieldMask, op, "missing field mask") + } + + oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) + if err != nil { + return nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithCode(errors.Encrypt), + errors.WithMsg(("unable to get oplog wrapper"))) + } + + mg = mg.Clone() + + metadata := mg.oplog(oplog.OpType_OP_TYPE_UPDATE, scopeId) + + // TODO/FIXME: if the filter is updated, remove all account/mg associations + + var rowsUpdated int + var returnedManagedGroup *ManagedGroup + _, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, + func(_ db.Reader, w db.Writer) error { + returnedManagedGroup = mg.Clone() + var err error + rowsUpdated, err = w.Update(ctx, returnedManagedGroup, dbMask, nullFields, db.WithOplog(oplogWrapper, metadata), db.WithVersion(&version)) + if err != nil { + return errors.Wrap(err, op) + } + if rowsUpdated > 1 { + return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated") + } + return nil + }, + ) + + if err != nil { + if errors.IsUniqueError(err) { + return nil, db.NoRowsAffected, errors.New(errors.NotUnique, op, + fmt.Sprintf("name %s already exists: %s", mg.Name, mg.PublicId)) + } + return nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(mg.PublicId)) + } + + return returnedManagedGroup, rowsUpdated, nil +} diff --git a/internal/auth/oidc/repository_managed_group_members.go b/internal/auth/oidc/repository_managed_group_members.go new file mode 100644 index 000000000..b2b9fc8e2 --- /dev/null +++ b/internal/auth/oidc/repository_managed_group_members.go @@ -0,0 +1,241 @@ +package oidc + +import ( + "context" + "fmt" + + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/oplog" +) + +// SetManagedGroupMemberships will set the managed groups for the given account +// ID. If mgs is empty, the set of groups the account belongs to will be +// cleared. It returns the set of managed group IDs. +// +// mgs contains the set of managed groups that matched. It must contain the +// group's version as this is used to ensure consistency between when the filter +// attached to the managed group was run and the point at which we are adding +// the account to the group. +func (r *Repository) SetManagedGroupMemberships(ctx context.Context, am *AuthMethod, acct *Account, mgs []*ManagedGroup, _ ...Option) ([]*ManagedGroupMemberAccount, int, error) { + const op = "oidc.(Repository).SetManagedGroupMemberships" + if am == nil { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing auth method") + } + if am.AuthMethod == nil { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing auth method store") + } + if am.PublicId == "" { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing auth method id") + } + if am.ScopeId == "" { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing auth method scope id") + } + if acct == nil { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing account") + } + if acct.Account == nil { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing account store") + } + if acct.PublicId == "" { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing account id") + } + + oplogWrapper, err := r.kms.GetWrapper(ctx, am.ScopeId, kms.KeyPurposeOplog) + if err != nil { + return nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get oplog wrapper")) + } + + newMgPublicIds := make(map[string]bool, len(mgs)) + mgsToUpdate := make([]*ManagedGroup, 0, len(mgs)) + for _, mg := range mgs { + if mg.Version == 0 { + return nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("missing version for managed group %s", mg.PublicId)) + } + if newMgPublicIds[mg.PublicId] { + // We've already seen this -- could be a duplicate in the incoming + // MGs. We don't want to add it again because the version won't be + // correct, and it's unnecessary. + continue + } + newMgPublicIds[mg.PublicId] = true + mgToUpdate := AllocManagedGroup() + mgToUpdate.PublicId = mg.PublicId + mgToUpdate.AuthMethodId = am.PublicId + mgToUpdate.Version = mg.Version + 1 + mgsToUpdate = append(mgsToUpdate, mgToUpdate) + } + + ticketMg := AllocManagedGroup() + var totalRowsAffected int + var currentMemberships []*ManagedGroupMemberAccount + _, err = r.writer.DoTx( + ctx, + db.StdRetryCnt, + db.ExpBackoff{}, + func(reader db.Reader, w db.Writer) error { + // We need a ticket, which won't be redeemed until all the other + // writes are successful. We can't just use a single ticket because + // we need to write oplog entries for deletes and adds. + mgTicket, err := w.GetTicket(ticketMg) + if err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to get ticket for oidc managed groups")) + } + + msgs := make([]*oplog.Message, 0, len(mgs)+5) + metadata := oplog.Metadata{ + "op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()}, + "scope-id": []string{am.ScopeId}, + "auth-method-id": []string{am.PublicId}, + "account-id": []string{acct.PublicId}, + } + + // Ensure that none of the filters have changed or will change + // during this operation + for _, mgToUpdate := range mgsToUpdate { + var mgOplogMsg oplog.Message + // mgToUpdate will have come in with an incremented version + // already, but WithVersion needs the current version + prevVersion := mgToUpdate.Version - 1 + rowsUpdated, err := w.Update(ctx, mgToUpdate, []string{"Version"}, nil, db.NewOplogMsg(&mgOplogMsg), db.WithVersion(&prevVersion)) + if err != nil { + return errors.Wrap(err, op) + } + if rowsUpdated != 1 { + return errors.New(errors.MultipleRecords, op, fmt.Sprintf("updated oidc managed group and %d rows updated", rowsUpdated)) + } + msgs = append(msgs, &mgOplogMsg) + } + + currentMemberships, err = r.ListManagedGroupMembershipsByMember(ctx, acct.PublicId, WithReader(reader)) + if err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to retrieve current managed group memberships before deletion")) + } + + // Figure out which ones to delete and which ones we already have + toDelete := make([]interface{}, 0, len(mgs)) + for _, currMg := range currentMemberships { + currMgId := currMg.ManagedGroupId + if newMgPublicIds[currMgId] { + // We're slated to add it in, but it's already in there, so + // take it out of the new list + delete(newMgPublicIds, currMgId) + } else { + // It's not currently matching a filter, so needs to be deleted + delMg := AllocManagedGroupMemberAccount() + delMg.ManagedGroupId = currMgId + delMg.MemberId = acct.PublicId + toDelete = append(toDelete, delMg) + } + } + + // At this point, anything in toDelete should be deleted, and + // anything left in newMgPublicIds should be added. However, if we + // had no managed group to update, because none were passed in, but + // also none to delete, we return at this point. Nothing will have + // changed and nothing will be changed either. + if len(mgs) == 0 && len(toDelete) == 0 { + return errors.New(errors.GracefullyAborted, op, "nothing to do") + } + + // Start with deletion + if len(toDelete) > 0 { + metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_DELETE.String()) + deleteOplogMsgs := make([]*oplog.Message, 0, len(toDelete)) + rowsDeleted, err := w.DeleteItems(ctx, toDelete, db.NewOplogMsgs(&deleteOplogMsgs)) + if err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to delete managed group member accounts")) + } + if rowsDeleted != len(toDelete) { + return errors.New(errors.MultipleRecords, op, fmt.Sprintf("managed group member accounts deleted %d did not match request for %d", rowsDeleted, len(toDelete))) + } + totalRowsAffected += rowsDeleted + msgs = append(msgs, deleteOplogMsgs...) + } + + // Now do insertion + if len(newMgPublicIds) > 0 { + metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_CREATE.String()) + addOplogMsgs := make([]*oplog.Message, 0, len(newMgPublicIds)) + toAdd := make([]interface{}, 0, len(newMgPublicIds)) + for mgId := range newMgPublicIds { + newMg := AllocManagedGroupMemberAccount() + newMg.ManagedGroupId = mgId + newMg.MemberId = acct.PublicId + toAdd = append(toAdd, newMg) + } + if err := w.CreateItems(ctx, toAdd, db.NewOplogMsgs(&addOplogMsgs)); err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to add managed group member accounts")) + } + totalRowsAffected += len(toAdd) + msgs = append(msgs, addOplogMsgs...) + } + + if len(msgs) > 0 { + if err := w.WriteOplogEntryWith(ctx, oplogWrapper, mgTicket, metadata, msgs); err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to write oplog")) + } + } + + currentMemberships, err = r.ListManagedGroupMembershipsByMember(ctx, acct.PublicId, WithReader(reader)) + if err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to retrieve current managed group memberships after set")) + } + return nil + }) + if err != nil && !errors.Match(errors.T(errors.GracefullyAborted), err) { + return nil, db.NoRowsAffected, errors.Wrap(err, op) + } + return currentMemberships, totalRowsAffected, nil +} + +// ListManagedGroupMembershipsByMember lists managed group memberships via the +// member (account) ID and supports WithLimit option. +func (r *Repository) ListManagedGroupMembershipsByMember(ctx context.Context, withAcctId string, opt ...Option) ([]*ManagedGroupMemberAccount, error) { + const op = "oidc.(Repository).ListManagedGroupMembershipsByMember" + if withAcctId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing account id") + } + opts := getOpts(opt...) + limit := r.defaultLimit + if opts.withLimit != 0 { + // non-zero signals an override of the default limit for the repo. + limit = opts.withLimit + } + reader := r.reader + if opts.withReader != nil { + reader = opts.withReader + } + var mgs []*ManagedGroupMemberAccount + err := reader.SearchWhere(ctx, &mgs, "member_id = ?", []interface{}{withAcctId}, db.WithLimit(limit)) + if err != nil { + return nil, errors.Wrap(err, op) + } + return mgs, nil +} + +// ListManagedGroupMembershipsByGroup lists managed group memberships via the +// group ID and supports WithLimit option. +func (r *Repository) ListManagedGroupMembershipsByGroup(ctx context.Context, withGroupId string, opt ...Option) ([]*ManagedGroupMemberAccount, error) { + const op = "oidc.(Repository).ListManagedGroupMembershipsByGroup" + if withGroupId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing managed group id") + } + opts := getOpts(opt...) + limit := r.defaultLimit + if opts.withLimit != 0 { + // non-zero signals an override of the default limit for the repo. + limit = opts.withLimit + } + reader := r.reader + if opts.withReader != nil { + reader = opts.withReader + } + var mgs []*ManagedGroupMemberAccount + err := reader.SearchWhere(ctx, &mgs, "managed_group_id = ?", []interface{}{withGroupId}, db.WithLimit(limit)) + if err != nil { + return nil, errors.Wrap(err, op) + } + return mgs, nil +} diff --git a/internal/auth/oidc/repository_managed_group_members_test.go b/internal/auth/oidc/repository_managed_group_members_test.go new file mode 100644 index 000000000..863ebdbfe --- /dev/null +++ b/internal/auth/oidc/repository_managed_group_members_test.go @@ -0,0 +1,291 @@ +package oidc_test + +import ( + "context" + "math/rand" + "strings" + "testing" + + "github.com/hashicorp/boundary/internal/auth/oidc" + "github.com/hashicorp/boundary/internal/auth/oidc/store" + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/servers/controller" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_ManagedGroupMemberships(t *testing.T) { + // This tests both managed group membership functions (set/list) as list is + // always called as a return from set and we are validating the values that + // come back against what we expect. + + // This test can be run in parallel; the subtests *cannot*. + t.Parallel() + + // Note: using a test controller here for ease of setup as we need a working + // dev OIDC auth method and associated accounts. This test is not making API + // calls! It's accessing the repo directly via the test controller's + // exposure of the underlying DB primitives. + tc := controller.NewTestController(t, nil) + defer tc.Shutdown() + + conn := tc.DbConn() + rw := db.New(conn) + + kmsCache := tc.Kms() + iamRepo := tc.IamRepo() + org, _ := iam.TestScopes(t, iamRepo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, org.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + repo, err := oidc.NewRepository(rw, rw, kmsCache) + require.NoError(t, err) + require.NotNil(t, repo) + + mgs := make([]*oidc.ManagedGroup, 0, 10) + + for i := 0; i < 100; i++ { + mg := oidc.AllocManagedGroup() + mg.AuthMethodId = authMethod.PublicId + mg.Filter = oidc.TestFakeManagedGroupFilter + got, err := repo.CreateManagedGroup(context.Background(), org.GetPublicId(), mg) + require.NoError(t, err) + mgs = append(mgs, got) + } + + // Fetch valid OIDC accounts. One will be "static" where we will simply + // ensure modifying the groups for the other doesn't affect it; the other + // will be used for testing. + var accts []*oidc.Account + err = rw.SearchWhere(ctx, &accts, "", nil, db.WithLimit(2)) + require.NoError(t, err) + require.Len(t, accts, 2) + staticAccountId := accts[0].PublicId + staticMembershipCount := 20 + accountId := accts[1].PublicId + + account := oidc.AllocAccount() + account.PublicId = accountId + + tests := []struct { + name string + // If true, we will auto populate necesary values into the function + validPrereqs bool + + // Else these can be used for testing + authMethod *oidc.AuthMethod + authMethodId string + account *oidc.Account + accountId string + authMethodScopeId string + wantPreseededMgsCount int + wantMgsCount int + specificMgs []*oidc.ManagedGroup + + wantErr errors.Code + wantErrContains string + }{ + { + name: "nil auth method", + wantErr: errors.InvalidParameter, + wantErrContains: "missing auth method", + }, + { + name: "missing auth method store", + authMethod: &oidc.AuthMethod{}, + wantErr: errors.InvalidParameter, + wantErrContains: "missing auth method store", + }, + { + name: "missing auth method id", + authMethod: &oidc.AuthMethod{AuthMethod: &store.AuthMethod{}}, + wantErr: errors.InvalidParameter, + wantErrContains: "missing auth method id", + }, + { + name: "missing auth method scope id", + authMethod: &oidc.AuthMethod{AuthMethod: &store.AuthMethod{PublicId: authMethod.PublicId}}, + wantErr: errors.InvalidParameter, + wantErrContains: "missing auth method scope id", + }, + { + name: "missing account", + authMethod: authMethod, + wantErr: errors.InvalidParameter, + wantErrContains: "missing account", + }, + { + name: "missing account store", + authMethod: authMethod, + account: &oidc.Account{}, + wantErr: errors.InvalidParameter, + wantErrContains: "missing account store", + }, + { + name: "missing account id", + authMethod: authMethod, + account: &oidc.Account{Account: &store.Account{}}, + wantErr: errors.InvalidParameter, + wantErrContains: "missing account id", + }, + { + name: "valid fixed, static", + validPrereqs: true, + accountId: staticAccountId, + specificMgs: mgs[0:staticMembershipCount], + }, + { + name: "valid fixed", + validPrereqs: true, + specificMgs: mgs[0:20], + }, + { + name: "valid fixed, same values", + validPrereqs: true, + specificMgs: mgs[0:20], + }, + { + name: "valid fixed, new values", + validPrereqs: true, + specificMgs: mgs[20:40], + }, + { + name: "valid none", + validPrereqs: true, + wantMgsCount: 0, + }, + { + name: "valid none, second test, testing gracefully aborting", + validPrereqs: true, + wantMgsCount: 0, + }, + { + name: "valid fixed, prep for random", + validPrereqs: true, + specificMgs: mgs[20:50], + }, + { + name: "valid random", + validPrereqs: true, + wantMgsCount: 30, + }, + { + name: "valid random, second test", + validPrereqs: true, + wantMgsCount: 20, + }, + { + name: "valid with duplicates", + validPrereqs: true, + specificMgs: append(mgs[0:20], mgs[0:20]...), + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // We are intentionally carrying things over between tests to be + // more realistic but that means we need correct versions, so update + // them first. + currMgs, err := repo.ListManagedGroups(ctx, authMethod.PublicId) + require.NoError(err) + require.Len(currMgs, 100) + currVersionMap := make(map[string]uint32, len(currMgs)) + for _, currMg := range currMgs { + currVersionMap[currMg.PublicId] = currMg.Version + } + for _, mg := range mgs { + mg.Version = currVersionMap[mg.PublicId] + } + + var mgsToTest []*oidc.ManagedGroup + var finalMgs map[string]*oidc.ManagedGroup + // If we know the inputs are sane, create the test data + if tt.validPrereqs { + tt.authMethod = authMethod + tt.account = oidc.AllocAccount() + tt.account.PublicId = accountId + if tt.accountId != "" { + // This is for the test where we initially populate the + // static account + tt.account.PublicId = tt.accountId + } + mgsToTest = tt.specificMgs + if mgsToTest == nil { + // Select at random + mgsToTest = make([]*oidc.ManagedGroup, tt.wantMgsCount) + for i := 0; i < tt.wantMgsCount; i++ { + mg := mgs[rand.Int()%len(mgs)] + mgsToTest[i] = mg + } + } + finalMgs = make(map[string]*oidc.ManagedGroup) + for _, v := range mgsToTest { + finalMgs[v.PublicId] = v + } + } + + memberships, _, err := repo.SetManagedGroupMemberships(ctx, tt.authMethod, tt.account, mgsToTest) + if tt.wantErr != 0 { + assert.Truef(errors.Match(errors.T(tt.wantErr), err), "Unexpected error %s", err) + if tt.wantErrContains != "" { + assert.True(strings.Contains(err.Error(), tt.wantErrContains)) + } + return + } + + require.NoError(err) + assert.Len(memberships, len(finalMgs)) + + // Ensure the same set was found; all memberships found should have + // been in the finalMgs map, and when they are all removed there + // should be nothing left. + for _, mship := range memberships { + // Randomly check a few to ensure the MembershipsByGroup function works + members, err := repo.ListManagedGroupMembershipsByGroup(ctx, mship.ManagedGroupId) + require.NoError(err) + require.NotEmpty(members) + var found bool + for _, v := range members { + if v.MemberId == tt.account.GetPublicId() { + found = true + break + } + } + assert.True(found) + assert.Contains(finalMgs, mship.ManagedGroupId) + delete(finalMgs, mship.ManagedGroupId) + } + assert.Len(finalMgs, 0) + + // Now check that the static account still has the same memberships + memberships, err = repo.ListManagedGroupMembershipsByMember(ctx, staticAccountId) + require.NoError(err) + assert.Len(memberships, staticMembershipCount) + finalMgs = make(map[string]*oidc.ManagedGroup, staticMembershipCount) + for _, mg := range mgs[0:staticMembershipCount] { + finalMgs[mg.PublicId] = mg + } + for _, mship := range memberships { + assert.Contains(finalMgs, mship.ManagedGroupId) + delete(finalMgs, mship.ManagedGroupId) + } + assert.Len(finalMgs, 0) + }) + } +} diff --git a/internal/auth/oidc/repository_managed_group_test.go b/internal/auth/oidc/repository_managed_group_test.go new file mode 100644 index 000000000..abd99f97c --- /dev/null +++ b/internal/auth/oidc/repository_managed_group_test.go @@ -0,0 +1,971 @@ +package oidc + +import ( + "context" + "fmt" + "sort" + "strings" + "testing" + "time" + + "github.com/hashicorp/boundary/internal/auth/oidc/store" + "github.com/hashicorp/boundary/internal/db" + dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/intglobals" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/oplog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRepository_CreateManagedGroup(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrapper := db.TestWrapper(t) + + kmsCache := kms.TestKms(t, conn, wrapper) + iamRepo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, iamRepo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := TestAuthMethod( + t, conn, databaseWrapper, org.GetPublicId(), ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + tests := []struct { + name string + scopeId string + in *ManagedGroup + opts []Option + want *ManagedGroup + wantIsErr errors.Code + wantErrMsg string + wantErrContains string + }{ + { + name: "nil-ManagedGroup", + scopeId: org.GetPublicId(), + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).CreateManagedGroup: missing ManagedGroup: parameter violation: error #100", + }, + { + name: "nil-embedded-ManagedGroup", + scopeId: org.GetPublicId(), + in: &ManagedGroup{}, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).CreateManagedGroup: missing embedded ManagedGroup: parameter violation: error #100", + }, + { + name: "invalid-no-auth-method-id", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{}, + }, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).CreateManagedGroup: missing auth method id: parameter violation: error #100", + }, + { + name: "invalid-no-filter", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + }, + }, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).CreateManagedGroup: missing filter: parameter violation: error #100", + }, + { + name: "invalid-public-id-set", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + PublicId: "mgoidc_OOOOOOOOOO", + }, + }, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).CreateManagedGroup: public id must be empty: parameter violation: error #100", + }, + { + name: "no-scope", + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + }, + }, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).CreateManagedGroup: missing scope id: parameter violation: error #100", + }, + { + name: "valid-no-options", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + }, + }, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + }, + }, + }, + { + name: "valid-with-name", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + Name: "test-name-repo", + }, + }, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + Name: "test-name-repo", + }, + }, + }, + { + name: "valid-with-description", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + Description: ("test-description-repo"), + Name: "myname", + }, + }, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + Description: ("test-description-repo"), + Name: "myname", + }, + }, + }, + { + name: "duplicate-name", + scopeId: org.GetPublicId(), + in: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + AuthMethodId: authMethod.PublicId, + Filter: TestFakeManagedGroupFilter, + Description: ("test-description-repo"), + Name: "myname", + }, + }, + wantIsErr: errors.NotUnique, + wantErrContains: `name "myname" already exists`, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + repo, err := NewRepository(rw, rw, kmsCache) + assert.NoError(err) + require.NotNil(repo) + got, err := repo.CreateManagedGroup(context.Background(), tt.scopeId, tt.in, tt.opts...) + if tt.wantIsErr != 0 { + require.Error(err) + assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err) + if tt.wantErrContains != "" { + assert.True(strings.Contains(err.Error(), tt.wantErrContains)) + } else { + assert.Equal(tt.wantErrMsg, err.Error()) + } + return + } + require.NoError(err) + assert.Empty(tt.in.PublicId) + require.NotNil(got) + assertPublicId(t, intglobals.OidcManagedGroupPrefix, got.PublicId) + assert.NotSame(tt.in, got) + assert.Equal(tt.want.Name, got.Name) + assert.Equal(tt.want.Description, got.Description) + assert.Equal(got.CreateTime, got.UpdateTime) + + assert.NoError(db.TestVerifyOplog(t, rw, got.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second))) + }) + } +} + +func TestRepository_LookupManagedGroup(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrapper := db.TestWrapper(t) + + kmsCache := kms.TestKms(t, conn, wrapper) + iamRepo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, iamRepo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + mg := TestManagedGroup(t, conn, authMethod, TestFakeManagedGroupFilter) + + newMgId, err := newManagedGroupId() + require.NoError(t, err) + tests := []struct { + name string + in string + want *ManagedGroup + wantIsErr errors.Code + wantErrMsg string + }{ + { + name: "With no public id", + wantIsErr: errors.InvalidPublicId, + wantErrMsg: "oidc.(Repository).LookupManagedGroup: missing public id: parameter violation: error #102", + }, + { + name: "With non existing mg id", + in: newMgId, + }, + { + name: "With existing mg id", + in: mg.GetPublicId(), + want: mg, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + repo, err := NewRepository(rw, rw, kmsCache) + assert.NoError(err) + require.NotNil(repo) + got, err := repo.LookupManagedGroup(context.Background(), tt.in) + if tt.wantIsErr != 0 { + assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err) + assert.Equal(tt.wantErrMsg, err.Error()) + return + } + require.NoError(err) + assert.EqualValues(tt.want, got) + }) + } +} + +func TestRepository_DeleteManagedGroup(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrapper := db.TestWrapper(t) + + ctx := context.Background() + kmsCache := kms.TestKms(t, conn, wrapper) + iamRepo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, iamRepo) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + authMethod := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + mg := TestManagedGroup(t, conn, authMethod, TestFakeManagedGroupFilter) + newMgId, err := newManagedGroupId() + require.NoError(t, err) + tests := []struct { + name string + scopeId string + in string + want int + wantIsErr errors.Code + wantErrMsg string + }{ + { + name: "With no scope id", + scopeId: "", + in: mg.GetPublicId(), + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).DeleteManagedGroup: missing scope id: parameter violation: error #100", + }, + { + name: "With no public id", + scopeId: org.GetPublicId(), + wantIsErr: errors.InvalidPublicId, + wantErrMsg: "oidc.(Repository).DeleteManagedGroup: missing public id: parameter violation: error #102", + }, + { + name: "With non existing managed group id", + scopeId: org.GetPublicId(), + in: newMgId, + want: 0, + }, + { + name: "With existing managed group id", + scopeId: org.GetPublicId(), + in: mg.GetPublicId(), + want: 1, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + repo, err := NewRepository(rw, rw, kmsCache) + assert.NoError(err) + require.NotNil(repo) + got, err := repo.DeleteManagedGroup(context.Background(), tt.scopeId, tt.in) + if tt.wantIsErr != 0 { + assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err) + assert.Equal(tt.wantErrMsg, err.Error()) + return + } + require.NoError(err) + assert.EqualValues(tt.want, got) + }) + } +} + +func TestRepository_ListManagedGroups(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrapper := db.TestWrapper(t) + + ctx := context.Background() + kmsCache := kms.TestKms(t, conn, wrapper) + iamRepo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, iamRepo) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + authMethod1 := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice1.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + authMethod2 := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice2.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + authMethod3 := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice3.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + mgs1 := []*ManagedGroup{ + TestManagedGroup(t, conn, authMethod1, TestFakeManagedGroupFilter), + TestManagedGroup(t, conn, authMethod1, TestFakeManagedGroupFilter), + TestManagedGroup(t, conn, authMethod1, TestFakeManagedGroupFilter), + } + sort.Slice(mgs1, func(i, j int) bool { + return strings.Compare(mgs1[i].PublicId, mgs1[j].PublicId) < 0 + }) + + mgs2 := []*ManagedGroup{ + TestManagedGroup(t, conn, authMethod2, TestFakeManagedGroupFilter), + TestManagedGroup(t, conn, authMethod2, TestFakeManagedGroupFilter), + TestManagedGroup(t, conn, authMethod2, TestFakeManagedGroupFilter), + } + sort.Slice(mgs2, func(i, j int) bool { + return strings.Compare(mgs2[i].PublicId, mgs2[j].PublicId) < 0 + }) + + tests := []struct { + name string + in string + opts []Option + want []*ManagedGroup + wantIsErr errors.Code + wantErrMsg string + }{ + { + name: "With no auth method id", + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).ListManagedGroups: missing auth method id: parameter violation: error #100", + }, + { + name: "With no managed groups", + in: authMethod3.GetPublicId(), + want: []*ManagedGroup{}, + }, + { + name: "With first auth method id", + in: authMethod1.GetPublicId(), + want: mgs1, + }, + { + name: "With first auth method id", + in: authMethod2.GetPublicId(), + want: mgs2, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + repo, err := NewRepository(rw, rw, kmsCache) + assert.NoError(err) + require.NotNil(repo) + got, err := repo.ListManagedGroups(context.Background(), tt.in, tt.opts...) + if tt.wantIsErr != 0 { + assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err) + assert.Equal(tt.wantErrMsg, err.Error()) + return + } + require.NoError(err) + + sort.Slice(got, func(i, j int) bool { + return strings.Compare(got[i].PublicId, got[j].PublicId) < 0 + }) + + assert.EqualValues(tt.want, got) + }) + } +} + +func TestRepository_ListManagedGroups_Limits(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrapper := db.TestWrapper(t) + + ctx := context.Background() + kmsCache := kms.TestKms(t, conn, wrapper) + iamRepo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, iamRepo) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + am := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice1.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + mgCount := 10 + for i := 0; i < mgCount; i++ { + TestManagedGroup(t, conn, am, fmt.Sprintf(`"/foo/%d" == "bar"`, i)) + } + + tests := []struct { + name string + repoOpts []Option + listOpts []Option + wantLen int + }{ + { + name: "With no limits", + wantLen: mgCount, + }, + { + name: "With repo limit", + repoOpts: []Option{WithLimit(3)}, + wantLen: 3, + }, + { + name: "With negative repo limit", + repoOpts: []Option{WithLimit(-1)}, + wantLen: mgCount, + }, + { + name: "With List limit", + listOpts: []Option{WithLimit(3)}, + wantLen: 3, + }, + { + name: "With negative List limit", + listOpts: []Option{WithLimit(-1)}, + wantLen: mgCount, + }, + { + name: "With repo smaller than list limit", + repoOpts: []Option{WithLimit(2)}, + listOpts: []Option{WithLimit(6)}, + wantLen: 6, + }, + { + name: "With repo larger than list limit", + repoOpts: []Option{WithLimit(6)}, + listOpts: []Option{WithLimit(2)}, + wantLen: 2, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + repo, err := NewRepository(rw, rw, kmsCache, tt.repoOpts...) + assert.NoError(err) + require.NotNil(repo) + got, err := repo.ListManagedGroups(context.Background(), am.GetPublicId(), tt.listOpts...) + require.NoError(err) + assert.Len(got, tt.wantLen) + }) + } +} + +func TestRepository_UpdateManagedGroup(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrapper := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrapper) + iamRepo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, iamRepo) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + am := TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, ActivePrivateState, + "alice-rp", "fido", + WithSigningAlgs(RS256), + WithIssuer(TestConvertToUrls(t, "https://www.alice.com")[0]), + WithApiUrl(TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + changeName := func(s string) func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + mg.Name = s + return mg + } + } + + changeDescription := func(s string) func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + mg.Description = s + return mg + } + } + + changeFilter := func(s string) func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + mg.Filter = s + return mg + } + } + + makeNil := func() func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + return nil + } + } + + makeEmbeddedNil := func() func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + return &ManagedGroup{} + } + } + + deletePublicId := func() func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + mg.PublicId = "" + return mg + } + } + + nonExistentPublicId := func() func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + mg.PublicId = "abcd_OOOOOOOOOO" + return mg + } + } + + combine := func(fns ...func(mg *ManagedGroup) *ManagedGroup) func(*ManagedGroup) *ManagedGroup { + return func(mg *ManagedGroup) *ManagedGroup { + for _, fn := range fns { + mg = fn(mg) + } + return mg + } + } + + tests := []struct { + name string + scopeId string + version uint32 + orig *ManagedGroup + chgFn func(*ManagedGroup) *ManagedGroup + masks []string + want *ManagedGroup + wantCount int + wantIsErr errors.Code + wantErrMsg string + wantErrContains string + }{ + { + name: "nil-ManagedGroup", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{}, + }, + chgFn: makeNil(), + masks: []string{NameField, DescriptionField}, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: missing ManagedGroup: parameter violation: error #100", + }, + { + name: "nil-embedded-ManagedGroup", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{}, + }, + chgFn: makeEmbeddedNil(), + masks: []string{NameField, DescriptionField}, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: missing embedded ManagedGroup: parameter violation: error #100", + }, + { + name: "no-scope-id", + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "no-scope-id-test-name-repo", + }, + }, + chgFn: changeName("no-scope-id-test-update-name-repo"), + masks: []string{NameField}, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: missing scope id: parameter violation: error #100", + }, + { + name: "missing-version", + scopeId: org.GetPublicId(), + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "missing-version-test-name-repo", + }, + }, + chgFn: changeName("test-update-name-repo"), + masks: []string{NameField}, + wantIsErr: errors.InvalidParameter, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: missing version: parameter violation: error #100", + }, + { + name: "no-public-id", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{}, + }, + chgFn: deletePublicId(), + masks: []string{NameField, DescriptionField}, + wantIsErr: errors.InvalidPublicId, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: missing public id: parameter violation: error #102", + }, + { + name: "updating-non-existent-ManagedGroup", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "updating-non-existent-ManagedGroup-test-name-repo", + }, + }, + chgFn: combine(nonExistentPublicId(), changeName("updating-non-existent-ManagedGroup-test-update-name-repo")), + masks: []string{NameField}, + wantIsErr: errors.RecordNotFound, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: abcd_OOOOOOOOOO: db.DoTx: oidc.(Repository).UpdateManagedGroup: db.Update: db.lookupAfterWrite: db.LookupById: record not found, search issue: error #1100", + }, + { + name: "empty-field-mask", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "empty-field-mask-test-name-repo", + }, + }, + chgFn: changeName("empty-field-mask-test-update-name-repo"), + wantIsErr: errors.EmptyFieldMask, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: missing field mask: parameter violation: error #104", + }, + { + name: "read-only-fields-in-field-mask", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "read-only-fields-in-field-mask-test-name-repo", + }, + }, + chgFn: changeName("read-only-fields-in-field-mask-test-update-name-repo"), + masks: []string{"PublicId", "CreateTime", "UpdateTime", "AuthMethodId"}, + wantIsErr: errors.InvalidFieldMask, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: PublicId: parameter violation: error #103", + }, + { + name: "unknown-field-in-field-mask", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "unknown-field-in-field-mask-test-name-repo", + }, + }, + chgFn: changeName("unknown-field-in-field-mask-test-update-name-repo"), + masks: []string{"Bilbo"}, + wantIsErr: errors.InvalidFieldMask, + wantErrMsg: "oidc.(Repository).UpdateManagedGroup: Bilbo: parameter violation: error #103", + }, + { + name: "change-name", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "change-name-test-name-repo", + }, + }, + chgFn: changeName("change-name-test-update-name-repo"), + masks: []string{NameField}, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "change-name-test-update-name-repo", + }, + }, + wantCount: 1, + }, + { + name: "change-description", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Description: "test-description-repo", + }, + }, + chgFn: changeDescription("test-update-description-repo"), + masks: []string{DescriptionField}, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Description: "test-update-description-repo", + }, + }, + wantCount: 1, + }, + { + name: "change-filter", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Filter: TestFakeManagedGroupFilter, + }, + }, + chgFn: changeFilter(`"/zip" == "zap"`), + masks: []string{FilterField}, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Filter: `"/zip" == "zap"`, + }, + }, + wantCount: 1, + }, + { + name: "change-name-and-description", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "change-name-and-description-test-name-repo", + Description: "test-description-repo", + }, + }, + chgFn: combine(changeDescription("test-update-description-repo"), changeName("change-name-and-description-test-update-name-repo")), + masks: []string{NameField, DescriptionField}, + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "change-name-and-description-test-update-name-repo", + Description: "test-update-description-repo", + }, + }, + wantCount: 1, + }, + { + name: "delete-name", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "delete-name-test-name-repo", + Description: "test-description-repo", + }, + }, + masks: []string{NameField}, + chgFn: combine(changeDescription("test-update-description-repo"), changeName("")), + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Description: "test-description-repo", + }, + }, + wantCount: 1, + }, + { + name: "delete-description", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "delete-description-test-name-repo", + Description: "test-description-repo", + }, + }, + masks: []string{DescriptionField}, + chgFn: combine(changeDescription(""), changeName("test-update-name-repo")), + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "delete-description-test-name-repo", + }, + }, + wantCount: 1, + }, + { + name: "delete-filter", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Filter: TestFakeManagedGroupFilter, + }, + }, + masks: []string{FilterField}, + chgFn: combine(changeFilter("")), + wantIsErr: errors.NotNull, + wantErrContains: "oidc.(Repository).UpdateManagedGroup: db.Update: filter must not be empty: not null constraint violated: integrity violation: error #1001", + }, + { + name: "do-not-delete-name", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "do-not-delete-name-test-name-repo", + Description: "test-description-repo", + }, + }, + masks: []string{DescriptionField}, + chgFn: combine(changeDescription("test-update-description-repo"), changeName("")), + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "do-not-delete-name-test-name-repo", + Description: "test-update-description-repo", + }, + }, + wantCount: 1, + }, + { + name: "do-not-delete-description", + scopeId: org.GetPublicId(), + version: 1, + orig: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "do-not-delete-description-test-name-repo", + Description: "test-description-repo", + }, + }, + masks: []string{NameField}, + chgFn: combine(changeDescription(""), changeName("do-not-delete-description-test-update-name-repo")), + want: &ManagedGroup{ + ManagedGroup: &store.ManagedGroup{ + Name: "do-not-delete-description-test-update-name-repo", + Description: "test-description-repo", + }, + }, + wantCount: 1, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + repo, err := NewRepository(rw, rw, kmsCache) + assert.NoError(err) + require.NotNil(repo) + + orig := TestManagedGroup(t, conn, am, TestFakeManagedGroupFilter, WithName(tt.orig.GetName()), WithDescription(tt.orig.GetDescription())) + + tt.orig.AuthMethodId = am.PublicId + if tt.chgFn != nil { + orig = tt.chgFn(orig) + } + got, gotCount, err := repo.UpdateManagedGroup(context.Background(), tt.scopeId, orig, tt.version, tt.masks) + if tt.wantIsErr != 0 { + assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "want err: %q got: %q", tt.wantIsErr, err) + if tt.wantErrContains != "" { + assert.True(strings.Contains(err.Error(), tt.wantErrContains)) + } else { + assert.Equal(tt.wantErrMsg, err.Error()) + } + assert.Equal(tt.wantCount, gotCount, "row count") + assert.Nil(got) + return + } + assert.NoError(err) + assert.Empty(tt.orig.PublicId) + if tt.wantCount == 0 { + assert.Equal(tt.wantCount, gotCount, "row count") + assert.Nil(got) + return + } + require.NotNil(got) + assertPublicId(t, intglobals.OidcManagedGroupPrefix, got.PublicId) + assert.Equal(tt.wantCount, gotCount, "row count") + assert.NotSame(tt.orig, got) + assert.Equal(tt.orig.AuthMethodId, got.AuthMethodId) + dbassert := dbassert.New(t, conn.DB()) + if tt.want.Name == "" { + dbassert.IsNull(got, "name") + return + } + assert.Equal(tt.want.Name, got.Name) + if tt.want.Description == "" { + dbassert.IsNull(got, "description") + return + } + assert.Equal(tt.want.Description, got.Description) + if tt.wantCount > 0 { + assert.NoError(db.TestVerifyOplog(t, rw, got.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second))) + } + }) + } +} diff --git a/internal/auth/oidc/service_callback.go b/internal/auth/oidc/service_callback.go index 074c3bf3c..9762d58ea 100644 --- a/internal/auth/oidc/service_callback.go +++ b/internal/auth/oidc/service_callback.go @@ -11,6 +11,8 @@ import ( "github.com/hashicorp/boundary/internal/authtoken" "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/cap/oidc" + "github.com/hashicorp/go-bexpr" + "github.com/mitchellh/pointerstructure" ) // Callback is an oidc domain service function for processing a successful OIDC @@ -185,6 +187,40 @@ func Callback( return "", errors.Wrap(err, op) } + // Get the set of all managed groups so we can filter + mgs, err := r.ListManagedGroups(ctx, am.GetPublicId()) + if err != nil { + return "", errors.Wrap(err, op) + } + if len(mgs) > 0 { + matchedMgs := make([]*ManagedGroup, 0, len(mgs)) + evalData := map[string]interface{}{ + "token": idTkClaims, + "userinfo": userInfoClaims, + } + // Iterate through and check claims against filters + for _, mg := range mgs { + eval, err := bexpr.CreateEvaluator(mg.Filter) + if err != nil { + // We check all filters on ingress so this should never happen, + // but we validate anyways + return "", errors.Wrap(err, op) + } + match, err := eval.Evaluate(evalData) + if err != nil && !errors.Is(err, pointerstructure.ErrNotFound) { + return "", errors.Wrap(err, op) + } + if match { + matchedMgs = append(matchedMgs, mg) + } + } + // We always pass it in, even if none match, because in that case we + // need to remove any mappings that exist + if _, _, err := r.SetManagedGroupMemberships(ctx, am, acct, matchedMgs); err != nil { + return "", errors.Wrap(err, op) + } + } + // before searching for the iam.User associated with the account, // we need to see if this particular auth method is allowed to // autovivify users for the scope. @@ -203,6 +239,8 @@ func Callback( return "", errors.Wrap(err, op) } + // Now we need to check filters and assign managed groups by filter. + // wow, we're getting close. we just need to create a pending token for this // successful authentication process, so it can be retrieved by the polling client // that initialed the authentication attempt. diff --git a/internal/auth/oidc/service_callback_test.go b/internal/auth/oidc/service_callback_test.go index 4b44af4fa..8be589e1b 100644 --- a/internal/auth/oidc/service_callback_test.go +++ b/internal/auth/oidc/service_callback_test.go @@ -17,6 +17,7 @@ import ( "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" iamStore "github.com/hashicorp/boundary/internal/iam/store" + "github.com/hashicorp/boundary/sdk/strutil" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -595,3 +596,198 @@ func Test_StartAuth_to_Callback(t *testing.T) { assert.Equal(tk.Status, string(authtoken.PendingStatus)) }) } + +func Test_ManagedGroupFiltering(t *testing.T) { + // DO NOT run these tests under t.Parallel() + + // A note about this test: other tests handle checking managed group + // membership, creation, etc. This test is only scoped to checking that + // given reasonable data in the jwt/userinfo, the result of a callback call + // results in association with the proper managed groups. + + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + rootWrapper := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, rootWrapper) + + // some standard factories for unit tests which + // are used in the Callback(...) call + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + repoFn := func() (*Repository, error) { + return NewRepository(rw, rw, kmsCache) + } + atRepoFn := func() (*authtoken.Repository, error) { + return authtoken.NewRepository(rw, rw, kmsCache) + } + + iamRepo := iam.TestRepo(t, conn, rootWrapper) + org, _ := iam.TestScopes(t, iamRepo) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + // a very simple test mock controller, that simply responds with a 200 OK to + // every request. + testController := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.WriteHeader(200) + })) + defer testController.Close() + + // test provider for the tests (see the oidc package docs for more info) + // it will provide discovery, JWKs, a token endpoint, etc for these tests. + tp := oidc.StartTestProvider(t) + tpCert, err := ParseCertificates(tp.CACert()) + require.NoError(t, err) + _, _, tpAlg, _ := tp.SigningKeys() + + // a reusable test authmethod for the unit tests + testAuthMethod := TestAuthMethod(t, conn, databaseWrapper, org.PublicId, ActivePublicState, + "alice-rp", "fido", + WithCertificates(tpCert...), + WithSigningAlgs(Alg(tpAlg)), + WithIssuer(TestConvertToUrls(t, tp.Addr())[0]), + WithApiUrl(TestConvertToUrls(t, testController.URL)[0])) + + // set this as the primary so users will be created on first login + iam.TestSetPrimaryAuthMethod(t, iamRepo, org, testAuthMethod.PublicId) + + // Create an account so it's a known account id + sub := "alice@example.com" + account := TestAccount(t, conn, testAuthMethod, sub) + + // Create two managed groups. We'll use these in tests to set filters and + // then check that the user belongs to the ones we expect. + mgs := []*ManagedGroup{ + TestManagedGroup(t, conn, testAuthMethod, TestFakeManagedGroupFilter), + TestManagedGroup(t, conn, testAuthMethod, TestFakeManagedGroupFilter), + } + + // A reusable oidc.Provider for the tests + testProvider, err := convertToProvider(ctx, testAuthMethod) + require.NoError(t, err) + testConfigHash, err := testProvider.ConfigHash() + require.NoError(t, err) + + // Set up the provider a bit + testNonce := "nonce" + tp.SetExpectedAuthNonce(testNonce) + code := "simple" + tp.SetExpectedAuthCode(code) + tp.SetExpectedSubject(sub) + tp.SetCustomAudience("foo", "alice-rp") + info := map[string]interface{}{ + "roles": []string{"user", "operator"}, + "sub": "alice@example.com", + "email": "alice-alias@example.com", + "name": "alice doe joe foe", + } + tp.SetUserInfoReply(info) + + repo, err := repoFn() + require.NoError(t, err) + + tests := []struct { + name string + filters []string // Should always be length 2, and specify the filters to use for the test + matchingMgs []*ManagedGroup // The public IDs of the managed groups we expect the user to be in + }{ + { + name: "no match", + filters: []string{ + TestFakeManagedGroupFilter, + TestFakeManagedGroupFilter, + }, + }, + { + name: "token match", + filters: []string{ + `"/token/nonce" == "nonce"`, + TestFakeManagedGroupFilter, + }, + matchingMgs: mgs[0:1], + }, + { + name: "token double match", + filters: []string{ + `"/token/nonce" == "nonce"`, + `"/token/name" == "Alice Doe Smith"`, + }, + matchingMgs: mgs[0:2], + }, + { + name: "userinfo double match", + filters: []string{ + `"user" in "/userinfo/roles"`, + `"/userinfo/email" == "alice-alias@example.com"`, + }, + matchingMgs: mgs[0:2], + }, + { + name: "userinfo match only", + filters: []string{ + `"/token/nonce" == "not-nonce"`, + `"/userinfo/email" == "alice-alias@example.com"`, + }, + matchingMgs: mgs[1:2], + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // A unique token ID for each test + testTokenRequestId, err := authtoken.NewAuthTokenId() + require.NoError(err) + + // the test provider is stateful, so we need to configure + // it for this unit test. + tp.SetClientCreds(testAuthMethod.ClientId, testAuthMethod.ClientSecret) + tpAllowedRedirect := fmt.Sprintf(CallbackEndpoint, testAuthMethod.ApiUrl) + tp.SetAllowedRedirectURIs([]string{tpAllowedRedirect}) + + state := testState(t, testAuthMethod, kmsCache, testTokenRequestId, 2000*time.Second, "https://testcontroler.com/hi-alice", testConfigHash, testNonce) + tp.SetExpectedState(state) + + // Set the filters on the MGs for this test. First we need to get the current versions. + currMgs, err := repo.ListManagedGroups(ctx, testAuthMethod.PublicId) + require.NoError(err) + require.Len(currMgs, 2) + currVersionMap := map[string]uint32{ + currMgs[0].PublicId: currMgs[0].Version, + currMgs[1].PublicId: currMgs[1].Version, + } + for i, filter := range tt.filters { + mgs[i].Filter = filter + _, numUpdated, err := repo.UpdateManagedGroup(ctx, org.PublicId, mgs[i], currVersionMap[mgs[i].PublicId], []string{"Filter"}) + require.Equal(numUpdated, 1) + require.NoError(err) + } + + // Run the callback + _, err = Callback(ctx, + repoFn, + iamRepoFn, + atRepoFn, + testAuthMethod, + state, + code, + ) + require.NoError(err) + + // Ensure that we get the expected groups + memberships, err := repo.ListManagedGroupMembershipsByMember(ctx, account.PublicId) + require.NoError(err) + assert.Equal(len(tt.matchingMgs), len(memberships)) + var matchingIds []string + for _, mg := range tt.matchingMgs { + matchingIds = append(matchingIds, mg.PublicId) + } + for _, mg := range memberships { + assert.True(strutil.StrListContains(matchingIds, mg.ManagedGroupId)) + } + }) + } +} diff --git a/internal/auth/oidc/store/oidc.pb.go b/internal/auth/oidc/store/oidc.pb.go index 1fc6ccee4..2e98b80bf 100644 --- a/internal/auth/oidc/store/oidc.pb.go +++ b/internal/auth/oidc/store/oidc.pb.go @@ -828,6 +828,196 @@ func (x *AccountClaimMap) GetCreateTime() *timestamp.Timestamp { return nil } +// ManagedGroup entries provide an OIDC auth method implementation of managed +// groups. +type ManagedGroup struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // @inject_tag: `gorm:"primary_key"` + PublicId string `protobuf:"bytes,10,opt,name=public_id,json=publicId,proto3" json:"public_id,omitempty" gorm:"primary_key"` + // The create_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + CreateTime *timestamp.Timestamp `protobuf:"bytes,20,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"` + // The update_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + UpdateTime *timestamp.Timestamp `protobuf:"bytes,30,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty" gorm:"default:current_timestamp"` + // name is optional. If set, it must be unique within auth_method_id. + // @inject_tag: `gorm:"default:null"` + Name string `protobuf:"bytes,40,opt,name=name,proto3" json:"name,omitempty" gorm:"default:null"` + // description is optional. + // @inject_tag: `gorm:"default:null"` + Description string `protobuf:"bytes,50,opt,name=description,proto3" json:"description,omitempty" gorm:"default:null"` + // @inject_tag: `gorm:"default:null"` + Version uint32 `protobuf:"varint,60,opt,name=version,proto3" json:"version,omitempty" gorm:"default:null"` + // auth_method_id is the fk to the account's auth method. + // @inject_tag: `gorm:"not_null"` + AuthMethodId string `protobuf:"bytes,70,opt,name=auth_method_id,json=authMethodId,proto3" json:"auth_method_id,omitempty" gorm:"not_null"` + // filter is a go-bexpr filter + // @inject_tag: `gorm:"not_null"` + Filter string `protobuf:"bytes,80,opt,name=filter,proto3" json:"filter,omitempty" gorm:"not_null"` +} + +func (x *ManagedGroup) Reset() { + *x = ManagedGroup{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ManagedGroup) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ManagedGroup) ProtoMessage() {} + +func (x *ManagedGroup) ProtoReflect() protoreflect.Message { + mi := &file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ManagedGroup.ProtoReflect.Descriptor instead. +func (*ManagedGroup) Descriptor() ([]byte, []int) { + return file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDescGZIP(), []int{7} +} + +func (x *ManagedGroup) GetPublicId() string { + if x != nil { + return x.PublicId + } + return "" +} + +func (x *ManagedGroup) GetCreateTime() *timestamp.Timestamp { + if x != nil { + return x.CreateTime + } + return nil +} + +func (x *ManagedGroup) GetUpdateTime() *timestamp.Timestamp { + if x != nil { + return x.UpdateTime + } + return nil +} + +func (x *ManagedGroup) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *ManagedGroup) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *ManagedGroup) GetVersion() uint32 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *ManagedGroup) GetAuthMethodId() string { + if x != nil { + return x.AuthMethodId + } + return "" +} + +func (x *ManagedGroup) GetFilter() string { + if x != nil { + return x.Filter + } + return "" +} + +// ManagedGroupMemberAccount contains a mapping between a managed group and a +// member account. +type ManagedGroupMemberAccount struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The create_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + CreateTime *timestamp.Timestamp `protobuf:"bytes,10,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"` + // managed_group_id is the fk to the oidc managed group public id + // @inject_tag: `gorm:"primary_key"` + ManagedGroupId string `protobuf:"bytes,20,opt,name=managed_group_id,json=managedGroupId,proto3" json:"managed_group_id,omitempty" gorm:"primary_key"` + // member_id is the fk to the oidc account public id + // @inject_tag: `gorm:"primary_key"` + MemberId string `protobuf:"bytes,30,opt,name=member_id,json=memberId,proto3" json:"member_id,omitempty" gorm:"primary_key"` +} + +func (x *ManagedGroupMemberAccount) Reset() { + *x = ManagedGroupMemberAccount{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ManagedGroupMemberAccount) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ManagedGroupMemberAccount) ProtoMessage() {} + +func (x *ManagedGroupMemberAccount) ProtoReflect() protoreflect.Message { + mi := &file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ManagedGroupMemberAccount.ProtoReflect.Descriptor instead. +func (*ManagedGroupMemberAccount) Descriptor() ([]byte, []int) { + return file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDescGZIP(), []int{8} +} + +func (x *ManagedGroupMemberAccount) GetCreateTime() *timestamp.Timestamp { + if x != nil { + return x.CreateTime + } + return nil +} + +func (x *ManagedGroupMemberAccount) GetManagedGroupId() string { + if x != nil { + return x.ManagedGroupId + } + return "" +} + +func (x *ManagedGroupMemberAccount) GetMemberId() string { + if x != nil { + return x.MemberId + } + return "" +} + var File_controller_storage_auth_oidc_store_v1_oidc_proto protoreflect.FileDescriptor var file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDesc = []byte{ @@ -1009,11 +1199,49 @@ var file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDesc = []byte{ 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, - 0x69, 0x6d, 0x65, 0x42, 0x3e, 0x5a, 0x3c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, - 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, - 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x61, 0x75, - 0x74, 0x68, 0x2f, 0x6f, 0x69, 0x64, 0x63, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, 0x74, - 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x69, 0x6d, 0x65, 0x22, 0xa6, 0x03, 0x0a, 0x0c, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, + 0x72, 0x6f, 0x75, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x69, + 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x49, + 0x64, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, + 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, + 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x4b, + 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x1e, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, + 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, + 0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, + 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x24, 0x0a, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x28, 0x20, 0x01, 0x28, 0x09, 0x42, 0x10, 0xc2, 0xdd, 0x29, 0x0c, 0x0a, + 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x40, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x18, 0x32, 0x20, 0x01, 0x28, 0x09, 0x42, 0x1e, 0xc2, 0xdd, 0x29, 0x1a, 0x0a, 0x0b, 0x44, 0x65, + 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x3c, + 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x24, 0x0a, + 0x0e, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x69, 0x64, 0x18, + 0x46, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x61, 0x75, 0x74, 0x68, 0x4d, 0x65, 0x74, 0x68, 0x6f, + 0x64, 0x49, 0x64, 0x12, 0x37, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x50, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x1f, 0xc2, 0xdd, 0x29, 0x1b, 0x0a, 0x06, 0x46, 0x69, 0x6c, 0x74, 0x65, + 0x72, 0x12, 0x11, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x2e, 0x66, 0x69, + 0x6c, 0x74, 0x65, 0x72, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x22, 0xaf, 0x01, 0x0a, + 0x19, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x4d, 0x65, 0x6d, + 0x62, 0x65, 0x72, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, + 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, + 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x10, 0x6d, 0x61, 0x6e, 0x61, 0x67, + 0x65, 0x64, 0x5f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x69, 0x64, 0x18, 0x14, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x0e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x49, + 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x1e, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x49, 0x64, 0x42, 0x3e, + 0x5a, 0x3c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, + 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, + 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x6f, 0x69, + 0x64, 0x63, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1028,32 +1256,37 @@ func file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDescGZIP() []byte return file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDescData } -var file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes = make([]protoimpl.MessageInfo, 7) +var file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes = make([]protoimpl.MessageInfo, 9) var file_controller_storage_auth_oidc_store_v1_oidc_proto_goTypes = []interface{}{ - (*AuthMethod)(nil), // 0: controller.storage.auth.oidc.store.v1.AuthMethod - (*Account)(nil), // 1: controller.storage.auth.oidc.store.v1.Account - (*SigningAlg)(nil), // 2: controller.storage.auth.oidc.store.v1.SigningAlg - (*AudClaim)(nil), // 3: controller.storage.auth.oidc.store.v1.AudClaim - (*Certificate)(nil), // 4: controller.storage.auth.oidc.store.v1.Certificate - (*ClaimsScope)(nil), // 5: controller.storage.auth.oidc.store.v1.ClaimsScope - (*AccountClaimMap)(nil), // 6: controller.storage.auth.oidc.store.v1.AccountClaimMap - (*timestamp.Timestamp)(nil), // 7: controller.storage.timestamp.v1.Timestamp + (*AuthMethod)(nil), // 0: controller.storage.auth.oidc.store.v1.AuthMethod + (*Account)(nil), // 1: controller.storage.auth.oidc.store.v1.Account + (*SigningAlg)(nil), // 2: controller.storage.auth.oidc.store.v1.SigningAlg + (*AudClaim)(nil), // 3: controller.storage.auth.oidc.store.v1.AudClaim + (*Certificate)(nil), // 4: controller.storage.auth.oidc.store.v1.Certificate + (*ClaimsScope)(nil), // 5: controller.storage.auth.oidc.store.v1.ClaimsScope + (*AccountClaimMap)(nil), // 6: controller.storage.auth.oidc.store.v1.AccountClaimMap + (*ManagedGroup)(nil), // 7: controller.storage.auth.oidc.store.v1.ManagedGroup + (*ManagedGroupMemberAccount)(nil), // 8: controller.storage.auth.oidc.store.v1.ManagedGroupMemberAccount + (*timestamp.Timestamp)(nil), // 9: controller.storage.timestamp.v1.Timestamp } var file_controller_storage_auth_oidc_store_v1_oidc_proto_depIdxs = []int32{ - 7, // 0: controller.storage.auth.oidc.store.v1.AuthMethod.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 1: controller.storage.auth.oidc.store.v1.AuthMethod.update_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 2: controller.storage.auth.oidc.store.v1.Account.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 3: controller.storage.auth.oidc.store.v1.Account.update_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 4: controller.storage.auth.oidc.store.v1.SigningAlg.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 5: controller.storage.auth.oidc.store.v1.AudClaim.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 6: controller.storage.auth.oidc.store.v1.Certificate.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 7: controller.storage.auth.oidc.store.v1.ClaimsScope.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 7, // 8: controller.storage.auth.oidc.store.v1.AccountClaimMap.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 9, // [9:9] is the sub-list for method output_type - 9, // [9:9] is the sub-list for method input_type - 9, // [9:9] is the sub-list for extension type_name - 9, // [9:9] is the sub-list for extension extendee - 0, // [0:9] is the sub-list for field type_name + 9, // 0: controller.storage.auth.oidc.store.v1.AuthMethod.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 1: controller.storage.auth.oidc.store.v1.AuthMethod.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 2: controller.storage.auth.oidc.store.v1.Account.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 3: controller.storage.auth.oidc.store.v1.Account.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 4: controller.storage.auth.oidc.store.v1.SigningAlg.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 5: controller.storage.auth.oidc.store.v1.AudClaim.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 6: controller.storage.auth.oidc.store.v1.Certificate.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 7: controller.storage.auth.oidc.store.v1.ClaimsScope.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 8: controller.storage.auth.oidc.store.v1.AccountClaimMap.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 9: controller.storage.auth.oidc.store.v1.ManagedGroup.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 10: controller.storage.auth.oidc.store.v1.ManagedGroup.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 9, // 11: controller.storage.auth.oidc.store.v1.ManagedGroupMemberAccount.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 12, // [12:12] is the sub-list for method output_type + 12, // [12:12] is the sub-list for method input_type + 12, // [12:12] is the sub-list for extension type_name + 12, // [12:12] is the sub-list for extension extendee + 0, // [0:12] is the sub-list for field type_name } func init() { file_controller_storage_auth_oidc_store_v1_oidc_proto_init() } @@ -1146,6 +1379,30 @@ func file_controller_storage_auth_oidc_store_v1_oidc_proto_init() { return nil } } + file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ManagedGroup); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_storage_auth_oidc_store_v1_oidc_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ManagedGroupMemberAccount); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } } type x struct{} out := protoimpl.TypeBuilder{ @@ -1153,7 +1410,7 @@ func file_controller_storage_auth_oidc_store_v1_oidc_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_controller_storage_auth_oidc_store_v1_oidc_proto_rawDesc, NumEnums: 0, - NumMessages: 7, + NumMessages: 9, NumExtensions: 0, NumServices: 0, }, diff --git a/internal/auth/oidc/testing.go b/internal/auth/oidc/testing.go index 62622083a..8bf403409 100644 --- a/internal/auth/oidc/testing.go +++ b/internal/auth/oidc/testing.go @@ -34,6 +34,8 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) +const TestFakeManagedGroupFilter = `"/foo" == "bar"` + // TestAuthMethod creates a test oidc auth method. WithName, WithDescription, // WithMaxAge, WithApiUrl, WithIssuer, WithCertificates, WithAudClaims, and // WithSigningAlgs options are supported. @@ -176,6 +178,38 @@ func TestAccount(t *testing.T, conn *gorm.DB, am *AuthMethod, subject string, op return a } +// TestManagedGroup creates a test oidc managed group. +func TestManagedGroup(t *testing.T, conn *gorm.DB, am *AuthMethod, filter string, opt ...Option) *ManagedGroup { + t.Helper() + require := require.New(t) + rw := db.New(conn) + ctx := context.Background() + + mg, err := NewManagedGroup(am.PublicId, filter, opt...) + require.NoError(err) + + id, err := newManagedGroupId() + require.NoError(err) + mg.PublicId = id + + require.NoError(rw.Create(ctx, mg)) + return mg +} + +// TestManagedGroupMember adds given account IDs to a managed group +func TestManagedGroupMember(t *testing.T, conn *gorm.DB, managedGroupId, memberId string, opt ...Option) *ManagedGroupMemberAccount { + t.Helper() + require := require.New(t) + rw := db.New(conn) + ctx := context.Background() + + mg, err := NewManagedGroupMemberAccount(managedGroupId, memberId, opt...) + require.NoError(err) + + require.NoError(rw.Create(ctx, mg)) + return mg +} + // TestConvertToUrls will convert URL string representations to a slice of // *url.URL func TestConvertToUrls(t *testing.T, urls ...string) []*url.URL { diff --git a/internal/auth/password/public_ids.go b/internal/auth/password/public_ids.go index d91d265d2..2f919fa8d 100644 --- a/internal/auth/password/public_ids.go +++ b/internal/auth/password/public_ids.go @@ -3,12 +3,12 @@ package password import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/intglobals" ) // PublicId prefixes for the resources in the password package. const ( AuthMethodPrefix = "ampw" - AccountPrefix = "apw" ) func newAuthMethodId() (string, error) { @@ -22,7 +22,7 @@ func newAuthMethodId() (string, error) { func newAccountId() (string, error) { const op = "password.newAccountId" - id, err := db.NewPublicId(AccountPrefix) + id, err := db.NewPublicId(intglobals.NewPasswordAccountPrefix) if err != nil { return "", errors.Wrap(err, op) } diff --git a/internal/auth/password/public_ids_test.go b/internal/auth/password/public_ids_test.go index a7d8e8872..0bd6b503e 100644 --- a/internal/auth/password/public_ids_test.go +++ b/internal/auth/password/public_ids_test.go @@ -4,6 +4,7 @@ import ( "strings" "testing" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -17,6 +18,6 @@ func Test_PublicIds(t *testing.T) { t.Run("account", func(t *testing.T) { id, err := newAccountId() require.NoError(t, err) - assert.True(t, strings.HasPrefix(id, AccountPrefix+"_")) + assert.True(t, strings.HasPrefix(id, intglobals.NewPasswordAccountPrefix+"_")) }) } diff --git a/internal/auth/password/repository_account.go b/internal/auth/password/repository_account.go index 4c1a70936..d2a71bcb7 100644 --- a/internal/auth/password/repository_account.go +++ b/internal/auth/password/repository_account.go @@ -9,19 +9,21 @@ import ( "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) // CreateAccount inserts a into the repository and returns a new Account -// containing the account's PublicId. a is not changed. a must contain a -// valid AuthMethodId. a must not contain a PublicId. The PublicId is -// generated and assigned by this method. +// containing the account's PublicId. a is not changed. a must contain a valid +// AuthMethodId. a must not contain a PublicId. The PublicId is generated and +// assigned by this method. // // a must contain a valid LoginName. a.LoginName must be unique within // a.AuthMethodId. // -// WithPassword is the only valid option. All other options are ignored. +// WithPassword and WithPublicId are the only valid options. All other options +// are ignored. // // Both a.Name and a.Description are optional. If a.Name is set, it must be // unique within a.AuthMethodId. @@ -55,21 +57,28 @@ func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Accou return nil, errors.New(errors.TooShort, op, fmt.Sprintf("username: %s, must be longer than %d", a.LoginName, cc.MinLoginNameLength)) } - a = a.clone() - id, err := newAccountId() - if err != nil { - return nil, errors.Wrap(err, op) - } - a.PublicId = id - opts := getOpts(opt...) + a = a.clone() + if opts.withPublicId != "" { + if !strings.HasPrefix(opts.withPublicId, intglobals.NewPasswordAccountPrefix+"_") { + return nil, errors.New(errors.InvalidParameter, op, "chosen account id does not have a valid prefix") + } + a.PublicId = opts.withPublicId + } else { + id, err := newAccountId() + if err != nil { + return nil, errors.Wrap(err, op) + } + a.PublicId = id + } + var cred *Argon2Credential if opts.withPassword { if cc.MinPasswordLength > len(opts.password) { return nil, errors.New(errors.PasswordTooShort, op, fmt.Sprintf("must be longer than %v", cc.MinPasswordLength)) } - if cred, err = newArgon2Credential(id, opts.password, cc.argon2()); err != nil { + if cred, err = newArgon2Credential(a.PublicId, opts.password, cc.argon2()); err != nil { return nil, errors.Wrap(err, op) } } diff --git a/internal/auth/password/repository_account_test.go b/internal/auth/password/repository_account_test.go index 27eed3183..0040cd720 100644 --- a/internal/auth/password/repository_account_test.go +++ b/internal/auth/password/repository_account_test.go @@ -10,6 +10,7 @@ import ( dbassert "github.com/hashicorp/boundary/internal/db/assert" "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" "github.com/stretchr/testify/assert" @@ -242,7 +243,7 @@ func TestRepository_CreateAccount(t *testing.T) { require.NoError(err) assert.Empty(tt.in.PublicId) require.NotNil(got) - assertPublicId(t, AccountPrefix, got.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got.PublicId) assert.NotSame(tt.in, got) assert.Equal(tt.want.Name, got.Name) assert.Equal(tt.want.Description, got.Description) @@ -289,7 +290,7 @@ func TestRepository_CreateAccount_DuplicateNames(t *testing.T) { got, err := repo.CreateAccount(context.Background(), org.GetPublicId(), in) require.NoError(err) require.NotNil(got) - assertPublicId(t, AccountPrefix, got.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got.PublicId) assert.NotSame(in, got) assert.Equal(in.Name, got.Name) assert.Equal(in.Description, got.Description) @@ -321,7 +322,7 @@ func TestRepository_CreateAccount_DuplicateNames(t *testing.T) { got, err := repo.CreateAccount(context.Background(), org.GetPublicId(), in) require.NoError(err) require.NotNil(got) - assertPublicId(t, AccountPrefix, got.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got.PublicId) assert.NotSame(in, got) assert.Equal(in.Name, got.Name) assert.Equal(in.Description, got.Description) @@ -331,7 +332,7 @@ func TestRepository_CreateAccount_DuplicateNames(t *testing.T) { got2, err := repo.CreateAccount(context.Background(), org.GetPublicId(), in2) assert.NoError(err) require.NotNil(got2) - assertPublicId(t, AccountPrefix, got2.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got2.PublicId) assert.NotSame(in2, got2) assert.Equal(in2.Name, got2.Name) assert.Equal(in2.Description, got2.Description) @@ -944,7 +945,7 @@ func TestRepository_UpdateAccount(t *testing.T) { return } require.NotNil(got) - assertPublicId(t, AccountPrefix, got.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got.PublicId) assert.Equal(tt.wantCount, gotCount, "row count") assert.NotSame(tt.orig, got) assert.Equal(tt.orig.AuthMethodId, got.AuthMethodId) @@ -1029,7 +1030,7 @@ func TestRepository_UpdateAccount_DupeNames(t *testing.T) { got, err := repo.CreateAccount(context.Background(), org.GetPublicId(), in) assert.NoError(err) require.NotNil(got) - assertPublicId(t, AccountPrefix, got.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got.PublicId) assert.NotSame(in, got) assert.Equal(in.Name, got.Name) assert.Equal(in.Description, got.Description) @@ -1106,7 +1107,7 @@ func TestRepository_UpdateAccount_DupeNames(t *testing.T) { got, err := repo.CreateAccount(context.Background(), org.GetPublicId(), in) assert.NoError(err) require.NotNil(got) - assertPublicId(t, AccountPrefix, got.PublicId) + assertPublicId(t, intglobals.NewPasswordAccountPrefix, got.PublicId) assert.NotSame(in, got) assert.Equal(in.LoginName, got.LoginName) diff --git a/internal/auth/subtype.go b/internal/auth/subtype.go index 927ae2d96..a0c054b24 100644 --- a/internal/auth/subtype.go +++ b/internal/auth/subtype.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/oidc" "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/intglobals" ) type Subtype int @@ -58,6 +59,18 @@ var ( _ Account = (*password.Account)(nil) ) +type ManagedGroup interface { + GetPublicId() string + GetCreateTime() *timestamp.Timestamp + GetUpdateTime() *timestamp.Timestamp + GetName() string + GetDescription() string + GetAuthMethodId() string + GetVersion() uint32 +} + +var _ ManagedGroup = (*oidc.ManagedGroup)(nil) + // SubtypeFromType converts a string to a Subtype. // returns UnknownSubtype if no Subtype with that name is found. func SubtypeFromType(t string) Subtype { @@ -76,10 +89,12 @@ func SubtypeFromType(t string) Subtype { func SubtypeFromId(id string) Subtype { switch { case strings.HasPrefix(strings.TrimSpace(id), password.AuthMethodPrefix), - strings.HasPrefix(strings.TrimSpace(id), password.AccountPrefix): + strings.HasPrefix(strings.TrimSpace(id), intglobals.OldPasswordAccountPrefix), + strings.HasPrefix(strings.TrimSpace(id), intglobals.NewPasswordAccountPrefix): return PasswordSubtype case strings.HasPrefix(strings.TrimSpace(id), oidc.AuthMethodPrefix), - strings.HasPrefix(strings.TrimSpace(id), oidc.AccountPrefix): + strings.HasPrefix(strings.TrimSpace(id), oidc.AccountPrefix), + strings.HasPrefix(strings.TrimSpace(id), intglobals.OidcManagedGroupPrefix): return OidcSubtype } return UnknownSubtype diff --git a/internal/auth/subtype_test.go b/internal/auth/subtype_test.go index 8ab6efdd2..63d58c3cb 100644 --- a/internal/auth/subtype_test.go +++ b/internal/auth/subtype_test.go @@ -5,6 +5,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/oidc" "github.com/hashicorp/boundary/internal/auth/password" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -30,7 +31,13 @@ func TestSubtype(t *testing.T) { }, { subtype: PasswordSubtype, - id: password.AccountPrefix + "1234567890", + id: intglobals.OldPasswordAccountPrefix + "1234567890", + wantString: "password", + wantSubtype: PasswordSubtype, + }, + { + subtype: PasswordSubtype, + id: intglobals.NewPasswordAccountPrefix + "1234567890", wantString: "password", wantSubtype: PasswordSubtype, }, diff --git a/internal/cmd/base/dev.go b/internal/cmd/base/dev.go new file mode 100644 index 000000000..4059eb934 --- /dev/null +++ b/internal/cmd/base/dev.go @@ -0,0 +1,441 @@ +package base + +import ( + "context" + "crypto/ed25519" + "fmt" + "net" + "net/url" + "strings" + + "github.com/hashicorp/boundary/internal/auth/oidc" + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/db/schema" + "github.com/hashicorp/boundary/internal/docker" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/types/scope" + capoidc "github.com/hashicorp/cap/oidc" + "github.com/hashicorp/go-multierror" +) + +func (b *Server) CreateDevDatabase(ctx context.Context, opt ...Option) error { + var container, url, dialect string + var err error + var c func() error + + opts := getOpts(opt...) + + // We should only get back postgres for now, but laying the foundation for non-postgres + switch opts.withDialect { + case "": + b.Logger.Error("unsupported dialect. wanted: postgres, got: %v", opts.withDialect) + default: + dialect = opts.withDialect + } + + switch b.DatabaseUrl { + case "": + c, url, container, err = docker.StartDbInDocker(dialect, docker.WithContainerImage(opts.withContainerImage)) + // In case of an error, run the cleanup function. If we pass all errors, c should be set to a noop + // function before returning from this method + defer func() { + if !opts.withSkipDatabaseDestruction { + if c != nil { + if err := c(); err != nil { + b.Logger.Error("error cleaning up docker container", "error", err) + } + } + } + }() + if err == docker.ErrDockerUnsupported { + return err + } + if err != nil { + return fmt.Errorf("unable to start dev database with dialect %s: %w", dialect, err) + } + + // Let migrate store manage the dirty bit since dev DBs should be ephemeral anyways. + _, err := schema.MigrateStore(ctx, dialect, url) + if err != nil { + err = fmt.Errorf("unable to initialize dev database with dialect %s: %w", dialect, err) + if c != nil { + err = multierror.Append(err, c()) + } + return err + } + + b.DevDatabaseCleanupFunc = c + b.DatabaseUrl = url + default: + // Let migrate store manage the dirty bit since dev DBs should be ephemeral anyways. + if _, err := schema.MigrateStore(ctx, dialect, b.DatabaseUrl); err != nil { + err = fmt.Errorf("error initializing store: %w", err) + if c != nil { + err = multierror.Append(err, c()) + } + return err + } + } + + b.InfoKeys = append(b.InfoKeys, "dev database url") + b.Info["dev database url"] = b.DatabaseUrl + if container != "" { + b.InfoKeys = append(b.InfoKeys, "dev database container") + b.Info["dev database container"] = strings.TrimPrefix(container, "/") + } + + if err := b.ConnectToDatabase(dialect); err != nil { + if c != nil { + err = multierror.Append(err, c()) + } + return err + } + + b.Database.LogMode(true) + + if err := b.CreateGlobalKmsKeys(ctx); err != nil { + if c != nil { + err = multierror.Append(err, c()) + } + return err + } + + if _, err := b.CreateInitialLoginRole(ctx); err != nil { + if c != nil { + err = multierror.Append(err, c()) + } + return err + } + + if opts.withSkipAuthMethodCreation { + // now that we have passed all the error cases, reset c to be a noop so the + // defer doesn't do anything. + c = func() error { return nil } + return nil + } + + if _, _, err := b.CreateInitialPasswordAuthMethod(ctx); err != nil { + return err + } + + if !opts.withSkipOidcAuthMethodCreation { + if err := b.CreateDevOidcAuthMethod(ctx); err != nil { + return err + } + } + + if opts.withSkipScopesCreation { + // now that we have passed all the error cases, reset c to be a noop so the + // defer doesn't do anything. + c = func() error { return nil } + return nil + } + + if _, _, err := b.CreateInitialScopes(ctx); err != nil { + return err + } + + if opts.withSkipHostResourcesCreation { + // now that we have passed all the error cases, reset c to be a noop so the + // defer doesn't do anything. + c = func() error { return nil } + return nil + } + + if _, _, _, err := b.CreateInitialHostResources(context.Background()); err != nil { + return err + } + + if opts.withSkipTargetCreation { + // now that we have passed all the error cases, reset c to be a noop so the + // defer doesn't do anything. + c = func() error { return nil } + return nil + } + + if _, err := b.CreateInitialTarget(ctx); err != nil { + return err + } + + // now that we have passed all the error cases, reset c to be a noop so the + // defer doesn't do anything. + c = func() error { return nil } + return nil +} + +type oidcSetup struct { + clientId string + clientSecret oidc.ClientSecret + oidcPort int + callbackPort string + hostAddr string + authMethod *oidc.AuthMethod + pubKey []byte + privKey []byte + testProvider *capoidc.TestProvider + createUnpriv bool + callbackUrl *url.URL +} + +func (b *Server) CreateDevOidcAuthMethod(ctx context.Context) error { + var err error + + if b.DevOidcAuthMethodId == "" { + b.DevOidcAuthMethodId, err = db.NewPublicId(oidc.AuthMethodPrefix) + if err != nil { + return fmt.Errorf("error generating initial oidc auth method id: %w", err) + } + } + b.InfoKeys = append(b.InfoKeys, "generated oidc auth method id") + b.Info["generated oidc auth method id"] = b.DevOidcAuthMethodId + + switch { + case b.DevUnprivilegedLoginName == "", + b.DevUnprivilegedPassword == "", + b.DevUnprivilegedUserId == "", + b.DevUnprivilegedOidcAccountId == "": + + default: + b.DevOidcSetup.createUnpriv = true + } + + // Trawl through the listeners and find the api listener so we can use the + // same host name/IP + { + for _, ln := range b.Listeners { + purpose := strings.ToLower(ln.Config.Purpose[0]) + if purpose != "api" { + continue + } + b.DevOidcSetup.hostAddr, b.DevOidcSetup.callbackPort, err = net.SplitHostPort(ln.Config.Address) + if err != nil { + if strings.Contains(err.Error(), "missing port") { + b.DevOidcSetup.hostAddr = ln.Config.Address + // Use the default API port in the callback + b.DevOidcSetup.callbackPort = "9200" + } else { + return fmt.Errorf("error splitting host/port: %w", err) + } + } + } + if b.DevOidcSetup.hostAddr == "" { + return fmt.Errorf("could not determine address to use for built-in oidc dev listener") + } + } + + // Find an available port -- allocate one, then close the listener, and + // re-use it. This is a sort of hacky way to get around the chicken and egg + // of the auth method needing to know the discovery URL and the test + // provider needing to know the callback URL. + l, err := net.Listen("tcp", net.JoinHostPort(b.DevOidcSetup.hostAddr, "0")) + if err != nil { + return fmt.Errorf("error finding port for oidc test provider: %w", err) + } + b.DevOidcSetup.oidcPort = l.(*net.TCPListener).Addr().(*net.TCPAddr).Port + if err := l.Close(); err != nil { + return fmt.Errorf("error closing initial test port: %w", err) + } + b.DevOidcSetup.callbackUrl, err = url.Parse(fmt.Sprintf("http://%s", net.JoinHostPort(b.DevOidcSetup.hostAddr, b.DevOidcSetup.callbackPort))) + if err != nil { + return fmt.Errorf("error parsing oidc test provider callback url: %w", err) + } + + // Generate initial IDs/keys + { + b.DevOidcSetup.clientId, err = capoidc.NewID() + if err != nil { + return fmt.Errorf("unable to generate client id: %w", err) + } + clientSecret, err := capoidc.NewID() + if err != nil { + return fmt.Errorf("unable to generate client secret: %w", err) + } + b.DevOidcSetup.clientSecret = oidc.ClientSecret(clientSecret) + b.DevOidcSetup.pubKey, b.DevOidcSetup.privKey, err = ed25519.GenerateKey(nil) + if err != nil { + return fmt.Errorf("unable to generate signing key: %w", err) + } + } + + // Create the subject information and testing provider + { + logger, err := capoidc.NewTestingLogger(b.Logger.Named("dev-oidc")) + if err != nil { + return fmt.Errorf("unable to create logger: %w", err) + } + + subInfo := map[string]*capoidc.TestSubject{ + b.DevLoginName: { + Password: b.DevPassword, + UserInfo: map[string]interface{}{ + "email": "admin@localhost", + "name": "Admin User", + }, + }, + } + if b.DevOidcSetup.createUnpriv { + subInfo[b.DevUnprivilegedLoginName] = &capoidc.TestSubject{ + Password: b.DevUnprivilegedPassword, + UserInfo: map[string]interface{}{ + "email": "user@localhost", + "name": "Unprivileged User", + }, + } + } + + clientSecret := string(b.DevOidcSetup.clientSecret) + + b.DevOidcSetup.testProvider = capoidc.StartTestProvider( + logger, + capoidc.WithNoTLS(), + capoidc.WithTestHost(b.DevOidcSetup.hostAddr), + capoidc.WithTestPort(b.DevOidcSetup.oidcPort), + capoidc.WithTestDefaults(&capoidc.TestProviderDefaults{ + CustomClaims: map[string]interface{}{ + "mode": "dev", + }, + SubjectInfo: subInfo, + SigningKey: &capoidc.TestSigningKey{ + PrivKey: ed25519.PrivateKey(b.DevOidcSetup.privKey), + PubKey: ed25519.PublicKey(b.DevOidcSetup.pubKey), + Alg: capoidc.EdDSA, + }, + AllowedRedirectURIs: []string{fmt.Sprintf("%s/v1/auth-methods/oidc:authenticate:callback", b.DevOidcSetup.callbackUrl.String())}, + ClientID: &b.DevOidcSetup.clientId, + ClientSecret: &clientSecret, + })) + + b.ShutdownFuncs = append(b.ShutdownFuncs, func() error { + b.DevOidcSetup.testProvider.Stop() + return nil + }) + } + + // Create auth method and link accounts + { + b.DevOidcSetup.authMethod, err = b.createInitialOidcAuthMethod(ctx) + if err != nil { + return fmt.Errorf("error creating initial oidc auth method: %w", err) + } + } + + return nil +} + +func (b *Server) createInitialOidcAuthMethod(ctx context.Context) (*oidc.AuthMethod, error) { + rw := db.New(b.Database) + + kmsRepo, err := kms.NewRepository(rw, rw) + if err != nil { + return nil, fmt.Errorf("error creating kms repository: %w", err) + } + kmsCache, err := kms.NewKms(kmsRepo, kms.WithLogger(b.Logger.Named("kms"))) + if err != nil { + return nil, fmt.Errorf("error creating kms cache: %w", err) + } + if err := kmsCache.AddExternalWrappers( + kms.WithRootWrapper(b.RootKms), + ); err != nil { + return nil, fmt.Errorf("error adding config keys to kms: %w", err) + } + + discoveryUrl, err := url.Parse(fmt.Sprintf("http://%s:%d", b.DevOidcSetup.hostAddr, b.DevOidcSetup.oidcPort)) + if err != nil { + return nil, fmt.Errorf("error parsing oidc test provider address: %w", err) + } + + // Create the auth method + oidcRepo, err := oidc.NewRepository(rw, rw, kmsCache) + if err != nil { + return nil, fmt.Errorf("error creating oidc repo: %w", err) + } + + authMethod, err := oidc.NewAuthMethod( + scope.Global.String(), + b.DevOidcSetup.clientId, + b.DevOidcSetup.clientSecret, + oidc.WithName("Generated global scope initial oidc auth method"), + oidc.WithDescription("Provides initial administrative and unprivileged authentication into Boundary"), + oidc.WithIssuer(discoveryUrl), + oidc.WithApiUrl(b.DevOidcSetup.callbackUrl), + oidc.WithSigningAlgs(oidc.EdDSA), + oidc.WithOperationalState(oidc.ActivePublicState)) + if err != nil { + return nil, fmt.Errorf("error creating new in memory oidc auth method: %w", err) + } + if b.DevOidcAuthMethodId == "" { + b.DevOidcAuthMethodId, err = db.NewPublicId(oidc.AuthMethodPrefix) + if err != nil { + return nil, fmt.Errorf("error generating initial oidc auth method id: %w", err) + } + } + + cancelCtx, cancel := context.WithCancel(ctx) + defer cancel() + go func() { + select { + case <-b.ShutdownCh: + cancel() + case <-cancelCtx.Done(): + } + }() + + b.DevOidcSetup.authMethod, err = oidcRepo.CreateAuthMethod( + cancelCtx, + authMethod, + oidc.WithPublicId(b.DevOidcAuthMethodId)) + if err != nil { + return nil, fmt.Errorf("error saving oidc auth method to the db: %w", err) + } + + // Create accounts + { + createAndLinkAccount := func(loginName, userId, accountId, typ string) error { + acct, err := oidc.NewAccount( + b.DevOidcSetup.authMethod.GetPublicId(), + loginName, + oidc.WithDescription(fmt.Sprintf("Initial %s OIDC account", typ)), + ) + if err != nil { + return fmt.Errorf("error generating %s oidc account: %w", typ, err) + } + acct, err = oidcRepo.CreateAccount( + cancelCtx, + b.DevOidcSetup.authMethod.GetScopeId(), + acct, + oidc.WithPublicId(accountId), + ) + if err != nil { + return fmt.Errorf("error creating %s oidc account: %w", typ, err) + } + + // Link accounts to existing user + iamRepo, err := iam.NewRepository(rw, rw, kmsCache) + if err != nil { + return fmt.Errorf("unable to create iam repo: %w", err) + } + + u, _, err := iamRepo.LookupUser(cancelCtx, userId) + if err != nil { + return fmt.Errorf("error looking up %s user: %w", typ, err) + } + if _, err = iamRepo.AddUserAccounts(cancelCtx, u.GetPublicId(), u.GetVersion(), []string{acct.GetPublicId()}); err != nil { + return fmt.Errorf("error associating initial %s user with account: %w", typ, err) + } + + return nil + } + + if err := createAndLinkAccount(b.DevLoginName, b.DevUserId, b.DevOidcAccountId, "admin"); err != nil { + return nil, err + } + if b.DevOidcSetup.createUnpriv { + if err := createAndLinkAccount(b.DevUnprivilegedLoginName, b.DevUnprivilegedUserId, b.DevUnprivilegedOidcAccountId, "unprivileged"); err != nil { + return nil, err + } + } + } + + return nil, nil +} diff --git a/internal/cmd/base/initial_resources.go b/internal/cmd/base/initial_resources.go index dfe5cfa3a..a7f1f6c84 100644 --- a/internal/cmd/base/initial_resources.go +++ b/internal/cmd/base/initial_resources.go @@ -145,7 +145,7 @@ func (b *Server) CreateInitialPasswordAuthMethod(ctx context.Context) (*password return nil, nil, fmt.Errorf("unable to set primary auth method for global scope: %w", err) } - createUser := func(loginName, loginPassword, userId string, admin bool) (*iam.User, error) { + createUser := func(loginName, loginPassword, userId, accountId string, admin bool) (*iam.User, error) { // Create the dev admin user if loginName == "" { return nil, fmt.Errorf("empty login name") @@ -167,7 +167,13 @@ func (b *Server) CreateInitialPasswordAuthMethod(ctx context.Context) (*password if err != nil { return nil, fmt.Errorf("error creating new in memory password auth account: %w", err) } - acct, err = pwRepo.CreateAccount(cancelCtx, scope.Global.String(), acct, password.WithPassword(loginPassword)) + acct, err = pwRepo.CreateAccount( + cancelCtx, + scope.Global.String(), + acct, + password.WithPassword(loginPassword), + password.WithPublicId(accountId), + ) if err != nil { return nil, fmt.Errorf("error saving auth account to the db: %w", err) } @@ -233,7 +239,7 @@ func (b *Server) CreateInitialPasswordAuthMethod(ctx context.Context) (*password b.DevUnprivilegedPassword == "", b.DevUnprivilegedUserId == "": default: - _, err := createUser(b.DevUnprivilegedLoginName, b.DevUnprivilegedPassword, b.DevUnprivilegedUserId, false) + _, err := createUser(b.DevUnprivilegedLoginName, b.DevUnprivilegedPassword, b.DevUnprivilegedUserId, b.DevUnprivilegedPasswordAccountId, false) if err != nil { return nil, nil, err } @@ -257,7 +263,7 @@ func (b *Server) CreateInitialPasswordAuthMethod(ctx context.Context) (*password return nil, nil, fmt.Errorf("error generating initial user id: %w", err) } } - u, err := createUser(b.DevLoginName, b.DevPassword, b.DevUserId, true) + u, err := createUser(b.DevLoginName, b.DevPassword, b.DevUserId, b.DevPasswordAccountId, true) if err != nil { return nil, nil, err } diff --git a/internal/cmd/base/option.go b/internal/cmd/base/option.go index 817880371..5fadf9220 100644 --- a/internal/cmd/base/option.go +++ b/internal/cmd/base/option.go @@ -14,15 +14,16 @@ type Option func(*Options) // Options - how Options are represented. type Options struct { - withNoTokenScope bool - withNoTokenValue bool - withSkipDatabaseDestruction bool - withSkipAuthMethodCreation bool - withSkipScopesCreation bool - withSkipHostResourcesCreation bool - withSkipTargetCreation bool - withContainerImage string - withDialect string + withNoTokenScope bool + withNoTokenValue bool + withSkipDatabaseDestruction bool + withSkipAuthMethodCreation bool + withSkipOidcAuthMethodCreation bool + withSkipScopesCreation bool + withSkipHostResourcesCreation bool + withSkipTargetCreation bool + withContainerImage string + withDialect string } func getDefaultOptions() Options { @@ -57,7 +58,7 @@ func WithNoTokenValue() Option { } } -// WithSkipAuthMethodCreation tells the command not to instantiate an auth +// WithSkipAuthMethodCreation tells the command not to instantiate any auth // method on first run. func WithSkipAuthMethodCreation() Option { return func(o *Options) { @@ -65,6 +66,14 @@ func WithSkipAuthMethodCreation() Option { } } +// WithSkipOidcAuthMethodCreation tells the command not to instantiate an OIDC auth +// method on first run, useful in some tests. +func WithSkipOidcAuthMethodCreation() Option { + return func(o *Options) { + o.withSkipOidcAuthMethodCreation = true + } +} + // WithSkipScopesCreation tells the command not to instantiate scopes on first // run. func WithSkipScopesCreation() Option { diff --git a/internal/cmd/base/servers.go b/internal/cmd/base/servers.go index 2c846412c..9dcd195f5 100644 --- a/internal/cmd/base/servers.go +++ b/internal/cmd/base/servers.go @@ -20,8 +20,6 @@ import ( "github.com/hashicorp/boundary/globals" "github.com/hashicorp/boundary/internal/cmd/config" "github.com/hashicorp/boundary/internal/db" - "github.com/hashicorp/boundary/internal/db/schema" - "github.com/hashicorp/boundary/internal/docker" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/types/scope" "github.com/hashicorp/boundary/sdk/strutil" @@ -69,24 +67,30 @@ type Server struct { Listeners []*ServerListener - DevPasswordAuthMethodId string - DevOidcAuthMethodId string - DevLoginName string - DevPassword string - DevUserId string - DevUnprivilegedLoginName string - DevUnprivilegedPassword string - DevUnprivilegedUserId string - DevOrgId string - DevProjectId string - DevHostCatalogId string - DevHostSetId string - DevHostId string - DevTargetId string - DevHostAddress string - DevTargetDefaultPort int - DevTargetSessionMaxSeconds int - DevTargetSessionConnectionLimit int + DevPasswordAuthMethodId string + DevOidcAuthMethodId string + DevLoginName string + DevPassword string + DevUserId string + DevPasswordAccountId string + DevOidcAccountId string + DevUnprivilegedLoginName string + DevUnprivilegedPassword string + DevUnprivilegedUserId string + DevUnprivilegedPasswordAccountId string + DevUnprivilegedOidcAccountId string + DevOrgId string + DevProjectId string + DevHostCatalogId string + DevHostSetId string + DevHostId string + DevTargetId string + DevHostAddress string + DevTargetDefaultPort int + DevTargetSessionMaxSeconds int + DevTargetSessionConnectionLimit int + + DevOidcSetup oidcSetup DatabaseUrl string DatabaseMaxOpenConnections int @@ -467,145 +471,6 @@ func (b *Server) ConnectToDatabase(dialect string) error { return nil } -func (b *Server) CreateDevDatabase(ctx context.Context, opt ...Option) error { - var container, url, dialect string - var err error - var c func() error - - opts := getOpts(opt...) - - // We should only get back postgres for now, but laying the foundation for non-postgres - switch opts.withDialect { - case "": - b.Logger.Error("unsupported dialect. wanted: postgres, got: %v", opts.withDialect) - default: - dialect = opts.withDialect - } - - switch b.DatabaseUrl { - case "": - c, url, container, err = docker.StartDbInDocker(dialect, docker.WithContainerImage(opts.withContainerImage)) - // In case of an error, run the cleanup function. If we pass all errors, c should be set to a noop - // function before returning from this method - defer func() { - if !opts.withSkipDatabaseDestruction { - if c != nil { - if err := c(); err != nil { - b.Logger.Error("error cleaning up docker container", "error", err) - } - } - } - }() - if err == docker.ErrDockerUnsupported { - return err - } - if err != nil { - return fmt.Errorf("unable to start dev database with dialect %s: %w", dialect, err) - } - - // Let migrate store manage the dirty bit since dev DBs should be ephemeral anyways. - _, err := schema.MigrateStore(ctx, dialect, url) - if err != nil { - err = fmt.Errorf("unable to initialize dev database with dialect %s: %w", dialect, err) - if c != nil { - err = multierror.Append(err, c()) - } - return err - } - - b.DevDatabaseCleanupFunc = c - b.DatabaseUrl = url - default: - // Let migrate store manage the dirty bit since dev DBs should be ephemeral anyways. - if _, err := schema.MigrateStore(ctx, dialect, b.DatabaseUrl); err != nil { - err = fmt.Errorf("error initializing store: %w", err) - if c != nil { - err = multierror.Append(err, c()) - } - return err - } - } - - b.InfoKeys = append(b.InfoKeys, "dev database url") - b.Info["dev database url"] = b.DatabaseUrl - if container != "" { - b.InfoKeys = append(b.InfoKeys, "dev database container") - b.Info["dev database container"] = strings.TrimPrefix(container, "/") - } - - if err := b.ConnectToDatabase(dialect); err != nil { - if c != nil { - err = multierror.Append(err, c()) - } - return err - } - - b.Database.LogMode(true) - - if err := b.CreateGlobalKmsKeys(ctx); err != nil { - if c != nil { - err = multierror.Append(err, c()) - } - return err - } - - if _, err := b.CreateInitialLoginRole(ctx); err != nil { - if c != nil { - err = multierror.Append(err, c()) - } - return err - } - - if opts.withSkipAuthMethodCreation { - // now that we have passed all the error cases, reset c to be a noop so the - // defer doesn't do anything. - c = func() error { return nil } - return nil - } - - if _, _, err := b.CreateInitialPasswordAuthMethod(ctx); err != nil { - return err - } - - if opts.withSkipScopesCreation { - // now that we have passed all the error cases, reset c to be a noop so the - // defer doesn't do anything. - c = func() error { return nil } - return nil - } - - if _, _, err := b.CreateInitialScopes(ctx); err != nil { - return err - } - - if opts.withSkipHostResourcesCreation { - // now that we have passed all the error cases, reset c to be a noop so the - // defer doesn't do anything. - c = func() error { return nil } - return nil - } - - if _, _, _, err := b.CreateInitialHostResources(context.Background()); err != nil { - return err - } - - if opts.withSkipTargetCreation { - // now that we have passed all the error cases, reset c to be a noop so the - // defer doesn't do anything. - c = func() error { return nil } - return nil - } - - if _, err := b.CreateInitialTarget(ctx); err != nil { - return err - } - - // now that we have passed all the error cases, reset c to be a noop so the - // defer doesn't do anything. - c = func() error { return nil } - return nil -} - func (b *Server) CreateGlobalKmsKeys(ctx context.Context) error { rw := db.New(b.Database) diff --git a/internal/cmd/commands.go b/internal/cmd/commands.go index e84dfa8b7..9cd8fdc75 100644 --- a/internal/cmd/commands.go +++ b/internal/cmd/commands.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/boundary/internal/cmd/commands/hostscmd" "github.com/hashicorp/boundary/internal/cmd/commands/hostsetscmd" "github.com/hashicorp/boundary/internal/cmd/commands/logout" + "github.com/hashicorp/boundary/internal/cmd/commands/managedgroupscmd" "github.com/hashicorp/boundary/internal/cmd/commands/rolescmd" "github.com/hashicorp/boundary/internal/cmd/commands/scopescmd" "github.com/hashicorp/boundary/internal/cmd/commands/server" @@ -546,6 +547,54 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) { }, nil }, + "managed-groups": func() (cli.Command, error) { + return &managedgroupscmd.Command{ + Command: base.NewCommand(ui), + }, nil + }, + "managed-groups read": func() (cli.Command, error) { + return &managedgroupscmd.Command{ + Command: base.NewCommand(ui), + Func: "read", + }, nil + }, + "managed-groups delete": func() (cli.Command, error) { + return &managedgroupscmd.Command{ + Command: base.NewCommand(ui), + Func: "delete", + }, nil + }, + "managed-groups list": func() (cli.Command, error) { + return &managedgroupscmd.Command{ + Command: base.NewCommand(ui), + Func: "list", + }, nil + }, + "managed-groups create": func() (cli.Command, error) { + return &managedgroupscmd.Command{ + Command: base.NewCommand(ui), + Func: "create", + }, nil + }, + "managed-groups create oidc": func() (cli.Command, error) { + return &managedgroupscmd.OidcCommand{ + Command: base.NewCommand(ui), + Func: "create", + }, nil + }, + "managed-groups update": func() (cli.Command, error) { + return &managedgroupscmd.Command{ + Command: base.NewCommand(ui), + Func: "update", + }, nil + }, + "managed-groups update oidc": func() (cli.Command, error) { + return &managedgroupscmd.OidcCommand{ + Command: base.NewCommand(ui), + Func: "update", + }, nil + }, + "roles": func() (cli.Command, error) { return &rolescmd.Command{ Command: base.NewCommand(ui), diff --git a/internal/cmd/commands/accountscmd/accounts.gen.go b/internal/cmd/commands/accountscmd/accounts.gen.go index 078d40a18..52cc2e27c 100644 --- a/internal/cmd/commands/accountscmd/accounts.gen.go +++ b/internal/cmd/commands/accountscmd/accounts.gen.go @@ -103,7 +103,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "account", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "account", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/accountscmd/funcs.go b/internal/cmd/commands/accountscmd/funcs.go index 54a2889fa..ea53057d2 100644 --- a/internal/cmd/commands/accountscmd/funcs.go +++ b/internal/cmd/commands/accountscmd/funcs.go @@ -58,7 +58,7 @@ func (c *Command) extraHelpFunc(helpMap map[string]func() string) string { "", " Read a account:", "", - ` $ boundary accounts read -id apw_1234567890`, + ` $ boundary accounts read -id acctpw_1234567890`, "", " Please see the accounts subcommand help for detailed usage information.", }) @@ -70,7 +70,7 @@ func (c *Command) extraHelpFunc(helpMap map[string]func() string) string { "", " Change the password on a password-type account:", "", - ` $ boundary accounts change-password -id apw_1234567890 -current-password -new-password `, + ` $ boundary accounts change-password -id acctpw_1234567890 -current-password -new-password `, "", "", }) @@ -82,7 +82,7 @@ func (c *Command) extraHelpFunc(helpMap map[string]func() string) string { "", " Set the password on a password-type account:", "", - ` $ boundary accounts set-password -id apw_1234567890 -password `, + ` $ boundary accounts set-password -id acctpw_1234567890 -password `, "", "", }) @@ -281,6 +281,14 @@ func printItemTable(result api.GenericResult) string { ) } + if len(item.ManagedGroupIds) > 0 { + ret = append(ret, + "", + " Managed Group IDs:", + base.WrapSlice(4, item.ManagedGroupIds), + ) + } + if len(item.AuthorizedActions) > 0 { ret = append(ret, "", diff --git a/internal/cmd/commands/accountscmd/oidc_accounts.gen.go b/internal/cmd/commands/accountscmd/oidc_accounts.gen.go index 3d8880066..3c87cc52c 100644 --- a/internal/cmd/commands/accountscmd/oidc_accounts.gen.go +++ b/internal/cmd/commands/accountscmd/oidc_accounts.gen.go @@ -91,7 +91,7 @@ func (c *OidcCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "oidc-type account", flagsOidcMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "oidc-type account", flagsOidcMap, c.Func) extraOidcFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/accountscmd/password_accounts.gen.go b/internal/cmd/commands/accountscmd/password_accounts.gen.go index c26571527..7cf27fc0d 100644 --- a/internal/cmd/commands/accountscmd/password_accounts.gen.go +++ b/internal/cmd/commands/accountscmd/password_accounts.gen.go @@ -91,7 +91,7 @@ func (c *PasswordCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "password-type account", flagsPasswordMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "password-type account", flagsPasswordMap, c.Func) extraPasswordFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/accountscmd/password_funcs.go b/internal/cmd/commands/accountscmd/password_funcs.go index c4984925c..521c66f95 100644 --- a/internal/cmd/commands/accountscmd/password_funcs.go +++ b/internal/cmd/commands/accountscmd/password_funcs.go @@ -49,7 +49,7 @@ func (c *PasswordCommand) extraPasswordHelpFunc(helpMap map[string]func() string "", " Update a password-type account given its ID. Example:", "", - ` $ boundary accounts update password -id apw_1234567890 -name "devops" -description "Password account for DevOps"`, + ` $ boundary accounts update password -id acctpw_1234567890 -name "devops" -description "Password account for DevOps"`, "", "", }) diff --git a/internal/cmd/commands/authmethodscmd/authmethods.gen.go b/internal/cmd/commands/authmethodscmd/authmethods.gen.go index 6b82e188e..bb3a5c904 100644 --- a/internal/cmd/commands/authmethodscmd/authmethods.gen.go +++ b/internal/cmd/commands/authmethodscmd/authmethods.gen.go @@ -101,7 +101,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "auth method", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "auth method", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/authmethodscmd/oidc_authmethods.gen.go b/internal/cmd/commands/authmethodscmd/oidc_authmethods.gen.go index 393c1f66c..b962acce5 100644 --- a/internal/cmd/commands/authmethodscmd/oidc_authmethods.gen.go +++ b/internal/cmd/commands/authmethodscmd/oidc_authmethods.gen.go @@ -91,7 +91,7 @@ func (c *OidcCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "oidc-type auth method", flagsOidcMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "oidc-type auth method", flagsOidcMap, c.Func) extraOidcFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/authmethodscmd/password_authmethods.gen.go b/internal/cmd/commands/authmethodscmd/password_authmethods.gen.go index 921028889..e242ddd3c 100644 --- a/internal/cmd/commands/authmethodscmd/password_authmethods.gen.go +++ b/internal/cmd/commands/authmethodscmd/password_authmethods.gen.go @@ -91,7 +91,7 @@ func (c *PasswordCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "password-type auth method", flagsPasswordMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "password-type auth method", flagsPasswordMap, c.Func) extraPasswordFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/authtokenscmd/authtokens.gen.go b/internal/cmd/commands/authtokenscmd/authtokens.gen.go index 21d1bc0e5..8a80bef69 100644 --- a/internal/cmd/commands/authtokenscmd/authtokens.gen.go +++ b/internal/cmd/commands/authtokenscmd/authtokens.gen.go @@ -101,7 +101,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "auth token", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "auth token", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/dev/dev.go b/internal/cmd/commands/dev/dev.go index 6f4f14021..d253e4f5a 100644 --- a/internal/cmd/commands/dev/dev.go +++ b/internal/cmd/commands/dev/dev.go @@ -1,11 +1,8 @@ package dev import ( - "context" - "crypto/ed25519" "fmt" "net" - "net/url" "runtime" "strings" @@ -13,17 +10,15 @@ import ( "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/cmd/base" "github.com/hashicorp/boundary/internal/cmd/config" - "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/host/static" "github.com/hashicorp/boundary/internal/iam" - "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/servers/controller" "github.com/hashicorp/boundary/internal/servers/controller/handlers" "github.com/hashicorp/boundary/internal/servers/worker" "github.com/hashicorp/boundary/internal/target" "github.com/hashicorp/boundary/internal/types/scope" "github.com/hashicorp/boundary/sdk/strutil" - capoidc "github.com/hashicorp/cap/oidc" "github.com/mitchellh/cli" "github.com/posener/complete" ) @@ -45,8 +40,6 @@ type Command struct { controller *controller.Controller worker *worker.Worker - oidcSetup oidcSetup - flagLogLevel string flagLogFormat string flagCombineLogs bool @@ -321,7 +314,11 @@ func (c *Command) Run(args []string) int { c.DevPasswordAuthMethodId = fmt.Sprintf("%s_%s", password.AuthMethodPrefix, c.flagIdSuffix) c.DevOidcAuthMethodId = fmt.Sprintf("%s_%s", oidc.AuthMethodPrefix, c.flagIdSuffix) c.DevUserId = fmt.Sprintf("%s_%s", iam.UserPrefix, c.flagIdSuffix) + c.DevPasswordAccountId = fmt.Sprintf("%s_%s", intglobals.NewPasswordAccountPrefix, c.flagIdSuffix) + c.DevOidcAccountId = fmt.Sprintf("%s_%s", oidc.AccountPrefix, c.flagIdSuffix) c.DevUnprivilegedUserId = "u_" + strutil.Reverse(strings.TrimPrefix(c.DevUserId, "u_")) + c.DevUnprivilegedPasswordAccountId = fmt.Sprintf("%s_", intglobals.NewPasswordAccountPrefix) + strutil.Reverse(strings.TrimPrefix(c.DevPasswordAccountId, fmt.Sprintf("%s_", intglobals.NewPasswordAccountPrefix))) + c.DevUnprivilegedOidcAccountId = fmt.Sprintf("%s_", oidc.AccountPrefix) + strutil.Reverse(strings.TrimPrefix(c.DevOidcAccountId, fmt.Sprintf("%s_", oidc.AccountPrefix))) c.DevOrgId = fmt.Sprintf("%s_%s", scope.Org.Prefix(), c.flagIdSuffix) c.DevProjectId = fmt.Sprintf("%s_%s", scope.Project.Prefix(), c.flagIdSuffix) c.DevHostCatalogId = fmt.Sprintf("%s_%s", static.HostCatalogPrefix, c.flagIdSuffix) @@ -497,11 +494,6 @@ func (c *Command) Run(args []string) int { } } - if err := c.startDevOidcAuthMethod(); err != nil { - c.UI.Error(fmt.Errorf("Error starting dev OIDC auth method: %w", err).Error()) - return base.CommandCliError - } - c.PrintInfo(c.UI) c.ReleaseLogGate() @@ -585,277 +577,3 @@ func (c *Command) Run(args []string) int { return base.CommandSuccess } - -type oidcSetup struct { - clientId string - clientSecret oidc.ClientSecret - oidcPort int - callbackPort string - hostAddr string - authMethod *oidc.AuthMethod - pubKey []byte - privKey []byte - testProvider *capoidc.TestProvider - createUnpriv bool - callbackUrl *url.URL -} - -func (c *Command) startDevOidcAuthMethod() error { - var err error - - if c.DevOidcAuthMethodId == "" { - c.DevOidcAuthMethodId, err = db.NewPublicId(oidc.AuthMethodPrefix) - if err != nil { - return fmt.Errorf("error generating initial oidc auth method id: %w", err) - } - } - c.InfoKeys = append(c.InfoKeys, "generated oidc auth method id") - c.Info["generated oidc auth method id"] = c.DevOidcAuthMethodId - - switch { - case c.DevUnprivilegedLoginName == "", - c.DevUnprivilegedPassword == "", - c.DevUnprivilegedUserId == "": - - default: - c.oidcSetup.createUnpriv = true - } - - // Trawl through the listeners and find the api listener so we can use the - // same host name/IP - { - for _, lnConfig := range c.Config.Listeners { - purpose := strings.ToLower(lnConfig.Purpose[0]) - if purpose != "api" { - continue - } - c.oidcSetup.hostAddr, c.oidcSetup.callbackPort, err = net.SplitHostPort(lnConfig.Address) - if err != nil { - if strings.Contains(err.Error(), "missing port") { - c.oidcSetup.hostAddr = lnConfig.Address - // Use the default API port in the callback - c.oidcSetup.callbackPort = "9200" - } else { - return fmt.Errorf("error splitting host/port: %w", err) - } - } - } - if c.oidcSetup.hostAddr == "" { - return fmt.Errorf("could not determine address to use for built-in oidc dev listener") - } - } - - // Find an available port -- allocate one, then close the listener, and - // re-use it. This is a sort of hacky way to get around the chicken and egg - // of the auth method needing to know the discovery URL and the test - // provider needing to know the callback URL. - l, err := net.Listen("tcp", fmt.Sprintf("%s:0", c.oidcSetup.hostAddr)) - if err != nil { - return fmt.Errorf("error finding port for oidc test provider: %w", err) - } - c.oidcSetup.oidcPort = l.(*net.TCPListener).Addr().(*net.TCPAddr).Port - if err := l.Close(); err != nil { - return fmt.Errorf("error closing initial test port: %w", err) - } - c.oidcSetup.callbackUrl, err = url.Parse(fmt.Sprintf("http://%s:%s", c.oidcSetup.hostAddr, c.oidcSetup.callbackPort)) - if err != nil { - return fmt.Errorf("error parsing oidc test provider callback url: %w", err) - } - - // Generate initial IDs/keys - { - c.oidcSetup.clientId, err = capoidc.NewID() - if err != nil { - return fmt.Errorf("unable to generate client id: %w", err) - } - clientSecret, err := capoidc.NewID() - if err != nil { - return fmt.Errorf("unable to generate client secret: %w", err) - } - c.oidcSetup.clientSecret = oidc.ClientSecret(clientSecret) - c.oidcSetup.pubKey, c.oidcSetup.privKey, err = ed25519.GenerateKey(nil) - if err != nil { - return fmt.Errorf("unable to generate signing key: %w", err) - } - } - - // Create the subject information and testing provider - { - logger, err := capoidc.NewTestingLogger(c.Logger.Named("dev-oidc")) - if err != nil { - return fmt.Errorf("unable to create logger: %w", err) - } - - subInfo := map[string]*capoidc.TestSubject{ - c.DevLoginName: { - Password: c.DevPassword, - UserInfo: map[string]interface{}{ - "email": "admin@localhost", - "name": "Admin User", - }, - }, - } - if c.oidcSetup.createUnpriv { - subInfo[c.DevUnprivilegedLoginName] = &capoidc.TestSubject{ - Password: c.DevUnprivilegedPassword, - UserInfo: map[string]interface{}{ - "email": "user@localhost", - "name": "Unprivileged User", - }, - } - } - - clientSecret := string(c.oidcSetup.clientSecret) - - c.oidcSetup.testProvider = capoidc.StartTestProvider( - logger, - capoidc.WithNoTLS(), - capoidc.WithTestHost(c.oidcSetup.hostAddr), - capoidc.WithTestPort(c.oidcSetup.oidcPort), - capoidc.WithTestDefaults(&capoidc.TestProviderDefaults{ - CustomClaims: map[string]interface{}{ - "mode": "dev", - }, - SubjectInfo: subInfo, - SigningKey: &capoidc.TestSigningKey{ - PrivKey: ed25519.PrivateKey(c.oidcSetup.privKey), - PubKey: ed25519.PublicKey(c.oidcSetup.pubKey), - Alg: capoidc.EdDSA, - }, - AllowedRedirectURIs: []string{fmt.Sprintf("%s/v1/auth-methods/oidc:authenticate:callback", c.oidcSetup.callbackUrl.String())}, - ClientID: &c.oidcSetup.clientId, - ClientSecret: &clientSecret, - })) - - c.ShutdownFuncs = append(c.ShutdownFuncs, func() error { - c.oidcSetup.testProvider.Stop() - return nil - }) - } - - // Create auth method and link accounts - { - c.oidcSetup.authMethod, err = c.createInitialOidcAuthMethod() - if err != nil { - return fmt.Errorf("error creating initial oidc auth method: %w", err) - } - } - - return nil -} - -func (c *Command) createInitialOidcAuthMethod() (*oidc.AuthMethod, error) { - rw := db.New(c.Database) - - kmsRepo, err := kms.NewRepository(rw, rw) - if err != nil { - return nil, fmt.Errorf("error creating kms repository: %w", err) - } - kmsCache, err := kms.NewKms(kmsRepo, kms.WithLogger(c.Logger.Named("kms"))) - if err != nil { - return nil, fmt.Errorf("error creating kms cache: %w", err) - } - if err := kmsCache.AddExternalWrappers( - kms.WithRootWrapper(c.RootKms), - ); err != nil { - return nil, fmt.Errorf("error adding config keys to kms: %w", err) - } - - discoveryUrl, err := url.Parse(fmt.Sprintf("http://%s:%d", c.oidcSetup.hostAddr, c.oidcSetup.oidcPort)) - if err != nil { - return nil, fmt.Errorf("error parsing oidc test provider address: %w", err) - } - - // Create the auth method - oidcRepo, err := oidc.NewRepository(rw, rw, kmsCache) - if err != nil { - return nil, fmt.Errorf("error creating oidc repo: %w", err) - } - - authMethod, err := oidc.NewAuthMethod( - scope.Global.String(), - c.oidcSetup.clientId, - c.oidcSetup.clientSecret, - oidc.WithName("Generated global scope initial oidc auth method"), - oidc.WithDescription("Provides initial administrative and unprivileged authentication into Boundary"), - oidc.WithIssuer(discoveryUrl), - oidc.WithApiUrl(c.oidcSetup.callbackUrl), - oidc.WithSigningAlgs(oidc.EdDSA), - oidc.WithOperationalState(oidc.ActivePublicState)) - if err != nil { - return nil, fmt.Errorf("error creating new in memory oidc auth method: %w", err) - } - if c.DevOidcAuthMethodId == "" { - c.DevOidcAuthMethodId, err = db.NewPublicId(oidc.AuthMethodPrefix) - if err != nil { - return nil, fmt.Errorf("error generating initial oidc auth method id: %w", err) - } - } - - cancelCtx, cancel := context.WithCancel(c.Context) - defer cancel() - go func() { - select { - case <-c.ShutdownCh: - cancel() - case <-cancelCtx.Done(): - } - }() - - c.oidcSetup.authMethod, err = oidcRepo.CreateAuthMethod( - cancelCtx, - authMethod, - oidc.WithPublicId(c.DevOidcAuthMethodId)) - if err != nil { - return nil, fmt.Errorf("error saving oidc auth method to the db: %w", err) - } - - // Create accounts - { - createAndLinkAccount := func(loginName, userId, typ string) error { - acct, err := oidc.NewAccount( - c.oidcSetup.authMethod.GetPublicId(), - loginName, - oidc.WithDescription(fmt.Sprintf("Initial %s OIDC account", typ)), - ) - if err != nil { - return fmt.Errorf("error generating %s oidc account: %w", typ, err) - } - acct, err = oidcRepo.CreateAccount( - cancelCtx, - c.oidcSetup.authMethod.GetScopeId(), - acct, - ) - if err != nil { - return fmt.Errorf("error creating %s oidc account: %w", typ, err) - } - - // Link accounts to existing user - iamRepo, err := iam.NewRepository(rw, rw, kmsCache) - if err != nil { - return fmt.Errorf("unable to create iam repo: %w", err) - } - - u, _, err := iamRepo.LookupUser(cancelCtx, userId) - if err != nil { - return fmt.Errorf("error looking up %s user: %w", typ, err) - } - if _, err = iamRepo.AddUserAccounts(cancelCtx, u.GetPublicId(), u.GetVersion(), []string{acct.GetPublicId()}); err != nil { - return fmt.Errorf("error associating initial %s user with account: %w", typ, err) - } - - return nil - } - - if err := createAndLinkAccount(c.DevLoginName, c.DevUserId, "admin"); err != nil { - return nil, err - } - if c.oidcSetup.createUnpriv { - if err := createAndLinkAccount(c.DevUnprivilegedLoginName, c.DevUnprivilegedUserId, "unprivileged"); err != nil { - return nil, err - } - } - } - - return nil, nil -} diff --git a/internal/cmd/commands/groupscmd/groups.gen.go b/internal/cmd/commands/groupscmd/groups.gen.go index 02d67527b..8bffb3d9d 100644 --- a/internal/cmd/commands/groupscmd/groups.gen.go +++ b/internal/cmd/commands/groupscmd/groups.gen.go @@ -113,7 +113,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "group", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "group", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/hostcatalogscmd/hostcatalogs.gen.go b/internal/cmd/commands/hostcatalogscmd/hostcatalogs.gen.go index b84f287ba..e7692f6dc 100644 --- a/internal/cmd/commands/hostcatalogscmd/hostcatalogs.gen.go +++ b/internal/cmd/commands/hostcatalogscmd/hostcatalogs.gen.go @@ -101,7 +101,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "host catalog", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "host catalog", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/hostcatalogscmd/static_hostcatalogs.gen.go b/internal/cmd/commands/hostcatalogscmd/static_hostcatalogs.gen.go index 902d8c91c..f4fb8970c 100644 --- a/internal/cmd/commands/hostcatalogscmd/static_hostcatalogs.gen.go +++ b/internal/cmd/commands/hostcatalogscmd/static_hostcatalogs.gen.go @@ -89,7 +89,7 @@ func (c *StaticCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "static-type host catalog", flagsStaticMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "static-type host catalog", flagsStaticMap, c.Func) extraStaticFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/hostscmd/hosts.gen.go b/internal/cmd/commands/hostscmd/hosts.gen.go index f29355a79..e31d1c365 100644 --- a/internal/cmd/commands/hostscmd/hosts.gen.go +++ b/internal/cmd/commands/hostscmd/hosts.gen.go @@ -101,7 +101,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "host", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "host", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/hostscmd/static_hosts.gen.go b/internal/cmd/commands/hostscmd/static_hosts.gen.go index 4a8a18e75..32dc0c26f 100644 --- a/internal/cmd/commands/hostscmd/static_hosts.gen.go +++ b/internal/cmd/commands/hostscmd/static_hosts.gen.go @@ -91,7 +91,7 @@ func (c *StaticCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "static-type host", flagsStaticMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "static-type host", flagsStaticMap, c.Func) extraStaticFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/hostsetscmd/hostsets.gen.go b/internal/cmd/commands/hostsetscmd/hostsets.gen.go index bf577c2de..e66b8b405 100644 --- a/internal/cmd/commands/hostsetscmd/hostsets.gen.go +++ b/internal/cmd/commands/hostsetscmd/hostsets.gen.go @@ -103,7 +103,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "host set", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "host set", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/hostsetscmd/static_hostsets.gen.go b/internal/cmd/commands/hostsetscmd/static_hostsets.gen.go index 63175eaba..08b1ddec1 100644 --- a/internal/cmd/commands/hostsetscmd/static_hostsets.gen.go +++ b/internal/cmd/commands/hostsetscmd/static_hostsets.gen.go @@ -89,7 +89,7 @@ func (c *StaticCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "static-type host set", flagsStaticMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "static-type host set", flagsStaticMap, c.Func) extraStaticFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/managedgroupscmd/funcs.go b/internal/cmd/commands/managedgroupscmd/funcs.go new file mode 100644 index 000000000..212cbd14a --- /dev/null +++ b/internal/cmd/commands/managedgroupscmd/funcs.go @@ -0,0 +1,138 @@ +package managedgroupscmd + +import ( + "fmt" + "time" + + "github.com/hashicorp/boundary/api" + "github.com/hashicorp/boundary/api/managedgroups" + "github.com/hashicorp/boundary/internal/cmd/base" +) + +func (c *Command) printListTable(items []*managedgroups.ManagedGroup) string { + if len(items) == 0 { + return "No managed groups found" + } + var output []string + output = []string{ + "", + "Managed Group information:", + } + for i, item := range items { + if i > 0 { + output = append(output, "") + } + if item.Id != "" { + output = append(output, + fmt.Sprintf(" ID: %s", item.Id), + ) + } else { + output = append(output, + fmt.Sprintf(" ID: %s", "(not available)"), + ) + } + if item.Version > 0 { + output = append(output, + fmt.Sprintf(" Version: %d", item.Version), + ) + } + if item.Type != "" { + output = append(output, + fmt.Sprintf(" Type: %s", item.Type), + ) + } + if item.Name != "" { + output = append(output, + fmt.Sprintf(" Name: %s", item.Name), + ) + } + if item.Description != "" { + output = append(output, + fmt.Sprintf(" Description: %s", item.Description), + ) + } + if len(item.AuthorizedActions) > 0 { + output = append(output, + " Authorized Actions:", + base.WrapSlice(6, item.AuthorizedActions), + ) + } + } + + return base.WrapForHelpText(output) +} + +func printItemTable(result api.GenericResult) string { + item := result.GetItem().(*managedgroups.ManagedGroup) + nonAttributeMap := map[string]interface{}{} + if item.Id != "" { + nonAttributeMap["ID"] = item.Id + } + if item.Version != 0 { + nonAttributeMap["Version"] = item.Version + } + if item.Type != "" { + nonAttributeMap["Type"] = item.Type + } + if !item.CreatedTime.IsZero() { + nonAttributeMap["Created Time"] = item.CreatedTime.Local().Format(time.RFC1123) + } + if !item.UpdatedTime.IsZero() { + nonAttributeMap["Updated Time"] = item.UpdatedTime.Local().Format(time.RFC1123) + } + if item.AuthMethodId != "" { + nonAttributeMap["Auth Method ID"] = item.AuthMethodId + } + if item.Name != "" { + nonAttributeMap["Name"] = item.Name + } + if item.Description != "" { + nonAttributeMap["Description"] = item.Description + } + + maxLength := base.MaxAttributesLength(nonAttributeMap, item.Attributes, keySubstMap) + + ret := []string{ + "", + "Managed Group information:", + base.WrapMap(2, maxLength+2, nonAttributeMap), + } + + if item.Scope != nil { + ret = append(ret, + "", + " Scope:", + base.ScopeInfoForOutput(item.Scope, maxLength), + ) + } + + if len(item.AuthorizedActions) > 0 { + ret = append(ret, + "", + " Authorized Actions:", + base.WrapSlice(4, item.AuthorizedActions), + ) + } + + if len(item.MemberIds) > 0 { + ret = append(ret, + "", + " Member IDs:", + base.WrapSlice(4, item.MemberIds), + ) + } + + if len(item.Attributes) > 0 { + ret = append(ret, + "", + " Attributes:", + base.WrapMap(4, maxLength, item.Attributes), + ) + } + + return base.WrapForHelpText(ret) +} + +var keySubstMap = map[string]string{ + "filter": "Filter", +} diff --git a/internal/cmd/commands/managedgroupscmd/managedgroups.gen.go b/internal/cmd/commands/managedgroupscmd/managedgroups.gen.go new file mode 100644 index 000000000..74b2f801f --- /dev/null +++ b/internal/cmd/commands/managedgroupscmd/managedgroups.gen.go @@ -0,0 +1,278 @@ +// Code generated by "make api"; DO NOT EDIT. +package managedgroupscmd + +import ( + "errors" + "fmt" + "sync" + + "github.com/hashicorp/boundary/api" + "github.com/hashicorp/boundary/api/managedgroups" + "github.com/hashicorp/boundary/internal/cmd/base" + "github.com/hashicorp/boundary/internal/cmd/common" + "github.com/hashicorp/boundary/sdk/strutil" + "github.com/mitchellh/cli" + "github.com/posener/complete" +) + +func initFlags() { + flagsOnce.Do(func() { + extraFlags := extraActionsFlagsMapFunc() + for k, v := range extraFlags { + flagsMap[k] = append(flagsMap[k], v...) + } + }) +} + +var ( + _ cli.Command = (*Command)(nil) + _ cli.CommandAutocomplete = (*Command)(nil) +) + +type Command struct { + *base.Command + + Func string + + plural string +} + +func (c *Command) AutocompleteArgs() complete.Predictor { + initFlags() + return complete.PredictAnything +} + +func (c *Command) AutocompleteFlags() complete.Flags { + initFlags() + return c.Flags().Completions() +} + +func (c *Command) Synopsis() string { + if extra := extraSynopsisFunc(c); extra != "" { + return extra + } + + synopsisStr := "managed group" + + return common.SynopsisFunc(c.Func, synopsisStr) +} + +func (c *Command) Help() string { + initFlags() + + var helpStr string + helpMap := common.HelpMap("managed group") + + switch c.Func { + + case "read": + helpStr = helpMap[c.Func]() + c.Flags().Help() + + case "delete": + helpStr = helpMap[c.Func]() + c.Flags().Help() + + case "list": + helpStr = helpMap[c.Func]() + c.Flags().Help() + + default: + + helpStr = helpMap["base"]() + + } + + // Keep linter from complaining if we don't actually generate code using it + _ = helpMap + return helpStr +} + +var flagsMap = map[string][]string{ + + "read": {"id"}, + + "delete": {"id"}, + + "list": {"auth-method-id", "filter"}, +} + +func (c *Command) Flags() *base.FlagSets { + if len(flagsMap[c.Func]) == 0 { + return c.FlagSet(base.FlagSetNone) + } + + set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) + f := set.NewFlagSet("Command Options") + common.PopulateCommonFlags(c.Command, f, "managed group", flagsMap, c.Func) + + extraFlagsFunc(c, set, f) + + return set +} + +func (c *Command) Run(args []string) int { + initFlags() + + switch c.Func { + case "": + return cli.RunResultHelp + + case "create", "update": + return cli.RunResultHelp + + } + + c.plural = "managed group" + switch c.Func { + case "list": + c.plural = "managed groups" + } + + f := c.Flags() + + if err := f.Parse(args); err != nil { + c.PrintCliError(err) + return base.CommandUserError + } + + if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { + c.PrintCliError(errors.New("ID is required but not passed in via -id")) + return base.CommandUserError + } + + var opts []managedgroups.Option + + if strutil.StrListContains(flagsMap[c.Func], "auth-method-id") { + switch c.Func { + case "list": + if c.FlagAuthMethodId == "" { + c.PrintCliError(errors.New("AuthMethod ID must be passed in via -auth-method-id or BOUNDARY_AUTH_METHOD_ID")) + return base.CommandUserError + } + } + } + + client, err := c.Client() + if err != nil { + c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error())) + return base.CommandCliError + } + managedgroupsClient := managedgroups.NewClient(client) + + switch c.FlagName { + case "": + case "null": + opts = append(opts, managedgroups.DefaultName()) + default: + opts = append(opts, managedgroups.WithName(c.FlagName)) + } + + switch c.FlagDescription { + case "": + case "null": + opts = append(opts, managedgroups.DefaultDescription()) + default: + opts = append(opts, managedgroups.WithDescription(c.FlagDescription)) + } + + if c.FlagFilter != "" { + opts = append(opts, managedgroups.WithFilter(c.FlagFilter)) + } + + var version uint32 + + if ok := extraFlagsHandlingFunc(c, f, &opts); !ok { + return base.CommandUserError + } + + var result api.GenericResult + + var listResult api.GenericListResult + + switch c.Func { + + case "read": + result, err = managedgroupsClient.Read(c.Context, c.FlagId, opts...) + + case "delete": + result, err = managedgroupsClient.Delete(c.Context, c.FlagId, opts...) + + case "list": + listResult, err = managedgroupsClient.List(c.Context, c.FlagAuthMethodId, opts...) + + } + + result, err = executeExtraActions(c, result, err, managedgroupsClient, version, opts) + + if err != nil { + if apiErr := api.AsServerError(err); apiErr != nil { + c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural)) + return base.CommandApiError + } + c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) + return base.CommandCliError + } + + output, err := printCustomActionOutput(c) + if err != nil { + c.PrintCliError(err) + return base.CommandUserError + } + if output { + return base.CommandSuccess + } + + switch c.Func { + + case "delete": + switch base.Format(c.UI) { + case "json": + if ok := c.PrintJsonItem(result); !ok { + return base.CommandCliError + } + + case "table": + c.UI.Output("The delete operation completed successfully.") + } + + return base.CommandSuccess + + case "list": + switch base.Format(c.UI) { + case "json": + if ok := c.PrintJsonItems(listResult); !ok { + return base.CommandCliError + } + + case "table": + listedItems := listResult.GetItems().([]*managedgroups.ManagedGroup) + c.UI.Output(c.printListTable(listedItems)) + } + + return base.CommandSuccess + + } + + switch base.Format(c.UI) { + case "table": + c.UI.Output(printItemTable(result)) + + case "json": + if ok := c.PrintJsonItem(result); !ok { + return base.CommandCliError + } + } + + return base.CommandSuccess +} + +var ( + flagsOnce = new(sync.Once) + + extraActionsFlagsMapFunc = func() map[string][]string { return nil } + extraSynopsisFunc = func(*Command) string { return "" } + extraFlagsFunc = func(*Command, *base.FlagSets, *base.FlagSet) {} + extraFlagsHandlingFunc = func(*Command, *base.FlagSets, *[]managedgroups.Option) bool { return true } + executeExtraActions = func(_ *Command, inResult api.GenericResult, inErr error, _ *managedgroups.Client, _ uint32, _ []managedgroups.Option) (api.GenericResult, error) { + return inResult, inErr + } + printCustomActionOutput = func(*Command) (bool, error) { return false, nil } +) diff --git a/internal/cmd/commands/managedgroupscmd/oidc_funcs.go b/internal/cmd/commands/managedgroupscmd/oidc_funcs.go new file mode 100644 index 000000000..a9f28de53 --- /dev/null +++ b/internal/cmd/commands/managedgroupscmd/oidc_funcs.go @@ -0,0 +1,95 @@ +package managedgroupscmd + +import ( + "fmt" + + "github.com/hashicorp/boundary/api/managedgroups" + "github.com/hashicorp/boundary/internal/cmd/base" + "github.com/hashicorp/go-bexpr" +) + +const ( + filterFlagName = "filter" +) + +func init() { + extraOidcFlagsFunc = extraOidcFlagsFuncImpl + extraOidcActionsFlagsMapFunc = extraOidcActionsFlagsMapFuncImpl + extraOidcFlagsHandlingFunc = extraOidcFlagsHandlingFuncImpl +} + +func extraOidcActionsFlagsMapFuncImpl() map[string][]string { + return map[string][]string{ + "create": {filterFlagName}, + "update": {filterFlagName}, + } +} + +type extraOidcCmdVars struct { + flagFilter string +} + +func (c *OidcCommand) extraOidcHelpFunc(helpMap map[string]func() string) string { + var helpStr string + switch c.Func { + case "create": + helpStr = base.WrapForHelpText([]string{ + "Usage: boundary managed-groups create oidc [options] [args]", + "", + " Create a oidc-type managed group. Example:", + "", + ` $ boundary managed-groups create oidc -filter '"/token/email" == "doe@example.com"' -description "Oidc managed group for ProdOps"`, + "", + "", + }) + + case "update": + helpStr = base.WrapForHelpText([]string{ + "Usage: boundary managed-groups update oidc [options] [args]", + "", + " Update a oidc-type managed group given its ID. Example:", + "", + ` $ boundary managed-groups update oidc -id acctoidc_1234567890 -name "devops" -description "Oidc managed group for DevOps"`, + "", + "", + }) + } + return helpStr + c.Flags().Help() +} + +func extraOidcFlagsFuncImpl(c *OidcCommand, _ *base.FlagSets, f *base.FlagSet) { + for _, name := range flagsOidcMap[c.Func] { + switch name { + case "filter": + f.StringVar(&base.StringVar{ + Name: filterFlagName, + Target: &c.flagFilter, + Usage: "The filter defining the criteria against which an accounts's OIDC token and/or userinfo will be evaluated to determined membership at login time.", + }) + } + } +} + +func extraOidcFlagsHandlingFuncImpl(c *OidcCommand, _ *base.FlagSets, opts *[]managedgroups.Option) bool { + switch c.flagFilter { + case "null": + c.UI.Error("Filter must be defined, and cannot be cleared.") + return false + + case "": + if c.Func == "create" { + c.UI.Error("The -filter flag must be provided when creating a managed group.") + return false + } + + default: + _, err := bexpr.CreateEvaluator(c.flagFilter) + if err != nil { + c.UI.Error(fmt.Sprintf("Error when parsing filter to check validity: %v", err)) + return false + } + *opts = append(*opts, managedgroups.WithAttributes(map[string]interface{}{filterFlagName: c.flagFilter})) + } + + return true +} diff --git a/internal/cmd/commands/managedgroupscmd/oidc_managedgroups.gen.go b/internal/cmd/commands/managedgroupscmd/oidc_managedgroups.gen.go new file mode 100644 index 000000000..98e04e911 --- /dev/null +++ b/internal/cmd/commands/managedgroupscmd/oidc_managedgroups.gen.go @@ -0,0 +1,239 @@ +// Code generated by "make api"; DO NOT EDIT. +package managedgroupscmd + +import ( + "errors" + "fmt" + + "github.com/hashicorp/boundary/api" + "github.com/hashicorp/boundary/api/managedgroups" + "github.com/hashicorp/boundary/internal/cmd/base" + "github.com/hashicorp/boundary/internal/cmd/common" + "github.com/hashicorp/boundary/sdk/strutil" + "github.com/mitchellh/cli" + "github.com/posener/complete" +) + +func initOidcFlags() { + flagsOnce.Do(func() { + extraFlags := extraOidcActionsFlagsMapFunc() + for k, v := range extraFlags { + flagsOidcMap[k] = append(flagsOidcMap[k], v...) + } + }) +} + +var ( + _ cli.Command = (*OidcCommand)(nil) + _ cli.CommandAutocomplete = (*OidcCommand)(nil) +) + +type OidcCommand struct { + *base.Command + + Func string + + plural string + + extraOidcCmdVars +} + +func (c *OidcCommand) AutocompleteArgs() complete.Predictor { + initOidcFlags() + return complete.PredictAnything +} + +func (c *OidcCommand) AutocompleteFlags() complete.Flags { + initOidcFlags() + return c.Flags().Completions() +} + +func (c *OidcCommand) Synopsis() string { + if extra := extraOidcSynopsisFunc(c); extra != "" { + return extra + } + + synopsisStr := "managed group" + + synopsisStr = fmt.Sprintf("%s %s", "oidc-type", synopsisStr) + + return common.SynopsisFunc(c.Func, synopsisStr) +} + +func (c *OidcCommand) Help() string { + initOidcFlags() + + var helpStr string + helpMap := common.HelpMap("managed group") + + switch c.Func { + default: + + helpStr = c.extraOidcHelpFunc(helpMap) + } + + // Keep linter from complaining if we don't actually generate code using it + _ = helpMap + return helpStr +} + +var flagsOidcMap = map[string][]string{ + + "create": {"auth-method-id", "name", "description"}, + + "update": {"id", "name", "description", "version"}, +} + +func (c *OidcCommand) Flags() *base.FlagSets { + if len(flagsOidcMap[c.Func]) == 0 { + return c.FlagSet(base.FlagSetNone) + } + + set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) + f := set.NewFlagSet("Command Options") + common.PopulateCommonFlags(c.Command, f, "oidc-type managed group", flagsOidcMap, c.Func) + + extraOidcFlagsFunc(c, set, f) + + return set +} + +func (c *OidcCommand) Run(args []string) int { + initOidcFlags() + + switch c.Func { + case "": + return cli.RunResultHelp + } + + c.plural = "oidc-type managed group" + switch c.Func { + case "list": + c.plural = "oidc-type managed groups" + } + + f := c.Flags() + + if err := f.Parse(args); err != nil { + c.PrintCliError(err) + return base.CommandUserError + } + + if strutil.StrListContains(flagsOidcMap[c.Func], "id") && c.FlagId == "" { + c.PrintCliError(errors.New("ID is required but not passed in via -id")) + return base.CommandUserError + } + + var opts []managedgroups.Option + + if strutil.StrListContains(flagsOidcMap[c.Func], "auth-method-id") { + switch c.Func { + case "create": + if c.FlagAuthMethodId == "" { + c.PrintCliError(errors.New("AuthMethod ID must be passed in via -auth-method-id or BOUNDARY_AUTH_METHOD_ID")) + return base.CommandUserError + } + } + } + + client, err := c.Client() + if err != nil { + c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error())) + return base.CommandCliError + } + managedgroupsClient := managedgroups.NewClient(client) + + switch c.FlagName { + case "": + case "null": + opts = append(opts, managedgroups.DefaultName()) + default: + opts = append(opts, managedgroups.WithName(c.FlagName)) + } + + switch c.FlagDescription { + case "": + case "null": + opts = append(opts, managedgroups.DefaultDescription()) + default: + opts = append(opts, managedgroups.WithDescription(c.FlagDescription)) + } + + if c.FlagFilter != "" { + opts = append(opts, managedgroups.WithFilter(c.FlagFilter)) + } + + var version uint32 + + switch c.Func { + case "update": + switch c.FlagVersion { + case 0: + opts = append(opts, managedgroups.WithAutomaticVersioning(true)) + default: + version = uint32(c.FlagVersion) + } + } + + if ok := extraOidcFlagsHandlingFunc(c, f, &opts); !ok { + return base.CommandUserError + } + + var result api.GenericResult + + switch c.Func { + + case "create": + result, err = managedgroupsClient.Create(c.Context, c.FlagAuthMethodId, opts...) + + case "update": + result, err = managedgroupsClient.Update(c.Context, c.FlagId, version, opts...) + + } + + result, err = executeExtraOidcActions(c, result, err, managedgroupsClient, version, opts) + + if err != nil { + if apiErr := api.AsServerError(err); apiErr != nil { + c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural)) + return base.CommandApiError + } + c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) + return base.CommandCliError + } + + output, err := printCustomOidcActionOutput(c) + if err != nil { + c.PrintCliError(err) + return base.CommandUserError + } + if output { + return base.CommandSuccess + } + + switch c.Func { + } + + switch base.Format(c.UI) { + case "table": + c.UI.Output(printItemTable(result)) + + case "json": + if ok := c.PrintJsonItem(result); !ok { + return base.CommandCliError + } + } + + return base.CommandSuccess +} + +var ( + extraOidcActionsFlagsMapFunc = func() map[string][]string { return nil } + extraOidcSynopsisFunc = func(*OidcCommand) string { return "" } + extraOidcFlagsFunc = func(*OidcCommand, *base.FlagSets, *base.FlagSet) {} + extraOidcFlagsHandlingFunc = func(*OidcCommand, *base.FlagSets, *[]managedgroups.Option) bool { return true } + executeExtraOidcActions = func(_ *OidcCommand, inResult api.GenericResult, inErr error, _ *managedgroups.Client, _ uint32, _ []managedgroups.Option) (api.GenericResult, error) { + return inResult, inErr + } + printCustomOidcActionOutput = func(*OidcCommand) (bool, error) { return false, nil } +) diff --git a/internal/cmd/commands/rolescmd/roles.gen.go b/internal/cmd/commands/rolescmd/roles.gen.go index 23a867c2a..1db46b122 100644 --- a/internal/cmd/commands/rolescmd/roles.gen.go +++ b/internal/cmd/commands/rolescmd/roles.gen.go @@ -113,7 +113,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "role", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "role", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/scopescmd/scopes.gen.go b/internal/cmd/commands/scopescmd/scopes.gen.go index b3250749f..5fab8d26d 100644 --- a/internal/cmd/commands/scopescmd/scopes.gen.go +++ b/internal/cmd/commands/scopescmd/scopes.gen.go @@ -113,7 +113,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "scope", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "scope", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/server/server_test.go b/internal/cmd/commands/server/server_test.go index 91372adad..0f6f23a51 100644 --- a/internal/cmd/commands/server/server_test.go +++ b/internal/cmd/commands/server/server_test.go @@ -36,8 +36,7 @@ func testServerCommand(t *testing.T, controllerKey string) *Command { require.NoError(err) require.NoError(cmd.SetupKMSes(cmd.UI, parsedKmsConfig)) - opts := base.WithContainerImage("postgres") - err = cmd.CreateDevDatabase(cmd.Context, opts) + err = cmd.CreateDevDatabase(cmd.Context, base.WithContainerImage("postgres"), base.WithSkipOidcAuthMethodCreation()) if err != nil { if cmd.DevDatabaseCleanupFunc != nil { require.NoError(cmd.DevDatabaseCleanupFunc()) diff --git a/internal/cmd/commands/sessionscmd/sessions.gen.go b/internal/cmd/commands/sessionscmd/sessions.gen.go index 3bec0714a..78fca6392 100644 --- a/internal/cmd/commands/sessionscmd/sessions.gen.go +++ b/internal/cmd/commands/sessionscmd/sessions.gen.go @@ -96,7 +96,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "session", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "session", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/targetscmd/targets.gen.go b/internal/cmd/commands/targetscmd/targets.gen.go index 4bb13c3df..97e4a14f5 100644 --- a/internal/cmd/commands/targetscmd/targets.gen.go +++ b/internal/cmd/commands/targetscmd/targets.gen.go @@ -104,7 +104,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "target", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "target", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/targetscmd/tcp_targets.gen.go b/internal/cmd/commands/targetscmd/tcp_targets.gen.go index 34d045239..fda35bbe8 100644 --- a/internal/cmd/commands/targetscmd/tcp_targets.gen.go +++ b/internal/cmd/commands/targetscmd/tcp_targets.gen.go @@ -91,7 +91,7 @@ func (c *TcpCommand) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "tcp-type target", flagsTcpMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "tcp-type target", flagsTcpMap, c.Func) extraTcpFlagsFunc(c, set, f) diff --git a/internal/cmd/commands/userscmd/users.gen.go b/internal/cmd/commands/userscmd/users.gen.go index 439037690..7650d389f 100644 --- a/internal/cmd/commands/userscmd/users.gen.go +++ b/internal/cmd/commands/userscmd/users.gen.go @@ -113,7 +113,7 @@ func (c *Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "user", flagsMap[c.Func]) + common.PopulateCommonFlags(c.Command, f, "user", flagsMap, c.Func) extraFlagsFunc(c, set, f) diff --git a/internal/cmd/common/flags.go b/internal/cmd/common/flags.go index 693a2bd6a..d2977f74d 100644 --- a/internal/cmd/common/flags.go +++ b/internal/cmd/common/flags.go @@ -7,8 +7,8 @@ import ( "github.com/posener/complete" ) -func PopulateCommonFlags(c *base.Command, f *base.FlagSet, resourceType string, flagNames []string) { - for _, name := range flagNames { +func PopulateCommonFlags(c *base.Command, f *base.FlagSet, resourceType string, flagNames map[string][]string, command string) { + for _, name := range flagNames[command] { switch name { case "scope-id": f.StringVar(&base.StringVar{ @@ -71,12 +71,18 @@ func PopulateCommonFlags(c *base.Command, f *base.FlagSet, resourceType string, Target: &c.FlagRecursive, Usage: "If set, the list operation will be applied recursively into child scopes, if supported by the type.", }) - case "filter": - f.StringVar(&base.StringVar{ - Name: "filter", - Target: &c.FlagFilter, - Usage: "If set, the list operation will be filtered before being returned. The filter operates against each item in the list. Using single quotes is recommended as filters contain double quotes. See https://www.boundaryproject.io/docs/concepts/filtering/resource-listing for details.", - }) + } + } + if command == "list" { + for _, name := range flagNames[command] { + switch name { + case "filter": + f.StringVar(&base.StringVar{ + Name: "filter", + Target: &c.FlagFilter, + Usage: "If set, the list operation will be filtered before being returned. The filter operates against each item in the list. Using single quotes is recommended as filters contain double quotes. See https://www.boundaryproject.io/docs/concepts/filtering/resource-listing for details.", + }) + } } } } diff --git a/internal/cmd/gencli/input.go b/internal/cmd/gencli/input.go index 88edb129c..9b902d53e 100644 --- a/internal/cmd/gencli/input.go +++ b/internal/cmd/gencli/input.go @@ -251,6 +251,32 @@ var inputStructs = map[string][]*cmdInfo{ VersionedActions: []string{"update"}, }, }, + "managedgroups": { + { + ResourceType: resource.ManagedGroup.String(), + Pkg: "managedgroups", + StdActions: []string{"read", "delete", "list"}, + IsAbstractType: true, + Container: "AuthMethod", + HasId: true, + HasName: true, + HasDescription: true, + }, + { + ResourceType: resource.ManagedGroup.String(), + Pkg: "managedgroups", + StdActions: []string{"create", "update"}, + SubActionPrefix: "oidc", + HasExtraCommandVars: true, + SkipNormalHelp: true, + HasExtraHelpFunc: true, + HasId: true, + HasName: true, + Container: "AuthMethod", + HasDescription: true, + VersionedActions: []string{"update"}, + }, + }, "roles": { { ResourceType: resource.Role.String(), diff --git a/internal/cmd/gencli/templates.go b/internal/cmd/gencli/templates.go index b417d50ff..63a7ef8ce 100644 --- a/internal/cmd/gencli/templates.go +++ b/internal/cmd/gencli/templates.go @@ -195,7 +195,7 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Flags() *base.FlagSets { set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat) f := set.NewFlagSet("Command Options") - common.PopulateCommonFlags(c.Command, f, "{{ if .SubActionPrefix }}{{ .SubActionPrefix }}-type {{ end }}{{ lowerSpaceCase .ResourceType }}", flags{{ camelCase .SubActionPrefix }}Map[c.Func]) + common.PopulateCommonFlags(c.Command, f, "{{ if .SubActionPrefix }}{{ .SubActionPrefix }}-type {{ end }}{{ lowerSpaceCase .ResourceType }}", flags{{ camelCase .SubActionPrefix }}Map, c.Func) extra{{ camelCase .SubActionPrefix }}FlagsFunc(c, set, f) diff --git a/internal/db/schema/migrations/postgres/0/06_iam.up.sql b/internal/db/schema/migrations/postgres/0/06_iam.up.sql index 10b32924b..3ab5438b5 100644 --- a/internal/db/schema/migrations/postgres/0/06_iam.up.sql +++ b/internal/db/schema/migrations/postgres/0/06_iam.up.sql @@ -565,6 +565,7 @@ $$ language plpgsql; -- iam_principle_role provides a consolidated view all principal roles assigned -- (user and group roles). +-- REPLACED in 9/04_oidc_managed_group_principal_role create view iam_principal_role as select ur.create_time, @@ -672,7 +673,7 @@ before insert on iam_group_member_user for each row execute procedure recovery_user_not_allowed('member_id'); --- get_scoped_principal_id is used by the iam_group_member view as a convient +-- get_scoped_member_id is used by the iam_group_member view as a convient -- way to create : to reference members from -- other scopes than the group's scope. create or replace function get_scoped_member_id(group_scope text, member_scope text, member_id text) returns text diff --git a/internal/db/schema/migrations/postgres/9/01_managed_groups.up.sql b/internal/db/schema/migrations/postgres/9/01_managed_groups.up.sql new file mode 100644 index 000000000..de1eb1319 --- /dev/null +++ b/internal/db/schema/migrations/postgres/9/01_managed_groups.up.sql @@ -0,0 +1,60 @@ +begin; + +-- The base abstract table +create table auth_managed_group ( + public_id wt_public_id + primary key, + auth_method_id wt_public_id + not null, + -- Ensure that if the auth method is deleted (which will also happen if the + -- scope is deleted) this is deleted too + constraint auth_method_fkey + foreign key (auth_method_id) -- fk1 + references auth_method(public_id) + on delete cascade + on update cascade, + constraint auth_managed_group_auth_method_id_public_id_uq + unique(auth_method_id, public_id) +); +comment on table auth_managed_group is +'auth_managed_group is the abstract base table for managed groups.'; + +-- Define the immutable fields of auth_managed_group +create trigger + immutable_columns +before +update on auth_managed_group + for each row execute procedure immutable_columns('public_id', 'auth_method_id'); + +-- Function to insert into the base table when values are inserted into a +-- concrete type table. This happens before inserts so the foreign keys in the +-- concrete type will be valid. +create or replace function + insert_managed_group_subtype() + returns trigger +as $$ +begin + + insert into auth_managed_group + (public_id, auth_method_id) + values + (new.public_id, new.auth_method_id); + + return new; + +end; +$$ language plpgsql; + +-- delete_managed_group_subtype() is an after delete trigger +-- function for subtypes of managed_group +create or replace function delete_managed_group_subtype() + returns trigger +as $$ +begin + delete from auth_managed_group + where public_id = old.public_id; + return null; -- result is ignored since this is an after trigger +end; +$$ language plpgsql; + +commit; diff --git a/internal/db/schema/migrations/postgres/9/02_oidc_managed_group.up.sql b/internal/db/schema/migrations/postgres/9/02_oidc_managed_group.up.sql new file mode 100644 index 000000000..49b579d79 --- /dev/null +++ b/internal/db/schema/migrations/postgres/9/02_oidc_managed_group.up.sql @@ -0,0 +1,83 @@ +begin; + +create table auth_oidc_managed_group ( + public_id wt_public_id + primary key, + auth_method_id wt_public_id + not null, + name wt_name, + description wt_description, + create_time wt_timestamp, + update_time wt_timestamp, + version wt_version, + filter wt_bexprfilter + not null, + -- Ensure that this managed group relates to an oidc auth method, as opposed + -- to other types + constraint auth_oidc_method_fkey + foreign key (auth_method_id) -- fk1 + references auth_oidc_method (public_id) + on delete cascade + on update cascade, + -- Ensure it relates to an abstract managed group + constraint auth_managed_group_fkey + foreign key (auth_method_id, public_id) -- fk2 + references auth_managed_group (auth_method_id, public_id) + on delete cascade + on update cascade, + constraint auth_oidc_managed_group_auth_method_id_name_uq + unique(auth_method_id, name) +); +comment on table auth_oidc_managed_group is +'auth_oidc_managed_group entries are subtypes of auth_managed_group and represent an oidc managed group.'; + +-- Define the immutable fields of auth_oidc_managed_group +create trigger + immutable_columns +before +update on auth_oidc_managed_group + for each row execute procedure immutable_columns('public_id', 'auth_method_id', 'create_time'); + +-- Populate create time on insert +create trigger + default_create_time_column +before +insert on auth_oidc_managed_group + for each row execute procedure default_create_time(); + +-- Generate update time on update +create trigger + update_time_column +before +update on auth_oidc_managed_group + for each row execute procedure update_time_column(); + +-- Update version when something changes +create trigger + update_version_column +after +update on auth_oidc_managed_group + for each row execute procedure update_version_column(); + +-- Add into the base table when inserting into the concrete table +create trigger + insert_managed_group_subtype +before insert on auth_oidc_managed_group + for each row execute procedure insert_managed_group_subtype(); + +-- Ensure that deletions in the oidc subtype result in deletions to the base +-- table. +create trigger + delete_managed_group_subtype +after +delete on auth_oidc_managed_group + for each row execute procedure delete_managed_group_subtype(); + +-- The tickets for oplog are the subtypes not the base types because no updates +-- are done to any values in the base types. +insert into oplog_ticket + (name, version) +values + ('auth_oidc_managed_group', 1); + +commit; diff --git a/internal/db/schema/migrations/postgres/9/03_oidc_managed_group_member.up.sql b/internal/db/schema/migrations/postgres/9/03_oidc_managed_group_member.up.sql new file mode 100644 index 000000000..a173dc14a --- /dev/null +++ b/internal/db/schema/migrations/postgres/9/03_oidc_managed_group_member.up.sql @@ -0,0 +1,52 @@ +begin; + +-- Mappings of account to oidc managed groups. This is a non-abstract table with +-- a view (below) so that it is a natural aggregate for the oplog (also below). +create table auth_oidc_managed_group_member_account ( + create_time wt_timestamp, + managed_group_id wt_public_id + references auth_oidc_managed_group(public_id) + on delete cascade + on update cascade, + member_id wt_public_id + references auth_oidc_account(public_id) + on delete cascade + on update cascade, + primary key (managed_group_id, member_id) +); +comment on table auth_oidc_managed_group_member_account is +'auth_oidc_managed_group_member_account is the join table for managed oidc groups and accounts.'; + +-- auth_immutable_managed_oidc_group_member_account() ensures that group members are immutable. +create or replace function + auth_immutable_managed_oidc_group_member_account() + returns trigger +as $$ +begin + raise exception 'managed oidc group members are immutable'; +end; +$$ language plpgsql; + +create trigger + default_create_time_column +before +insert on auth_oidc_managed_group_member_account + for each row execute procedure default_create_time(); + +create trigger + auth_immutable_managed_oidc_group_member_account +before +update on auth_oidc_managed_group_member_account + for each row execute procedure auth_immutable_managed_oidc_group_member_account(); + +-- Initially create the view with just oidc; eventually we can replace this view +-- to union with other subtype tables. +create view auth_managed_group_member_account as +select + oidc.create_time, + oidc.managed_group_id, + oidc.member_id +from + auth_oidc_managed_group_member_account oidc; + +commit; diff --git a/internal/db/schema/migrations/postgres/9/04_oidc_managed_group_principal_role.up.sql b/internal/db/schema/migrations/postgres/9/04_oidc_managed_group_principal_role.up.sql new file mode 100644 index 000000000..810cc955c --- /dev/null +++ b/internal/db/schema/migrations/postgres/9/04_oidc_managed_group_principal_role.up.sql @@ -0,0 +1,79 @@ +begin; + +-- iam_managed_group_role contains roles that have been assigned to managed +-- groups. Managed groups can be from any scope. The rows in this table must be +-- immutable after insert, which will be ensured with a before update trigger +-- using iam_immutable_role_principal(). +create table iam_managed_group_role ( + create_time wt_timestamp, + role_id wt_role_id + references iam_role(public_id) + on delete cascade + on update cascade, + principal_id wt_public_id + references auth_managed_group(public_id) + on delete cascade + on update cascade, + primary key (role_id, principal_id) + ); + +create trigger immutable_role_principal +before update on iam_managed_group_role + for each row execute procedure iam_immutable_role_principal(); + +create trigger default_create_time_column +before insert on iam_managed_group_role + for each row execute procedure default_create_time(); + +-- iam_principal_role provides a consolidated view all principal roles assigned +-- (user and group roles). +create or replace view iam_principal_role as +select + ur.create_time, + ur.principal_id, + ur.role_id, + u.scope_id as principal_scope_id, + r.scope_id as role_scope_id, + get_scoped_principal_id(r.scope_id, u.scope_id, ur.principal_id) as scoped_principal_id, + 'user' as type +from + iam_user_role ur, + iam_role r, + iam_user u +where + ur.role_id = r.public_id and + u.public_id = ur.principal_id +union +select + gr.create_time, + gr.principal_id, + gr.role_id, + g.scope_id as principal_scope_id, + r.scope_id as role_scope_id, + get_scoped_principal_id(r.scope_id, g.scope_id, gr.principal_id) as scoped_principal_id, + 'group' as type +from + iam_group_role gr, + iam_role r, + iam_group g +where + gr.role_id = r.public_id and + g.public_id = gr.principal_id +union +select + mgr.create_time, + mgr.principal_id, + mgr.role_id, + (select scope_id from auth_method am where am.public_id = amg.auth_method_id) as principal_scope_id, + r.scope_id as role_scope_id, + get_scoped_principal_id(r.scope_id, (select scope_id from auth_method am where am.public_id = amg.auth_method_id), mgr.principal_id) as scoped_principal_id, + 'managed group' as type +from + iam_managed_group_role mgr, + iam_role r, + auth_managed_group amg +where + mgr.role_id = r.public_id and + amg.public_id = mgr.principal_id; + +commit; diff --git a/internal/db/schema/migrations/postgres/9/managed_group_test.go b/internal/db/schema/migrations/postgres/9/managed_group_test.go new file mode 100644 index 000000000..b6060519a --- /dev/null +++ b/internal/db/schema/migrations/postgres/9/managed_group_test.go @@ -0,0 +1,376 @@ +package migration + +import ( + "fmt" + "testing" + "time" + + "github.com/hashicorp/boundary/internal/servers/controller" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_ManagedGroupTable(t *testing.T) { + t.Parallel() + tc := controller.NewTestController(t, nil) + defer tc.Shutdown() + + db := tc.DbConn().DB() + var err error + + managedGroupId := "a_bcdefghijk" + defaultPasswordAuthMethodId := "ampw_1234567890" + defaultOidcAuthMethodId := "amoidc_1234567890" + + insertTests := []struct { + testName string + publicId string + authMethodId string + wantErr bool + }{ + { + testName: "invalid auth method", + publicId: managedGroupId, + authMethodId: "amoid_1234567890", + wantErr: true, + }, + { + testName: "valid", + publicId: managedGroupId, + authMethodId: defaultOidcAuthMethodId, + wantErr: false, + }, + } + for _, tt := range insertTests { + t.Run("insert: "+tt.testName, func(t *testing.T) { + require := require.New(t) + _, err = db.Exec("insert into auth_managed_group values ($1, $2)", + tt.publicId, + tt.authMethodId) + require.True(tt.wantErr == (err != nil)) + }) + } + + updateTests := []struct { + testName string + column string + value string + publicId string + wantErr bool + }{ + { + testName: "immutable public id", + column: "public_id", + value: "z_yxwvutsrqp", + publicId: managedGroupId, + wantErr: true, + }, + { + testName: "immutable auth method", + column: "auth_method_id", + value: defaultPasswordAuthMethodId, + publicId: managedGroupId, + wantErr: true, + }, + } + for _, tt := range updateTests { + t.Run("update: "+tt.testName, func(t *testing.T) { + assert := assert.New(t) + _, err = db.Exec(fmt.Sprintf("update auth_managed_group set %s = $1 where public_id = $2", tt.column), tt.value, tt.publicId) + assert.True(tt.wantErr == (err != nil)) + }) + } +} + +func Test_OidcManagedGroupTable(t *testing.T) { + t.Parallel() + tc := controller.NewTestController(t, nil) + defer tc.Shutdown() + + db := tc.DbConn().DB() + var err error + + managedGroupId := "a_bcdefghijk" + defaultPasswordAuthMethodId := "ampw_1234567890" + defaultOidcAuthMethodId := "amoidc_1234567890" + name := "this is the name" + filter := "this is a filter" + + // The first set of tests is for initial insertion + { + insertTests := []struct { + testName string + publicId string + authMethodId string + name string + filter string + wantErr bool + }{ + { + testName: "null filter", + publicId: managedGroupId, + authMethodId: "amoid_1234567890", + name: name, + filter: "", + wantErr: true, + }, + { + testName: "invalid auth method", + publicId: managedGroupId, + authMethodId: defaultPasswordAuthMethodId, + name: name, + filter: filter, + wantErr: true, + }, + { + testName: "valid", + publicId: managedGroupId, + authMethodId: defaultOidcAuthMethodId, + name: name, + filter: filter, + wantErr: false, + }, + { + testName: "duplicate public id", + publicId: managedGroupId, + authMethodId: defaultOidcAuthMethodId, + name: name, + filter: filter, + wantErr: true, + }, + { + testName: "duplicate name", + publicId: "z_yxwvutsrqp", + authMethodId: defaultOidcAuthMethodId, + name: name, + filter: filter, + wantErr: true, + }, + } + for _, tt := range insertTests { + t.Run("insert: "+tt.testName, func(t *testing.T) { + require := require.New(t) + _, err = db.Exec("insert into auth_oidc_managed_group (public_id, auth_method_id, name, filter) values ($1, $2, $3, $4)", + tt.publicId, + tt.authMethodId, + tt.name, + tt.filter) + require.True(tt.wantErr == (err != nil)) + }) + } + } + + // Read some values to validate that things were set automatically + rows, err := db.Query("select create_time, update_time, version from auth_oidc_managed_group") + require.NoError(t, err) + require.True(t, rows.Next()) + var create_time, update_time time.Time + var version int + require.NoError(t, rows.Scan(&create_time, &update_time, &version)) + assert.False(t, create_time.IsZero()) + assert.Equal(t, update_time, create_time) + assert.Equal(t, 1, version) + + // These update tests check immutability + { + updateTests := []struct { + testName string + column string + value interface{} + wantErr bool + }{ + { + testName: "immutable public id", + column: "public_id", + value: "z_yxwvutsrqp", + wantErr: true, + }, + { + testName: "immutable auth method", + column: "auth_method_id", + value: defaultPasswordAuthMethodId, + wantErr: true, + }, + { + testName: "immutable creation time", + column: "create_time", + value: time.Now(), + wantErr: true, + }, + { + testName: "valid", + column: "description", + value: "this is the description", + wantErr: false, + }, + } + for _, tt := range updateTests { + t.Run("update: "+tt.testName, func(t *testing.T) { + require := require.New(t) + _, err = db.Exec(fmt.Sprintf("update auth_oidc_managed_group set %s = $1 where public_id = $2", tt.column), tt.value, managedGroupId) + require.True(tt.wantErr == (err != nil)) + }) + } + } + + // Read values again to validate that things were updated automatically + rows, err = db.Query("select create_time, update_time, version from auth_oidc_managed_group") + require.NoError(t, err) + require.True(t, rows.Next()) + var updated_create_time, updated_update_time time.Time + require.NoError(t, rows.Scan(&updated_create_time, &updated_update_time, &version)) + assert.Equal(t, create_time, updated_create_time) + assert.NotEqual(t, update_time, updated_update_time) + assert.Equal(t, 2, version) + + // Read values from auth_managed_group to ensure it was populated automatically + rows, err = db.Query("select public_id, auth_method_id from auth_managed_group") + require.NoError(t, err) + require.True(t, rows.Next()) + var public_id, auth_method_id string + require.NoError(t, rows.Scan(&public_id, &auth_method_id)) + assert.Equal(t, managedGroupId, public_id) + assert.Equal(t, defaultOidcAuthMethodId, auth_method_id) + + // Delete the value from the subtype table + res, err := db.Exec("delete from auth_oidc_managed_group where public_id = $1", managedGroupId) + require.NoError(t, err) + affected, err := res.RowsAffected() + require.NoError(t, err) + require.EqualValues(t, 1, affected) + + // It should no longer be in the base table + rows, err = db.Query("select public_id, auth_method_id from auth_managed_group") + require.NoError(t, err) + require.False(t, rows.Next()) +} + +func Test_AuthManagedOidcGroupMemberAccountTable(t *testing.T) { + t.Parallel() + tc := controller.NewTestController(t, nil) + defer tc.Shutdown() + + db := tc.DbConn().DB() + var err error + + managedGroupId := "a_bcdefghijk" + defaultOidcAuthMethodId := "amoidc_1234567890" + name := "this is the name" + filter := "this is a filter" + + // Insert valid data in auth_oidc_managed_group to use for the following tests + _, err = db.Exec("insert into auth_oidc_managed_group (public_id, auth_method_id, name, filter) values ($1, $2, $3, $4)", + managedGroupId, + defaultOidcAuthMethodId, + name, + filter) + require.NoError(t, err) + + // Fetch a valid (oidc) account ID to use in insertion + rows, err := db.Query("select public_id from auth_oidc_account limit 1") + require.NoError(t, err) + require.True(t, rows.Next()) + var accountId string + require.NoError(t, rows.Scan(&accountId)) + require.NotEmpty(t, accountId) + + // The first set of tests is for initial insertion + { + insertTests := []struct { + testName string + managedGroupId string + memberId string + wantErr bool + }{ + { + testName: "invalid managed group id", + managedGroupId: "z_yxwvutsrqp", + memberId: accountId, + wantErr: true, + }, + { + testName: "invalid member id", + managedGroupId: managedGroupId, + memberId: "acct_1234567890", + wantErr: true, + }, + { + testName: "valid", + managedGroupId: managedGroupId, + memberId: accountId, + wantErr: false, + }, + { + testName: "duplicate values", + managedGroupId: managedGroupId, + memberId: accountId, + wantErr: true, + }, + } + for _, tt := range insertTests { + t.Run("insert: "+tt.testName, func(t *testing.T) { + assert := assert.New(t) + _, err = db.Exec("insert into auth_oidc_managed_group_member_account (managed_group_id, member_id) values ($1, $2)", + tt.managedGroupId, + tt.memberId) + assert.True(tt.wantErr == (err != nil)) + }) + } + } + + // Read some values to validate that things were set automatically + rows, err = db.Query("select create_time, managed_group_id, member_id from auth_oidc_managed_group_member_account") + require.NoError(t, err) + require.True(t, rows.Next()) + var create_time time.Time + var managed_group_id, member_id string + require.NoError(t, rows.Scan(&create_time, &managed_group_id, &member_id)) + assert.False(t, create_time.IsZero()) + + // These update tests check immutability + { + updateTests := []struct { + testName string + column string + value interface{} + wantErr bool + }{ + { + testName: "immutable managed group id", + column: "managed_group_id", + value: "z_yxwvutsrqp", + wantErr: true, + }, + { + testName: "immutable member_id", + column: "member_id", + value: "acct_1234567890", + wantErr: true, + }, + { + testName: "immutable creation time", + column: "create_time", + value: time.Now(), + wantErr: true, + }, + } + for _, tt := range updateTests { + t.Run("update: "+tt.testName, func(t *testing.T) { + assert := assert.New(t) + _, err = db.Exec(fmt.Sprintf("update auth_managed_group_member_account set %s = $1 where managed_group_id = $2 and member_id = $3", tt.column), managedGroupId, accountId) + assert.True(tt.wantErr == (err != nil)) + }) + } + } + + // Read from the view to ensure we see it there + rows, err = db.Query("select create_time, managed_group_id, member_id from auth_managed_group_member_account") + require.NoError(t, err) + require.True(t, rows.Next()) + var view_create_time time.Time + var view_managed_group_id, view_member_id string + require.NoError(t, rows.Scan(&view_create_time, &view_managed_group_id, &view_member_id)) + assert.Equal(t, create_time, view_create_time) + assert.Equal(t, managed_group_id, view_managed_group_id) + assert.Equal(t, member_id, view_member_id) +} diff --git a/internal/db/schema/postgres_migration.gen.go b/internal/db/schema/postgres_migration.gen.go index 4d5db009b..44c899164 100644 --- a/internal/db/schema/postgres_migration.gen.go +++ b/internal/db/schema/postgres_migration.gen.go @@ -4,7 +4,7 @@ package schema func init() { migrationStates["postgres"] = migrationState{ - binarySchemaVersion: 8001, + binarySchemaVersion: 9004, upMigrations: map[int][]byte{ 1: []byte(` create domain wt_public_id as text @@ -966,6 +966,7 @@ $$ language plpgsql; -- iam_principle_role provides a consolidated view all principal roles assigned -- (user and group roles). +-- REPLACED in 9/04_oidc_managed_group_principal_role create view iam_principal_role as select ur.create_time, @@ -1073,7 +1074,7 @@ before insert on iam_group_member_user for each row execute procedure recovery_user_not_allowed('member_id'); --- get_scoped_principal_id is used by the iam_group_member view as a convient +-- get_scoped_member_id is used by the iam_group_member view as a convient -- way to create : to reference members from -- other scopes than the group's scope. create or replace function get_scoped_member_id(group_scope text, member_scope text, member_id text) returns text @@ -6373,6 +6374,272 @@ from session s where sc.session_id = s.public_id; +`), + 9001: []byte(` +-- The base abstract table +create table auth_managed_group ( + public_id wt_public_id + primary key, + auth_method_id wt_public_id + not null, + -- Ensure that if the auth method is deleted (which will also happen if the + -- scope is deleted) this is deleted too + constraint auth_method_fkey + foreign key (auth_method_id) -- fk1 + references auth_method(public_id) + on delete cascade + on update cascade, + constraint auth_managed_group_auth_method_id_public_id_uq + unique(auth_method_id, public_id) +); +comment on table auth_managed_group is +'auth_managed_group is the abstract base table for managed groups.'; + +-- Define the immutable fields of auth_managed_group +create trigger + immutable_columns +before +update on auth_managed_group + for each row execute procedure immutable_columns('public_id', 'auth_method_id'); + +-- Function to insert into the base table when values are inserted into a +-- concrete type table. This happens before inserts so the foreign keys in the +-- concrete type will be valid. +create or replace function + insert_managed_group_subtype() + returns trigger +as $$ +begin + + insert into auth_managed_group + (public_id, auth_method_id) + values + (new.public_id, new.auth_method_id); + + return new; + +end; +$$ language plpgsql; + +-- delete_managed_group_subtype() is an after delete trigger +-- function for subtypes of managed_group +create or replace function delete_managed_group_subtype() + returns trigger +as $$ +begin + delete from auth_managed_group + where public_id = old.public_id; + return null; -- result is ignored since this is an after trigger +end; +$$ language plpgsql; +`), + 9002: []byte(` +create table auth_oidc_managed_group ( + public_id wt_public_id + primary key, + auth_method_id wt_public_id + not null, + name wt_name, + description wt_description, + create_time wt_timestamp, + update_time wt_timestamp, + version wt_version, + filter wt_bexprfilter + not null, + -- Ensure that this managed group relates to an oidc auth method, as opposed + -- to other types + constraint auth_oidc_method_fkey + foreign key (auth_method_id) -- fk1 + references auth_oidc_method (public_id) + on delete cascade + on update cascade, + -- Ensure it relates to an abstract managed group + constraint auth_managed_group_fkey + foreign key (auth_method_id, public_id) -- fk2 + references auth_managed_group (auth_method_id, public_id) + on delete cascade + on update cascade, + constraint auth_oidc_managed_group_auth_method_id_name_uq + unique(auth_method_id, name) +); +comment on table auth_oidc_managed_group is +'auth_oidc_managed_group entries are subtypes of auth_managed_group and represent an oidc managed group.'; + +-- Define the immutable fields of auth_oidc_managed_group +create trigger + immutable_columns +before +update on auth_oidc_managed_group + for each row execute procedure immutable_columns('public_id', 'auth_method_id', 'create_time'); + +-- Populate create time on insert +create trigger + default_create_time_column +before +insert on auth_oidc_managed_group + for each row execute procedure default_create_time(); + +-- Generate update time on update +create trigger + update_time_column +before +update on auth_oidc_managed_group + for each row execute procedure update_time_column(); + +-- Update version when something changes +create trigger + update_version_column +after +update on auth_oidc_managed_group + for each row execute procedure update_version_column(); + +-- Add into the base table when inserting into the concrete table +create trigger + insert_managed_group_subtype +before insert on auth_oidc_managed_group + for each row execute procedure insert_managed_group_subtype(); + +-- Ensure that deletions in the oidc subtype result in deletions to the base +-- table. +create trigger + delete_managed_group_subtype +after +delete on auth_oidc_managed_group + for each row execute procedure delete_managed_group_subtype(); + +-- The tickets for oplog are the subtypes not the base types because no updates +-- are done to any values in the base types. +insert into oplog_ticket + (name, version) +values + ('auth_oidc_managed_group', 1); +`), + 9003: []byte(` +-- Mappings of account to oidc managed groups. This is a non-abstract table with +-- a view (below) so that it is a natural aggregate for the oplog (also below). +create table auth_oidc_managed_group_member_account ( + create_time wt_timestamp, + managed_group_id wt_public_id + references auth_oidc_managed_group(public_id) + on delete cascade + on update cascade, + member_id wt_public_id + references auth_oidc_account(public_id) + on delete cascade + on update cascade, + primary key (managed_group_id, member_id) +); +comment on table auth_oidc_managed_group_member_account is +'auth_oidc_managed_group_member_account is the join table for managed oidc groups and accounts.'; + +-- auth_immutable_managed_oidc_group_member_account() ensures that group members are immutable. +create or replace function + auth_immutable_managed_oidc_group_member_account() + returns trigger +as $$ +begin + raise exception 'managed oidc group members are immutable'; +end; +$$ language plpgsql; + +create trigger + default_create_time_column +before +insert on auth_oidc_managed_group_member_account + for each row execute procedure default_create_time(); + +create trigger + auth_immutable_managed_oidc_group_member_account +before +update on auth_oidc_managed_group_member_account + for each row execute procedure auth_immutable_managed_oidc_group_member_account(); + +-- Initially create the view with just oidc; eventually we can replace this view +-- to union with other subtype tables. +create view auth_managed_group_member_account as +select + oidc.create_time, + oidc.managed_group_id, + oidc.member_id +from + auth_oidc_managed_group_member_account oidc; +`), + 9004: []byte(` +-- iam_managed_group_role contains roles that have been assigned to managed +-- groups. Managed groups can be from any scope. The rows in this table must be +-- immutable after insert, which will be ensured with a before update trigger +-- using iam_immutable_role_principal(). +create table iam_managed_group_role ( + create_time wt_timestamp, + role_id wt_role_id + references iam_role(public_id) + on delete cascade + on update cascade, + principal_id wt_public_id + references auth_managed_group(public_id) + on delete cascade + on update cascade, + primary key (role_id, principal_id) + ); + +create trigger immutable_role_principal +before update on iam_managed_group_role + for each row execute procedure iam_immutable_role_principal(); + +create trigger default_create_time_column +before insert on iam_managed_group_role + for each row execute procedure default_create_time(); + +-- iam_principal_role provides a consolidated view all principal roles assigned +-- (user and group roles). +create or replace view iam_principal_role as +select + ur.create_time, + ur.principal_id, + ur.role_id, + u.scope_id as principal_scope_id, + r.scope_id as role_scope_id, + get_scoped_principal_id(r.scope_id, u.scope_id, ur.principal_id) as scoped_principal_id, + 'user' as type +from + iam_user_role ur, + iam_role r, + iam_user u +where + ur.role_id = r.public_id and + u.public_id = ur.principal_id +union +select + gr.create_time, + gr.principal_id, + gr.role_id, + g.scope_id as principal_scope_id, + r.scope_id as role_scope_id, + get_scoped_principal_id(r.scope_id, g.scope_id, gr.principal_id) as scoped_principal_id, + 'group' as type +from + iam_group_role gr, + iam_role r, + iam_group g +where + gr.role_id = r.public_id and + g.public_id = gr.principal_id +union +select + mgr.create_time, + mgr.principal_id, + mgr.role_id, + (select scope_id from auth_method am where am.public_id = amg.auth_method_id) as principal_scope_id, + r.scope_id as role_scope_id, + get_scoped_principal_id(r.scope_id, (select scope_id from auth_method am where am.public_id = amg.auth_method_id), mgr.principal_id) as scoped_principal_id, + 'managed group' as type +from + iam_managed_group_role mgr, + iam_role r, + auth_managed_group amg +where + mgr.role_id = r.public_id and + amg.public_id = mgr.principal_id; `), }, } diff --git a/internal/errors/code.go b/internal/errors/code.go index 89d515f88..b33fbc679 100644 --- a/internal/errors/code.go +++ b/internal/errors/code.go @@ -79,6 +79,11 @@ const ( MaxRetries Code = 1103 // MaxRetries represent that a db Tx hit max retires allowed Exception Code = 1104 // Exception represent that an underlying db exception was raised VersionMismatch Code = 1105 // VersionMismatch represents the update version and the db version for an entry do not match. + // GracefullyAborted means we intended to abort a transaction but the + // enclosing function should not treat it as an error; we aborted for + // reasons related to the state of the DDL and/or inputs (such as we're + // already in the right state and don't want to end up writing oplogs). + GracefullyAborted Code = 1106 // Migration setup errors are codes 2000-2999 MigrationIntegrity Code = 2000 // MigrationIntegrity represents an error with the generated migration related code diff --git a/internal/errors/code_test.go b/internal/errors/code_test.go index adb33dc62..3198f0a48 100644 --- a/internal/errors/code_test.go +++ b/internal/errors/code_test.go @@ -252,6 +252,11 @@ func TestCode_Both_String_Info(t *testing.T) { c: OidcProviderCallbackError, want: OidcProviderCallbackError, }, + { + name: "GracefullyAborted", + c: GracefullyAborted, + want: GracefullyAborted, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/errors/info.go b/internal/errors/info.go index 5b9351208..e96f141e9 100644 --- a/internal/errors/info.go +++ b/internal/errors/info.go @@ -196,4 +196,8 @@ var errorCodeInfo = map[Code]Info{ Message: "oidc provider callback error", Kind: External, }, + GracefullyAborted: { + Message: "purposefully aborted without error", + Kind: Other, + }, } diff --git a/internal/gen/controller.swagger.json b/internal/gen/controller.swagger.json index dc567010f..231bdbda2 100644 --- a/internal/gen/controller.swagger.json +++ b/internal/gen/controller.swagger.json @@ -29,6 +29,9 @@ { "name": "HostSetService" }, + { + "name": "ManagedGroupService" + }, { "name": "RoleService" }, @@ -1367,6 +1370,147 @@ ] } }, + "/v1/managed-groups": { + "get": { + "summary": "Lists all ManagedGroups in a specific Auth Method.", + "operationId": "ManagedGroupService_ListManagedGroups", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/controller.api.services.v1.ListManagedGroupsResponse" + } + } + }, + "parameters": [ + { + "name": "auth_method_id", + "in": "query", + "required": false, + "type": "string" + }, + { + "name": "filter", + "in": "query", + "required": false, + "type": "string" + } + ], + "tags": [ + "controller.api.services.v1.ManagedGroupService" + ] + }, + "post": { + "summary": "Creates a single ManagedGroup in the provided Auth Method.", + "operationId": "ManagedGroupService_CreateManagedGroup", + "responses": { + "200": { + "description": "", + "schema": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + }, + "parameters": [ + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + ], + "tags": [ + "controller.api.services.v1.ManagedGroupService" + ] + } + }, + "/v1/managed-groups/{id}": { + "get": { + "summary": "Gets a single ManagedGroup.", + "operationId": "ManagedGroupService_GetManagedGroup", + "responses": { + "200": { + "description": "", + "schema": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "type": "string" + } + ], + "tags": [ + "controller.api.services.v1.ManagedGroupService" + ] + }, + "delete": { + "summary": "Deletes a ManagedGroup.", + "operationId": "ManagedGroupService_DeleteManagedGroup", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/controller.api.services.v1.DeleteManagedGroupResponse" + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "type": "string" + } + ], + "tags": [ + "controller.api.services.v1.ManagedGroupService" + ] + }, + "patch": { + "summary": "Updates a ManagedGroup.", + "operationId": "ManagedGroupService_UpdateManagedGroup", + "responses": { + "200": { + "description": "", + "schema": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "type": "string" + }, + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + }, + { + "name": "update_mask", + "in": "query", + "required": false, + "type": "string" + } + ], + "tags": [ + "controller.api.services.v1.ManagedGroupService" + ] + } + }, "/v1/roles": { "get": { "summary": "Lists all Roles.", @@ -2544,6 +2688,14 @@ "type": "object", "description": "The attributes that are applicable for the specific Account type." }, + "managed_group_ids": { + "type": "array", + "items": { + "type": "string" + }, + "title": "Output only. managed_group_ids indicates IDs of the managed groups that currently contain this account", + "readOnly": true + }, "authorized_actions": { "type": "array", "items": { @@ -2998,6 +3150,75 @@ }, "title": "HostSet is a collection of Hosts created and managed by a Host Catalog" }, + "controller.api.resources.managedgroups.v1.ManagedGroup": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Output only. The ID of the ManagedGroup.", + "readOnly": true + }, + "scope": { + "$ref": "#/definitions/controller.api.resources.scopes.v1.ScopeInfo", + "description": "Output only. Scope information for the ManagedGroup.", + "readOnly": true + }, + "name": { + "type": "string", + "description": "Optional name for identification purposes." + }, + "description": { + "type": "string", + "description": "Optional user-set description for identification purposes." + }, + "created_time": { + "type": "string", + "format": "date-time", + "description": "Output only. The time this resource was created.", + "readOnly": true + }, + "updated_time": { + "type": "string", + "format": "date-time", + "description": "Output only. The time this resource was last updated.", + "readOnly": true + }, + "version": { + "type": "integer", + "format": "int64", + "description": "Version is used in mutation requests, after the initial creation, to ensure this resource has not changed.\nThe mutation will fail if the version does not match the latest known good version." + }, + "type": { + "type": "string", + "description": "The type of this ManagedGroup." + }, + "auth_method_id": { + "type": "string", + "description": "The ID of the Auth Method that is associated with this ManagedGroup." + }, + "attributes": { + "type": "object", + "description": "The attributes that are applicable for the specific ManagedGroup type." + }, + "member_ids": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Output only. The IDs of the current set of members (accounts) that are associated with this ManagedGroup.", + "readOnly": true + }, + "authorized_actions": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Output only. The available actions on this resource for this user.", + "readOnly": true + } + }, + "title": "ManagedGroup contains all fields related to an ManagedGroup resource" + }, "controller.api.resources.roles.v1.Grant": { "type": "object", "properties": { @@ -4067,6 +4288,17 @@ } } }, + "controller.api.services.v1.CreateManagedGroupResponse": { + "type": "object", + "properties": { + "uri": { + "type": "string" + }, + "item": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + }, "controller.api.services.v1.CreateRoleResponse": { "type": "object", "properties": { @@ -4132,6 +4364,9 @@ "controller.api.services.v1.DeleteHostSetResponse": { "type": "object" }, + "controller.api.services.v1.DeleteManagedGroupResponse": { + "type": "object" + }, "controller.api.services.v1.DeleteRoleResponse": { "type": "object" }, @@ -4200,6 +4435,14 @@ } } }, + "controller.api.services.v1.GetManagedGroupResponse": { + "type": "object", + "properties": { + "item": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + }, "controller.api.services.v1.GetRoleResponse": { "type": "object", "properties": { @@ -4317,6 +4560,17 @@ } } }, + "controller.api.services.v1.ListManagedGroupsResponse": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + } + }, "controller.api.services.v1.ListRolesResponse": { "type": "object", "properties": { @@ -4770,6 +5024,14 @@ } } }, + "controller.api.services.v1.UpdateManagedGroupResponse": { + "type": "object", + "properties": { + "item": { + "$ref": "#/definitions/controller.api.resources.managedgroups.v1.ManagedGroup" + } + } + }, "controller.api.services.v1.UpdateRoleResponse": { "type": "object", "properties": { diff --git a/internal/gen/controller/api/resources/accounts/account.pb.go b/internal/gen/controller/api/resources/accounts/account.pb.go index 85083d190..7f23c0d55 100644 --- a/internal/gen/controller/api/resources/accounts/account.pb.go +++ b/internal/gen/controller/api/resources/accounts/account.pb.go @@ -52,6 +52,8 @@ type Account struct { AuthMethodId string `protobuf:"bytes,90,opt,name=auth_method_id,proto3" json:"auth_method_id,omitempty"` // The attributes that are applicable for the specific Account type. Attributes *structpb.Struct `protobuf:"bytes,100,opt,name=attributes,proto3" json:"attributes,omitempty"` + // Output only. managed_group_ids indicates IDs of the managed groups that currently contain this account + ManagedGroupIds []string `protobuf:"bytes,110,rep,name=managed_group_ids,proto3" json:"managed_group_ids,omitempty"` // Output only. The available actions on this resource for this user. AuthorizedActions []string `protobuf:"bytes,300,rep,name=authorized_actions,proto3" json:"authorized_actions,omitempty"` } @@ -158,6 +160,13 @@ func (x *Account) GetAttributes() *structpb.Struct { return nil } +func (x *Account) GetManagedGroupIds() []string { + if x != nil { + return x.ManagedGroupIds + } + return nil +} + func (x *Account) GetAuthorizedActions() []string { if x != nil { return x.AuthorizedActions @@ -235,7 +244,7 @@ type OidcAccountAttributes struct { // subject is a case sensitive string that maps to the OIDC sub claim. // This value is immutable after creation time. Subject string `protobuf:"bytes,90,opt,name=subject,proto3" json:"subject,omitempty"` - // Output only. full_name is a string that maps to the OIDC name claim + // Output only. full_name is a string that maps to the OIDC name claim. FullName string `protobuf:"bytes,100,opt,name=full_name,proto3" json:"full_name,omitempty"` // Output only. email is a string that maps to the OIDC email claim. Email string `protobuf:"bytes,110,opt,name=email,proto3" json:"email,omitempty"` @@ -321,7 +330,7 @@ var file_controller_api_resources_accounts_v1_account_proto_rawDesc = []byte{ 0x6f, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xd0, 0x04, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xfe, 0x04, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x43, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, @@ -355,35 +364,38 @@ var file_controller_api_resources_accounts_v1_account_proto_rawDesc = []byte{ 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x64, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x04, 0xa0, 0xda, 0x29, 0x01, 0x52, 0x0a, 0x61, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x2f, 0x0a, 0x12, 0x61, 0x75, 0x74, 0x68, 0x6f, - 0x72, 0x69, 0x7a, 0x65, 0x64, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xac, 0x02, - 0x20, 0x03, 0x28, 0x09, 0x52, 0x12, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, - 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xa7, 0x01, 0x0a, 0x19, 0x50, 0x61, 0x73, - 0x73, 0x77, 0x6f, 0x72, 0x64, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x41, 0x74, 0x74, 0x72, - 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x4a, 0x0a, 0x0a, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x5f, - 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x42, 0x2a, 0xa0, 0xda, 0x29, 0x01, - 0xc2, 0xdd, 0x29, 0x22, 0x0a, 0x15, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, - 0x2e, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x09, 0x4c, 0x6f, 0x67, - 0x69, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x0a, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x5f, 0x6e, 0x61, - 0x6d, 0x65, 0x12, 0x3e, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x14, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x42, 0x04, 0xa0, 0xda, 0x29, 0x01, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, - 0x72, 0x64, 0x22, 0x89, 0x01, 0x0a, 0x15, 0x4f, 0x69, 0x64, 0x63, 0x41, 0x63, 0x63, 0x6f, 0x75, - 0x6e, 0x74, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x1c, 0x0a, 0x06, - 0x69, 0x73, 0x73, 0x75, 0x65, 0x72, 0x18, 0x50, 0x20, 0x01, 0x28, 0x09, 0x42, 0x04, 0xa0, 0xda, - 0x29, 0x01, 0x52, 0x06, 0x69, 0x73, 0x73, 0x75, 0x65, 0x72, 0x12, 0x1e, 0x0a, 0x07, 0x73, 0x75, - 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x5a, 0x20, 0x01, 0x28, 0x09, 0x42, 0x04, 0xa0, 0xda, 0x29, - 0x01, 0x52, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x66, 0x75, - 0x6c, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x64, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x66, - 0x75, 0x6c, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, - 0x6c, 0x18, 0x6e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x42, 0x57, - 0x5a, 0x55, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, - 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, - 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x63, 0x6f, 0x6e, - 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x3b, 0x61, - 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x2c, 0x0a, 0x11, 0x6d, 0x61, 0x6e, 0x61, 0x67, + 0x65, 0x64, 0x5f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x6e, 0x20, 0x03, + 0x28, 0x09, 0x52, 0x11, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x5f, 0x67, 0x72, 0x6f, 0x75, + 0x70, 0x5f, 0x69, 0x64, 0x73, 0x12, 0x2f, 0x0a, 0x12, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, + 0x7a, 0x65, 0x64, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xac, 0x02, 0x20, 0x03, + 0x28, 0x09, 0x52, 0x12, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x5f, 0x61, + 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xa7, 0x01, 0x0a, 0x19, 0x50, 0x61, 0x73, 0x73, 0x77, + 0x6f, 0x72, 0x64, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, + 0x75, 0x74, 0x65, 0x73, 0x12, 0x4a, 0x0a, 0x0a, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x5f, 0x6e, 0x61, + 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x42, 0x2a, 0xa0, 0xda, 0x29, 0x01, 0xc2, 0xdd, + 0x29, 0x22, 0x0a, 0x15, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x2e, 0x6c, + 0x6f, 0x67, 0x69, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x09, 0x4c, 0x6f, 0x67, 0x69, 0x6e, + 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x0a, 0x6c, 0x6f, 0x67, 0x69, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, + 0x12, 0x3e, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x14, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x42, 0x04, 0xa0, 0xda, 0x29, 0x01, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, + 0x22, 0x89, 0x01, 0x0a, 0x15, 0x4f, 0x69, 0x64, 0x63, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x1c, 0x0a, 0x06, 0x69, 0x73, + 0x73, 0x75, 0x65, 0x72, 0x18, 0x50, 0x20, 0x01, 0x28, 0x09, 0x42, 0x04, 0xa0, 0xda, 0x29, 0x01, + 0x52, 0x06, 0x69, 0x73, 0x73, 0x75, 0x65, 0x72, 0x12, 0x1e, 0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, + 0x65, 0x63, 0x74, 0x18, 0x5a, 0x20, 0x01, 0x28, 0x09, 0x42, 0x04, 0xa0, 0xda, 0x29, 0x01, 0x52, + 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x66, 0x75, 0x6c, 0x6c, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x64, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x66, 0x75, 0x6c, + 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, + 0x6e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x42, 0x57, 0x5a, 0x55, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, + 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x73, 0x2f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x3b, 0x61, 0x63, 0x63, + 0x6f, 0x75, 0x6e, 0x74, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/internal/gen/controller/api/resources/managedgroups/managed_group.pb.go b/internal/gen/controller/api/resources/managedgroups/managed_group.pb.go new file mode 100644 index 000000000..73ddd729e --- /dev/null +++ b/internal/gen/controller/api/resources/managedgroups/managed_group.pb.go @@ -0,0 +1,386 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.15.8 +// source: controller/api/resources/managedgroups/v1/managed_group.proto + +package managedgroups + +import ( + scopes "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes" + _ "github.com/hashicorp/boundary/internal/gen/controller/protooptions" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + structpb "google.golang.org/protobuf/types/known/structpb" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + wrapperspb "google.golang.org/protobuf/types/known/wrapperspb" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// ManagedGroup contains all fields related to an ManagedGroup resource +type ManagedGroup struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Output only. The ID of the ManagedGroup. + Id string `protobuf:"bytes,10,opt,name=id,proto3" json:"id,omitempty"` + // Output only. Scope information for the ManagedGroup. + Scope *scopes.ScopeInfo `protobuf:"bytes,20,opt,name=scope,proto3" json:"scope,omitempty"` + // Optional name for identification purposes. + Name *wrapperspb.StringValue `protobuf:"bytes,30,opt,name=name,proto3" json:"name,omitempty"` + // Optional user-set description for identification purposes. + Description *wrapperspb.StringValue `protobuf:"bytes,40,opt,name=description,proto3" json:"description,omitempty"` + // Output only. The time this resource was created. + CreatedTime *timestamppb.Timestamp `protobuf:"bytes,50,opt,name=created_time,proto3" json:"created_time,omitempty"` + // Output only. The time this resource was last updated. + UpdatedTime *timestamppb.Timestamp `protobuf:"bytes,60,opt,name=updated_time,proto3" json:"updated_time,omitempty"` + // Version is used in mutation requests, after the initial creation, to ensure this resource has not changed. + // The mutation will fail if the version does not match the latest known good version. + Version uint32 `protobuf:"varint,70,opt,name=version,proto3" json:"version,omitempty"` + // The type of this ManagedGroup. + Type string `protobuf:"bytes,80,opt,name=type,proto3" json:"type,omitempty"` + // The ID of the Auth Method that is associated with this ManagedGroup. + AuthMethodId string `protobuf:"bytes,90,opt,name=auth_method_id,proto3" json:"auth_method_id,omitempty"` + // The attributes that are applicable for the specific ManagedGroup type. + Attributes *structpb.Struct `protobuf:"bytes,100,opt,name=attributes,proto3" json:"attributes,omitempty"` + // Output only. The IDs of the current set of members (accounts) that are associated with this ManagedGroup. + MemberIds []string `protobuf:"bytes,110,rep,name=member_ids,proto3" json:"member_ids,omitempty"` + // Output only. The available actions on this resource for this user. + AuthorizedActions []string `protobuf:"bytes,300,rep,name=authorized_actions,proto3" json:"authorized_actions,omitempty"` +} + +func (x *ManagedGroup) Reset() { + *x = ManagedGroup{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ManagedGroup) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ManagedGroup) ProtoMessage() {} + +func (x *ManagedGroup) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ManagedGroup.ProtoReflect.Descriptor instead. +func (*ManagedGroup) Descriptor() ([]byte, []int) { + return file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescGZIP(), []int{0} +} + +func (x *ManagedGroup) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *ManagedGroup) GetScope() *scopes.ScopeInfo { + if x != nil { + return x.Scope + } + return nil +} + +func (x *ManagedGroup) GetName() *wrapperspb.StringValue { + if x != nil { + return x.Name + } + return nil +} + +func (x *ManagedGroup) GetDescription() *wrapperspb.StringValue { + if x != nil { + return x.Description + } + return nil +} + +func (x *ManagedGroup) GetCreatedTime() *timestamppb.Timestamp { + if x != nil { + return x.CreatedTime + } + return nil +} + +func (x *ManagedGroup) GetUpdatedTime() *timestamppb.Timestamp { + if x != nil { + return x.UpdatedTime + } + return nil +} + +func (x *ManagedGroup) GetVersion() uint32 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *ManagedGroup) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *ManagedGroup) GetAuthMethodId() string { + if x != nil { + return x.AuthMethodId + } + return "" +} + +func (x *ManagedGroup) GetAttributes() *structpb.Struct { + if x != nil { + return x.Attributes + } + return nil +} + +func (x *ManagedGroup) GetMemberIds() []string { + if x != nil { + return x.MemberIds + } + return nil +} + +func (x *ManagedGroup) GetAuthorizedActions() []string { + if x != nil { + return x.AuthorizedActions + } + return nil +} + +// Attributes associated only with ManagedGroups with type "oidc". +type OidcManagedGroupAttributes struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The boolean expression filter to use to determine membership. + Filter string `protobuf:"bytes,10,opt,name=filter,proto3" json:"filter,omitempty"` +} + +func (x *OidcManagedGroupAttributes) Reset() { + *x = OidcManagedGroupAttributes{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OidcManagedGroupAttributes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OidcManagedGroupAttributes) ProtoMessage() {} + +func (x *OidcManagedGroupAttributes) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OidcManagedGroupAttributes.ProtoReflect.Descriptor instead. +func (*OidcManagedGroupAttributes) Descriptor() ([]byte, []int) { + return file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescGZIP(), []int{1} +} + +func (x *OidcManagedGroupAttributes) GetFilter() string { + if x != nil { + return x.Filter + } + return "" +} + +var File_controller_api_resources_managedgroups_v1_managed_group_proto protoreflect.FileDescriptor + +var file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDesc = []byte{ + 0x0a, 0x3d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69, + 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x6d, 0x61, 0x6e, 0x61, 0x67, + 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x61, 0x6e, 0x61, + 0x67, 0x65, 0x64, 0x5f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x29, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, + 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, + 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2e, 0x76, 0x31, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, + 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, + 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x73, 0x2f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x63, + 0x6f, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xf5, 0x04, 0x0a, 0x0c, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, + 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x43, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, + 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, + 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, + 0x2e, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f, 0x70, 0x65, + 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x46, 0x0a, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, + 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x14, 0xa0, 0xda, 0x29, 0x01, 0xc2, 0xdd, 0x29, + 0x0c, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x62, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x28, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, + 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x22, 0xa0, 0xda, 0x29, 0x01, 0xc2, 0xdd, 0x29, 0x1a, + 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0b, 0x44, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, + 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x3e, 0x0a, 0x0c, 0x63, 0x72, 0x65, 0x61, 0x74, + 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x32, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0c, 0x63, 0x72, 0x65, 0x61, 0x74, + 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x12, 0x3e, 0x0a, 0x0c, 0x75, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x3c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0c, 0x75, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x46, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x50, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x26, 0x0a, 0x0e, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x6d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x5a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x61, + 0x75, 0x74, 0x68, 0x5f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x69, 0x64, 0x12, 0x3d, 0x0a, + 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x64, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x04, 0xa0, 0xda, 0x29, 0x01, + 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0a, + 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x6e, 0x20, 0x03, 0x28, 0x09, + 0x52, 0x0a, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x73, 0x12, 0x2f, 0x0a, 0x12, + 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x18, 0xac, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x12, 0x61, 0x75, 0x74, 0x68, 0x6f, + 0x72, 0x69, 0x7a, 0x65, 0x64, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x59, 0x0a, + 0x1a, 0x4f, 0x69, 0x64, 0x63, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, + 0x70, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x3b, 0x0a, 0x06, 0x66, + 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xa0, 0xda, 0x29, + 0x01, 0xc2, 0xdd, 0x29, 0x1b, 0x0a, 0x11, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, + 0x73, 0x2e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x06, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, + 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x42, 0x61, 0x5a, 0x5f, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, + 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, + 0x61, 0x6c, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, + 0x72, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, + 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x3b, 0x6d, 0x61, + 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescOnce sync.Once + file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescData = file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDesc +) + +func file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescGZIP() []byte { + file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescOnce.Do(func() { + file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescData) + }) + return file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDescData +} + +var file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_controller_api_resources_managedgroups_v1_managed_group_proto_goTypes = []interface{}{ + (*ManagedGroup)(nil), // 0: controller.api.resources.managedgroups.v1.ManagedGroup + (*OidcManagedGroupAttributes)(nil), // 1: controller.api.resources.managedgroups.v1.OidcManagedGroupAttributes + (*scopes.ScopeInfo)(nil), // 2: controller.api.resources.scopes.v1.ScopeInfo + (*wrapperspb.StringValue)(nil), // 3: google.protobuf.StringValue + (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp + (*structpb.Struct)(nil), // 5: google.protobuf.Struct +} +var file_controller_api_resources_managedgroups_v1_managed_group_proto_depIdxs = []int32{ + 2, // 0: controller.api.resources.managedgroups.v1.ManagedGroup.scope:type_name -> controller.api.resources.scopes.v1.ScopeInfo + 3, // 1: controller.api.resources.managedgroups.v1.ManagedGroup.name:type_name -> google.protobuf.StringValue + 3, // 2: controller.api.resources.managedgroups.v1.ManagedGroup.description:type_name -> google.protobuf.StringValue + 4, // 3: controller.api.resources.managedgroups.v1.ManagedGroup.created_time:type_name -> google.protobuf.Timestamp + 4, // 4: controller.api.resources.managedgroups.v1.ManagedGroup.updated_time:type_name -> google.protobuf.Timestamp + 5, // 5: controller.api.resources.managedgroups.v1.ManagedGroup.attributes:type_name -> google.protobuf.Struct + 6, // [6:6] is the sub-list for method output_type + 6, // [6:6] is the sub-list for method input_type + 6, // [6:6] is the sub-list for extension type_name + 6, // [6:6] is the sub-list for extension extendee + 0, // [0:6] is the sub-list for field type_name +} + +func init() { file_controller_api_resources_managedgroups_v1_managed_group_proto_init() } +func file_controller_api_resources_managedgroups_v1_managed_group_proto_init() { + if File_controller_api_resources_managedgroups_v1_managed_group_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ManagedGroup); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*OidcManagedGroupAttributes); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_controller_api_resources_managedgroups_v1_managed_group_proto_goTypes, + DependencyIndexes: file_controller_api_resources_managedgroups_v1_managed_group_proto_depIdxs, + MessageInfos: file_controller_api_resources_managedgroups_v1_managed_group_proto_msgTypes, + }.Build() + File_controller_api_resources_managedgroups_v1_managed_group_proto = out.File + file_controller_api_resources_managedgroups_v1_managed_group_proto_rawDesc = nil + file_controller_api_resources_managedgroups_v1_managed_group_proto_goTypes = nil + file_controller_api_resources_managedgroups_v1_managed_group_proto_depIdxs = nil +} diff --git a/internal/gen/controller/api/services/managed_group_service.pb.go b/internal/gen/controller/api/services/managed_group_service.pb.go new file mode 100644 index 000000000..0b3b3566e --- /dev/null +++ b/internal/gen/controller/api/services/managed_group_service.pb.go @@ -0,0 +1,873 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.15.8 +// source: controller/api/services/v1/managed_group_service.proto + +package services + +import ( + _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options" + managedgroups "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups" + _ "google.golang.org/genproto/googleapis/api/annotations" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb" + _ "google.golang.org/protobuf/types/known/wrapperspb" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type GetManagedGroupRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` +} + +func (x *GetManagedGroupRequest) Reset() { + *x = GetManagedGroupRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetManagedGroupRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetManagedGroupRequest) ProtoMessage() {} + +func (x *GetManagedGroupRequest) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetManagedGroupRequest.ProtoReflect.Descriptor instead. +func (*GetManagedGroupRequest) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{0} +} + +func (x *GetManagedGroupRequest) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +type GetManagedGroupResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Item *managedgroups.ManagedGroup `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"` +} + +func (x *GetManagedGroupResponse) Reset() { + *x = GetManagedGroupResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetManagedGroupResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetManagedGroupResponse) ProtoMessage() {} + +func (x *GetManagedGroupResponse) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetManagedGroupResponse.ProtoReflect.Descriptor instead. +func (*GetManagedGroupResponse) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{1} +} + +func (x *GetManagedGroupResponse) GetItem() *managedgroups.ManagedGroup { + if x != nil { + return x.Item + } + return nil +} + +type ListManagedGroupsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AuthMethodId string `protobuf:"bytes,1,opt,name=auth_method_id,proto3" json:"auth_method_id,omitempty"` + Filter string `protobuf:"bytes,30,opt,name=filter,proto3" json:"filter,omitempty"` +} + +func (x *ListManagedGroupsRequest) Reset() { + *x = ListManagedGroupsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListManagedGroupsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListManagedGroupsRequest) ProtoMessage() {} + +func (x *ListManagedGroupsRequest) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListManagedGroupsRequest.ProtoReflect.Descriptor instead. +func (*ListManagedGroupsRequest) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{2} +} + +func (x *ListManagedGroupsRequest) GetAuthMethodId() string { + if x != nil { + return x.AuthMethodId + } + return "" +} + +func (x *ListManagedGroupsRequest) GetFilter() string { + if x != nil { + return x.Filter + } + return "" +} + +type ListManagedGroupsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Items []*managedgroups.ManagedGroup `protobuf:"bytes,1,rep,name=items,proto3" json:"items,omitempty"` +} + +func (x *ListManagedGroupsResponse) Reset() { + *x = ListManagedGroupsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListManagedGroupsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListManagedGroupsResponse) ProtoMessage() {} + +func (x *ListManagedGroupsResponse) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListManagedGroupsResponse.ProtoReflect.Descriptor instead. +func (*ListManagedGroupsResponse) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{3} +} + +func (x *ListManagedGroupsResponse) GetItems() []*managedgroups.ManagedGroup { + if x != nil { + return x.Items + } + return nil +} + +type CreateManagedGroupRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Item *managedgroups.ManagedGroup `protobuf:"bytes,2,opt,name=item,proto3" json:"item,omitempty"` +} + +func (x *CreateManagedGroupRequest) Reset() { + *x = CreateManagedGroupRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CreateManagedGroupRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateManagedGroupRequest) ProtoMessage() {} + +func (x *CreateManagedGroupRequest) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateManagedGroupRequest.ProtoReflect.Descriptor instead. +func (*CreateManagedGroupRequest) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{4} +} + +func (x *CreateManagedGroupRequest) GetItem() *managedgroups.ManagedGroup { + if x != nil { + return x.Item + } + return nil +} + +type CreateManagedGroupResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` + Item *managedgroups.ManagedGroup `protobuf:"bytes,2,opt,name=item,proto3" json:"item,omitempty"` +} + +func (x *CreateManagedGroupResponse) Reset() { + *x = CreateManagedGroupResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CreateManagedGroupResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateManagedGroupResponse) ProtoMessage() {} + +func (x *CreateManagedGroupResponse) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateManagedGroupResponse.ProtoReflect.Descriptor instead. +func (*CreateManagedGroupResponse) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{5} +} + +func (x *CreateManagedGroupResponse) GetUri() string { + if x != nil { + return x.Uri + } + return "" +} + +func (x *CreateManagedGroupResponse) GetItem() *managedgroups.ManagedGroup { + if x != nil { + return x.Item + } + return nil +} + +type UpdateManagedGroupRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Item *managedgroups.ManagedGroup `protobuf:"bytes,2,opt,name=item,proto3" json:"item,omitempty"` + UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,3,opt,name=update_mask,proto3" json:"update_mask,omitempty"` +} + +func (x *UpdateManagedGroupRequest) Reset() { + *x = UpdateManagedGroupRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateManagedGroupRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateManagedGroupRequest) ProtoMessage() {} + +func (x *UpdateManagedGroupRequest) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateManagedGroupRequest.ProtoReflect.Descriptor instead. +func (*UpdateManagedGroupRequest) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{6} +} + +func (x *UpdateManagedGroupRequest) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *UpdateManagedGroupRequest) GetItem() *managedgroups.ManagedGroup { + if x != nil { + return x.Item + } + return nil +} + +func (x *UpdateManagedGroupRequest) GetUpdateMask() *fieldmaskpb.FieldMask { + if x != nil { + return x.UpdateMask + } + return nil +} + +type UpdateManagedGroupResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Item *managedgroups.ManagedGroup `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"` +} + +func (x *UpdateManagedGroupResponse) Reset() { + *x = UpdateManagedGroupResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateManagedGroupResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateManagedGroupResponse) ProtoMessage() {} + +func (x *UpdateManagedGroupResponse) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateManagedGroupResponse.ProtoReflect.Descriptor instead. +func (*UpdateManagedGroupResponse) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{7} +} + +func (x *UpdateManagedGroupResponse) GetItem() *managedgroups.ManagedGroup { + if x != nil { + return x.Item + } + return nil +} + +type DeleteManagedGroupRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` +} + +func (x *DeleteManagedGroupRequest) Reset() { + *x = DeleteManagedGroupRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DeleteManagedGroupRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteManagedGroupRequest) ProtoMessage() {} + +func (x *DeleteManagedGroupRequest) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteManagedGroupRequest.ProtoReflect.Descriptor instead. +func (*DeleteManagedGroupRequest) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{8} +} + +func (x *DeleteManagedGroupRequest) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +type DeleteManagedGroupResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *DeleteManagedGroupResponse) Reset() { + *x = DeleteManagedGroupResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DeleteManagedGroupResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteManagedGroupResponse) ProtoMessage() {} + +func (x *DeleteManagedGroupResponse) ProtoReflect() protoreflect.Message { + mi := &file_controller_api_services_v1_managed_group_service_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteManagedGroupResponse.ProtoReflect.Descriptor instead. +func (*DeleteManagedGroupResponse) Descriptor() ([]byte, []int) { + return file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP(), []int{9} +} + +var File_controller_api_services_v1_managed_group_service_proto protoreflect.FileDescriptor + +var file_controller_api_services_v1_managed_group_service_proto_rawDesc = []byte{ + 0x0a, 0x36, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69, + 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x5f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1a, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, + 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x73, 0x2e, 0x76, 0x31, 0x1a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, + 0x2d, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x76, 0x32, 0x2f, 0x6f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, + 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, + 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x6d, + 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2f, 0x76, 0x31, 0x2f, + 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x5f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x22, 0x28, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, + 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, + 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x66, 0x0a, + 0x17, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x73, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2e, + 0x76, 0x31, 0x2e, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, + 0x04, 0x69, 0x74, 0x65, 0x6d, 0x22, 0x5a, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x26, 0x0a, 0x0e, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x61, 0x75, 0x74, 0x68, 0x5f, + 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, + 0x74, 0x65, 0x72, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, + 0x72, 0x22, 0x6a, 0x0a, 0x19, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, + 0x47, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4d, + 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x37, 0x2e, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x72, + 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, + 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, + 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x22, 0x68, 0x0a, + 0x19, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x4b, 0x0a, 0x04, 0x69, 0x74, + 0x65, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x73, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, + 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, + 0x70, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x22, 0x7b, 0x0a, 0x1a, 0x43, 0x72, 0x65, 0x61, 0x74, + 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x69, 0x12, 0x4b, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, + 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, + 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2e, 0x76, + 0x31, 0x2e, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x04, + 0x69, 0x74, 0x65, 0x6d, 0x22, 0xb6, 0x01, 0x0a, 0x19, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, + 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, + 0x69, 0x64, 0x12, 0x4b, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x37, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, + 0x69, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2e, 0x6d, 0x61, 0x6e, 0x61, + 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x12, + 0x3c, 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, + 0x52, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x22, 0x69, 0x0a, + 0x1a, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x04, 0x69, + 0x74, 0x65, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x73, 0x2e, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x67, 0x72, 0x6f, 0x75, + 0x70, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, + 0x75, 0x70, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x22, 0x2b, 0x0a, 0x19, 0x44, 0x65, 0x6c, 0x65, + 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x1c, 0x0a, 0x1a, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4d, + 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x32, 0xae, 0x08, 0x0a, 0x13, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, + 0x72, 0x6f, 0x75, 0x70, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0xc1, 0x01, 0x0a, 0x0f, + 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, + 0x32, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, + 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, + 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, + 0x2e, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x45, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x1f, + 0x12, 0x17, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x2d, 0x67, 0x72, + 0x6f, 0x75, 0x70, 0x73, 0x2f, 0x7b, 0x69, 0x64, 0x7d, 0x62, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x92, + 0x41, 0x1d, 0x12, 0x1b, 0x47, 0x65, 0x74, 0x73, 0x20, 0x61, 0x20, 0x73, 0x69, 0x6e, 0x67, 0x6c, + 0x65, 0x20, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x2e, 0x12, + 0xd3, 0x01, 0x0a, 0x11, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, + 0x72, 0x6f, 0x75, 0x70, 0x73, 0x12, 0x34, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, + 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, + 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x35, 0x2e, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, + 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x22, 0x51, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x14, 0x12, 0x12, 0x2f, 0x76, 0x31, 0x2f, + 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x2d, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x92, 0x41, + 0x34, 0x12, 0x32, 0x4c, 0x69, 0x73, 0x74, 0x73, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x4d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x61, 0x20, + 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x20, 0x41, 0x75, 0x74, 0x68, 0x20, 0x4d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x2e, 0x12, 0xea, 0x01, 0x0a, 0x12, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x35, 0x2e, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x36, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, + 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x65, 0x82, 0xd3, 0xe4, + 0x93, 0x02, 0x20, 0x22, 0x12, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, + 0x2d, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x3a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x62, 0x04, 0x69, + 0x74, 0x65, 0x6d, 0x92, 0x41, 0x3c, 0x12, 0x3a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x73, 0x20, + 0x61, 0x20, 0x73, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x20, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, + 0x47, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x72, 0x6f, + 0x76, 0x69, 0x64, 0x65, 0x64, 0x20, 0x41, 0x75, 0x74, 0x68, 0x20, 0x4d, 0x65, 0x74, 0x68, 0x6f, + 0x64, 0x2e, 0x12, 0xcc, 0x01, 0x0a, 0x12, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x35, 0x2e, 0x63, 0x6f, 0x6e, 0x74, + 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, + 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x36, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, + 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, + 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x47, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x25, + 0x32, 0x17, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x2d, 0x67, 0x72, + 0x6f, 0x75, 0x70, 0x73, 0x2f, 0x7b, 0x69, 0x64, 0x7d, 0x3a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x62, + 0x04, 0x69, 0x74, 0x65, 0x6d, 0x92, 0x41, 0x19, 0x12, 0x17, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, + 0x73, 0x20, 0x61, 0x20, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, + 0x2e, 0x12, 0xc0, 0x01, 0x0a, 0x12, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, + 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x35, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, + 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x36, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x61, 0x70, 0x69, + 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x65, 0x6c, + 0x65, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x3b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x19, 0x2a, + 0x17, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x2d, 0x67, 0x72, 0x6f, + 0x75, 0x70, 0x73, 0x2f, 0x7b, 0x69, 0x64, 0x7d, 0x92, 0x41, 0x19, 0x12, 0x17, 0x44, 0x65, 0x6c, + 0x65, 0x74, 0x65, 0x73, 0x20, 0x61, 0x20, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x47, 0x72, + 0x6f, 0x75, 0x70, 0x2e, 0x42, 0x4d, 0x5a, 0x4b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, + 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x67, + 0x65, 0x6e, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x61, 0x70, + 0x69, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x3b, 0x73, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_controller_api_services_v1_managed_group_service_proto_rawDescOnce sync.Once + file_controller_api_services_v1_managed_group_service_proto_rawDescData = file_controller_api_services_v1_managed_group_service_proto_rawDesc +) + +func file_controller_api_services_v1_managed_group_service_proto_rawDescGZIP() []byte { + file_controller_api_services_v1_managed_group_service_proto_rawDescOnce.Do(func() { + file_controller_api_services_v1_managed_group_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_api_services_v1_managed_group_service_proto_rawDescData) + }) + return file_controller_api_services_v1_managed_group_service_proto_rawDescData +} + +var file_controller_api_services_v1_managed_group_service_proto_msgTypes = make([]protoimpl.MessageInfo, 10) +var file_controller_api_services_v1_managed_group_service_proto_goTypes = []interface{}{ + (*GetManagedGroupRequest)(nil), // 0: controller.api.services.v1.GetManagedGroupRequest + (*GetManagedGroupResponse)(nil), // 1: controller.api.services.v1.GetManagedGroupResponse + (*ListManagedGroupsRequest)(nil), // 2: controller.api.services.v1.ListManagedGroupsRequest + (*ListManagedGroupsResponse)(nil), // 3: controller.api.services.v1.ListManagedGroupsResponse + (*CreateManagedGroupRequest)(nil), // 4: controller.api.services.v1.CreateManagedGroupRequest + (*CreateManagedGroupResponse)(nil), // 5: controller.api.services.v1.CreateManagedGroupResponse + (*UpdateManagedGroupRequest)(nil), // 6: controller.api.services.v1.UpdateManagedGroupRequest + (*UpdateManagedGroupResponse)(nil), // 7: controller.api.services.v1.UpdateManagedGroupResponse + (*DeleteManagedGroupRequest)(nil), // 8: controller.api.services.v1.DeleteManagedGroupRequest + (*DeleteManagedGroupResponse)(nil), // 9: controller.api.services.v1.DeleteManagedGroupResponse + (*managedgroups.ManagedGroup)(nil), // 10: controller.api.resources.managedgroups.v1.ManagedGroup + (*fieldmaskpb.FieldMask)(nil), // 11: google.protobuf.FieldMask +} +var file_controller_api_services_v1_managed_group_service_proto_depIdxs = []int32{ + 10, // 0: controller.api.services.v1.GetManagedGroupResponse.item:type_name -> controller.api.resources.managedgroups.v1.ManagedGroup + 10, // 1: controller.api.services.v1.ListManagedGroupsResponse.items:type_name -> controller.api.resources.managedgroups.v1.ManagedGroup + 10, // 2: controller.api.services.v1.CreateManagedGroupRequest.item:type_name -> controller.api.resources.managedgroups.v1.ManagedGroup + 10, // 3: controller.api.services.v1.CreateManagedGroupResponse.item:type_name -> controller.api.resources.managedgroups.v1.ManagedGroup + 10, // 4: controller.api.services.v1.UpdateManagedGroupRequest.item:type_name -> controller.api.resources.managedgroups.v1.ManagedGroup + 11, // 5: controller.api.services.v1.UpdateManagedGroupRequest.update_mask:type_name -> google.protobuf.FieldMask + 10, // 6: controller.api.services.v1.UpdateManagedGroupResponse.item:type_name -> controller.api.resources.managedgroups.v1.ManagedGroup + 0, // 7: controller.api.services.v1.ManagedGroupService.GetManagedGroup:input_type -> controller.api.services.v1.GetManagedGroupRequest + 2, // 8: controller.api.services.v1.ManagedGroupService.ListManagedGroups:input_type -> controller.api.services.v1.ListManagedGroupsRequest + 4, // 9: controller.api.services.v1.ManagedGroupService.CreateManagedGroup:input_type -> controller.api.services.v1.CreateManagedGroupRequest + 6, // 10: controller.api.services.v1.ManagedGroupService.UpdateManagedGroup:input_type -> controller.api.services.v1.UpdateManagedGroupRequest + 8, // 11: controller.api.services.v1.ManagedGroupService.DeleteManagedGroup:input_type -> controller.api.services.v1.DeleteManagedGroupRequest + 1, // 12: controller.api.services.v1.ManagedGroupService.GetManagedGroup:output_type -> controller.api.services.v1.GetManagedGroupResponse + 3, // 13: controller.api.services.v1.ManagedGroupService.ListManagedGroups:output_type -> controller.api.services.v1.ListManagedGroupsResponse + 5, // 14: controller.api.services.v1.ManagedGroupService.CreateManagedGroup:output_type -> controller.api.services.v1.CreateManagedGroupResponse + 7, // 15: controller.api.services.v1.ManagedGroupService.UpdateManagedGroup:output_type -> controller.api.services.v1.UpdateManagedGroupResponse + 9, // 16: controller.api.services.v1.ManagedGroupService.DeleteManagedGroup:output_type -> controller.api.services.v1.DeleteManagedGroupResponse + 12, // [12:17] is the sub-list for method output_type + 7, // [7:12] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name +} + +func init() { file_controller_api_services_v1_managed_group_service_proto_init() } +func file_controller_api_services_v1_managed_group_service_proto_init() { + if File_controller_api_services_v1_managed_group_service_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_controller_api_services_v1_managed_group_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetManagedGroupRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetManagedGroupResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListManagedGroupsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListManagedGroupsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateManagedGroupRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateManagedGroupResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateManagedGroupRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateManagedGroupResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DeleteManagedGroupRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_api_services_v1_managed_group_service_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DeleteManagedGroupResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_controller_api_services_v1_managed_group_service_proto_rawDesc, + NumEnums: 0, + NumMessages: 10, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_controller_api_services_v1_managed_group_service_proto_goTypes, + DependencyIndexes: file_controller_api_services_v1_managed_group_service_proto_depIdxs, + MessageInfos: file_controller_api_services_v1_managed_group_service_proto_msgTypes, + }.Build() + File_controller_api_services_v1_managed_group_service_proto = out.File + file_controller_api_services_v1_managed_group_service_proto_rawDesc = nil + file_controller_api_services_v1_managed_group_service_proto_goTypes = nil + file_controller_api_services_v1_managed_group_service_proto_depIdxs = nil +} diff --git a/internal/gen/controller/api/services/managed_group_service.pb.gw.go b/internal/gen/controller/api/services/managed_group_service.pb.gw.go new file mode 100644 index 000000000..0fe29d9d1 --- /dev/null +++ b/internal/gen/controller/api/services/managed_group_service.pb.gw.go @@ -0,0 +1,622 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: controller/api/services/v1/managed_group_service.proto + +/* +Package services is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package services + +import ( + "context" + "io" + "net/http" + + "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" + "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = metadata.Join + +func request_ManagedGroupService_GetManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, client ManagedGroupServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GetManagedGroupRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + msg, err := client.GetManagedGroup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_ManagedGroupService_GetManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, server ManagedGroupServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GetManagedGroupRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + msg, err := server.GetManagedGroup(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_ManagedGroupService_ListManagedGroups_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_ManagedGroupService_ListManagedGroups_0(ctx context.Context, marshaler runtime.Marshaler, client ManagedGroupServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq ListManagedGroupsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ManagedGroupService_ListManagedGroups_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.ListManagedGroups(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_ManagedGroupService_ListManagedGroups_0(ctx context.Context, marshaler runtime.Marshaler, server ManagedGroupServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq ListManagedGroupsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ManagedGroupService_ListManagedGroups_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.ListManagedGroups(ctx, &protoReq) + return msg, metadata, err + +} + +func request_ManagedGroupService_CreateManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, client ManagedGroupServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq CreateManagedGroupRequest + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Item); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.CreateManagedGroup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_ManagedGroupService_CreateManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, server ManagedGroupServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq CreateManagedGroupRequest + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Item); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.CreateManagedGroup(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_ManagedGroupService_UpdateManagedGroup_0 = &utilities.DoubleArray{Encoding: map[string]int{"item": 0, "id": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} +) + +func request_ManagedGroupService_UpdateManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, client ManagedGroupServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq UpdateManagedGroupRequest + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Item); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { + if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), protoReq.Item); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } else { + protoReq.UpdateMask = fieldMask + } + } + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ManagedGroupService_UpdateManagedGroup_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.UpdateManagedGroup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_ManagedGroupService_UpdateManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, server ManagedGroupServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq UpdateManagedGroupRequest + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq.Item); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if protoReq.UpdateMask == nil || len(protoReq.UpdateMask.GetPaths()) == 0 { + if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), protoReq.Item); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } else { + protoReq.UpdateMask = fieldMask + } + } + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ManagedGroupService_UpdateManagedGroup_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.UpdateManagedGroup(ctx, &protoReq) + return msg, metadata, err + +} + +func request_ManagedGroupService_DeleteManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, client ManagedGroupServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq DeleteManagedGroupRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + msg, err := client.DeleteManagedGroup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_ManagedGroupService_DeleteManagedGroup_0(ctx context.Context, marshaler runtime.Marshaler, server ManagedGroupServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq DeleteManagedGroupRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") + } + + protoReq.Id, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) + } + + msg, err := server.DeleteManagedGroup(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterManagedGroupServiceHandlerServer registers the http handlers for service ManagedGroupService to "mux". +// UnaryRPC :call ManagedGroupServiceServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterManagedGroupServiceHandlerFromEndpoint instead. +func RegisterManagedGroupServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ManagedGroupServiceServer) error { + + mux.Handle("GET", pattern_ManagedGroupService_GetManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/GetManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ManagedGroupService_GetManagedGroup_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_GetManagedGroup_0(ctx, mux, outboundMarshaler, w, req, response_ManagedGroupService_GetManagedGroup_0{resp}, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_ManagedGroupService_ListManagedGroups_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/ListManagedGroups") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ManagedGroupService_ListManagedGroups_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_ListManagedGroups_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_ManagedGroupService_CreateManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/CreateManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ManagedGroupService_CreateManagedGroup_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_CreateManagedGroup_0(ctx, mux, outboundMarshaler, w, req, response_ManagedGroupService_CreateManagedGroup_0{resp}, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("PATCH", pattern_ManagedGroupService_UpdateManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/UpdateManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ManagedGroupService_UpdateManagedGroup_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_UpdateManagedGroup_0(ctx, mux, outboundMarshaler, w, req, response_ManagedGroupService_UpdateManagedGroup_0{resp}, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("DELETE", pattern_ManagedGroupService_DeleteManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/DeleteManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ManagedGroupService_DeleteManagedGroup_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_DeleteManagedGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterManagedGroupServiceHandlerFromEndpoint is same as RegisterManagedGroupServiceHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterManagedGroupServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterManagedGroupServiceHandler(ctx, mux, conn) +} + +// RegisterManagedGroupServiceHandler registers the http handlers for service ManagedGroupService to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterManagedGroupServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterManagedGroupServiceHandlerClient(ctx, mux, NewManagedGroupServiceClient(conn)) +} + +// RegisterManagedGroupServiceHandlerClient registers the http handlers for service ManagedGroupService +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "ManagedGroupServiceClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "ManagedGroupServiceClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "ManagedGroupServiceClient" to call the correct interceptors. +func RegisterManagedGroupServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ManagedGroupServiceClient) error { + + mux.Handle("GET", pattern_ManagedGroupService_GetManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/GetManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ManagedGroupService_GetManagedGroup_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_GetManagedGroup_0(ctx, mux, outboundMarshaler, w, req, response_ManagedGroupService_GetManagedGroup_0{resp}, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_ManagedGroupService_ListManagedGroups_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/ListManagedGroups") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ManagedGroupService_ListManagedGroups_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_ListManagedGroups_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_ManagedGroupService_CreateManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/CreateManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ManagedGroupService_CreateManagedGroup_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_CreateManagedGroup_0(ctx, mux, outboundMarshaler, w, req, response_ManagedGroupService_CreateManagedGroup_0{resp}, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("PATCH", pattern_ManagedGroupService_UpdateManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/UpdateManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ManagedGroupService_UpdateManagedGroup_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_UpdateManagedGroup_0(ctx, mux, outboundMarshaler, w, req, response_ManagedGroupService_UpdateManagedGroup_0{resp}, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("DELETE", pattern_ManagedGroupService_DeleteManagedGroup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req, "/controller.api.services.v1.ManagedGroupService/DeleteManagedGroup") + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ManagedGroupService_DeleteManagedGroup_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_ManagedGroupService_DeleteManagedGroup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +type response_ManagedGroupService_GetManagedGroup_0 struct { + proto.Message +} + +func (m response_ManagedGroupService_GetManagedGroup_0) XXX_ResponseBody() interface{} { + response := m.Message.(*GetManagedGroupResponse) + return response.Item +} + +type response_ManagedGroupService_CreateManagedGroup_0 struct { + proto.Message +} + +func (m response_ManagedGroupService_CreateManagedGroup_0) XXX_ResponseBody() interface{} { + response := m.Message.(*CreateManagedGroupResponse) + return response.Item +} + +type response_ManagedGroupService_UpdateManagedGroup_0 struct { + proto.Message +} + +func (m response_ManagedGroupService_UpdateManagedGroup_0) XXX_ResponseBody() interface{} { + response := m.Message.(*UpdateManagedGroupResponse) + return response.Item +} + +var ( + pattern_ManagedGroupService_GetManagedGroup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"v1", "managed-groups", "id"}, "")) + + pattern_ManagedGroupService_ListManagedGroups_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "managed-groups"}, "")) + + pattern_ManagedGroupService_CreateManagedGroup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "managed-groups"}, "")) + + pattern_ManagedGroupService_UpdateManagedGroup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"v1", "managed-groups", "id"}, "")) + + pattern_ManagedGroupService_DeleteManagedGroup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"v1", "managed-groups", "id"}, "")) +) + +var ( + forward_ManagedGroupService_GetManagedGroup_0 = runtime.ForwardResponseMessage + + forward_ManagedGroupService_ListManagedGroups_0 = runtime.ForwardResponseMessage + + forward_ManagedGroupService_CreateManagedGroup_0 = runtime.ForwardResponseMessage + + forward_ManagedGroupService_UpdateManagedGroup_0 = runtime.ForwardResponseMessage + + forward_ManagedGroupService_DeleteManagedGroup_0 = runtime.ForwardResponseMessage +) diff --git a/internal/gen/controller/api/services/managed_group_service_grpc.pb.go b/internal/gen/controller/api/services/managed_group_service_grpc.pb.go new file mode 100644 index 000000000..69bd29978 --- /dev/null +++ b/internal/gen/controller/api/services/managed_group_service_grpc.pb.go @@ -0,0 +1,291 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package services + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// ManagedGroupServiceClient is the client API for ManagedGroupService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type ManagedGroupServiceClient interface { + // GetManagedGroup returns a stored ManagedGroup if present. The provided request must + // include the id for the ManagedGroup be retrieved. If missing, malformed or + // referencing a non existing ManagedGroup an error is returned. + GetManagedGroup(ctx context.Context, in *GetManagedGroupRequest, opts ...grpc.CallOption) (*GetManagedGroupResponse, error) + // ListManagedGroups returns a list of stored ManagedGroups which exist inside the + // provided Auth Method. The request must include the Auth Method id which + // contains the ManagedGroups being listed. If missing or malformed an error + // is returned. + ListManagedGroups(ctx context.Context, in *ListManagedGroupsRequest, opts ...grpc.CallOption) (*ListManagedGroupsResponse, error) + // CreateManagedGroup creates and stores a ManagedGroup. The provided request + // must include the Auth Method ID in which the ManagedGroup will be created. + // If the Auth Method ID is missing, malformed, or references a non existing + // resource an error is returned. If a name or login_name is provided that is + // in use in another ManagedGroup in the same Auth Method an error is + // returned. + CreateManagedGroup(ctx context.Context, in *CreateManagedGroupRequest, opts ...grpc.CallOption) (*CreateManagedGroupResponse, error) + // UpdateManagedGroup updates an existing ManagedGroup. The provided + // ManagedGroup must not have any read only fields set. The update mask must + // be included in the request and contain at least 1 mutable field. To unset a + // field's value, include the field in the update mask and don't set it in the + // provided ManagedGroup. An error is returned if the ManagedGroup id is + // missing or references a non-existing resource. An error is also returned if + // the request attempts to update the name to one that is already in use in + // the containing Auth Method. + UpdateManagedGroup(ctx context.Context, in *UpdateManagedGroupRequest, opts ...grpc.CallOption) (*UpdateManagedGroupResponse, error) + // DeleteManagedGroup removes a ManagedGroup. If the provided ManagedGroup Id + // is malformed or not provided an error is returned. + DeleteManagedGroup(ctx context.Context, in *DeleteManagedGroupRequest, opts ...grpc.CallOption) (*DeleteManagedGroupResponse, error) +} + +type managedGroupServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewManagedGroupServiceClient(cc grpc.ClientConnInterface) ManagedGroupServiceClient { + return &managedGroupServiceClient{cc} +} + +func (c *managedGroupServiceClient) GetManagedGroup(ctx context.Context, in *GetManagedGroupRequest, opts ...grpc.CallOption) (*GetManagedGroupResponse, error) { + out := new(GetManagedGroupResponse) + err := c.cc.Invoke(ctx, "/controller.api.services.v1.ManagedGroupService/GetManagedGroup", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *managedGroupServiceClient) ListManagedGroups(ctx context.Context, in *ListManagedGroupsRequest, opts ...grpc.CallOption) (*ListManagedGroupsResponse, error) { + out := new(ListManagedGroupsResponse) + err := c.cc.Invoke(ctx, "/controller.api.services.v1.ManagedGroupService/ListManagedGroups", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *managedGroupServiceClient) CreateManagedGroup(ctx context.Context, in *CreateManagedGroupRequest, opts ...grpc.CallOption) (*CreateManagedGroupResponse, error) { + out := new(CreateManagedGroupResponse) + err := c.cc.Invoke(ctx, "/controller.api.services.v1.ManagedGroupService/CreateManagedGroup", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *managedGroupServiceClient) UpdateManagedGroup(ctx context.Context, in *UpdateManagedGroupRequest, opts ...grpc.CallOption) (*UpdateManagedGroupResponse, error) { + out := new(UpdateManagedGroupResponse) + err := c.cc.Invoke(ctx, "/controller.api.services.v1.ManagedGroupService/UpdateManagedGroup", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *managedGroupServiceClient) DeleteManagedGroup(ctx context.Context, in *DeleteManagedGroupRequest, opts ...grpc.CallOption) (*DeleteManagedGroupResponse, error) { + out := new(DeleteManagedGroupResponse) + err := c.cc.Invoke(ctx, "/controller.api.services.v1.ManagedGroupService/DeleteManagedGroup", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ManagedGroupServiceServer is the server API for ManagedGroupService service. +// All implementations must embed UnimplementedManagedGroupServiceServer +// for forward compatibility +type ManagedGroupServiceServer interface { + // GetManagedGroup returns a stored ManagedGroup if present. The provided request must + // include the id for the ManagedGroup be retrieved. If missing, malformed or + // referencing a non existing ManagedGroup an error is returned. + GetManagedGroup(context.Context, *GetManagedGroupRequest) (*GetManagedGroupResponse, error) + // ListManagedGroups returns a list of stored ManagedGroups which exist inside the + // provided Auth Method. The request must include the Auth Method id which + // contains the ManagedGroups being listed. If missing or malformed an error + // is returned. + ListManagedGroups(context.Context, *ListManagedGroupsRequest) (*ListManagedGroupsResponse, error) + // CreateManagedGroup creates and stores a ManagedGroup. The provided request + // must include the Auth Method ID in which the ManagedGroup will be created. + // If the Auth Method ID is missing, malformed, or references a non existing + // resource an error is returned. If a name or login_name is provided that is + // in use in another ManagedGroup in the same Auth Method an error is + // returned. + CreateManagedGroup(context.Context, *CreateManagedGroupRequest) (*CreateManagedGroupResponse, error) + // UpdateManagedGroup updates an existing ManagedGroup. The provided + // ManagedGroup must not have any read only fields set. The update mask must + // be included in the request and contain at least 1 mutable field. To unset a + // field's value, include the field in the update mask and don't set it in the + // provided ManagedGroup. An error is returned if the ManagedGroup id is + // missing or references a non-existing resource. An error is also returned if + // the request attempts to update the name to one that is already in use in + // the containing Auth Method. + UpdateManagedGroup(context.Context, *UpdateManagedGroupRequest) (*UpdateManagedGroupResponse, error) + // DeleteManagedGroup removes a ManagedGroup. If the provided ManagedGroup Id + // is malformed or not provided an error is returned. + DeleteManagedGroup(context.Context, *DeleteManagedGroupRequest) (*DeleteManagedGroupResponse, error) + mustEmbedUnimplementedManagedGroupServiceServer() +} + +// UnimplementedManagedGroupServiceServer must be embedded to have forward compatible implementations. +type UnimplementedManagedGroupServiceServer struct { +} + +func (UnimplementedManagedGroupServiceServer) GetManagedGroup(context.Context, *GetManagedGroupRequest) (*GetManagedGroupResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetManagedGroup not implemented") +} +func (UnimplementedManagedGroupServiceServer) ListManagedGroups(context.Context, *ListManagedGroupsRequest) (*ListManagedGroupsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListManagedGroups not implemented") +} +func (UnimplementedManagedGroupServiceServer) CreateManagedGroup(context.Context, *CreateManagedGroupRequest) (*CreateManagedGroupResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreateManagedGroup not implemented") +} +func (UnimplementedManagedGroupServiceServer) UpdateManagedGroup(context.Context, *UpdateManagedGroupRequest) (*UpdateManagedGroupResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateManagedGroup not implemented") +} +func (UnimplementedManagedGroupServiceServer) DeleteManagedGroup(context.Context, *DeleteManagedGroupRequest) (*DeleteManagedGroupResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method DeleteManagedGroup not implemented") +} +func (UnimplementedManagedGroupServiceServer) mustEmbedUnimplementedManagedGroupServiceServer() {} + +// UnsafeManagedGroupServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ManagedGroupServiceServer will +// result in compilation errors. +type UnsafeManagedGroupServiceServer interface { + mustEmbedUnimplementedManagedGroupServiceServer() +} + +func RegisterManagedGroupServiceServer(s grpc.ServiceRegistrar, srv ManagedGroupServiceServer) { + s.RegisterService(&ManagedGroupService_ServiceDesc, srv) +} + +func _ManagedGroupService_GetManagedGroup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetManagedGroupRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ManagedGroupServiceServer).GetManagedGroup(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/controller.api.services.v1.ManagedGroupService/GetManagedGroup", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ManagedGroupServiceServer).GetManagedGroup(ctx, req.(*GetManagedGroupRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ManagedGroupService_ListManagedGroups_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListManagedGroupsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ManagedGroupServiceServer).ListManagedGroups(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/controller.api.services.v1.ManagedGroupService/ListManagedGroups", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ManagedGroupServiceServer).ListManagedGroups(ctx, req.(*ListManagedGroupsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ManagedGroupService_CreateManagedGroup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateManagedGroupRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ManagedGroupServiceServer).CreateManagedGroup(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/controller.api.services.v1.ManagedGroupService/CreateManagedGroup", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ManagedGroupServiceServer).CreateManagedGroup(ctx, req.(*CreateManagedGroupRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ManagedGroupService_UpdateManagedGroup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateManagedGroupRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ManagedGroupServiceServer).UpdateManagedGroup(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/controller.api.services.v1.ManagedGroupService/UpdateManagedGroup", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ManagedGroupServiceServer).UpdateManagedGroup(ctx, req.(*UpdateManagedGroupRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ManagedGroupService_DeleteManagedGroup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeleteManagedGroupRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ManagedGroupServiceServer).DeleteManagedGroup(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/controller.api.services.v1.ManagedGroupService/DeleteManagedGroup", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ManagedGroupServiceServer).DeleteManagedGroup(ctx, req.(*DeleteManagedGroupRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ManagedGroupService_ServiceDesc is the grpc.ServiceDesc for ManagedGroupService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ManagedGroupService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "controller.api.services.v1.ManagedGroupService", + HandlerType: (*ManagedGroupServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetManagedGroup", + Handler: _ManagedGroupService_GetManagedGroup_Handler, + }, + { + MethodName: "ListManagedGroups", + Handler: _ManagedGroupService_ListManagedGroups_Handler, + }, + { + MethodName: "CreateManagedGroup", + Handler: _ManagedGroupService_CreateManagedGroup_Handler, + }, + { + MethodName: "UpdateManagedGroup", + Handler: _ManagedGroupService_UpdateManagedGroup_Handler, + }, + { + MethodName: "DeleteManagedGroup", + Handler: _ManagedGroupService_DeleteManagedGroup_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "controller/api/services/v1/managed_group_service.proto", +} diff --git a/internal/iam/ids_test.go b/internal/iam/ids_test.go index e28ce8fd6..7b8aacebb 100644 --- a/internal/iam/ids_test.go +++ b/internal/iam/ids_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/types/scope" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -26,6 +27,9 @@ func Test_PublicIds(t *testing.T) { require.NoError(t, err) assert.True(t, strings.HasPrefix(id, GroupPrefix+"_")) }) + t.Run("oidc managed group", func(t *testing.T) { + assert.True(t, strings.HasPrefix("mgoidc_1234567890", intglobals.OidcManagedGroupPrefix+"_")) + }) t.Run("scopes", func(t *testing.T) { id, err := newScopeId(scope.Org) require.NoError(t, err) diff --git a/internal/iam/principal_role.go b/internal/iam/principal_role.go index ce0f01968..363bb713e 100644 --- a/internal/iam/principal_role.go +++ b/internal/iam/principal_role.go @@ -13,9 +13,10 @@ import ( type RoleType uint32 const ( - UnknownRoleType RoleType = 0 - UserRoleType RoleType = 1 - GroupRoleType RoleType = 2 + UnknownRoleType RoleType = 0 + UserRoleType RoleType = 1 + GroupRoleType RoleType = 2 + ManagedGroupRoleType RoleType = 3 ) // String returns a string representation of the role type. @@ -24,6 +25,7 @@ func (r RoleType) String() string { "unknown", "user", "group", + "managed group", }[r] } @@ -31,6 +33,7 @@ const ( principalRoleViewDefaultTable = "iam_principal_role" userRoleDefaultTable = "iam_user_role" groupRoleDefaultTable = "iam_group_role" + managedGroupRoleDefaultTable = "iam_managed_group_role" ) // PrincipalRole provides a common way to return roles regardless of their @@ -188,7 +191,7 @@ func (role *GroupRole) VetForWrite(ctx context.Context, r db.Reader, opType db.O return errors.New(errors.InvalidParameter, op, "missing role id") } if role.PrincipalId == "" { - return errors.New(errors.InvalidParameter, op, "missing user id") + return errors.New(errors.InvalidParameter, op, "missing group id") } return nil } @@ -212,3 +215,82 @@ func (r *GroupRole) SetTableName(n string) { r.tableName = n } } + +// ManagedGroupRole is a managed group assigned to a role +type ManagedGroupRole struct { + *store.ManagedGroupRole + tableName string `gorm:"-"` +} + +// ensure that GroupRole implements the interfaces of: Cloneable and +// db.VetForWriter +var ( + _ Cloneable = (*ManagedGroupRole)(nil) + _ db.VetForWriter = (*ManagedGroupRole)(nil) +) + +// NewGroupRole creates a new group role in memory. No options are supported +// currently. +func NewManagedGroupRole(roleId, managedGroupId string, opt ...Option) (*ManagedGroupRole, error) { + const op = "iam.NewManagedGroupRole" + if roleId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing role id") + } + if managedGroupId == "" { + return nil, errors.New(errors.InvalidParameter, op, "missing managed group id") + } + return &ManagedGroupRole{ + ManagedGroupRole: &store.ManagedGroupRole{ + PrincipalId: managedGroupId, + RoleId: roleId, + }, + }, nil +} + +// AllocManagedGroupRole returns a new ManagedGroupRole with an initialized +// store. +func AllocManagedGroupRole() ManagedGroupRole { + return ManagedGroupRole{ + ManagedGroupRole: &store.ManagedGroupRole{}, + } +} + +// Clone creates a clone of the ManagedGroupRole. +func (r *ManagedGroupRole) Clone() interface{} { + cp := proto.Clone(r.ManagedGroupRole) + return &ManagedGroupRole{ + ManagedGroupRole: cp.(*store.ManagedGroupRole), + } +} + +// VetForWrite implements db.VetForWrite() interface for managed group roles. +func (role ManagedGroupRole) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { + const op = "iam.(ManagedGroupRole).VetForWrite" + if role.RoleId == "" { + return errors.New(errors.InvalidParameter, op, "missing role id") + } + if role.PrincipalId == "" { + return errors.New(errors.InvalidParameter, op, "missing managed group id") + } + return nil +} + +// TableName returns the tablename to override the default gorm table name for +// managed group roles. +func (r *ManagedGroupRole) TableName() string { + if r.tableName != "" { + return r.tableName + } + return managedGroupRoleDefaultTable +} + +// SetTableName sets the table name for the resource. If the caller attempts to +// set the name to "" the name will be reset to the default name. +func (r *ManagedGroupRole) SetTableName(n string) { + switch n { + case "": + r.tableName = managedGroupRoleDefaultTable + default: + r.tableName = n + } +} diff --git a/internal/iam/principal_role_ext_test.go b/internal/iam/principal_role_ext_test.go new file mode 100644 index 000000000..58020e462 --- /dev/null +++ b/internal/iam/principal_role_ext_test.go @@ -0,0 +1,387 @@ +package iam_test + +import ( + "context" + "testing" + + "github.com/hashicorp/boundary/internal/auth/oidc" + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/iam/store" + "github.com/hashicorp/boundary/internal/kms" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +// This is in an iam_test package because managed groups are an abstract type so +// we need to reach into an implementation for testing, which itself reaches +// into IAM. So this avoids a dependency loop. + +func TestNewManagedGroupRole(t *testing.T) { + t.Parallel() + conn, _ := db.TestSetup(t, "postgres") + wrapper := db.TestWrapper(t) + repo := iam.TestRepo(t, conn, wrapper) + org, _ := iam.TestScopes(t, repo) + orgRole := iam.TestRole(t, conn, org.PublicId) + const managedGroupId = "mgoidc_1234567890" + + type args struct { + roleId string + ManagedGroupId string + opt []iam.Option + } + tests := []struct { + name string + args args + want *iam.ManagedGroupRole + wantErr bool + wantIsErr errors.Code + }{ + { + name: "valid-org", + args: args{ + roleId: orgRole.PublicId, + ManagedGroupId: managedGroupId, + }, + want: func() *iam.ManagedGroupRole { + r := iam.AllocManagedGroupRole() + r.RoleId = orgRole.PublicId + r.PrincipalId = managedGroupId + return &r + }(), + }, + { + name: "empty-role-id", + args: args{ + roleId: "", + ManagedGroupId: managedGroupId, + }, + want: nil, + wantErr: true, + wantIsErr: errors.InvalidParameter, + }, + { + name: "empty-ManagedGroup-id", + args: args{ + roleId: orgRole.PublicId, + ManagedGroupId: "", + }, + want: nil, + wantErr: true, + wantIsErr: errors.InvalidParameter, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + got, err := iam.NewManagedGroupRole(tt.args.roleId, tt.args.ManagedGroupId, tt.args.opt...) + if tt.wantErr { + require.Error(err) + assert.True(errors.Match(errors.T(tt.wantIsErr), err)) + return + } + require.NoError(err) + assert.Equal(tt.want, got) + }) + } +} + +func TestManagedGroupRole_Create(t *testing.T) { + t.Parallel() + conn, _ := db.TestSetup(t, "postgres") + + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + + repo := iam.TestRepo(t, conn, wrap) + org, _ := iam.TestScopes(t, repo) + org2, _ := iam.TestScopes(t, repo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, org.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + mg := oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter) + + type args struct { + role *iam.ManagedGroupRole + } + tests := []struct { + name string + args args + wantDup bool + wantErr bool + wantErrMsg string + wantIsErr errors.Code + }{ + { + name: "valid-with-org", + args: args{ + role: func() *iam.ManagedGroupRole { + role := iam.TestRole(t, conn, org.PublicId) + principalRole, err := iam.NewManagedGroupRole(role.PublicId, mg.PublicId) + require.NoError(t, err) + return principalRole + }(), + }, + wantErr: false, + }, + { + name: "cross-org", + args: args{ + role: func() *iam.ManagedGroupRole { + role := iam.TestRole(t, conn, org2.PublicId) + principalRole, err := iam.NewManagedGroupRole(role.PublicId, mg.PublicId) + require.NoError(t, err) + return principalRole + }(), + }, + }, + { + name: "bad-role-id", + args: args{ + role: func() *iam.ManagedGroupRole { + id := testId(t) + principalRole, err := iam.NewManagedGroupRole(id, mg.PublicId) + require.NoError(t, err) + return principalRole + }(), + }, + wantErr: true, + wantErrMsg: "db.Create: create failed: insert or update on table \"iam_managed_group_role\" violates foreign key constraint \"iam_managed_group_role_role_id_fkey\"", + }, + { + name: "bad-principal-id", + args: args{ + role: func() *iam.ManagedGroupRole { + id := testId(t) + role := iam.TestRole(t, conn, org.PublicId) + principalRole, err := iam.NewManagedGroupRole(role.PublicId, id) + require.NoError(t, err) + return principalRole + }(), + }, + wantErr: true, + wantErrMsg: "db.Create: create failed: insert or update on table \"iam_managed_group_role\" violates foreign key constraint \"iam_managed_group_role_principal_id_fkey\"", + }, + { + name: "missing-role-id", + args: args{ + role: func() *iam.ManagedGroupRole { + return &iam.ManagedGroupRole{ + ManagedGroupRole: &store.ManagedGroupRole{ + RoleId: "", + PrincipalId: mg.PublicId, + }, + } + }(), + }, + wantErr: true, + wantErrMsg: "db.Create: iam.(ManagedGroupRole).VetForWrite: missing role id: parameter violation: error #100", + wantIsErr: errors.InvalidParameter, + }, + { + name: "missing-principal-id", + args: args{ + role: func() *iam.ManagedGroupRole { + role := iam.TestRole(t, conn, org.PublicId) + return &iam.ManagedGroupRole{ + ManagedGroupRole: &store.ManagedGroupRole{ + RoleId: role.PublicId, + PrincipalId: "", + }, + } + }(), + }, + wantErr: true, + wantErrMsg: "db.Create: iam.(ManagedGroupRole).VetForWrite: missing managed group id: parameter violation: error #100", + wantIsErr: errors.InvalidParameter, + }, + { + name: "dup-at-org", + args: args{ + role: func() *iam.ManagedGroupRole { + role := iam.TestRole(t, conn, org.PublicId) + principalRole, err := iam.NewManagedGroupRole(role.PublicId, mg.PublicId) + require.NoError(t, err) + return principalRole + }(), + }, + wantDup: true, + wantErr: true, + wantErrMsg: `db.Create: create failed: duplicate key value violates unique constraint`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + w := db.New(conn) + if tt.wantDup { + r := tt.args.role.Clone().(*iam.ManagedGroupRole) + err := w.Create(context.Background(), r) + require.NoError(err) + } + r := tt.args.role.Clone().(*iam.ManagedGroupRole) + err := w.Create(context.Background(), r) + if tt.wantErr { + require.Error(err) + assert.Contains(err.Error(), tt.wantErrMsg) + assert.True(errors.Match(errors.T(tt.wantIsErr), err)) + return + } + assert.NoError(err) + + found := iam.AllocManagedGroupRole() + err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", r.RoleId, r.PrincipalId) + require.NoError(err) + assert.Equal(r, &found) + }) + } +} + +func TestManagedGroupRole_Update(t *testing.T) { + t.Parallel() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + + repo := iam.TestRepo(t, conn, wrap) + org, _ := iam.TestScopes(t, repo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, org.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + t.Run("updates not allowed", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + r := iam.TestRole(t, conn, org.PublicId) + mg := oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter) + mg2 := oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter) + mgr := iam.TestManagedGroupRole(t, conn, r.PublicId, mg.PublicId) + updateRole := mgr.Clone().(*iam.ManagedGroupRole) + updateRole.PrincipalId = mg2.PublicId + updatedRows, err := rw.Update(context.Background(), updateRole, []string{"PrincipalId"}, nil) + require.Error(err) + assert.Equal(0, updatedRows) + }) +} + +func TestManagedGroupRole_Delete(t *testing.T) { + t.Parallel() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + + repo := iam.TestRepo(t, conn, wrap) + org, _ := iam.TestScopes(t, repo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, org.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + id := testId(t) + mg := oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter) + r := iam.TestRole(t, conn, org.PublicId) + + tests := []struct { + name string + role *iam.ManagedGroupRole + wantRowsDeleted int + wantErr bool + wantErrMsg string + }{ + { + name: "valid", + role: iam.TestManagedGroupRole(t, conn, r.PublicId, mg.PublicId), + wantErr: false, + wantRowsDeleted: 1, + }, + { + name: "bad-id", + role: func() *iam.ManagedGroupRole { + r := iam.AllocManagedGroupRole() + r.PrincipalId = id + r.RoleId = id + return &r + }(), + wantErr: false, + wantRowsDeleted: 0, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + deleteRole := iam.AllocManagedGroupRole() + deleteRole.RoleId = tt.role.GetRoleId() + deleteRole.PrincipalId = tt.role.GetPrincipalId() + deletedRows, err := rw.Delete(context.Background(), &deleteRole) + if tt.wantErr { + require.Error(err) + return + } + require.NoError(err) + if tt.wantRowsDeleted == 0 { + assert.Equal(tt.wantRowsDeleted, deletedRows) + return + } + assert.Equal(tt.wantRowsDeleted, deletedRows) + found := iam.AllocManagedGroupRole() + err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", tt.role.GetRoleId(), tt.role.GetPrincipalId()) + require.Error(err) + assert.True(errors.IsNotFoundError(err)) + }) + } +} + +func TestManagedGroupRole_Clone(t *testing.T) { + t.Parallel() + t.Run("valid", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + mgr, err := iam.NewManagedGroupRole("r_abc", "mgoidc_abc") + require.NoError(err) + cp := mgr.Clone() + assert.True(proto.Equal(cp.(*iam.ManagedGroupRole).ManagedGroupRole, mgr.ManagedGroupRole)) + }) + t.Run("not-equal", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + mgr, err := iam.NewManagedGroupRole("r_abc", "mgoidc_abc") + require.NoError(err) + mgr2, err := iam.NewManagedGroupRole("r_xyz", "mgoidc_xyz") + require.NoError(err) + cp := mgr.Clone() + + assert.True(!proto.Equal(cp.(*iam.ManagedGroupRole).ManagedGroupRole, mgr2.ManagedGroupRole)) + }) +} diff --git a/internal/iam/principal_role_test.go b/internal/iam/principal_role_test.go index e6af872bb..9f03c1a90 100644 --- a/internal/iam/principal_role_test.go +++ b/internal/iam/principal_role_test.go @@ -571,7 +571,7 @@ func TestGroupRole_Create(t *testing.T) { wantIsErr: errors.InvalidParameter, }, { - name: "missing-user-id", + name: "missing-group-id", args: args{ role: func() *GroupRole { role := TestRole(t, conn, proj.PublicId) @@ -584,7 +584,7 @@ func TestGroupRole_Create(t *testing.T) { }(), }, wantErr: true, - wantErrMsg: "db.Create: iam.(GroupRole).VetForWrite: missing user id: parameter violation: error #100", + wantErrMsg: "db.Create: iam.(GroupRole).VetForWrite: missing group id: parameter violation: error #100", wantIsErr: errors.InvalidParameter, }, { @@ -865,3 +865,39 @@ func TestGroupRole_SetTableName(t *testing.T) { }) } } + +func TestManagedGroupRole_SetTableName(t *testing.T) { + defaultTableName := managedGroupRoleDefaultTable + tests := []struct { + name string + initialName string + setNameTo string + want string + }{ + { + name: "new-name", + initialName: "", + setNameTo: "new-name", + want: "new-name", + }, + { + name: "reset to default", + initialName: "initial", + setNameTo: "", + want: defaultTableName, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + def := AllocManagedGroupRole() + require.Equal(defaultTableName, def.TableName()) + s := &ManagedGroupRole{ + ManagedGroupRole: &store.ManagedGroupRole{}, + tableName: tt.initialName, + } + s.SetTableName(tt.setNameTo) + assert.Equal(tt.want, s.TableName()) + }) + } +} diff --git a/internal/iam/repository_principal_role.go b/internal/iam/repository_principal_role.go index 02797e52d..e412313bd 100644 --- a/internal/iam/repository_principal_role.go +++ b/internal/iam/repository_principal_role.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -24,12 +25,12 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV if roleVersion == 0 { return nil, errors.New(errors.InvalidParameter, op, "missing version") } - userIds, groupIds, err := splitPrincipals(principalIds) + userIds, groupIds, managedGroupIds, err := splitPrincipals(principalIds) if err != nil { return nil, errors.Wrap(err, op) } - if len(userIds) == 0 && len(groupIds) == 0 { - return nil, errors.New(errors.InvalidParameter, op, "missing either user or groups to add") + if len(userIds) == 0 && len(groupIds) == 0 && len(managedGroupIds) == 0 { + return nil, errors.New(errors.InvalidParameter, op, "missing any of users, groups, or managed groups to add") } newUserRoles := make([]interface{}, 0, len(userIds)) @@ -48,6 +49,14 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV } newGrpRoles = append(newGrpRoles, grpRole) } + newManagedGrpRoles := make([]interface{}, 0, len(managedGroupIds)) + for _, id := range managedGroupIds { + managedGrpRole, err := NewManagedGroupRole(roleId, id) + if err != nil { + return nil, errors.Wrap(err, op, errors.WithMsg("unable to create in memory managed group role")) + } + newManagedGrpRoles = append(newManagedGrpRoles, managedGrpRole) + } role := allocRole() role.PublicId = roleId @@ -98,6 +107,13 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV } msgs = append(msgs, grpOplogMsgs...) } + if len(newManagedGrpRoles) > 0 { + managedGrpOplogMsgs := make([]*oplog.Message, 0, len(newManagedGrpRoles)) + if err := w.CreateItems(ctx, newManagedGrpRoles, db.NewOplogMsgs(&managedGrpOplogMsgs)); err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to add managed groups")) + } + msgs = append(msgs, managedGrpOplogMsgs...) + } metadata := oplog.Metadata{ "op-type": []string{oplog.OpType_OP_TYPE_CREATE.String()}, "scope-id": []string{scope.PublicId}, @@ -147,18 +163,18 @@ func (r *Repository) SetPrincipalRoles(ctx context.Context, roleId string, roleV // it's "safe" to do this lookup outside the DoTx transaction because we // have a roleVersion so the principals can’t change without the version // changing. - userIds, groupIds, err := splitPrincipals(principalIds) + userIds, groupIds, managedGroupIds, err := splitPrincipals(principalIds) if err != nil { return nil, db.NoRowsAffected, errors.Wrap(err, op) } - toSet, err := r.principalsToSet(ctx, &role, userIds, groupIds) + toSet, err := r.PrincipalsToSet(ctx, &role, userIds, groupIds, managedGroupIds) if err != nil { return nil, db.NoRowsAffected, errors.Wrap(err, op) } // handle no change to existing principal roles - if len(toSet.unchangedPrincipalRoles) > 0 { - return toSet.unchangedPrincipalRoles, db.NoRowsAffected, nil + if len(toSet.UnchangedPrincipalRoles) > 0 { + return toSet.UnchangedPrincipalRoles, db.NoRowsAffected, nil } scope, err := role.GetScope(ctx, r.reader) @@ -204,51 +220,75 @@ func (r *Repository) SetPrincipalRoles(ctx context.Context, roleId string, roleV } msgs = append(msgs, &roleOplogMsg) - if len(toSet.deleteUserRoles) > 0 || len(toSet.deleteGroupRoles) > 0 { + if len(toSet.DeleteUserRoles) > 0 || + len(toSet.DeleteGroupRoles) > 0 || + len(toSet.DeleteManagedGroupRoles) > 0 { metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_DELETE.String()) - if len(toSet.deleteUserRoles) > 0 { - userOplogMsgs := make([]*oplog.Message, 0, len(toSet.deleteUserRoles)) - rowsDeleted, err := w.DeleteItems(ctx, toSet.deleteUserRoles, db.NewOplogMsgs(&userOplogMsgs)) + if len(toSet.DeleteUserRoles) > 0 { + userOplogMsgs := make([]*oplog.Message, 0, len(toSet.DeleteUserRoles)) + rowsDeleted, err := w.DeleteItems(ctx, toSet.DeleteUserRoles, db.NewOplogMsgs(&userOplogMsgs)) if err != nil { return errors.Wrap(err, op, errors.WithMsg("unable to delete user roles")) } - if rowsDeleted != len(toSet.deleteUserRoles) { - return errors.New(errors.MultipleRecords, op, fmt.Sprintf("user roles deleted %d did not match request for %d", rowsDeleted, len(toSet.deleteUserRoles))) + if rowsDeleted != len(toSet.DeleteUserRoles) { + return errors.New(errors.MultipleRecords, op, fmt.Sprintf("user roles deleted %d did not match request for %d", rowsDeleted, len(toSet.DeleteUserRoles))) } totalRowsAffected += rowsDeleted msgs = append(msgs, userOplogMsgs...) } - if len(toSet.deleteGroupRoles) > 0 { - grpOplogMsgs := make([]*oplog.Message, 0, len(toSet.deleteGroupRoles)) - rowsDeleted, err := w.DeleteItems(ctx, toSet.deleteGroupRoles, db.NewOplogMsgs(&grpOplogMsgs)) + if len(toSet.DeleteGroupRoles) > 0 { + grpOplogMsgs := make([]*oplog.Message, 0, len(toSet.DeleteGroupRoles)) + rowsDeleted, err := w.DeleteItems(ctx, toSet.DeleteGroupRoles, db.NewOplogMsgs(&grpOplogMsgs)) if err != nil { return errors.Wrap(err, op, errors.WithMsg("unable to delete groups")) } - if rowsDeleted != len(toSet.deleteGroupRoles) { - return errors.New(errors.MultipleRecords, op, fmt.Sprintf("group roles deleted %d did not match request for %d", rowsDeleted, len(toSet.deleteGroupRoles))) + if rowsDeleted != len(toSet.DeleteGroupRoles) { + return errors.New(errors.MultipleRecords, op, fmt.Sprintf("group roles deleted %d did not match request for %d", rowsDeleted, len(toSet.DeleteGroupRoles))) } totalRowsAffected += rowsDeleted msgs = append(msgs, grpOplogMsgs...) } + if len(toSet.DeleteManagedGroupRoles) > 0 { + managedGrpOplogMsgs := make([]*oplog.Message, 0, len(toSet.DeleteManagedGroupRoles)) + rowsDeleted, err := w.DeleteItems(ctx, toSet.DeleteManagedGroupRoles, db.NewOplogMsgs(&managedGrpOplogMsgs)) + if err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to delete managed groups")) + } + if rowsDeleted != len(toSet.DeleteManagedGroupRoles) { + return errors.New(errors.MultipleRecords, op, fmt.Sprintf("managed group roles deleted %d did not match request for %d", rowsDeleted, len(toSet.DeleteManagedGroupRoles))) + } + totalRowsAffected += rowsDeleted + msgs = append(msgs, managedGrpOplogMsgs...) + } } - if len(toSet.addUserRoles) > 0 || len(toSet.addGroupRoles) > 0 { + if len(toSet.AddUserRoles) > 0 || + len(toSet.AddGroupRoles) > 0 || + len(toSet.AddManagedGroupRoles) > 0 { metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_CREATE.String()) - if len(toSet.addUserRoles) > 0 { - userOplogMsgs := make([]*oplog.Message, 0, len(toSet.addUserRoles)) - if err := w.CreateItems(ctx, toSet.addUserRoles, db.NewOplogMsgs(&userOplogMsgs)); err != nil { + if len(toSet.AddUserRoles) > 0 { + userOplogMsgs := make([]*oplog.Message, 0, len(toSet.AddUserRoles)) + if err := w.CreateItems(ctx, toSet.AddUserRoles, db.NewOplogMsgs(&userOplogMsgs)); err != nil { return errors.Wrap(err, op, errors.WithMsg("unable to add users")) } - totalRowsAffected += len(toSet.addUserRoles) + totalRowsAffected += len(toSet.AddUserRoles) msgs = append(msgs, userOplogMsgs...) } - if len(toSet.addGroupRoles) > 0 { - grpOplogMsgs := make([]*oplog.Message, 0, len(toSet.addGroupRoles)) - if err := w.CreateItems(ctx, toSet.addGroupRoles, db.NewOplogMsgs(&grpOplogMsgs)); err != nil { + if len(toSet.AddGroupRoles) > 0 { + grpOplogMsgs := make([]*oplog.Message, 0, len(toSet.AddGroupRoles)) + if err := w.CreateItems(ctx, toSet.AddGroupRoles, db.NewOplogMsgs(&grpOplogMsgs)); err != nil { return errors.Wrap(err, op, errors.WithMsg("unable to add groups")) } - totalRowsAffected += len(toSet.addGroupRoles) + totalRowsAffected += len(toSet.AddGroupRoles) msgs = append(msgs, grpOplogMsgs...) } + if len(toSet.AddManagedGroupRoles) > 0 { + managedGrpOplogMsgs := make([]*oplog.Message, 0, len(toSet.AddManagedGroupRoles)) + if err := w.CreateItems(ctx, toSet.AddManagedGroupRoles, db.NewOplogMsgs(&managedGrpOplogMsgs)); err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to add managed groups")) + } + totalRowsAffected += len(toSet.AddManagedGroupRoles) + msgs = append(msgs, managedGrpOplogMsgs...) + } } if err := w.WriteOplogEntryWith(ctx, oplogWrapper, roleTicket, metadata, msgs); err != nil { return errors.Wrap(err, op, errors.WithMsg("unable to write oplog")) @@ -282,12 +322,12 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro if roleId == "" { return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing role id") } - userIds, groupIds, err := splitPrincipals(principalIds) + userIds, groupIds, managedGroupIds, err := splitPrincipals(principalIds) if err != nil { return db.NoRowsAffected, errors.Wrap(err, op) } - if len(userIds) == 0 && len(groupIds) == 0 { - return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing either user or groups to delete") + if len(userIds) == 0 && len(groupIds) == 0 && len(managedGroupIds) == 0 { + return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing any of users, groups, or managed groups to delete") } if roleVersion == 0 { return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing version") @@ -311,6 +351,14 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro } deleteGrpRoles = append(deleteGrpRoles, grpRole) } + deleteManagedGrpRoles := make([]interface{}, 0, len(managedGroupIds)) + for _, id := range managedGroupIds { + managedGrpRole, err := NewManagedGroupRole(roleId, id) + if err != nil { + return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to create in memory managed group role")) + } + deleteManagedGrpRoles = append(deleteManagedGrpRoles, managedGrpRole) + } scope, err := role.GetScope(ctx, r.reader) if err != nil { @@ -368,6 +416,18 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro totalRowsDeleted += rowsDeleted msgs = append(msgs, grpOplogMsgs...) } + if len(deleteManagedGrpRoles) > 0 { + managedGrpOplogMsgs := make([]*oplog.Message, 0, len(deleteManagedGrpRoles)) + rowsDeleted, err := w.DeleteItems(ctx, deleteManagedGrpRoles, db.NewOplogMsgs(&managedGrpOplogMsgs)) + if err != nil { + return errors.Wrap(err, op, errors.WithMsg("unable to delete managed groups")) + } + if rowsDeleted != len(deleteManagedGrpRoles) { + return errors.New(errors.MultipleRecords, op, fmt.Sprintf("managed group roles deleted %d did not match request for %d", rowsDeleted, len(deleteManagedGrpRoles))) + } + totalRowsDeleted += rowsDeleted + msgs = append(msgs, managedGrpOplogMsgs...) + } metadata := oplog.Metadata{ "op-type": []string{oplog.OpType_OP_TYPE_DELETE.String()}, "scope-id": []string{scope.PublicId}, @@ -401,19 +461,22 @@ func (r *Repository) ListPrincipalRoles(ctx context.Context, roleId string, opt return principals, nil } -type principalSet struct { - addUserRoles []interface{} - addGroupRoles []interface{} - deleteUserRoles []interface{} - deleteGroupRoles []interface{} +type PrincipalSet struct { + AddUserRoles []interface{} + AddGroupRoles []interface{} + AddManagedGroupRoles []interface{} + DeleteUserRoles []interface{} + DeleteGroupRoles []interface{} + DeleteManagedGroupRoles []interface{} // unchangedPrincipalRoles is set iff there are no changes, that is, the // length of all other members is zero - unchangedPrincipalRoles []PrincipalRole + UnchangedPrincipalRoles []PrincipalRole } // TODO: Should this be moved inside the transaction, at this point? -func (r *Repository) principalsToSet(ctx context.Context, role *Role, userIds, groupIds []string) (*principalSet, error) { - const op = "iam.(Repository).principalsToSet" +// PrincipalsToSet sets principals on a role from the given lists. +func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, groupIds, managedGroupIds []string) (*PrincipalSet, error) { + const op = "iam.(Repository).PrincipalsToSet" // TODO(mgaffney) 08/2020: Use SQL to calculate changes. if role == nil { return nil, errors.New(errors.InvalidParameter, op, "missing role") @@ -424,12 +487,15 @@ func (r *Repository) principalsToSet(ctx context.Context, role *Role, userIds, g } existingUsers := map[string]PrincipalRole{} existingGroups := map[string]PrincipalRole{} + existingManagedGroups := map[string]PrincipalRole{} for _, p := range existing { switch p.GetType() { case UserRoleType.String(): existingUsers[p.PrincipalId] = p case GroupRoleType.String(): existingGroups[p.PrincipalId] = p + case ManagedGroupRoleType.String(): + existingManagedGroups[p.PrincipalId] = p default: return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s is unknown principal type %s", p.PrincipalId, p.GetType())) } @@ -458,6 +524,18 @@ func (r *Repository) principalsToSet(ctx context.Context, role *Role, userIds, g newGrpRoles = append(newGrpRoles, grpRole) } } + var newManagedGrpRoles []interface{} + managedGroupIdsMap := map[string]struct{}{} + for _, id := range managedGroupIds { + managedGroupIdsMap[id] = struct{}{} + if _, ok := existingManagedGroups[id]; !ok { + managedGrpRole, err := NewManagedGroupRole(role.PublicId, id) + if err != nil { + return nil, errors.Wrap(err, op, errors.WithMsg("unable to create in memory managed group role for add")) + } + newManagedGrpRoles = append(newManagedGrpRoles, managedGrpRole) + } + } var deleteUserRoles []interface{} for _, p := range existingUsers { if _, ok := userIdsMap[p.PrincipalId]; !ok { @@ -478,35 +556,61 @@ func (r *Repository) principalsToSet(ctx context.Context, role *Role, userIds, g deleteGrpRoles = append(deleteGrpRoles, grpRole) } } - - toSet := &principalSet{ - addUserRoles: newUserRoles, - addGroupRoles: newGrpRoles, - deleteUserRoles: deleteUserRoles, - deleteGroupRoles: deleteGrpRoles, + var deleteManagedGrpRoles []interface{} + for _, p := range existingManagedGroups { + if _, ok := managedGroupIdsMap[p.PrincipalId]; !ok { + managedGrpRole, err := NewManagedGroupRole(p.GetRoleId(), p.GetPrincipalId()) + if err != nil { + return nil, errors.Wrap(err, op, errors.WithMsg("unable to create in memory managed group role for delete")) + } + deleteManagedGrpRoles = append(deleteManagedGrpRoles, managedGrpRole) + } } - if len(toSet.addUserRoles) == 0 && len(toSet.addGroupRoles) == 0 && len(toSet.deleteUserRoles) == 0 && len(toSet.deleteGroupRoles) == 0 { - toSet.unchangedPrincipalRoles = existing + toSet := &PrincipalSet{ + AddUserRoles: newUserRoles, + AddGroupRoles: newGrpRoles, + AddManagedGroupRoles: newManagedGrpRoles, + DeleteUserRoles: deleteUserRoles, + DeleteGroupRoles: deleteGrpRoles, + DeleteManagedGroupRoles: deleteManagedGrpRoles, + } + + if len(toSet.AddUserRoles) == 0 && + len(toSet.AddGroupRoles) == 0 && + len(toSet.AddManagedGroupRoles) == 0 && + len(toSet.DeleteUserRoles) == 0 && + len(toSet.DeleteGroupRoles) == 0 && + len(toSet.DeleteManagedGroupRoles) == 0 { + toSet.UnchangedPrincipalRoles = existing } return toSet, nil } -func splitPrincipals(principals []string) ([]string, []string, error) { +func splitPrincipals(principals []string) (users, groups, managedGroups []string, retErr error) { const op = "iam.splitPrincipals" - var users, groups []string for _, principal := range principals { switch { case strings.HasPrefix(principal, UserPrefix): + if users == nil { + users = make([]string, 0, len(principals)) + } users = append(users, principal) - // TODO: This needs to handle all of the kinds of group prefixes (sg_, dg_, etc.) case strings.HasPrefix(principal, GroupPrefix): + if groups == nil { + groups = make([]string, 0, len(principals)) + } groups = append(groups, principal) + case strings.HasPrefix(principal, intglobals.OidcManagedGroupPrefix): + if managedGroups == nil { + managedGroups = make([]string, 0, len(principals)) + } + managedGroups = append(managedGroups, principal) default: - return nil, nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("invalid principal ID %q", principal)) + return nil, nil, nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("invalid principal ID %q", principal)) } } - return users, groups, nil + return } diff --git a/internal/iam/repository_principal_role_ext_test.go b/internal/iam/repository_principal_role_ext_test.go new file mode 100644 index 000000000..8ab944a80 --- /dev/null +++ b/internal/iam/repository_principal_role_ext_test.go @@ -0,0 +1,251 @@ +package iam_test + +import ( + "context" + "sort" + "testing" + + "github.com/hashicorp/boundary/internal/auth/oidc" + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/kms" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRepository_PrincipalsToSet(t *testing.T) { + t.Parallel() + conn, _ := db.TestSetup(t, "postgres") + + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + + repo := iam.TestRepo(t, conn, wrap) + org, proj := iam.TestScopes(t, repo) + + ctx := context.Background() + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, org.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + createUsersFn := func() []string { + results := []string{} + for i := 0; i < 5; i++ { + u := iam.TestUser(t, repo, org.PublicId) + results = append(results, u.PublicId) + } + return results + } + createGrpsFn := func() []string { + results := []string{} + for i := 0; i < 5; i++ { + g := iam.TestGroup(t, conn, proj.PublicId) + results = append(results, g.PublicId) + } + return results + } + createManagedGrpsFn := func() []string { + results := []string{} + for i := 0; i < 5; i++ { + g := oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter) + results = append(results, g.PublicId) + } + return results + } + setupFn := func() (*iam.Role, []string, []string, []string) { + users := createUsersFn() + grps := createGrpsFn() + managedGrps := createManagedGrpsFn() + role := iam.TestRole(t, conn, proj.PublicId) + _, err := repo.AddPrincipalRoles(context.Background(), role.PublicId, 1, append(users, append(grps, managedGrps...)...)) + require.NoError(t, err) + return role, users, grps, managedGrps + } + + type args struct { + userIds []string + groupIds []string + managedGroupIds []string + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "all new", + args: args{ + userIds: createUsersFn(), + groupIds: createGrpsFn(), + managedGroupIds: createManagedGrpsFn(), + }, + wantErr: false, + }, + { + name: "clear all", + args: args{ + userIds: nil, + groupIds: nil, + managedGroupIds: nil, + }, + wantErr: false, + }, + { + name: "just new users", + args: args{ + userIds: createUsersFn(), + groupIds: nil, + managedGroupIds: nil, + }, + wantErr: false, + }, + { + name: "just new groups", + args: args{ + userIds: nil, + groupIds: createGrpsFn(), + managedGroupIds: nil, + }, + wantErr: false, + }, + { + name: "just new managed groups", + args: args{ + userIds: nil, + groupIds: nil, + managedGroupIds: createManagedGrpsFn(), + }, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require := require.New(t) + r, origUsers, origGrps, origManagedGrps := setupFn() + got, err := repo.PrincipalsToSet(context.Background(), r, tt.args.userIds, tt.args.groupIds, tt.args.managedGroupIds) + if tt.wantErr { + require.Error(err) + return + } + require.NoError(err) + assertSetResults(t, got, tt.args.userIds, tt.args.groupIds, tt.args.managedGroupIds, origUsers, origGrps, origManagedGrps) + }) + } + t.Run("nil role", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + _, users, grps, managedGrps := setupFn() + got, err := repo.PrincipalsToSet(context.Background(), nil, users, grps, managedGrps) + require.Error(err) + assert.Nil(got) + assert.Truef(errors.Match(errors.T(errors.InvalidParameter), err), "unexpected error %s", err.Error()) + }) + t.Run("no change", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + r, users, grps, managedGrps := setupFn() + got, err := repo.PrincipalsToSet(context.Background(), r, users, grps, managedGrps) + require.NoError(err) + assert.Empty(got.AddUserRoles) + assert.Empty(got.AddGroupRoles) + assert.Empty(got.AddManagedGroupRoles) + assert.Empty(got.DeleteUserRoles) + assert.Empty(got.DeleteGroupRoles) + assert.Empty(got.DeleteManagedGroupRoles) + assert.Equal(len(users)+len(grps)+len(managedGrps), len(got.UnchangedPrincipalRoles)) + }) + t.Run("mixed", func(t *testing.T) { + require := require.New(t) + r, users, grps, managedGrps := setupFn() + var wantSetUsers, wantSetGrps, wantSetManagedGrps, wantDeleteUsers, wantDeleteGrps, wantDeleteManagedGrps []string + for i, id := range users { + if i < 2 { + wantSetUsers = append(wantSetUsers, id) + } else { + wantDeleteUsers = append(wantDeleteUsers, id) + } + } + for i, id := range grps { + if i < 2 { + wantSetGrps = append(wantSetGrps, id) + } else { + wantDeleteGrps = append(wantDeleteGrps, id) + } + } + for i, id := range managedGrps { + if i < 2 { + wantSetManagedGrps = append(wantSetManagedGrps, id) + } else { + wantDeleteManagedGrps = append(wantDeleteManagedGrps, id) + } + } + newUser := iam.TestUser(t, repo, org.PublicId) + newGrp := iam.TestGroup(t, conn, proj.PublicId) + newManagedGrp := oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter) + wantSetUsers = append(wantSetUsers, newUser.PublicId) + wantSetGrps = append(wantSetGrps, newGrp.PublicId) + wantSetManagedGrps = append(wantSetManagedGrps, newManagedGrp.PublicId) + + got, err := repo.PrincipalsToSet(context.Background(), r, wantSetUsers, wantSetGrps, wantSetManagedGrps) + require.NoError(err) + assertSetResults(t, got, []string{newUser.PublicId}, []string{newGrp.PublicId}, []string{newManagedGrp.PublicId}, wantDeleteUsers, wantDeleteGrps, wantDeleteManagedGrps) + }) +} + +func assertSetResults(t *testing.T, got *iam.PrincipalSet, wantAddUsers, wantAddGroups, wantAddManagedGroups, wantDeleteUsers, wantDeleteGroups, wantDeleteManagedGroups []string) { + t.Helper() + assert := assert.New(t) + var gotAddUsers []string + for _, r := range got.AddUserRoles { + gotAddUsers = append(gotAddUsers, r.(*iam.UserRole).PrincipalId) + } + // sort.Strings(wantAddUsers) + // sort.Strings(gotAddUsers) + assert.Equal(wantAddUsers, gotAddUsers) + + var gotAddGrps []string + for _, r := range got.AddGroupRoles { + gotAddGrps = append(gotAddGrps, r.(*iam.GroupRole).PrincipalId) + } + // sort.Strings(wantAddGroups) + // sort.Strings(gotAddGrps) + assert.Equal(wantAddGroups, gotAddGrps) + + var gotAddManagedGrps []string + for _, r := range got.AddManagedGroupRoles { + gotAddManagedGrps = append(gotAddManagedGrps, r.(*iam.ManagedGroupRole).PrincipalId) + } + // sort.Strings(wantAddGroups) + // sort.Strings(gotAddGrps) + assert.Equal(wantAddManagedGroups, gotAddManagedGrps) + + var gotDeleteUsers []string + for _, r := range got.DeleteUserRoles { + gotDeleteUsers = append(gotDeleteUsers, r.(*iam.UserRole).PrincipalId) + } + sort.Strings(wantDeleteUsers) + sort.Strings(gotDeleteUsers) + assert.Equal(wantDeleteUsers, gotDeleteUsers) + + var gotDeleteGroups []string + for _, r := range got.DeleteGroupRoles { + gotDeleteGroups = append(gotDeleteGroups, r.(*iam.GroupRole).PrincipalId) + } + sort.Strings(wantDeleteGroups) + sort.Strings(gotDeleteGroups) + assert.Equal(wantDeleteGroups, gotDeleteGroups) + + var gotDeleteManagedGroups []string + for _, r := range got.DeleteManagedGroupRoles { + gotDeleteManagedGroups = append(gotDeleteManagedGroups, r.(*iam.ManagedGroupRole).PrincipalId) + } + sort.Strings(wantDeleteManagedGroups) + sort.Strings(gotDeleteManagedGroups) + assert.Equal(wantDeleteManagedGroups, gotDeleteManagedGroups) +} diff --git a/internal/iam/repository_principal_role_test.go b/internal/iam/repository_principal_role_test.go index e04298b99..9ac480aef 100644 --- a/internal/iam/repository_principal_role_test.go +++ b/internal/iam/repository_principal_role_test.go @@ -677,173 +677,3 @@ func TestRepository_SetPrincipalRoles(t *testing.T) { }) } } - -func TestRepository_principalsToSet(t *testing.T) { - t.Parallel() - conn, _ := db.TestSetup(t, "postgres") - wrapper := db.TestWrapper(t) - repo := TestRepo(t, conn, wrapper) - org, proj := TestScopes(t, repo) - createUsersFn := func() []string { - results := []string{} - for i := 0; i < 5; i++ { - u := TestUser(t, repo, org.PublicId) - results = append(results, u.PublicId) - } - return results - } - createGrpsFn := func() []string { - results := []string{} - for i := 0; i < 5; i++ { - g := TestGroup(t, conn, proj.PublicId) - results = append(results, g.PublicId) - } - return results - } - setupFn := func() (*Role, []string, []string) { - users := createUsersFn() - grps := createGrpsFn() - role := TestRole(t, conn, proj.PublicId) - _, err := repo.AddPrincipalRoles(context.Background(), role.PublicId, 1, append(users, grps...)) - require.NoError(t, err) - return role, users, grps - } - - type args struct { - userIds []string - groupIds []string - } - tests := []struct { - name string - args args - wantErr bool - }{ - { - name: "all new", - args: args{ - userIds: createUsersFn(), - groupIds: createGrpsFn(), - }, - wantErr: false, - }, - { - name: "clear all", - args: args{ - userIds: nil, - groupIds: nil, - }, - wantErr: false, - }, - { - name: "just new users", - args: args{ - userIds: createUsersFn(), - groupIds: nil, - }, - wantErr: false, - }, - { - name: "just new groups", - args: args{ - userIds: nil, - groupIds: createGrpsFn(), - }, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - r, origUsers, origGrps := setupFn() - got, err := repo.principalsToSet(context.Background(), r, tt.args.userIds, tt.args.groupIds) - if tt.wantErr { - require.Error(err) - return - } - require.NoError(err) - assertSetResults(t, got, tt.args.userIds, tt.args.groupIds, origUsers, origGrps) - }) - } - t.Run("nil role", func(t *testing.T) { - assert, require := assert.New(t), require.New(t) - _, users, grps := setupFn() - got, err := repo.principalsToSet(context.Background(), nil, users, grps) - require.Error(err) - assert.Nil(got) - assert.Truef(errors.Match(errors.T(errors.InvalidParameter), err), "unexpected error %s", err.Error()) - }) - t.Run("no change", func(t *testing.T) { - assert, require := assert.New(t), require.New(t) - r, users, grps := setupFn() - got, err := repo.principalsToSet(context.Background(), r, users, grps) - require.NoError(err) - assert.Empty(got.addUserRoles) - assert.Empty(got.addGroupRoles) - assert.Empty(got.deleteUserRoles) - assert.Empty(got.deleteGroupRoles) - assert.Equal(len(users)+len(grps), len(got.unchangedPrincipalRoles)) - }) - t.Run("mixed", func(t *testing.T) { - require := require.New(t) - r, users, grps := setupFn() - var wantSetUsers, wantSetGrps, wantDeleteUsers, wantDeleteGrps []string - for i, id := range users { - if i < 2 { - wantSetUsers = append(wantSetUsers, id) - } else { - wantDeleteUsers = append(wantDeleteUsers, id) - } - } - for i, id := range grps { - if i < 2 { - wantSetGrps = append(wantSetGrps, id) - } else { - wantDeleteGrps = append(wantDeleteGrps, id) - } - } - newUser := TestUser(t, repo, org.PublicId) - newGrp := TestGroup(t, conn, proj.PublicId) - wantSetUsers = append(wantSetUsers, newUser.PublicId) - wantSetGrps = append(wantSetGrps, newGrp.PublicId) - - got, err := repo.principalsToSet(context.Background(), r, wantSetUsers, wantSetGrps) - require.NoError(err) - assertSetResults(t, got, []string{newUser.PublicId}, []string{newGrp.PublicId}, wantDeleteUsers, wantDeleteGrps) - }) -} - -func assertSetResults(t *testing.T, got *principalSet, wantAddUsers, wantAddGroups, wantDeleteUsers, wantDeleteGroups []string) { - t.Helper() - assert := assert.New(t) - var gotAddUsers []string - for _, r := range got.addUserRoles { - gotAddUsers = append(gotAddUsers, r.(*UserRole).PrincipalId) - } - // sort.Strings(wantAddUsers) - // sort.Strings(gotAddUsers) - assert.Equal(wantAddUsers, gotAddUsers) - - var gotAddGrps []string - for _, r := range got.addGroupRoles { - gotAddGrps = append(gotAddGrps, r.(*GroupRole).PrincipalId) - } - // sort.Strings(wantAddGroups) - // sort.Strings(gotAddGrps) - assert.Equal(wantAddGroups, gotAddGrps) - - var gotDeleteUsers []string - for _, r := range got.deleteUserRoles { - gotDeleteUsers = append(gotDeleteUsers, r.(*UserRole).PrincipalId) - } - sort.Strings(wantDeleteUsers) - sort.Strings(gotDeleteUsers) - assert.Equal(wantDeleteUsers, gotDeleteUsers) - - var gotDeleteGroups []string - for _, r := range got.deleteGroupRoles { - gotDeleteGroups = append(gotDeleteGroups, r.(*GroupRole).PrincipalId) - } - sort.Strings(wantDeleteGroups) - sort.Strings(gotDeleteGroups) - assert.Equal(wantDeleteGroups, gotDeleteGroups) -} diff --git a/internal/iam/repository_role_grant.go b/internal/iam/repository_role_grant.go index 280ecbf44..498cddda9 100644 --- a/internal/iam/repository_role_grant.go +++ b/internal/iam/repository_role_grant.go @@ -385,7 +385,7 @@ func (r *Repository) ListRoleGrants(ctx context.Context, roleId string, opt ...O return roleGrants, nil } -func (r *Repository) GrantsForUser(ctx context.Context, userId string, _ ...Option) ([]perms.GrantPair, error) { +func (r *Repository) GrantsForUser(ctx context.Context, userId string, _ ...Option) ([]perms.GrantTuple, error) { const op = "iam.(Repository).GrantsForUser" if userId == "" { return nil, errors.New(errors.InvalidParameter, op, "missing user id") @@ -407,6 +407,24 @@ user_groups (id) as ( users where member_id in (users.id) ), +user_accounts (id) as ( + select public_id + from auth_account, + users + where iam_user_id in (users.id) +), +user_managed_groups (id) as ( + select managed_group_id + from auth_managed_group_member_account, + user_accounts + where member_id in (user_accounts.id) +), +managed_group_roles (role_id) as ( + select role_id + from iam_managed_group_role, + user_managed_groups + where principal_id in (user_managed_groups.id) +), group_roles (role_id) as ( select role_id from iam_group_role, @@ -425,6 +443,9 @@ user_group_roles (role_id) as ( union select role_id from user_roles + union + select role_id + from managed_group_roles ), roles (role_id, grant_scope_id) as ( select iam_role.public_id, @@ -433,15 +454,16 @@ roles (role_id, grant_scope_id) as ( user_group_roles where public_id in (user_group_roles.role_id) ), -final (role_scope, role_grant) as ( - select roles.grant_scope_id, +final (role_id, role_scope, role_grant) as ( + select roles.role_id, + roles.grant_scope_id, iam_role_grant.canonical_grant from roles inner join iam_role_grant on roles.role_id = iam_role_grant.role_id ) -select role_scope as scope_id, role_grant as grant from final; +select role_id as role_id, role_scope as scope_id, role_grant as grant from final; ` ) @@ -453,14 +475,14 @@ select role_scope as scope_id, role_grant as grant from final; query = fmt.Sprintf(grantsQuery, authUser) } - var grants []perms.GrantPair + var grants []perms.GrantTuple rows, err := r.reader.Query(ctx, query, []interface{}{userId}) if err != nil { return nil, errors.Wrap(err, op) } defer rows.Close() for rows.Next() { - var g perms.GrantPair + var g perms.GrantTuple if err := r.reader.ScanRows(rows, &g); err != nil { return nil, errors.Wrap(err, op) } diff --git a/internal/iam/repository_role_grant_ext_test.go b/internal/iam/repository_role_grant_ext_test.go new file mode 100644 index 000000000..ebc0f08f6 --- /dev/null +++ b/internal/iam/repository_role_grant_ext_test.go @@ -0,0 +1,252 @@ +package iam_test + +import ( + "context" + "fmt" + mathrand "math/rand" + "testing" + + "github.com/hashicorp/boundary/internal/auth/oidc" + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/types/scope" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGrantsForUser(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + wrap := db.TestWrapper(t) + iamRepo := iam.TestRepo(t, conn, wrap) + + userCount := 10 + groupCount := 30 + managedGroupCount := 30 + roleCount := 30 + // probFactor acts as a mod value; increasing means less probability. 2 = + // 50%, 5 = 20%, etc. + probFactor := 5 + // Turning this off will let users be cross-scope instead of in the same + // scope as the OIDC auth method + testManagedGroups := true + // Turning this off means users are not directly added to roles. Useful + // since we can't set users to 0 (or we won't accounts) but if we want to + // test only managed groups. + addUsersDirectly := true + + o, p := iam.TestScopes( + t, + iamRepo, + iam.WithSkipAdminRoleCreation(true), + iam.WithSkipDefaultRoleCreation(true), + ) + + kmsCache := kms.TestKms(t, conn, wrap) + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + // We're going to generate a bunch of users (each tied to an account), + // groups, and managed groups. These will be randomly assigned and we will + // record assignations. + users, accounts := func() (usrs []*iam.User, accts []*oidc.Account) { + usrs = make([]*iam.User, 0, userCount) + accts = make([]*oidc.Account, 0, userCount) + scopeId := scope.Global.String() + if mathrand.Int()%2 == 0 || testManagedGroups { + scopeId = o.GetPublicId() + } + for i := 0; i < userCount; i++ { + accts = append(accts, oidc.TestAccount(t, conn, authMethod, fmt.Sprintf("sub-%d", i))) + usrs = append(usrs, iam.TestUser( + t, + iamRepo, + scopeId, + iam.WithAccountIds(accts[i].PublicId), + iam.WithName(fmt.Sprintf("testuser%d", i)), + )) + } + return + }() + groups := func() (ret []*iam.Group) { + ret = make([]*iam.Group, 0, groupCount) + scopeId := o.GetPublicId() + if mathrand.Int()%2 == 0 { + scopeId = p.GetPublicId() + } + for i := 0; i < groupCount; i++ { + ret = append(ret, iam.TestGroup(t, conn, scopeId, iam.WithName(fmt.Sprintf("testgroup%d", i)))) + } + return + }() + managedGroups := func() (ret []*oidc.ManagedGroup) { + ret = make([]*oidc.ManagedGroup, 0, managedGroupCount) + for i := 0; i < managedGroupCount; i++ { + ret = append(ret, oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter, oidc.WithName(fmt.Sprintf("testmanagedgroup%d", i)))) + } + return + }() + roles := func() (ret []*iam.Role) { + ret = make([]*iam.Role, 0, roleCount) + scopeId := o.GetPublicId() + if mathrand.Int()%2 == 0 { + scopeId = p.GetPublicId() + } + for i := 0; i < roleCount; i++ { + role := iam.TestRole(t, conn, scopeId, iam.WithName(fmt.Sprintf("testrole%d", i))) + iam.TestRoleGrant(t, conn, role.PublicId, "id=*;type=*;actions=*") + ret = append(ret, role) + } + return + }() + + // This variable stores an easy way to lookup, given a group ID, whether a + // user is in that group. + userToGroupsMapping := map[string]map[string]bool{} + for _, user := range users { + for _, group := range groups { + // Give each user a chance of being in any specific group + if mathrand.Int()%probFactor == 0 { + userId := user.PublicId + groupId := group.PublicId + iam.TestGroupMember(t, conn, groupId, userId) + currentMapping := userToGroupsMapping[userId] + if currentMapping == nil { + currentMapping = make(map[string]bool) + } + currentMapping[groupId] = true + userToGroupsMapping[userId] = currentMapping + } + } + } + // This variable stores an easy way to lookup, given a managed group ID, whether a + // user is in that group. + userToManagedGroupsMapping := map[string]map[string]bool{} + for i, user := range users { + for _, managedGroup := range managedGroups { + // Give each user (account) a chance of being in any specific managed group + if mathrand.Int()%probFactor == 0 { + userId := user.PublicId + accountId := accounts[i].PublicId + managedGroupId := managedGroup.PublicId + oidc.TestManagedGroupMember(t, conn, managedGroupId, accountId) + currentMapping := userToManagedGroupsMapping[userId] + if currentMapping == nil { + currentMapping = make(map[string]bool) + } + currentMapping[managedGroupId] = true + userToManagedGroupsMapping[userId] = currentMapping + } + } + } + + // Now, we're going to randomly assign users and groups to roles and also + // store mappings + userToRolesMapping := map[string]map[string]bool{} + groupToRolesMapping := map[string]map[string]bool{} + managedGroupToRolesMapping := map[string]map[string]bool{} + if addUsersDirectly { + for _, role := range roles { + for _, user := range users { + // Give each user a chance of being directly added to any specific + // role + if mathrand.Int()%probFactor == 0 { + roleId := role.PublicId + userId := user.PublicId + iam.TestUserRole(t, conn, roleId, userId) + currentMapping := userToRolesMapping[userId] + if currentMapping == nil { + currentMapping = make(map[string]bool) + } + currentMapping[roleId] = true + userToRolesMapping[userId] = currentMapping + } + } + } + } + for _, role := range roles { + for _, group := range groups { + // Give each group a chance of being directly added to any specific + // role + if mathrand.Int()%probFactor == 0 { + roleId := role.PublicId + groupId := group.PublicId + iam.TestGroupRole(t, conn, roleId, groupId) + currentMapping := groupToRolesMapping[groupId] + if currentMapping == nil { + currentMapping = make(map[string]bool) + } + currentMapping[roleId] = true + groupToRolesMapping[groupId] = currentMapping + } + } + } + for _, role := range roles { + for _, managedGroup := range managedGroups { + // Give each managed group a chance of being directly added to any + // specific role + if mathrand.Int()%probFactor == 0 { + roleId := role.PublicId + managedGroupId := managedGroup.PublicId + iam.TestManagedGroupRole(t, conn, roleId, managedGroupId) + currentMapping := managedGroupToRolesMapping[managedGroupId] + if currentMapping == nil { + currentMapping = make(map[string]bool) + } + currentMapping[roleId] = true + managedGroupToRolesMapping[managedGroupId] = currentMapping + } + } + } + + // Now, fetch the set of grants. We're going to be testing this by looking + // at the role IDs of the matching grant tuples. + for _, user := range users { + var rolesFromUsers, rolesFromGroups, rolesFromManagedGroups int + + tuples, err := iamRepo.GrantsForUser(ctx, user.PublicId) + require.NoError(t, err) + + // De-dupe role IDs + roleIds := make(map[string]bool, len(tuples)) + for _, tuple := range tuples { + roleIds[tuple.RoleId] = true + } + + // Now, using the previous maps, figure out which roles we _expect_ to + // see returned. This is the set of roles with directly added users, + // plus the set of roles where we added the user as a group member and + // that group to a role. + expectedRoleIds := make(map[string]bool, len(tuples)) + for roleId := range userToRolesMapping[user.PublicId] { + expectedRoleIds[roleId] = true + rolesFromUsers++ + } + for groupId := range userToGroupsMapping[user.PublicId] { + for roleId := range groupToRolesMapping[groupId] { + expectedRoleIds[roleId] = true + rolesFromGroups++ + } + } + for managedGroupId := range userToManagedGroupsMapping[user.PublicId] { + for roleId := range managedGroupToRolesMapping[managedGroupId] { + expectedRoleIds[roleId] = true + rolesFromManagedGroups++ + } + } + + // Now verify that the expected set and returned set match + assert.EqualValues(t, expectedRoleIds, roleIds) + + t.Log("finished user", user.PublicId, "total roles", len(expectedRoleIds), "roles from users", rolesFromUsers, "roles from groups", rolesFromGroups, "roles from managed groups", rolesFromManagedGroups) + } +} diff --git a/internal/iam/store/principal_role.pb.go b/internal/iam/store/principal_role.pb.go index fd97ae7d4..83fa05db5 100644 --- a/internal/iam/store/principal_role.pb.go +++ b/internal/iam/store/principal_role.pb.go @@ -159,6 +159,75 @@ func (x *GroupRole) GetPrincipalId() string { return "" } +type ManagedGroupRole struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // create_time from the RDBMS + // @inject_tag: `gorm:"default:current_timestamp"` + CreateTime *timestamp.Timestamp `protobuf:"bytes,1,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"` + // role_id is the role of this principal. + // @inject_tag: gorm:"primary_key" + RoleId string `protobuf:"bytes,2,opt,name=role_id,json=roleId,proto3" json:"role_id,omitempty" gorm:"primary_key"` + // principal_id is the public_id of the managed group (which is the principal) + // @inject_tag: gorm:"primary_key" + PrincipalId string `protobuf:"bytes,3,opt,name=principal_id,json=principalId,proto3" json:"principal_id,omitempty" gorm:"primary_key"` +} + +func (x *ManagedGroupRole) Reset() { + *x = ManagedGroupRole{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ManagedGroupRole) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ManagedGroupRole) ProtoMessage() {} + +func (x *ManagedGroupRole) ProtoReflect() protoreflect.Message { + mi := &file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ManagedGroupRole.ProtoReflect.Descriptor instead. +func (*ManagedGroupRole) Descriptor() ([]byte, []int) { + return file_controller_storage_iam_store_v1_principal_role_proto_rawDescGZIP(), []int{2} +} + +func (x *ManagedGroupRole) GetCreateTime() *timestamp.Timestamp { + if x != nil { + return x.CreateTime + } + return nil +} + +func (x *ManagedGroupRole) GetRoleId() string { + if x != nil { + return x.RoleId + } + return "" +} + +func (x *ManagedGroupRole) GetPrincipalId() string { + if x != nil { + return x.PrincipalId + } + return "" +} + type PrincipalRoleView struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -188,7 +257,7 @@ type PrincipalRoleView struct { func (x *PrincipalRoleView) Reset() { *x = PrincipalRoleView{} if protoimpl.UnsafeEnabled { - mi := &file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[2] + mi := &file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -201,7 +270,7 @@ func (x *PrincipalRoleView) String() string { func (*PrincipalRoleView) ProtoMessage() {} func (x *PrincipalRoleView) ProtoReflect() protoreflect.Message { - mi := &file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[2] + mi := &file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -214,7 +283,7 @@ func (x *PrincipalRoleView) ProtoReflect() protoreflect.Message { // Deprecated: Use PrincipalRoleView.ProtoReflect.Descriptor instead. func (*PrincipalRoleView) Descriptor() ([]byte, []int) { - return file_controller_storage_iam_store_v1_principal_role_proto_rawDescGZIP(), []int{2} + return file_controller_storage_iam_store_v1_principal_role_proto_rawDescGZIP(), []int{3} } func (x *PrincipalRoleView) GetCreateTime() *timestamp.Timestamp { @@ -296,30 +365,40 @@ var file_controller_storage_iam_store_v1_principal_role_proto_rawDesc = []byte{ 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x6f, 0x6c, 0x65, 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, - 0x70, 0x61, 0x6c, 0x49, 0x64, 0x22, 0xb2, 0x02, 0x0a, 0x11, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, - 0x70, 0x61, 0x6c, 0x52, 0x6f, 0x6c, 0x65, 0x56, 0x69, 0x65, 0x77, 0x12, 0x4b, 0x0a, 0x0b, 0x63, - 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, - 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, - 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, - 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x72, 0x6f, 0x6c, 0x65, - 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x6f, 0x6c, 0x65, 0x49, - 0x64, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, - 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x72, 0x69, - 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x2c, 0x0a, 0x12, 0x70, 0x72, 0x69, 0x6e, - 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x53, - 0x63, 0x6f, 0x70, 0x65, 0x49, 0x64, 0x12, 0x22, 0x0a, 0x0d, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x73, - 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x72, - 0x6f, 0x6c, 0x65, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x49, 0x64, 0x12, 0x2e, 0x0a, 0x13, 0x73, 0x63, - 0x6f, 0x70, 0x65, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, - 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x64, 0x50, - 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x42, 0x38, 0x5a, 0x36, 0x67, 0x69, - 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, - 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, - 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, - 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x70, 0x61, 0x6c, 0x49, 0x64, 0x22, 0x9b, 0x01, 0x0a, 0x10, 0x4d, 0x61, 0x6e, 0x61, 0x67, 0x65, + 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x6f, 0x6c, 0x65, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, + 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, + 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x72, 0x6f, 0x6c, 0x65, 0x5f, + 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x6f, 0x6c, 0x65, 0x49, 0x64, + 0x12, 0x21, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, + 0x6c, 0x49, 0x64, 0x22, 0xb2, 0x02, 0x0a, 0x11, 0x50, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, + 0x6c, 0x52, 0x6f, 0x6c, 0x65, 0x56, 0x69, 0x65, 0x77, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, + 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, + 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, 0x31, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, + 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x69, + 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x72, 0x6f, 0x6c, 0x65, 0x49, 0x64, 0x12, + 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, + 0x79, 0x70, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, + 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x72, 0x69, 0x6e, 0x63, + 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x12, 0x2c, 0x0a, 0x12, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, + 0x70, 0x61, 0x6c, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x10, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x53, 0x63, 0x6f, + 0x70, 0x65, 0x49, 0x64, 0x12, 0x22, 0x0a, 0x0d, 0x72, 0x6f, 0x6c, 0x65, 0x5f, 0x73, 0x63, 0x6f, + 0x70, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x72, 0x6f, 0x6c, + 0x65, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x49, 0x64, 0x12, 0x2e, 0x0a, 0x13, 0x73, 0x63, 0x6f, 0x70, + 0x65, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x5f, 0x69, 0x64, 0x18, + 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x64, 0x50, 0x72, 0x69, + 0x6e, 0x63, 0x69, 0x70, 0x61, 0x6c, 0x49, 0x64, 0x42, 0x38, 0x5a, 0x36, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, + 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, + 0x61, 0x6c, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, 0x74, 0x6f, + 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -334,22 +413,24 @@ func file_controller_storage_iam_store_v1_principal_role_proto_rawDescGZIP() []b return file_controller_storage_iam_store_v1_principal_role_proto_rawDescData } -var file_controller_storage_iam_store_v1_principal_role_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_controller_storage_iam_store_v1_principal_role_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_controller_storage_iam_store_v1_principal_role_proto_goTypes = []interface{}{ (*UserRole)(nil), // 0: controller.storage.iam.store.v1.UserRole (*GroupRole)(nil), // 1: controller.storage.iam.store.v1.GroupRole - (*PrincipalRoleView)(nil), // 2: controller.storage.iam.store.v1.PrincipalRoleView - (*timestamp.Timestamp)(nil), // 3: controller.storage.timestamp.v1.Timestamp + (*ManagedGroupRole)(nil), // 2: controller.storage.iam.store.v1.ManagedGroupRole + (*PrincipalRoleView)(nil), // 3: controller.storage.iam.store.v1.PrincipalRoleView + (*timestamp.Timestamp)(nil), // 4: controller.storage.timestamp.v1.Timestamp } var file_controller_storage_iam_store_v1_principal_role_proto_depIdxs = []int32{ - 3, // 0: controller.storage.iam.store.v1.UserRole.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 3, // 1: controller.storage.iam.store.v1.GroupRole.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 3, // 2: controller.storage.iam.store.v1.PrincipalRoleView.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 3, // [3:3] is the sub-list for method output_type - 3, // [3:3] is the sub-list for method input_type - 3, // [3:3] is the sub-list for extension type_name - 3, // [3:3] is the sub-list for extension extendee - 0, // [0:3] is the sub-list for field type_name + 4, // 0: controller.storage.iam.store.v1.UserRole.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 4, // 1: controller.storage.iam.store.v1.GroupRole.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 4, // 2: controller.storage.iam.store.v1.ManagedGroupRole.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 4, // 3: controller.storage.iam.store.v1.PrincipalRoleView.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 4, // [4:4] is the sub-list for method output_type + 4, // [4:4] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name } func init() { file_controller_storage_iam_store_v1_principal_role_proto_init() } @@ -383,6 +464,18 @@ func file_controller_storage_iam_store_v1_principal_role_proto_init() { } } file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ManagedGroupRole); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_controller_storage_iam_store_v1_principal_role_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PrincipalRoleView); i { case 0: return &v.state @@ -401,7 +494,7 @@ func file_controller_storage_iam_store_v1_principal_role_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_controller_storage_iam_store_v1_principal_role_proto_rawDesc, NumEnums: 0, - NumMessages: 3, + NumMessages: 4, NumExtensions: 0, NumServices: 0, }, diff --git a/internal/iam/testing.go b/internal/iam/testing.go index 5741d2e39..68babe53d 100644 --- a/internal/iam/testing.go +++ b/internal/iam/testing.go @@ -242,6 +242,18 @@ func TestGroupRole(t *testing.T, conn *gorm.DB, roleId, grpId string, opt ...Opt return r } +func TestManagedGroupRole(t *testing.T, conn *gorm.DB, roleId, managedGrpId string, opt ...Option) *ManagedGroupRole { + t.Helper() + require := require.New(t) + rw := db.New(conn) + r, err := NewManagedGroupRole(roleId, managedGrpId, opt...) + require.NoError(err) + + err = rw.Create(context.Background(), r) + require.NoError(err) + return r +} + // testAccount is a temporary test function. TODO - replace with an auth // subsystem testAccount function. If userId is zero value, then an auth // account will be created with a null IamUserId diff --git a/internal/intglobals/prefixes.go b/internal/intglobals/prefixes.go new file mode 100644 index 000000000..c14309b5c --- /dev/null +++ b/internal/intglobals/prefixes.go @@ -0,0 +1,18 @@ +package intglobals + +// This set of consts is intended to be a place to collect commonly-used +// prefixes. This can avoid some cross-package dependency issues. Unlike the +// top-level globals package, these are not currently meant to be available to +// clients or test writers. + +const ( + // OidcManagedGroupPrefix defines the prefix for ManagedGroup public ids + // from the OIDC auth method. + OidcManagedGroupPrefix = "mgoidc" + + // OldPasswordAccountPrefix is the previously-used account prefix + OldPasswordAccountPrefix = "apw" + + // NewPasswordAccountPrefix is the new account prefix + NewPasswordAccountPrefix = "acctpw" +) diff --git a/internal/perms/acl_test.go b/internal/perms/acl_test.go index a09e45590..20699e412 100644 --- a/internal/perms/acl_test.go +++ b/internal/perms/acl_test.go @@ -1,8 +1,10 @@ package perms import ( + "fmt" "testing" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" "github.com/stretchr/testify/assert" @@ -227,7 +229,7 @@ func Test_ACLAllowed(t *testing.T) { userId: "u_abcd1234", }, { - name: "bad templated account id", + name: "bad templated old account id", resource: Resource{ScopeId: "o_c"}, scopeGrants: commonGrants, actionsAuthorized: []actionAuthorized{ @@ -235,17 +237,38 @@ func Test_ACLAllowed(t *testing.T) { {action: action.Authenticate}, {action: action.Delete}, }, - accountId: "apw_1234567890", + accountId: fmt.Sprintf("%s_1234567890", intglobals.OldPasswordAccountPrefix), }, { - name: "good templated account id", - resource: Resource{ScopeId: "o_c", Id: "apw_1234567890"}, + name: "good templated old account id", + resource: Resource{ScopeId: "o_c", Id: fmt.Sprintf("%s_1234567890", intglobals.OldPasswordAccountPrefix)}, scopeGrants: commonGrants, actionsAuthorized: []actionAuthorized{ {action: action.ChangePassword, authorized: true}, {action: action.Update}, }, - accountId: "apw_1234567890", + accountId: fmt.Sprintf("%s_1234567890", intglobals.OldPasswordAccountPrefix), + }, + { + name: "bad templated new account id", + resource: Resource{ScopeId: "o_c"}, + scopeGrants: commonGrants, + actionsAuthorized: []actionAuthorized{ + {action: action.List}, + {action: action.Authenticate}, + {action: action.Delete}, + }, + accountId: fmt.Sprintf("%s_1234567890", intglobals.NewPasswordAccountPrefix), + }, + { + name: "good templated new account id", + resource: Resource{ScopeId: "o_c", Id: fmt.Sprintf("%s_1234567890", intglobals.NewPasswordAccountPrefix)}, + scopeGrants: commonGrants, + actionsAuthorized: []actionAuthorized{ + {action: action.ChangePassword, authorized: true}, + {action: action.Update}, + }, + accountId: fmt.Sprintf("%s_1234567890", intglobals.NewPasswordAccountPrefix), }, { name: "all type", diff --git a/internal/perms/grants.go b/internal/perms/grants.go index c9dc66b4c..63450fa44 100644 --- a/internal/perms/grants.go +++ b/internal/perms/grants.go @@ -12,9 +12,10 @@ import ( "github.com/hashicorp/boundary/internal/types/scope" ) -// GrantPair is simply a struct that can be reference from other code to return +// GrantTuple is simply a struct that can be reference from other code to return // a set of scopes and grants to parse -type GrantPair struct { +type GrantTuple struct { + RoleId string ScopeId string Grant string } diff --git a/internal/perms/grants_test.go b/internal/perms/grants_test.go index 91573188a..25d6ba3d8 100644 --- a/internal/perms/grants_test.go +++ b/internal/perms/grants_test.go @@ -1,8 +1,10 @@ package perms import ( + "fmt" "testing" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" "github.com/hashicorp/boundary/internal/types/scope" @@ -652,21 +654,43 @@ func Test_Parse(t *testing.T) { }, }, { - name: "bad account id template", + name: "bad old account id template", input: `id={{superman}};actions=read`, - accountId: "apw_1234567890", + accountId: fmt.Sprintf("%s_1234567890", intglobals.OldPasswordAccountPrefix), err: `perms.Parse: unknown template "{{superman}}" in grant "id" value: parameter violation: error #100`, }, { - name: "good account id template", + name: "bad new account id template", + input: `id={{superman}};actions=read`, + accountId: fmt.Sprintf("%s_1234567890", intglobals.NewPasswordAccountPrefix), + err: `perms.Parse: unknown template "{{superman}}" in grant "id" value: parameter violation: error #100`, + }, + { + name: "good old account id template", input: `id={{ account.id}};actions=update,read`, - accountId: "apw_1234567890", + accountId: fmt.Sprintf("%s_1234567890", intglobals.OldPasswordAccountPrefix), expected: Grant{ scope: Scope{ Id: "o_scope", Type: scope.Org, }, - id: "apw_1234567890", + id: fmt.Sprintf("%s_1234567890", intglobals.OldPasswordAccountPrefix), + actions: map[action.Type]bool{ + action.Update: true, + action.Read: true, + }, + }, + }, + { + name: "good new account id template", + input: `id={{ account.id}};actions=update,read`, + accountId: fmt.Sprintf("%s_1234567890", intglobals.NewPasswordAccountPrefix), + expected: Grant{ + scope: Scope{ + Id: "o_scope", + Type: scope.Org, + }, + id: fmt.Sprintf("%s_1234567890", intglobals.NewPasswordAccountPrefix), actions: map[action.Type]bool{ action.Update: true, action.Read: true, diff --git a/internal/proto/local/controller/api/resources/accounts/v1/account.proto b/internal/proto/local/controller/api/resources/accounts/v1/account.proto index 304c6a7cb..f4c16f564 100644 --- a/internal/proto/local/controller/api/resources/accounts/v1/account.proto +++ b/internal/proto/local/controller/api/resources/accounts/v1/account.proto @@ -43,6 +43,9 @@ message Account { // The attributes that are applicable for the specific Account type. google.protobuf.Struct attributes = 100 [(custom_options.v1.generate_sdk_option) = true]; + // Output only. managed_group_ids indicates IDs of the managed groups that currently contain this account + repeated string managed_group_ids = 110 [json_name="managed_group_ids"]; + // Output only. The available actions on this resource for this user. repeated string authorized_actions = 300 [json_name="authorized_actions"]; } @@ -66,7 +69,7 @@ message OidcAccountAttributes { // This value is immutable after creation time. string subject = 90 [json_name="subject", (custom_options.v1.generate_sdk_option) = true]; - // Output only. full_name is a string that maps to the OIDC name claim + // Output only. full_name is a string that maps to the OIDC name claim. string full_name = 100 [json_name="full_name"]; // Output only. email is a string that maps to the OIDC email claim. diff --git a/internal/proto/local/controller/api/resources/managedgroups/v1/managed_group.proto b/internal/proto/local/controller/api/resources/managedgroups/v1/managed_group.proto new file mode 100644 index 000000000..618fc499c --- /dev/null +++ b/internal/proto/local/controller/api/resources/managedgroups/v1/managed_group.proto @@ -0,0 +1,57 @@ +syntax = "proto3"; + +package controller.api.resources.managedgroups.v1; + +option go_package = "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups;managedgroups"; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; +import "google/protobuf/struct.proto"; +import "controller/api/resources/scopes/v1/scope.proto"; +import "controller/custom_options/v1/options.proto"; + +// ManagedGroup contains all fields related to an ManagedGroup resource +message ManagedGroup { + // Output only. The ID of the ManagedGroup. + string id = 10; + + // Output only. Scope information for the ManagedGroup. + resources.scopes.v1.ScopeInfo scope = 20; + + // Optional name for identification purposes. + google.protobuf.StringValue name = 30 [(custom_options.v1.generate_sdk_option) = true, (custom_options.v1.mask_mapping) = {this:"name" that: "Name"}]; + + // Optional user-set description for identification purposes. + google.protobuf.StringValue description = 40 [(custom_options.v1.generate_sdk_option) = true, (custom_options.v1.mask_mapping) = {this:"description" that: "Description"}]; + + // Output only. The time this resource was created. + google.protobuf.Timestamp created_time = 50 [json_name="created_time"]; + + // Output only. The time this resource was last updated. + google.protobuf.Timestamp updated_time = 60 [json_name="updated_time"]; + + // Version is used in mutation requests, after the initial creation, to ensure this resource has not changed. + // The mutation will fail if the version does not match the latest known good version. + uint32 version = 70; + + // The type of this ManagedGroup. + string type = 80; + + // The ID of the Auth Method that is associated with this ManagedGroup. + string auth_method_id = 90 [json_name="auth_method_id"]; + + // The attributes that are applicable for the specific ManagedGroup type. + google.protobuf.Struct attributes = 100 [(custom_options.v1.generate_sdk_option) = true]; + + // Output only. The IDs of the current set of members (accounts) that are associated with this ManagedGroup. + repeated string member_ids = 110 [json_name="member_ids"]; + + // Output only. The available actions on this resource for this user. + repeated string authorized_actions = 300 [json_name="authorized_actions"]; +} + +// Attributes associated only with ManagedGroups with type "oidc". +message OidcManagedGroupAttributes { + // The boolean expression filter to use to determine membership. + string filter = 10 [json_name="filter", (custom_options.v1.generate_sdk_option) = true, (custom_options.v1.mask_mapping) = {this:"attributes.filter" that: "Filter"}]; +} \ No newline at end of file diff --git a/internal/proto/local/controller/api/services/v1/managed_group_service.proto b/internal/proto/local/controller/api/services/v1/managed_group_service.proto new file mode 100644 index 000000000..4804b1d68 --- /dev/null +++ b/internal/proto/local/controller/api/services/v1/managed_group_service.proto @@ -0,0 +1,129 @@ +syntax = "proto3"; + +package controller.api.services.v1; + +option go_package = "github.com/hashicorp/boundary/internal/gen/controller/api/services;services"; + +import "protoc-gen-openapiv2/options/annotations.proto"; +import "google/api/annotations.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/wrappers.proto"; +import "controller/api/resources/managedgroups/v1/managed_group.proto"; + +service ManagedGroupService { + + // GetManagedGroup returns a stored ManagedGroup if present. The provided request must + // include the id for the ManagedGroup be retrieved. If missing, malformed or + // referencing a non existing ManagedGroup an error is returned. + rpc GetManagedGroup(GetManagedGroupRequest) returns (GetManagedGroupResponse) { + option (google.api.http) = { + get: "/v1/managed-groups/{id}" + response_body: "item" + }; + option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = { + summary: "Gets a single ManagedGroup." + }; + } + + // ListManagedGroups returns a list of stored ManagedGroups which exist inside the + // provided Auth Method. The request must include the Auth Method id which + // contains the ManagedGroups being listed. If missing or malformed an error + // is returned. + rpc ListManagedGroups(ListManagedGroupsRequest) returns (ListManagedGroupsResponse) { + option (google.api.http) = { + get: "/v1/managed-groups" + }; + option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = { + summary: "Lists all ManagedGroups in a specific Auth Method." + }; + } + + // CreateManagedGroup creates and stores a ManagedGroup. The provided request + // must include the Auth Method ID in which the ManagedGroup will be created. + // If the Auth Method ID is missing, malformed, or references a non existing + // resource an error is returned. If a name or login_name is provided that is + // in use in another ManagedGroup in the same Auth Method an error is + // returned. + rpc CreateManagedGroup(CreateManagedGroupRequest) returns (CreateManagedGroupResponse) { + option (google.api.http) = { + post: "/v1/managed-groups" + body: "item" + response_body: "item" + }; + option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = { + summary: "Creates a single ManagedGroup in the provided Auth Method." + }; + } + + // UpdateManagedGroup updates an existing ManagedGroup. The provided + // ManagedGroup must not have any read only fields set. The update mask must + // be included in the request and contain at least 1 mutable field. To unset a + // field's value, include the field in the update mask and don't set it in the + // provided ManagedGroup. An error is returned if the ManagedGroup id is + // missing or references a non-existing resource. An error is also returned if + // the request attempts to update the name to one that is already in use in + // the containing Auth Method. + rpc UpdateManagedGroup(UpdateManagedGroupRequest) returns (UpdateManagedGroupResponse) { + option (google.api.http) = { + patch: "/v1/managed-groups/{id}" + body: "item" + response_body: "item" + }; + option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = { + summary: "Updates a ManagedGroup." + }; + } + + // DeleteManagedGroup removes a ManagedGroup. If the provided ManagedGroup Id + // is malformed or not provided an error is returned. + rpc DeleteManagedGroup(DeleteManagedGroupRequest) returns (DeleteManagedGroupResponse) { + option (google.api.http) = { + delete: "/v1/managed-groups/{id}" + }; + option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = { + summary: "Deletes a ManagedGroup." + }; + } +} + +message GetManagedGroupRequest { + string id = 1; +} + +message GetManagedGroupResponse { + resources.managedgroups.v1.ManagedGroup item = 1; +} + +message ListManagedGroupsRequest { + string auth_method_id = 1 [json_name="auth_method_id"]; + string filter = 30 [json_name="filter"]; +} + +message ListManagedGroupsResponse { + repeated resources.managedgroups.v1.ManagedGroup items = 1; +} + +message CreateManagedGroupRequest { + resources.managedgroups.v1.ManagedGroup item = 2; +} + +message CreateManagedGroupResponse { + string uri = 1; + resources.managedgroups.v1.ManagedGroup item = 2; +} + +message UpdateManagedGroupRequest { + string id = 1; + resources.managedgroups.v1.ManagedGroup item = 2; + google.protobuf.FieldMask update_mask = 3 [json_name="update_mask"]; +} + +message UpdateManagedGroupResponse { + resources.managedgroups.v1.ManagedGroup item = 1; +} + +message DeleteManagedGroupRequest { + string id = 1; +} + +message DeleteManagedGroupResponse {} \ No newline at end of file diff --git a/internal/proto/local/controller/storage/auth/oidc/store/v1/oidc.proto b/internal/proto/local/controller/storage/auth/oidc/store/v1/oidc.proto index 9e274fdaf..33d82aa34 100644 --- a/internal/proto/local/controller/storage/auth/oidc/store/v1/oidc.proto +++ b/internal/proto/local/controller/storage/auth/oidc/store/v1/oidc.proto @@ -251,3 +251,53 @@ message AccountClaimMap { // @inject_tag: `gorm:"default:current_timestamp"` timestamp.v1.Timestamp create_time = 40; } + +// ManagedGroup entries provide an OIDC auth method implementation of managed +// groups. +message ManagedGroup { + // @inject_tag: `gorm:"primary_key"` + string public_id = 10; + + // The create_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp create_time = 20; + + // The update_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp update_time = 30; + + // name is optional. If set, it must be unique within auth_method_id. + // @inject_tag: `gorm:"default:null"` + string name = 40 [(custom_options.v1.mask_mapping) = { this: "Name" that: "name" }]; + + // description is optional. + // @inject_tag: `gorm:"default:null"` + string description = 50 [(custom_options.v1.mask_mapping) = { this: "Description" that: "description" }]; + + // @inject_tag: `gorm:"default:null"` + uint32 version = 60; + + // auth_method_id is the fk to the account's auth method. + // @inject_tag: `gorm:"not_null"` + string auth_method_id = 70; + + // filter is a go-bexpr filter + // @inject_tag: `gorm:"not_null"` + string filter = 80 [(custom_options.v1.mask_mapping) = { this: "Filter" that: "attributes.filter" }]; +} + +// ManagedGroupMemberAccount contains a mapping between a managed group and a +// member account. +message ManagedGroupMemberAccount { + // The create_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp create_time = 10; + + // managed_group_id is the fk to the oidc managed group public id + // @inject_tag: `gorm:"primary_key"` + string managed_group_id = 20; + + // member_id is the fk to the oidc account public id + // @inject_tag: `gorm:"primary_key"` + string member_id = 30; +} diff --git a/internal/proto/local/controller/storage/iam/store/v1/principal_role.proto b/internal/proto/local/controller/storage/iam/store/v1/principal_role.proto index 2cbde85ac..de73e6003 100644 --- a/internal/proto/local/controller/storage/iam/store/v1/principal_role.proto +++ b/internal/proto/local/controller/storage/iam/store/v1/principal_role.proto @@ -34,6 +34,20 @@ message GroupRole { string principal_id = 3; } +message ManagedGroupRole { + // create_time from the RDBMS + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp create_time = 1; + + // role_id is the role of this principal. + // @inject_tag: gorm:"primary_key" + string role_id = 2; + + // principal_id is the public_id of the managed group (which is the principal) + // @inject_tag: gorm:"primary_key" + string principal_id = 3; +} + message PrincipalRoleView { // create_time from the RDBMS // @inject_tag: `gorm:"default:current_timestamp"` diff --git a/internal/servers/controller/handler.go b/internal/servers/controller/handler.go index af4e79ee2..0101f37e1 100644 --- a/internal/servers/controller/handler.go +++ b/internal/servers/controller/handler.go @@ -21,6 +21,7 @@ import ( "github.com/hashicorp/boundary/internal/servers/controller/handlers/accounts" "github.com/hashicorp/boundary/internal/servers/controller/handlers/authmethods" "github.com/hashicorp/boundary/internal/servers/controller/handlers/host_sets" + "github.com/hashicorp/boundary/internal/servers/controller/handlers/managed_groups" "github.com/hashicorp/boundary/internal/servers/controller/handlers/sessions" "github.com/hashicorp/boundary/internal/servers/controller/handlers/targets" "github.com/hashicorp/boundary/sdk/strutil" @@ -166,6 +167,13 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er if err := services.RegisterSessionServiceHandlerServer(ctx, mux, ss); err != nil { return nil, fmt.Errorf("failed to register session service handler: %w", err) } + mgs, err := managed_groups.NewService(c.OidcRepoFn) + if err != nil { + return nil, fmt.Errorf("failed to create managed groups handler service: %w", err) + } + if err := services.RegisterManagedGroupServiceHandlerServer(ctx, mux, mgs); err != nil { + return nil, fmt.Errorf("failed to register managed groups service handler: %w", err) + } return mux, nil } diff --git a/internal/servers/controller/handler_test.go b/internal/servers/controller/handler_test.go index 868db7617..8ed729817 100644 --- a/internal/servers/controller/handler_test.go +++ b/internal/servers/controller/handler_test.go @@ -20,7 +20,7 @@ import ( func TestAuthenticationHandler(t *testing.T) { c := NewTestController(t, &TestControllerOpts{ DisableAuthorizationFailures: true, - DefaultAuthMethodId: "ampw_1234567890", + DefaultPasswordAuthMethodId: "ampw_1234567890", DefaultLoginName: "admin", DefaultPassword: "password123", }) diff --git a/internal/servers/controller/handlers/accounts/account_service.go b/internal/servers/controller/handlers/accounts/account_service.go index 25fb279b2..e1fae10bd 100644 --- a/internal/servers/controller/handlers/accounts/account_service.go +++ b/internal/servers/controller/handlers/accounts/account_service.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/accounts" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/perms" "github.com/hashicorp/boundary/internal/requests" "github.com/hashicorp/boundary/internal/servers/controller/common" @@ -95,7 +96,7 @@ type Service struct { oidcRepoFn common.OidcAuthRepoFactory } -// NewService returns a user service which handles user related requests to boundary. +// NewService returns a account service which handles account related requests to boundary. func NewService(pwRepo common.PasswordAuthRepoFactory, oidcRepo common.OidcAuthRepoFactory) (Service, error) { const op = "accounts.NewService" if pwRepo == nil { @@ -180,7 +181,7 @@ func (s Service) GetAccount(ctx context.Context, req *pbs.GetAccountRequest) (*p if authResults.Error != nil { return nil, authResults.Error } - acct, err := s.getFromRepo(ctx, req.GetId()) + acct, mgIds, err := s.getFromRepo(ctx, req.GetId()) if err != nil { return nil, err } @@ -198,6 +199,9 @@ func (s Service) GetAccount(ctx context.Context, req *pbs.GetAccountRequest) (*p if outputFields.Has(globals.AuthorizedActionsField) { outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, acct.GetPublicId(), IdActions[auth.SubtypeFromId(acct.GetPublicId())]).Strings())) } + if outputFields.Has(globals.ManagedGroupIdsField) { + outputOpts = append(outputOpts, handlers.WithManagedGroupIds(mgIds)) + } item, err := toProto(ctx, acct, outputOpts...) if err != nil { @@ -379,39 +383,49 @@ func (s Service) SetPassword(ctx context.Context, req *pbs.SetPasswordRequest) ( return &pbs.SetPasswordResponse{Item: item}, nil } -func (s Service) getFromRepo(ctx context.Context, id string) (auth.Account, error) { +// getFromRepo returns the account and, if available, managed groups the account +// belongs to within the auth method +func (s Service) getFromRepo(ctx context.Context, id string) (auth.Account, []string, error) { var acct auth.Account + var mgIds []string switch auth.SubtypeFromId(id) { case auth.PasswordSubtype: repo, err := s.pwRepoFn() if err != nil { - return nil, err + return nil, nil, err } a, err := repo.LookupAccount(ctx, id) if err != nil { if errors.IsNotFoundError(err) { - return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id) + return nil, nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id) } - return nil, err + return nil, nil, err } acct = a case auth.OidcSubtype: repo, err := s.oidcRepoFn() if err != nil { - return nil, err + return nil, nil, err } a, err := repo.LookupAccount(ctx, id) if err != nil { if errors.IsNotFoundError(err) { - return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id) + return nil, nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id) } - return nil, err + return nil, nil, err + } + mgs, err := repo.ListManagedGroupMembershipsByMember(ctx, a.GetPublicId()) + if err != nil { + return nil, nil, err + } + for _, mg := range mgs { + mgIds = append(mgIds, mg.GetManagedGroupId()) } acct = a default: - return nil, handlers.NotFoundErrorf("Unrecognized id.") + return nil, nil, handlers.NotFoundErrorf("Unrecognized id.") } - return acct, nil + return acct, mgIds, nil } func (s Service) createPwInRepo(ctx context.Context, am auth.AuthMethod, item *pb.Account) (*password.Account, error) { @@ -433,7 +447,7 @@ func (s Service) createPwInRepo(ctx context.Context, am auth.AuthMethod, item *p } a, err := password.NewAccount(am.GetPublicId(), opts...) if err != nil { - return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err) + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build account for creation: %v.", err) } repo, err := s.pwRepoFn() if err != nil { @@ -449,7 +463,7 @@ func (s Service) createPwInRepo(ctx context.Context, am auth.AuthMethod, item *p return nil, errors.Wrap(err, op) } if out == nil { - return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create user but no error returned from repository.") + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.") } return out, nil } @@ -480,7 +494,7 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item } a, err := oidc.NewAccount(am.GetPublicId(), attrs.GetSubject(), opts...) if err != nil { - return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err) + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build account for creation: %v.", err) } repo, err := s.oidcRepoFn() if err != nil { @@ -489,10 +503,10 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item out, err := repo.CreateAccount(ctx, am.GetScopeId(), a) if err != nil { - return nil, errors.Wrap(err, op, errors.WithMsg("unable to create user")) + return nil, errors.Wrap(err, op, errors.WithMsg("unable to create account")) } if out == nil { - return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create user but no error returned from repository.") + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.") } return out, nil } @@ -510,7 +524,7 @@ func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb. return nil, errors.Wrap(err, op) } if am == nil { - return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.") + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.") } out = am case auth.OidcSubtype: @@ -519,7 +533,7 @@ func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb. return nil, errors.Wrap(err, op) } if am == nil { - return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.") + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.") } out = am } @@ -836,6 +850,9 @@ func toProto(ctx context.Context, in auth.Account, opt ...handlers.Option) (*pb. if outputFields.Has(globals.AuthorizedActionsField) { out.AuthorizedActions = opts.WithAuthorizedActions } + if outputFields.Has(globals.ManagedGroupIdsField) { + out.ManagedGroupIds = opts.WithManagedGroupIds + } switch i := in.(type) { case *password.Account: if outputFields.Has(globals.TypeField) { @@ -910,7 +927,7 @@ func validateGetRequest(req *pbs.GetAccountRequest) error { if req == nil { return errors.New(errors.InvalidParameter, op, "nil request") } - return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, password.AccountPrefix, oidc.AccountPrefix) + return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, intglobals.OldPasswordAccountPrefix, intglobals.NewPasswordAccountPrefix, oidc.AccountPrefix) } func validateCreateRequest(req *pbs.CreateAccountRequest) error { @@ -1006,7 +1023,7 @@ func validateUpdateRequest(req *pbs.UpdateAccountRequest) error { } } return badFields - }, password.AccountPrefix, oidc.AccountPrefix) + }, intglobals.OldPasswordAccountPrefix, intglobals.NewPasswordAccountPrefix, oidc.AccountPrefix) } func validateDeleteRequest(req *pbs.DeleteAccountRequest) error { @@ -1014,7 +1031,7 @@ func validateDeleteRequest(req *pbs.DeleteAccountRequest) error { if req == nil { return errors.New(errors.InvalidParameter, op, "nil request") } - return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, password.AccountPrefix, oidc.AccountPrefix) + return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, intglobals.OldPasswordAccountPrefix, intglobals.NewPasswordAccountPrefix, oidc.AccountPrefix) } func validateListRequest(req *pbs.ListAccountsRequest) error { @@ -1041,7 +1058,7 @@ func validateChangePasswordRequest(req *pbs.ChangePasswordRequest) error { return errors.New(errors.InvalidParameter, op, "nil request") } badFields := map[string]string{} - if !handlers.ValidId(handlers.Id(req.GetId()), password.AccountPrefix) { + if !handlers.ValidId(handlers.Id(req.GetId()), intglobals.OldPasswordAccountPrefix, intglobals.NewPasswordAccountPrefix) { badFields[idField] = "Improperly formatted identifier." } if req.GetVersion() == 0 { @@ -1065,7 +1082,7 @@ func validateSetPasswordRequest(req *pbs.SetPasswordRequest) error { return errors.New(errors.InvalidParameter, op, "nil request") } badFields := map[string]string{} - if !handlers.ValidId(handlers.Id(req.GetId()), password.AccountPrefix) { + if !handlers.ValidId(handlers.Id(req.GetId()), intglobals.OldPasswordAccountPrefix, intglobals.NewPasswordAccountPrefix) { badFields[idField] = "Improperly formatted identifier." } if req.GetVersion() == 0 { diff --git a/internal/servers/controller/handlers/accounts/account_service_test.go b/internal/servers/controller/handlers/accounts/account_service_test.go index d5db6cc83..0556e3108 100644 --- a/internal/servers/controller/handlers/accounts/account_service_test.go +++ b/internal/servers/controller/handlers/accounts/account_service_test.go @@ -19,6 +19,7 @@ import ( scopepb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/servers/controller/common" "github.com/hashicorp/boundary/internal/servers/controller/handlers" @@ -148,6 +149,9 @@ func TestGet(t *testing.T) { oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), ) oidcA := oidc.TestAccount(t, conn, oidcAm, "test-subject") + // Create a managed group that will always match, so we can test that it is + // returned in results + mg := oidc.TestManagedGroup(t, conn, oidcAm, `"/token/sub" matches ".*"`) oidcWireAccount := pb.Account{ Id: oidcA.GetPublicId(), AuthMethodId: oidcA.GetAuthMethodId(), @@ -161,6 +165,7 @@ func TestGet(t *testing.T) { "subject": structpb.NewStringValue("test-subject"), }}, AuthorizedActions: oidcAuthorizedActions, + ManagedGroupIds: []string{mg.GetPublicId()}, } cases := []struct { @@ -180,8 +185,14 @@ func TestGet(t *testing.T) { res: &pbs.GetAccountResponse{Item: &oidcWireAccount}, }, { - name: "Get a non existing password account", - req: &pbs.GetAccountRequest{Id: password.AccountPrefix + "_DoesntExis"}, + name: "Get a non existing old password account", + req: &pbs.GetAccountRequest{Id: intglobals.OldPasswordAccountPrefix + "_DoesntExis"}, + res: nil, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Get a non existing new password account", + req: &pbs.GetAccountRequest{Id: intglobals.NewPasswordAccountPrefix + "_DoesntExis"}, res: nil, err: handlers.ApiErrorWithCode(codes.NotFound), }, @@ -207,6 +218,18 @@ func TestGet(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) + + if auth.SubtypeFromId(tc.req.Id) == auth.OidcSubtype { + // Set up managed groups before getting. First get the current + // managed group to make sure we have the right version. + oidcRepo, err := oidcRepoFn() + require.NoError(err) + currMg, err := oidcRepo.LookupManagedGroup(ctx, mg.GetPublicId()) + require.NoError(err) + _, _, err = oidcRepo.SetManagedGroupMemberships(ctx, oidcAm, oidcA, []*oidc.ManagedGroup{currMg}) + require.NoError(err) + } + got, gErr := s.GetAccount(auth.DisabledAuthTestContext(iamRepoFn, org.GetPublicId()), tc.req) if tc.err != nil { require.Error(gErr) @@ -559,9 +582,16 @@ func TestDelete(t *testing.T) { }, }, { - name: "Delete bad pw account id", + name: "Delete bad old pw account id", req: &pbs.DeleteAccountRequest{ - Id: password.AccountPrefix + "_doesntexis", + Id: intglobals.OldPasswordAccountPrefix + "_doesntexis", + }, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Delete bad new pw account id", + req: &pbs.DeleteAccountRequest{ + Id: intglobals.NewPasswordAccountPrefix + "_doesntexis", }, err: handlers.ApiErrorWithCode(codes.NotFound), }, @@ -622,7 +652,7 @@ func TestDelete_twice(t *testing.T) { assert.NoError(gErr, "First attempt") _, gErr = s.DeleteAccount(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), req) assert.Error(gErr, "Second attempt") - assert.True(errors.Is(gErr, handlers.ApiErrorWithCode(codes.NotFound)), "Expected permission denied for the second delete.") + assert.True(errors.Is(gErr, handlers.ApiErrorWithCode(codes.NotFound)), "Expected not found for the second delete.") } func TestCreatePassword(t *testing.T) { @@ -677,7 +707,7 @@ func TestCreatePassword(t *testing.T) { }, }, res: &pbs.CreateAccountResponse{ - Uri: fmt.Sprintf("accounts/%s_", password.AccountPrefix), + Uri: fmt.Sprintf("accounts/%s_", intglobals.NewPasswordAccountPrefix), Item: &pb.Account{ AuthMethodId: defaultAccount.GetAuthMethodId(), Name: &wrapperspb.StringValue{Value: "name"}, @@ -699,7 +729,7 @@ func TestCreatePassword(t *testing.T) { }, }, res: &pbs.CreateAccountResponse{ - Uri: fmt.Sprintf("accounts/%s_", password.AccountPrefix), + Uri: fmt.Sprintf("accounts/%s_", intglobals.NewPasswordAccountPrefix), Item: &pb.Account{ AuthMethodId: defaultAccount.GetAuthMethodId(), Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, @@ -721,7 +751,7 @@ func TestCreatePassword(t *testing.T) { }, }, res: &pbs.CreateAccountResponse{ - Uri: fmt.Sprintf("accounts/%s_", password.AccountPrefix), + Uri: fmt.Sprintf("accounts/%s_", intglobals.NewPasswordAccountPrefix), Item: &pb.Account{ AuthMethodId: defaultAccount.GetAuthMethodId(), Name: &wrapperspb.StringValue{Value: "name_with_password"}, @@ -751,7 +781,7 @@ func TestCreatePassword(t *testing.T) { req: &pbs.CreateAccountRequest{ Item: &pb.Account{ AuthMethodId: defaultAccount.GetAuthMethodId(), - Id: password.AccountPrefix + "_notallowed", + Id: intglobals.NewPasswordAccountPrefix + "_notallowed", Type: "password", Attributes: createAttr("cantprovideid", ""), }, @@ -807,7 +837,7 @@ func TestCreatePassword(t *testing.T) { } if got != nil { assert.Contains(got.GetUri(), tc.res.Uri) - assert.True(strings.HasPrefix(got.GetItem().GetId(), password.AccountPrefix+"_")) + assert.True(strings.HasPrefix(got.GetItem().GetId(), intglobals.NewPasswordAccountPrefix+"_")) gotCreateTime := got.GetItem().GetCreatedTime() require.NoError(err, "Error converting proto to timestamp.") gotUpdateTime := got.GetItem().GetUpdatedTime() @@ -1057,7 +1087,7 @@ func TestUpdatePassword(t *testing.T) { o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0] tested, err := accounts.NewService(pwRepoFn, oidcRepoFn) - require.NoError(t, err, "Error when getting new auth_method service.") + require.NoError(t, err, "Error when getting new accounts service.") defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()} defaultAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{ @@ -1288,9 +1318,23 @@ func TestUpdatePassword(t *testing.T) { }, }, { - name: "Update a Non Existing Account", + name: "Update a Non Existing Old ID Account", req: &pbs.UpdateAccountRequest{ - Id: password.AccountPrefix + "_DoesntExis", + Id: intglobals.OldPasswordAccountPrefix + "_DoesntExis", + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.DescriptionField}, + }, + Item: &pb.Account{ + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + }, + }, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Update a Non Existing New ID Account", + req: &pbs.UpdateAccountRequest{ + Id: intglobals.NewPasswordAccountPrefix + "_DoesntExis", UpdateMask: &field_mask.FieldMask{ Paths: []string{globals.DescriptionField}, }, @@ -1308,7 +1352,7 @@ func TestUpdatePassword(t *testing.T) { Paths: []string{"id"}, }, Item: &pb.Account{ - Id: password.AccountPrefix + "_somethinge", + Id: intglobals.NewPasswordAccountPrefix + "_somethinge", Name: &wrapperspb.StringValue{Value: "new"}, Description: &wrapperspb.StringValue{Value: "new desc"}, }, @@ -1647,7 +1691,7 @@ func TestUpdateOidc(t *testing.T) { { name: "Update a Non Existing Account", req: &pbs.UpdateAccountRequest{ - Id: password.AccountPrefix + "_DoesntExis", + Id: intglobals.NewPasswordAccountPrefix + "_DoesntExis", UpdateMask: &field_mask.FieldMask{ Paths: []string{globals.DescriptionField}, }, @@ -1665,7 +1709,7 @@ func TestUpdateOidc(t *testing.T) { Paths: []string{"id"}, }, Item: &pb.Account{ - Id: password.AccountPrefix + "_somethinge", + Id: intglobals.NewPasswordAccountPrefix + "_somethinge", Name: &wrapperspb.StringValue{Value: "new"}, Description: &wrapperspb.StringValue{Value: "new desc"}, }, @@ -1892,8 +1936,14 @@ func TestSetPassword(t *testing.T) { password: "somepassword", }, { - name: "notfound account id", - accountId: password.AccountPrefix + "_DoesntExis", + name: "notfound old account id", + accountId: intglobals.OldPasswordAccountPrefix + "_DoesntExis", + version: defaultAcct.GetVersion(), + password: "anewpassword", + }, + { + name: "notfound new account id", + accountId: intglobals.NewPasswordAccountPrefix + "_DoesntExis", version: defaultAcct.GetVersion(), password: "anewpassword", }, @@ -2053,9 +2103,17 @@ func TestChangePassword(t *testing.T) { newPW: "somepassword", }, { - name: "notfound account id", + name: "notfound old account id", authMethodId: defaultAcct.GetAuthMethodId(), - accountId: password.AccountPrefix + "_DoesntExis", + accountId: intglobals.OldPasswordAccountPrefix + "_DoesntExis", + version: defaultAcct.GetVersion(), + oldPW: "somepassword", + newPW: "anewpassword", + }, + { + name: "notfound new account id", + authMethodId: defaultAcct.GetAuthMethodId(), + accountId: intglobals.NewPasswordAccountPrefix + "_DoesntExis", version: defaultAcct.GetVersion(), oldPW: "somepassword", newPW: "anewpassword", diff --git a/internal/servers/controller/handlers/accounts/validate_test.go b/internal/servers/controller/handlers/accounts/validate_test.go index ec7a51a58..b771d58fd 100644 --- a/internal/servers/controller/handlers/accounts/validate_test.go +++ b/internal/servers/controller/handlers/accounts/validate_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/password" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/accounts" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/types/known/fieldmaskpb" @@ -21,6 +22,7 @@ func fieldError(field, details string) string { } func TestValidateCreateRequest(t *testing.T) { + t.Parallel() cases := []struct { name string item *pb.Account @@ -132,6 +134,7 @@ func TestValidateCreateRequest(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { + t.Parallel() req := &pbs.CreateAccountRequest{Item: tc.item} err := validateCreateRequest(req) if tc.errContains == "" { @@ -145,15 +148,26 @@ func TestValidateCreateRequest(t *testing.T) { } func TestValidateUpdateRequest(t *testing.T) { + t.Parallel() cases := []struct { name string req *pbs.UpdateAccountRequest errContains string }{ { - name: "password to oidc change type", + name: "password to oidc change type, old prefix", req: &pbs.UpdateAccountRequest{ - Id: password.AccountPrefix + "_1234567890", + Id: intglobals.OldPasswordAccountPrefix + "_1234567890", + Item: &pb.Account{ + Type: auth.OidcSubtype.String(), + }, + }, + errContains: fieldError(typeField, "Cannot modify the resource type."), + }, + { + name: "password to oidc change type, new prefix", + req: &pbs.UpdateAccountRequest{ + Id: intglobals.NewPasswordAccountPrefix + "_1234567890", Item: &pb.Account{ Type: auth.OidcSubtype.String(), }, @@ -171,9 +185,21 @@ func TestValidateUpdateRequest(t *testing.T) { errContains: fieldError(typeField, "Cannot modify the resource type."), }, { - name: "password bad attributes", + name: "password bad attributes old prefix", req: &pbs.UpdateAccountRequest{ - Id: password.AccountPrefix + "_1234567890", + Id: intglobals.OldPasswordAccountPrefix + "_1234567890", + Item: &pb.Account{ + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "test": structpb.NewStringValue("something"), + }}, + }, + }, + errContains: fieldError(attributesField, "Attribute fields do not match the expected format."), + }, + { + name: "password bad attributes new prefix", + req: &pbs.UpdateAccountRequest{ + Id: intglobals.NewPasswordAccountPrefix + "_1234567890", Item: &pb.Account{ Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ "test": structpb.NewStringValue("something"), @@ -207,6 +233,7 @@ func TestValidateUpdateRequest(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { + t.Parallel() err := validateUpdateRequest(tc.req) if tc.errContains == "" { require.NoError(t, err) @@ -218,6 +245,7 @@ func TestValidateUpdateRequest(t *testing.T) { } t.Run("oidc read only fields", func(t *testing.T) { + t.Parallel() readOnlyFields := []string{ emailClaimField, nameClaimField, @@ -235,6 +263,7 @@ func TestValidateUpdateRequest(t *testing.T) { }) t.Run("oidc write only at create fields", func(t *testing.T) { + t.Parallel() readOnlyFields := []string{ issuerField, subjectField, diff --git a/internal/servers/controller/handlers/managed_groups/managed_group_service.go b/internal/servers/controller/handlers/managed_groups/managed_group_service.go new file mode 100644 index 000000000..e85879703 --- /dev/null +++ b/internal/servers/controller/handlers/managed_groups/managed_group_service.go @@ -0,0 +1,670 @@ +package managed_groups + +import ( + "context" + "fmt" + + "github.com/hashicorp/boundary/globals" + "github.com/hashicorp/boundary/internal/auth" + "github.com/hashicorp/boundary/internal/auth/oidc" + oidcstore "github.com/hashicorp/boundary/internal/auth/oidc/store" + "github.com/hashicorp/boundary/internal/errors" + pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups" + pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" + "github.com/hashicorp/boundary/internal/intglobals" + "github.com/hashicorp/boundary/internal/perms" + "github.com/hashicorp/boundary/internal/requests" + "github.com/hashicorp/boundary/internal/servers/controller/common" + "github.com/hashicorp/boundary/internal/servers/controller/handlers" + "github.com/hashicorp/boundary/internal/types/action" + "github.com/hashicorp/boundary/internal/types/resource" + "github.com/hashicorp/go-bexpr" + "google.golang.org/grpc/codes" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +const ( + // oidc field names + attrFilterField = "attributes.filter" +) + +var ( + oidcMaskManager handlers.MaskManager + + // IdActions contains the set of actions that can be performed on + // individual resources + IdActions = map[auth.Subtype]action.ActionSet{ + auth.OidcSubtype: { + action.NoOp, + action.Read, + action.Update, + action.Delete, + }, + } + + // CollectionActions contains the set of actions that can be performed on + // this collection + CollectionActions = action.ActionSet{ + action.Create, + action.List, + } +) + +func init() { + var err error + if oidcMaskManager, err = handlers.NewMaskManager(&oidcstore.ManagedGroup{}, &pb.ManagedGroup{}, &pb.OidcManagedGroupAttributes{}); err != nil { + panic(err) + } +} + +// Service handles request as described by the pbs.ManagedGroupServiceServer interface. +type Service struct { + pbs.UnimplementedManagedGroupServiceServer + + oidcRepoFn common.OidcAuthRepoFactory +} + +// NewService returns a managed group service which handles managed group related requests to boundary. +func NewService(oidcRepo common.OidcAuthRepoFactory) (Service, error) { + const op = "managed_groups.NewService" + if oidcRepo == nil { + return Service{}, errors.New(errors.InvalidParameter, op, "missing oidc repository provided") + } + return Service{oidcRepoFn: oidcRepo}, nil +} + +var _ pbs.ManagedGroupServiceServer = Service{} + +// ListManagedGroups implements the interface pbs.ManagedGroupsServiceServer. +func (s Service) ListManagedGroups(ctx context.Context, req *pbs.ListManagedGroupsRequest) (*pbs.ListManagedGroupsResponse, error) { + if err := validateListRequest(req); err != nil { + return nil, err + } + _, authResults := s.parentAndAuthResult(ctx, req.GetAuthMethodId(), action.List) + if authResults.Error != nil { + return nil, authResults.Error + } + ul, err := s.listFromRepo(ctx, req.GetAuthMethodId()) + if err != nil { + return nil, err + } + if len(ul) == 0 { + return &pbs.ListManagedGroupsResponse{}, nil + } + + filter, err := handlers.NewFilter(req.GetFilter()) + if err != nil { + return nil, err + } + finalItems := make([]*pb.ManagedGroup, 0, len(ul)) + + res := perms.Resource{ + ScopeId: authResults.Scope.Id, + Type: resource.ManagedGroup, + Pin: req.GetAuthMethodId(), + } + for _, mg := range ul { + res.Id = mg.GetPublicId() + authorizedActions := authResults.FetchActionSetForId(ctx, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())], auth.WithResource(&res)).Strings() + if len(authorizedActions) == 0 { + continue + } + + outputFields := authResults.FetchOutputFields(res, action.List).SelfOrDefaults(authResults.UserId) + outputOpts := make([]handlers.Option, 0, 3) + outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields)) + if outputFields.Has(globals.ScopeField) { + outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope)) + } + if outputFields.Has(globals.AuthorizedActionsField) { + outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions)) + } + + item, err := toProto(ctx, mg, outputOpts...) + if err != nil { + return nil, err + } + + // This comes last so that we can use item fields in the filter after + // the allowed fields are populated above + if filter.Match(item) { + finalItems = append(finalItems, item) + } + } + return &pbs.ListManagedGroupsResponse{Items: finalItems}, nil +} + +// GetManagedGroup implements the interface pbs.ManagedGroupServiceServer. +func (s Service) GetManagedGroup(ctx context.Context, req *pbs.GetManagedGroupRequest) (*pbs.GetManagedGroupResponse, error) { + const op = "managed_groups.(Service).GetManagedGroup" + + if err := validateGetRequest(req); err != nil { + return nil, err + } + + _, authResults := s.parentAndAuthResult(ctx, req.GetId(), action.Read) + if authResults.Error != nil { + return nil, authResults.Error + } + mg, memberIds, err := s.getFromRepo(ctx, req.GetId()) + if err != nil { + return nil, err + } + + outputFields, ok := requests.OutputFields(ctx) + if !ok { + return nil, errors.New(errors.Internal, op, "no request context found") + } + + outputOpts := make([]handlers.Option, 0, 3) + outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields)) + if outputFields.Has(globals.ScopeField) { + outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope)) + } + if outputFields.Has(globals.AuthorizedActionsField) { + outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())]).Strings())) + } + if outputFields.Has(globals.MemberIdsField) { + outputOpts = append(outputOpts, handlers.WithMemberIds(memberIds)) + } + + item, err := toProto(ctx, mg, outputOpts...) + if err != nil { + return nil, err + } + + return &pbs.GetManagedGroupResponse{Item: item}, nil +} + +// CreateManagedGroup implements the interface pbs.ManagedGroupServiceServer. +func (s Service) CreateManagedGroup(ctx context.Context, req *pbs.CreateManagedGroupRequest) (*pbs.CreateManagedGroupResponse, error) { + const op = "managed_groups.(Service).CreateManagedGroup" + + if err := validateCreateRequest(req); err != nil { + return nil, err + } + + authMeth, authResults := s.parentAndAuthResult(ctx, req.GetItem().GetAuthMethodId(), action.Create) + if authResults.Error != nil { + return nil, authResults.Error + } + mg, err := s.createInRepo(ctx, authMeth, req.GetItem()) + if err != nil { + return nil, err + } + + outputFields, ok := requests.OutputFields(ctx) + if !ok { + return nil, errors.New(errors.Internal, op, "no request context found") + } + + outputOpts := make([]handlers.Option, 0, 3) + outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields)) + if outputFields.Has(globals.ScopeField) { + outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope)) + } + if outputFields.Has(globals.AuthorizedActionsField) { + outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())]).Strings())) + } + + item, err := toProto(ctx, mg, outputOpts...) + if err != nil { + return nil, err + } + + return &pbs.CreateManagedGroupResponse{Item: item, Uri: fmt.Sprintf("managed-groups/%s", item.GetId())}, nil +} + +// UpdateManagedGroup implements the interface pbs.ManagedGroupServiceServer. +func (s Service) UpdateManagedGroup(ctx context.Context, req *pbs.UpdateManagedGroupRequest) (*pbs.UpdateManagedGroupResponse, error) { + const op = "managed_groups.(Service).UpdateManagedGroup" + + if err := validateUpdateRequest(req); err != nil { + return nil, err + } + + authMeth, authResults := s.parentAndAuthResult(ctx, req.GetId(), action.Update) + if authResults.Error != nil { + return nil, authResults.Error + } + mg, err := s.updateInRepo(ctx, authResults.Scope.GetId(), authMeth.GetPublicId(), req) + if err != nil { + return nil, err + } + + outputFields, ok := requests.OutputFields(ctx) + if !ok { + return nil, errors.New(errors.Internal, op, "no request context found") + } + + outputOpts := make([]handlers.Option, 0, 3) + outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields)) + if outputFields.Has(globals.ScopeField) { + outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope)) + } + if outputFields.Has(globals.AuthorizedActionsField) { + outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, mg.GetPublicId(), IdActions[auth.SubtypeFromId(mg.GetPublicId())]).Strings())) + } + + item, err := toProto(ctx, mg, outputOpts...) + if err != nil { + return nil, err + } + + return &pbs.UpdateManagedGroupResponse{Item: item}, nil +} + +// DeleteManagedGroup implements the interface pbs.ManagedGroupServiceServer. +func (s Service) DeleteManagedGroup(ctx context.Context, req *pbs.DeleteManagedGroupRequest) (*pbs.DeleteManagedGroupResponse, error) { + if err := validateDeleteRequest(req); err != nil { + return nil, err + } + _, authResults := s.parentAndAuthResult(ctx, req.GetId(), action.Delete) + if authResults.Error != nil { + return nil, authResults.Error + } + _, err := s.deleteFromRepo(ctx, authResults.Scope.GetId(), req.GetId()) + if err != nil { + return nil, err + } + return nil, nil +} + +func (s Service) getFromRepo(ctx context.Context, id string) (auth.ManagedGroup, []string, error) { + var out auth.ManagedGroup + var memberIds []string + switch auth.SubtypeFromId(id) { + case auth.OidcSubtype: + repo, err := s.oidcRepoFn() + if err != nil { + return nil, nil, err + } + mg, err := repo.LookupManagedGroup(ctx, id) + if err != nil { + if errors.IsNotFoundError(err) { + return nil, nil, handlers.NotFoundErrorf("ManagedGroup %q doesn't exist.", id) + } + return nil, nil, err + } + ids, err := repo.ListManagedGroupMembershipsByGroup(ctx, mg.GetPublicId()) + if err != nil { + return nil, nil, err + } + if len(ids) > 0 { + memberIds = make([]string, len(ids)) + for i, v := range ids { + memberIds[i] = v.MemberId + } + } + out = mg + default: + return nil, nil, handlers.NotFoundErrorf("Unrecognized id.") + } + return out, memberIds, nil +} + +func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item *pb.ManagedGroup) (*oidc.ManagedGroup, error) { + const op = "managed_groups.(Service).createOidcInRepo" + if item == nil { + return nil, errors.New(errors.InvalidParameter, op, "missing item") + } + var opts []oidc.Option + if item.GetName() != nil { + opts = append(opts, oidc.WithName(item.GetName().GetValue())) + } + if item.GetDescription() != nil { + opts = append(opts, oidc.WithDescription(item.GetDescription().GetValue())) + } + attrs := &pb.OidcManagedGroupAttributes{} + if err := handlers.StructToProto(item.GetAttributes(), attrs); err != nil { + return nil, handlers.InvalidArgumentErrorf("Error in provided request.", + map[string]string{"attributes": "Attribute fields do not match the expected format."}) + } + mg, err := oidc.NewManagedGroup(am.GetPublicId(), attrs.GetFilter(), opts...) + if err != nil { + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err) + } + repo, err := s.oidcRepoFn() + if err != nil { + return nil, err + } + + out, err := repo.CreateManagedGroup(ctx, am.GetScopeId(), mg) + if err != nil { + return nil, errors.Wrap(err, op, errors.WithMsg("unable to create managed group")) + } + if out == nil { + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create managed group but no error returned from repository.") + } + return out, nil +} + +func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.ManagedGroup) (auth.ManagedGroup, error) { + const op = "managed_groups.(Service).createInRepo" + if item == nil { + return nil, errors.New(errors.InvalidParameter, op, "missing item") + } + var out auth.ManagedGroup + switch auth.SubtypeFromId(am.GetPublicId()) { + case auth.OidcSubtype: + am, err := s.createOidcInRepo(ctx, am, item) + if err != nil { + return nil, errors.Wrap(err, op) + } + if am == nil { + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create managed group but no error returned from repository.") + } + out = am + } + return out, nil +} + +func (s Service) updateOidcInRepo(ctx context.Context, scopeId, amId, id string, mask []string, item *pb.ManagedGroup) (*oidc.ManagedGroup, error) { + const op = "managed_groups.(Service).updateOidcInRepo" + if item == nil { + return nil, errors.New(errors.InvalidParameter, op, "nil managed group.") + } + mg := oidc.AllocManagedGroup() + mg.PublicId = id + if item.GetName() != nil { + mg.Name = item.GetName().GetValue() + } + if item.GetDescription() != nil { + mg.Description = item.GetDescription().GetValue() + } + if apiAttr := item.GetAttributes(); apiAttr != nil { + attrs := &pb.OidcManagedGroupAttributes{} + if err := handlers.StructToProto(apiAttr, attrs); err != nil { + return nil, handlers.InvalidArgumentErrorf("Error in provided request.", + map[string]string{globals.AttributesField: "Attribute fields do not match the expected format."}) + } + // Set this regardless; it'll only take effect if the masks contain the value + mg.Filter = attrs.Filter + } + + version := item.GetVersion() + + dbMask := oidcMaskManager.Translate(mask) + if len(dbMask) == 0 { + return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."}) + } + repo, err := s.oidcRepoFn() + if err != nil { + return nil, errors.Wrap(err, op) + } + out, rowsUpdated, err := repo.UpdateManagedGroup(ctx, scopeId, mg, version, dbMask) + if err != nil { + return nil, errors.Wrap(err, op, errors.WithMsg("unable to update managed group")) + } + if rowsUpdated == 0 { + return nil, handlers.NotFoundErrorf("Managed Group %q doesn't exist or incorrect version provided.", id) + } + return out, nil +} + +func (s Service) updateInRepo(ctx context.Context, scopeId, authMethodId string, req *pbs.UpdateManagedGroupRequest) (auth.ManagedGroup, error) { + const op = "managed_groups.(Service).updateInRepo" + var out auth.ManagedGroup + switch auth.SubtypeFromId(req.GetId()) { + case auth.OidcSubtype: + mg, err := s.updateOidcInRepo(ctx, scopeId, authMethodId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem()) + if err != nil { + return nil, errors.Wrap(err, op) + } + if mg == nil { + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update managed group but no error returned from repository.") + } + out = mg + } + return out, nil +} + +func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, error) { + const op = "managed_groups.(Service).deleteFromRepo" + var rows int + var err error + switch auth.SubtypeFromId(id) { + case auth.OidcSubtype: + repo, iErr := s.oidcRepoFn() + if iErr != nil { + return false, iErr + } + rows, err = repo.DeleteManagedGroup(ctx, scopeId, id) + } + if err != nil { + if errors.IsNotFoundError(err) { + return false, nil + } + return false, errors.Wrap(err, op) + } + return rows > 0, nil +} + +func (s Service) listFromRepo(ctx context.Context, authMethodId string) ([]auth.ManagedGroup, error) { + const op = "managed_groups.(Service).listFromRepo" + + var outUl []auth.ManagedGroup + switch auth.SubtypeFromId(authMethodId) { + case auth.OidcSubtype: + oidcRepo, err := s.oidcRepoFn() + if err != nil { + return nil, errors.Wrap(err, op) + } + oidcl, err := oidcRepo.ListManagedGroups(ctx, authMethodId) + if err != nil { + return nil, errors.Wrap(err, op) + } + for _, a := range oidcl { + outUl = append(outUl, a) + } + } + return outUl, nil +} + +func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Type) (auth.AuthMethod, auth.VerifyResults) { + res := auth.VerifyResults{} + oidcRepo, err := s.oidcRepoFn() + if err != nil { + res.Error = err + return nil, res + } + + var parentId string + opts := []auth.Option{auth.WithType(resource.ManagedGroup), auth.WithAction(a)} + switch a { + case action.List, action.Create: + parentId = id + default: + switch auth.SubtypeFromId(id) { + case auth.OidcSubtype: + acct, err := oidcRepo.LookupManagedGroup(ctx, id) + if err != nil { + res.Error = err + return nil, res + } + if acct == nil { + res.Error = handlers.NotFoundError() + return nil, res + } + parentId = acct.GetAuthMethodId() + } + opts = append(opts, auth.WithId(id)) + } + + var authMeth auth.AuthMethod + switch auth.SubtypeFromId(parentId) { + case auth.OidcSubtype: + am, err := oidcRepo.LookupAuthMethod(ctx, parentId) + if err != nil { + res.Error = err + return nil, res + } + if am == nil { + res.Error = handlers.NotFoundError() + return nil, res + } + authMeth = am + } + opts = append(opts, auth.WithScopeId(authMeth.GetScopeId()), auth.WithPin(parentId)) + return authMeth, auth.Verify(ctx, opts...) +} + +func toProto(ctx context.Context, in auth.ManagedGroup, opt ...handlers.Option) (*pb.ManagedGroup, error) { + opts := handlers.GetOpts(opt...) + if opts.WithOutputFields == nil { + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building managed group proto") + } + outputFields := *opts.WithOutputFields + + out := pb.ManagedGroup{} + if outputFields.Has(globals.IdField) { + out.Id = in.GetPublicId() + } + if outputFields.Has(globals.AuthMethodIdField) { + out.AuthMethodId = in.GetAuthMethodId() + } + if outputFields.Has(globals.DescriptionField) && in.GetDescription() != "" { + out.Description = &wrapperspb.StringValue{Value: in.GetDescription()} + } + if outputFields.Has(globals.NameField) && in.GetName() != "" { + out.Name = &wrapperspb.StringValue{Value: in.GetName()} + } + if outputFields.Has(globals.CreatedTimeField) { + out.CreatedTime = in.GetCreateTime().GetTimestamp() + } + if outputFields.Has(globals.UpdatedTimeField) { + out.UpdatedTime = in.GetUpdateTime().GetTimestamp() + } + if outputFields.Has(globals.VersionField) { + out.Version = in.GetVersion() + } + if outputFields.Has(globals.ScopeField) { + out.Scope = opts.WithScope + } + if outputFields.Has(globals.AuthorizedActionsField) { + out.AuthorizedActions = opts.WithAuthorizedActions + } + if outputFields.Has(globals.MemberIdsField) { + out.MemberIds = opts.WithMemberIds + } + switch i := in.(type) { + case *oidc.ManagedGroup: + if outputFields.Has(globals.TypeField) { + out.Type = auth.OidcSubtype.String() + } + if !outputFields.Has(globals.AttributesField) { + break + } + attrs := &pb.OidcManagedGroupAttributes{ + Filter: i.GetFilter(), + } + st, err := handlers.ProtoToStruct(attrs) + if err != nil { + return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "failed building oidc attribute struct: %v", err) + } + out.Attributes = st + } + return &out, nil +} + +// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce +// requirements on the structure of the request. They verify that: +// * The path passed in is correctly formatted +// * All required parameters are set +// * There are no conflicting parameters provided +func validateGetRequest(req *pbs.GetManagedGroupRequest) error { + const op = "managed_groups.validateGetRequest" + if req == nil { + return errors.New(errors.InvalidParameter, op, "nil request") + } + return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, intglobals.OidcManagedGroupPrefix) +} + +func validateCreateRequest(req *pbs.CreateManagedGroupRequest) error { + const op = "managed_groups.validateCreateRequest" + if req == nil { + return errors.New(errors.InvalidParameter, op, "nil request") + } + return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string { + badFields := map[string]string{} + if req.GetItem().GetAuthMethodId() == "" { + badFields[globals.AuthMethodIdField] = "This field is required." + } + switch auth.SubtypeFromId(req.GetItem().GetAuthMethodId()) { + case auth.OidcSubtype: + if req.GetItem().GetType() != "" && req.GetItem().GetType() != auth.OidcSubtype.String() { + badFields[globals.TypeField] = "Doesn't match the parent resource's type." + } + attrs := &pb.OidcManagedGroupAttributes{} + if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil { + badFields[globals.AttributesField] = "Attribute fields do not match the expected format." + } + if attrs.Filter == "" { + badFields[attrFilterField] = "This field is required." + } else { + if _, err := bexpr.CreateEvaluator(attrs.Filter); err != nil { + badFields[attrFilterField] = fmt.Sprintf("Error evaluating submitted filter expression: %v.", err) + } + } + default: + badFields[globals.AuthMethodIdField] = "Unknown auth method type from ID." + } + return badFields + }) +} + +func validateUpdateRequest(req *pbs.UpdateManagedGroupRequest) error { + const op = "managed_groups.validateUpdateRequest" + if req == nil { + return errors.New(errors.InvalidParameter, op, "nil request") + } + return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string { + badFields := map[string]string{} + switch auth.SubtypeFromId(req.GetId()) { + case auth.OidcSubtype: + if req.GetItem().GetType() != "" && req.GetItem().GetType() != auth.OidcSubtype.String() { + badFields[globals.TypeField] = "Cannot modify the resource type." + } + attrs := &pb.OidcManagedGroupAttributes{} + if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil { + badFields[globals.AttributesField] = "Attribute fields do not match the expected format." + } + if handlers.MaskContains(req.GetUpdateMask().GetPaths(), attrFilterField) { + if attrs.Filter == "" { + badFields[attrFilterField] = "Field cannot be empty." + } else { + if _, err := bexpr.CreateEvaluator(attrs.Filter); err != nil { + badFields[attrFilterField] = fmt.Sprintf("Error evaluating submitted filter expression: %v.", err) + } + } + } + } + return badFields + }, intglobals.OidcManagedGroupPrefix) +} + +func validateDeleteRequest(req *pbs.DeleteManagedGroupRequest) error { + const op = "managed_groups.validateDeleteRequest" + if req == nil { + return errors.New(errors.InvalidParameter, op, "nil request") + } + return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, intglobals.OidcManagedGroupPrefix) +} + +func validateListRequest(req *pbs.ListManagedGroupsRequest) error { + const op = "managed_groups.validateListRequest" + if req == nil { + return errors.New(errors.InvalidParameter, op, "nil request") + } + badFields := map[string]string{} + if !handlers.ValidId(handlers.Id(req.GetAuthMethodId()), oidc.AuthMethodPrefix) { + badFields[globals.AuthMethodIdField] = "Invalid formatted identifier." + } + if _, err := handlers.NewFilter(req.GetFilter()); err != nil { + badFields[globals.FilterField] = fmt.Sprintf("This field could not be parsed. %v", err) + } + if len(badFields) > 0 { + return handlers.InvalidArgumentErrorf("Error in provided request.", badFields) + } + return nil +} diff --git a/internal/servers/controller/handlers/managed_groups/managed_group_service_test.go b/internal/servers/controller/handlers/managed_groups/managed_group_service_test.go new file mode 100644 index 000000000..a875e3455 --- /dev/null +++ b/internal/servers/controller/handlers/managed_groups/managed_group_service_test.go @@ -0,0 +1,1001 @@ +package managed_groups_test + +import ( + "context" + "errors" + "fmt" + "sort" + "strconv" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/boundary/globals" + "github.com/hashicorp/boundary/internal/auth" + "github.com/hashicorp/boundary/internal/auth/oidc" + "github.com/hashicorp/boundary/internal/authtoken" + "github.com/hashicorp/boundary/internal/db" + pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups" + scopepb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes" + pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/intglobals" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/servers/controller/common" + "github.com/hashicorp/boundary/internal/servers/controller/handlers" + "github.com/hashicorp/boundary/internal/servers/controller/handlers/managed_groups" + "github.com/hashicorp/boundary/internal/types/action" + "github.com/hashicorp/boundary/internal/types/scope" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/protobuf/field_mask" + "google.golang.org/grpc/codes" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +var oidcAuthorizedActions = []string{ + action.NoOp.String(), + action.Read.String(), + action.Update.String(), + action.Delete.String(), +} + +func TestNewService(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + + cases := []struct { + name string + oidcRepo common.OidcAuthRepoFactory + wantErr bool + }{ + { + name: "nil-oidc-repo", + wantErr: true, + }, + { + name: "success", + oidcRepo: oidcRepoFn, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := managed_groups.NewService(tc.oidcRepo) + if tc.wantErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestGet(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + + s, err := managed_groups.NewService(oidcRepoFn) + require.NoError(t, err, "Couldn't create new managed groups service.") + + org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, org.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + oidcAm := oidc.TestAuthMethod( + t, conn, databaseWrapper, org.PublicId, oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + oidcA := oidc.TestAccount(t, conn, oidcAm, "test-subject") + omg := oidc.TestManagedGroup(t, conn, oidcAm, oidc.TestFakeManagedGroupFilter) + + // Set up managed group before getting. First get the current + // managed group to make sure we have the right version, then ensure + // the account is a member so we can test that return value. + oidcRepo, err := oidcRepoFn() + require.NoError(t, err) + currMg, err := oidcRepo.LookupManagedGroup(ctx, omg.GetPublicId()) + require.NoError(t, err) + _, _, err = oidcRepo.SetManagedGroupMemberships(ctx, oidcAm, oidcA, []*oidc.ManagedGroup{currMg}) + require.NoError(t, err) + // Fetch the group once more to get the updated time + currMg, err = oidcRepo.LookupManagedGroup(ctx, omg.GetPublicId()) + require.NoError(t, err) + + oidcWireManagedGroup := pb.ManagedGroup{ + Id: omg.GetPublicId(), + AuthMethodId: omg.GetAuthMethodId(), + CreatedTime: omg.GetCreateTime().GetTimestamp(), + UpdatedTime: currMg.GetUpdateTime().GetTimestamp(), + Scope: &scopepb.ScopeInfo{Id: org.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, + Version: currMg.Version, + Type: "oidc", + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{"filter": structpb.NewStringValue(omg.GetFilter())}}, + AuthorizedActions: oidcAuthorizedActions, + MemberIds: []string{oidcA.GetPublicId()}, + } + + cases := []struct { + name string + req *pbs.GetManagedGroupRequest + res *pbs.GetManagedGroupResponse + err error + }{ + { + name: "Get an oidc managed group", + req: &pbs.GetManagedGroupRequest{Id: oidcWireManagedGroup.GetId()}, + res: &pbs.GetManagedGroupResponse{Item: &oidcWireManagedGroup}, + }, + { + name: "Get a non existing oidc managed group", + req: &pbs.GetManagedGroupRequest{Id: intglobals.OidcManagedGroupPrefix + "_DoesntExis"}, + res: nil, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Wrong id prefix", + req: &pbs.GetManagedGroupRequest{Id: "j_1234567890"}, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "space in id", + req: &pbs.GetManagedGroupRequest{Id: authtoken.AuthTokenPrefix + "_1 23456789"}, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + got, gErr := s.GetManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, org.GetPublicId()), tc.req) + if tc.err != nil { + require.Error(gErr) + assert.True(errors.Is(gErr, tc.err), "GetManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err) + return + } + require.NoError(gErr) + assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res) + }) + } +} + +func TestListOidc(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + + o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + amNoManagedGroups := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, "noManagedGroups", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.nomanagedgroups.com")[0]), oidc.WithSigningAlgs(oidc.RS256), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0])) + amSomeManagedGroups := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, "someManagedGroups", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.somemanagedgroups.com")[0]), oidc.WithSigningAlgs(oidc.RS256), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0])) + amOtherManagedGroups := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, "otherManagedGroups", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.othermanagedgroups.com")[0]), oidc.WithSigningAlgs(oidc.RS256), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0])) + + var wantSomeManagedGroups []*pb.ManagedGroup + for i := 0; i < 3; i++ { + mg := oidc.TestManagedGroup(t, conn, amSomeManagedGroups, oidc.TestFakeManagedGroupFilter, oidc.WithName(strconv.Itoa(i))) + wantSomeManagedGroups = append(wantSomeManagedGroups, &pb.ManagedGroup{ + Id: mg.GetPublicId(), + AuthMethodId: mg.GetAuthMethodId(), + Name: wrapperspb.String(strconv.Itoa(i)), + CreatedTime: mg.GetCreateTime().GetTimestamp(), + UpdatedTime: mg.GetUpdateTime().GetTimestamp(), + Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, + Version: 1, + Type: auth.OidcSubtype.String(), + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(oidc.TestFakeManagedGroupFilter), + }}, + AuthorizedActions: oidcAuthorizedActions, + }) + } + + var wantOtherManagedGroups []*pb.ManagedGroup + for i := 0; i < 3; i++ { + mg := oidc.TestManagedGroup(t, conn, amOtherManagedGroups, oidc.TestFakeManagedGroupFilter, oidc.WithName(strconv.Itoa(i))) + wantOtherManagedGroups = append(wantOtherManagedGroups, &pb.ManagedGroup{ + Id: mg.GetPublicId(), + AuthMethodId: mg.GetAuthMethodId(), + Name: wrapperspb.String(strconv.Itoa(i)), + CreatedTime: mg.GetCreateTime().GetTimestamp(), + UpdatedTime: mg.GetUpdateTime().GetTimestamp(), + Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, + Version: 1, + Type: auth.OidcSubtype.String(), + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(oidc.TestFakeManagedGroupFilter), + }}, + AuthorizedActions: oidcAuthorizedActions, + }) + } + + cases := []struct { + name string + req *pbs.ListManagedGroupsRequest + res *pbs.ListManagedGroupsResponse + err error + skipAnon bool + }{ + { + name: "List Some ManagedGroups", + req: &pbs.ListManagedGroupsRequest{AuthMethodId: amSomeManagedGroups.GetPublicId()}, + res: &pbs.ListManagedGroupsResponse{Items: wantSomeManagedGroups}, + }, + { + name: "List Other ManagedGroups", + req: &pbs.ListManagedGroupsRequest{AuthMethodId: amOtherManagedGroups.GetPublicId()}, + res: &pbs.ListManagedGroupsResponse{Items: wantOtherManagedGroups}, + }, + { + name: "List No ManagedGroups", + req: &pbs.ListManagedGroupsRequest{AuthMethodId: amNoManagedGroups.GetPublicId()}, + res: &pbs.ListManagedGroupsResponse{}, + }, + { + name: "Unfound Auth Method", + req: &pbs.ListManagedGroupsRequest{AuthMethodId: oidc.AuthMethodPrefix + "_DoesntExis"}, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Filter Some ManagedGroups", + req: &pbs.ListManagedGroupsRequest{ + AuthMethodId: amSomeManagedGroups.GetPublicId(), + Filter: fmt.Sprintf(`"/item/name"==%q`, wantSomeManagedGroups[1].Name.GetValue()), + }, + res: &pbs.ListManagedGroupsResponse{Items: wantSomeManagedGroups[1:2]}, + skipAnon: true, + }, + { + name: "Filter All ManagedGroups", + req: &pbs.ListManagedGroupsRequest{ + AuthMethodId: amSomeManagedGroups.GetPublicId(), + Filter: `"/item/id"=="noManagedGroupmatchesthis"`, + }, + res: &pbs.ListManagedGroupsResponse{}, + }, + { + name: "Filter Bad Format", + req: &pbs.ListManagedGroupsRequest{AuthMethodId: amSomeManagedGroups.GetPublicId(), Filter: `"//id/"=="bad"`}, + err: handlers.InvalidArgumentErrorf("bad format", nil), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + s, err := managed_groups.NewService(oidcRepoFn) + require.NoError(err, "Couldn't create new managed group service.") + + got, gErr := s.ListManagedGroups(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req) + if tc.err != nil { + require.Error(gErr) + assert.True(errors.Is(gErr, tc.err), "ListManagedGroups() with auth method %q got error %v, wanted %v", tc.req, gErr, tc.err) + return + } else { + require.NoError(gErr) + } + sort.Slice(got.Items, func(i, j int) bool { + return strings.Compare(got.Items[i].GetName().GetValue(), + got.Items[j].GetName().GetValue()) < 0 + }) + assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListManagedGroups() with scope %q got response %q, wanted %q", tc.req, got, tc.res) + + // Now test with anon + if tc.skipAnon { + return + } + got, gErr = s.ListManagedGroups(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId(), auth.WithUserId(auth.AnonymousUserId)), tc.req) + require.NoError(gErr) + assert.Len(got.Items, len(tc.res.Items)) + for _, g := range got.GetItems() { + assert.Nil(g.Attributes) + assert.Nil(g.CreatedTime) + assert.Nil(g.UpdatedTime) + assert.Empty(g.Version) + } + }) + } +} + +func TestDelete(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + + o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + oidcAm := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + oidcMg := oidc.TestManagedGroup(t, conn, oidcAm, oidc.TestFakeManagedGroupFilter) + + s, err := managed_groups.NewService(oidcRepoFn) + require.NoError(t, err, "Error when getting new user service.") + + cases := []struct { + name string + scope string + req *pbs.DeleteManagedGroupRequest + res *pbs.DeleteManagedGroupResponse + err error + }{ + { + name: "Delete an existing oidc managed group", + req: &pbs.DeleteManagedGroupRequest{ + Id: oidcMg.GetPublicId(), + }, + }, + { + name: "Delete bad oidc managed group id", + req: &pbs.DeleteManagedGroupRequest{ + Id: intglobals.OidcManagedGroupPrefix + "_doesntexis", + }, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Bad managed group id formatting", + req: &pbs.DeleteManagedGroupRequest{ + Id: "bad_format", + }, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + got, gErr := s.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req) + if tc.err != nil { + require.Error(gErr) + assert.True(errors.Is(gErr, tc.err), "DeleteManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err) + } + assert.EqualValuesf(tc.res, got, "DeleteManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res) + }) + } +} + +func TestDelete_twice(t *testing.T) { + assert, require := assert.New(t), require.New(t) + conn, _ := db.TestSetup(t, "postgres") + wrap := db.TestWrapper(t) + rw := db.New(conn) + kmsCache := kms.TestKms(t, conn, wrap) + + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + + o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) + + databaseWrapper, err := kmsCache.GetWrapper(context.Background(), o.PublicId, kms.KeyPurposeDatabase) + + oidcAm := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + oidcMg := oidc.TestManagedGroup(t, conn, oidcAm, oidc.TestFakeManagedGroupFilter) + + s, err := managed_groups.NewService(oidcRepoFn) + require.NoError(err, "Error when getting new user service") + req := &pbs.DeleteManagedGroupRequest{ + Id: oidcMg.GetPublicId(), + } + _, gErr := s.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), req) + assert.NoError(gErr, "First attempt") + _, gErr = s.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), req) + assert.Error(gErr, "Second attempt") + assert.True(errors.Is(gErr, handlers.ApiErrorWithCode(codes.NotFound)), "Expected not found for the second delete.") +} + +func TestCreateOidc(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + + s, err := managed_groups.NewService(oidcRepoFn) + require.NoError(t, err, "Error when getting new managed group service.") + + o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + am := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + + createAttr := func() *structpb.Struct { + attr := &pb.OidcManagedGroupAttributes{Filter: oidc.TestFakeManagedGroupFilter} + ret, err := handlers.ProtoToStruct(attr) + require.NoError(t, err, "Error converting proto to struct.") + return ret + } + + cases := []struct { + name string + req *pbs.CreateManagedGroupRequest + res *pbs.CreateManagedGroupResponse + err error + }{ + { + name: "Create a valid ManagedGroup", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "name"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + Type: auth.OidcSubtype.String(), + Attributes: createAttr(), + }, + }, + res: &pbs.CreateManagedGroupResponse{ + Uri: fmt.Sprintf("managed-groups/%s_", intglobals.OidcManagedGroupPrefix), + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "name"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, + Version: 1, + Type: auth.OidcSubtype.String(), + Attributes: func() *structpb.Struct { + a := createAttr() + a.Fields["filter"] = structpb.NewStringValue(oidc.TestFakeManagedGroupFilter) + return a + }(), + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "Create a valid ManagedGroup without type defined", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Attributes: createAttr(), + }, + }, + res: &pbs.CreateManagedGroupResponse{ + Uri: fmt.Sprintf("managed-groups/%s_", intglobals.OidcManagedGroupPrefix), + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, + Version: 1, + Type: auth.OidcSubtype.String(), + Attributes: func() *structpb.Struct { + a := createAttr() + a.Fields["filter"] = structpb.NewStringValue(oidc.TestFakeManagedGroupFilter) + return a + }(), + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "Cant specify mismatching type", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Type: auth.PasswordSubtype.String(), + Attributes: createAttr(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Can't specify Id", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Id: intglobals.OidcManagedGroupPrefix + "_notallowed", + Type: auth.OidcSubtype.String(), + Attributes: createAttr(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Can't specify Created Time", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + CreatedTime: timestamppb.Now(), + Type: auth.OidcSubtype.String(), + Attributes: createAttr(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Can't specify Update Time", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + UpdatedTime: timestamppb.Now(), + Type: auth.OidcSubtype.String(), + Attributes: createAttr(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Can't specify bad filter", + req: &pbs.CreateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + UpdatedTime: timestamppb.Now(), + Type: auth.OidcSubtype.String(), + Attributes: func() *structpb.Struct { + a := createAttr() + a.Fields["filter"] = structpb.NewStringValue("foobar") + return a + }(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + got, gErr := s.CreateManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req) + if tc.err != nil { + require.Error(gErr) + assert.True(errors.Is(gErr, tc.err), "CreateManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err) + return + } + require.NoError(gErr) + if got != nil { + assert.Contains(got.GetUri(), tc.res.Uri) + assert.True(strings.HasPrefix(got.GetItem().GetId(), intglobals.OidcManagedGroupPrefix+"_")) + // Clear all values which are hard to compare against. + got.Uri, tc.res.Uri = "", "" + got.Item.Id, tc.res.Item.Id = "", "" + got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil + } + assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res) + }) + } +} + +func TestUpdateOidc(t *testing.T) { + ctx := context.Background() + conn, _ := db.TestSetup(t, "postgres") + rw := db.New(conn) + wrap := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrap) + oidcRepoFn := func() (*oidc.Repository, error) { + return oidc.NewRepository(rw, rw, kmsCache) + } + iamRepoFn := func() (*iam.Repository, error) { + return iam.NewRepository(rw, rw, kmsCache) + } + + o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap)) + + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + am := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.PublicId, oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0])) + + tested, err := managed_groups.NewService(oidcRepoFn) + require.NoError(t, err, "Error when getting new managed_groups service.") + + defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()} + defaultAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(oidc.TestFakeManagedGroupFilter), + }} + + modifiedFilter := `"/token/zip" == "zap"` + modifiedAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(modifiedFilter), + }} + + badFilter := `"foobar"` + badAttributes := &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(badFilter), + }} + + freshManagedGroup := func(t *testing.T) (*oidc.ManagedGroup, func()) { + t.Helper() + mg := oidc.TestManagedGroup(t, conn, am, oidc.TestFakeManagedGroupFilter, oidc.WithName("default"), oidc.WithDescription("default")) + + clean := func() { + _, err := tested.DeleteManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), + &pbs.DeleteManagedGroupRequest{Id: mg.GetPublicId()}) + require.NoError(t, err) + } + + return mg, clean + } + + cases := []struct { + name string + req *pbs.UpdateManagedGroupRequest + res *pbs.UpdateManagedGroupResponse + err error + }{ + { + name: "Update an Existing AuthMethod", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.NameField, globals.DescriptionField}, + }, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + Type: auth.OidcSubtype.String(), + }, + }, + res: &pbs.UpdateManagedGroupResponse{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + Type: auth.OidcSubtype.String(), + Attributes: defaultAttributes, + Scope: defaultScopeInfo, + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "Multiple Paths in single string", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"name,description"}, + }, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + Type: auth.OidcSubtype.String(), + }, + }, + res: &pbs.UpdateManagedGroupResponse{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + Type: auth.OidcSubtype.String(), + Attributes: defaultAttributes, + Scope: defaultScopeInfo, + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "No Update Mask", + req: &pbs.UpdateManagedGroupRequest{ + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "updated name"}, + Description: &wrapperspb.StringValue{Value: "updated desc"}, + Attributes: modifiedAttributes, + }, + }, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Cant change type", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.NameField}, + }, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: ""}, + Type: "oidc", + }, + }, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "No Paths in Mask", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{Paths: []string{}}, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "updated name"}, + Description: &wrapperspb.StringValue{Value: "updated desc"}, + Attributes: modifiedAttributes, + }, + }, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Only non-existant paths in Mask", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{Paths: []string{"nonexistant_field"}}, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "updated name"}, + Description: &wrapperspb.StringValue{Value: "updated desc"}, + Attributes: modifiedAttributes, + }, + }, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Unset Name", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.NameField}, + }, + Item: &pb.ManagedGroup{ + Description: &wrapperspb.StringValue{Value: "ignored"}, + Attributes: modifiedAttributes, + }, + }, + res: &pbs.UpdateManagedGroupResponse{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Description: &wrapperspb.StringValue{Value: "default"}, + Type: auth.OidcSubtype.String(), + Attributes: defaultAttributes, + Scope: defaultScopeInfo, + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "Update Only Name", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.NameField}, + }, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "updated"}, + Description: &wrapperspb.StringValue{Value: "ignored"}, + Attributes: modifiedAttributes, + }, + }, + res: &pbs.UpdateManagedGroupResponse{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "updated"}, + Description: &wrapperspb.StringValue{Value: "default"}, + Type: auth.OidcSubtype.String(), + Attributes: defaultAttributes, + Scope: defaultScopeInfo, + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "Update Only Description", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.DescriptionField}, + }, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "ignored"}, + Description: &wrapperspb.StringValue{Value: "notignored"}, + Attributes: modifiedAttributes, + }, + }, + res: &pbs.UpdateManagedGroupResponse{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "default"}, + Description: &wrapperspb.StringValue{Value: "notignored"}, + Type: auth.OidcSubtype.String(), + Attributes: defaultAttributes, + Scope: defaultScopeInfo, + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + { + name: "Update a Non Existing ManagedGroup", + req: &pbs.UpdateManagedGroupRequest{ + Id: intglobals.OidcManagedGroupPrefix + "_DoesntExis", + UpdateMask: &field_mask.FieldMask{ + Paths: []string{globals.DescriptionField}, + }, + Item: &pb.ManagedGroup{ + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "desc"}, + }, + }, + err: handlers.ApiErrorWithCode(codes.NotFound), + }, + { + name: "Cant change Id", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"id"}, + }, + Item: &pb.ManagedGroup{ + Id: intglobals.OidcManagedGroupPrefix + "_somethinge", + Name: &wrapperspb.StringValue{Value: "new"}, + Description: &wrapperspb.StringValue{Value: "new desc"}, + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Cant specify Created Time", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"created_time"}, + }, + Item: &pb.ManagedGroup{ + CreatedTime: timestamppb.Now(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Cant specify Updated Time", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"updated_time"}, + }, + Item: &pb.ManagedGroup{ + UpdatedTime: timestamppb.Now(), + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Cant specify Type", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"type"}, + }, + Item: &pb.ManagedGroup{ + Type: "oidc", + }, + }, + res: nil, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Update Filter with Bad Value", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"attributes.filter"}, + }, + Item: &pb.ManagedGroup{ + Attributes: badAttributes, + }, + }, + err: handlers.ApiErrorWithCode(codes.InvalidArgument), + }, + { + name: "Update Filter With Good Value", + req: &pbs.UpdateManagedGroupRequest{ + UpdateMask: &field_mask.FieldMask{ + Paths: []string{"attributes.filter"}, + }, + Item: &pb.ManagedGroup{ + Attributes: modifiedAttributes, + }, + }, + res: &pbs.UpdateManagedGroupResponse{ + Item: &pb.ManagedGroup{ + AuthMethodId: am.GetPublicId(), + Name: &wrapperspb.StringValue{Value: "default"}, + Description: &wrapperspb.StringValue{Value: "default"}, + Type: auth.OidcSubtype.String(), + Attributes: modifiedAttributes, + Scope: defaultScopeInfo, + AuthorizedActions: oidcAuthorizedActions, + }, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + mg, cleanup := freshManagedGroup(t) + defer cleanup() + + tc.req.Item.Version = 1 + + if tc.req.GetId() == "" { + tc.req.Id = mg.GetPublicId() + } + + if tc.res != nil && tc.res.Item != nil { + tc.res.Item.Id = mg.GetPublicId() + tc.res.Item.CreatedTime = mg.GetCreateTime().GetTimestamp() + } + + got, gErr := tested.UpdateManagedGroup(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req) + if tc.err != nil { + require.Error(gErr) + assert.True(errors.Is(gErr, tc.err), "UpdateManagedGroup(%+v) got error %v, wanted %v", tc.req, gErr, tc.err) + } + + if tc.res == nil { + require.Nil(got) + } + + if got != nil { + assert.NotNilf(tc.res, "Expected UpdateManagedGroup response to be nil, but was %v", got) + gotUpdateTime := got.GetItem().GetUpdatedTime() + require.NoError(err, "Error converting proto to timestamp") + + created := mg.GetCreateTime().GetTimestamp() + require.NoError(err, "Error converting proto to timestamp") + + // Verify it is a auth_method updated after it was created + assert.True(gotUpdateTime.AsTime().After(created.AsTime()), "Updated account should have been updated after it's creation. Was updated %v, which is after %v", gotUpdateTime, created) + + // Clear all values which are hard to compare against. + got.Item.UpdatedTime, tc.res.Item.UpdatedTime = nil, nil + + assert.EqualValues(2, got.Item.Version) + tc.res.Item.Version = 2 + } + assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "UpdateManagedGroup(%q) got response %q, wanted %q", tc.req, got, tc.res) + }) + } +} diff --git a/internal/servers/controller/handlers/managed_groups/validate_test.go b/internal/servers/controller/handlers/managed_groups/validate_test.go new file mode 100644 index 000000000..c1048cc73 --- /dev/null +++ b/internal/servers/controller/handlers/managed_groups/validate_test.go @@ -0,0 +1,147 @@ +package managed_groups + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/boundary/globals" + "github.com/hashicorp/boundary/internal/auth" + "github.com/hashicorp/boundary/internal/auth/oidc" + pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/managedgroups" + pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" + "github.com/hashicorp/boundary/internal/intglobals" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/fieldmaskpb" + "google.golang.org/protobuf/types/known/structpb" +) + +func fieldError(field, details string) string { + return fmt.Sprintf(`{name: %q, desc: %q}`, field, details) +} + +func TestValidateCreateRequest(t *testing.T) { + t.Parallel() + cases := []struct { + name string + item *pb.ManagedGroup + errContains string + }{ + { + name: "unrecognized authmethod prefix", + item: &pb.ManagedGroup{ + AuthMethodId: "anything_1234567890", + }, + errContains: fieldError(globals.AuthMethodIdField, "Unknown auth method type from ID."), + }, + { + name: "mismatched oidc authmethod pw type", + item: &pb.ManagedGroup{ + Type: "ldap", + AuthMethodId: oidc.AuthMethodPrefix + "_1234567890", + }, + errContains: fieldError(globals.TypeField, "Doesn't match the parent resource's type."), + }, + { + name: "missing oidc attributes", + item: &pb.ManagedGroup{ + Type: auth.OidcSubtype.String(), + AuthMethodId: oidc.AuthMethodPrefix + "_1234567890", + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{}}, + }, + errContains: fieldError(attrFilterField, "This field is required."), + }, + { + name: "bad oidc attributes", + item: &pb.ManagedGroup{ + Type: auth.OidcSubtype.String(), + AuthMethodId: oidc.AuthMethodPrefix + "_1234567890", + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue("foobar"), + }}, + }, + errContains: "Error evaluating submitted filter", + }, + { + name: "no oidc errors", + item: &pb.ManagedGroup{ + Type: auth.OidcSubtype.String(), + AuthMethodId: oidc.AuthMethodPrefix + "_1234567890", + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(`"/foo/bar" == "zipzap"`), + }}, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + req := &pbs.CreateManagedGroupRequest{Item: tc.item} + err := validateCreateRequest(req) + if tc.errContains == "" { + require.NoError(t, err) + return + } + assert.True(t, strings.Contains(err.Error(), tc.errContains), + "%q wasn't contained in %q", tc.errContains, err.Error()) + }) + } +} + +func TestValidateUpdateRequest(t *testing.T) { + t.Parallel() + cases := []struct { + name string + req *pbs.UpdateManagedGroupRequest + errContains string + }{ + { + name: "oidc to password change type", + req: &pbs.UpdateManagedGroupRequest{ + Id: intglobals.OidcManagedGroupPrefix + "_1234567890", + Item: &pb.ManagedGroup{ + Type: auth.PasswordSubtype.String(), + }, + }, + errContains: fieldError(globals.TypeField, "Cannot modify the resource type."), + }, + { + name: "oidc bad attributes", + req: &pbs.UpdateManagedGroupRequest{ + Id: intglobals.OidcManagedGroupPrefix + "_1234567890", + Item: &pb.ManagedGroup{ + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "test": structpb.NewStringValue("something"), + }}, + }, + }, + errContains: fieldError(globals.AttributesField, "Attribute fields do not match the expected format."), + }, + { + name: "no error", + req: &pbs.UpdateManagedGroupRequest{ + Id: intglobals.OidcManagedGroupPrefix + "_1234567890", + UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{}}, + Item: &pb.ManagedGroup{ + Version: 1, + Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{ + "filter": structpb.NewStringValue(`"/foo/bar" == "zipzap"`), + }}, + }, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + err := validateUpdateRequest(tc.req) + if tc.errContains == "" { + require.NoError(t, err) + return + } + assert.True(t, strings.Contains(err.Error(), tc.errContains), + "%q wasn't contained in %q", tc.errContains, err.Error()) + }) + } +} diff --git a/internal/servers/controller/handlers/option_test.go b/internal/servers/controller/handlers/option_test.go index 2e806db12..6f5eb5dd3 100644 --- a/internal/servers/controller/handlers/option_test.go +++ b/internal/servers/controller/handlers/option_test.go @@ -60,4 +60,28 @@ func Test_GetOpts(t *testing.T) { require.NotNil(opts.WithOutputFields) assert.Nil(*opts.WithOutputFields) }) + t.Run("WithManagedGroupIds", func(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + opts := GetOpts() + assert.Nil(opts.WithManagedGroupIds) + + out := []string{"foobar"} + + opts = GetOpts(WithManagedGroupIds(out)) + require.Equal(out, opts.WithManagedGroupIds) + }) + t.Run("WithMemberIds", func(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + opts := GetOpts() + assert.Nil(opts.WithMemberIds) + + out := []string{"foobar"} + + opts = GetOpts(WithMemberIds(out)) + require.Equal(out, opts.WithMemberIds) + }) } diff --git a/internal/servers/controller/handlers/options.go b/internal/servers/controller/handlers/options.go index 50265a352..3735a5ddd 100644 --- a/internal/servers/controller/handlers/options.go +++ b/internal/servers/controller/handlers/options.go @@ -30,6 +30,8 @@ type options struct { WithScope *scopes.ScopeInfo WithAuthorizedActions []string WithAuthorizedCollectionActions map[string]*structpb.ListValue + WithManagedGroupIds []string + WithMemberIds []string } func getDefaultOptions() options { @@ -91,3 +93,19 @@ func WithAuthorizedCollectionActions(colActs map[string]*structpb.ListValue) Opt o.WithAuthorizedCollectionActions = colActs } } + +// WithManagedGroupIds provides an option when creating responses to include the given +// managed group IDs if allowed +func WithManagedGroupIds(ids []string) Option { + return func(o *options) { + o.WithManagedGroupIds = ids + } +} + +// WithMemberIds provides an option when creating responses to include the given +// member IDs if allowed +func WithMemberIds(ids []string) Option { + return func(o *options) { + o.WithMemberIds = ids + } +} diff --git a/internal/servers/controller/handlers/roles/role_service.go b/internal/servers/controller/handlers/roles/role_service.go index 5d3a2bbc8..57dc33594 100644 --- a/internal/servers/controller/handlers/roles/role_service.go +++ b/internal/servers/controller/handlers/roles/role_service.go @@ -11,6 +11,7 @@ import ( pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/iam/store" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/perms" "github.com/hashicorp/boundary/internal/requests" "github.com/hashicorp/boundary/internal/servers/controller/common" @@ -967,8 +968,10 @@ func validateAddRolePrincipalsRequest(req *pbs.AddRolePrincipalsRequest) error { badFields["principal_ids"] = "Must be non-empty." } for _, id := range req.GetPrincipalIds() { - if !handlers.ValidId(handlers.Id(id), iam.GroupPrefix) && !handlers.ValidId(handlers.Id(id), iam.UserPrefix) { - badFields["principal_ids"] = "Must only have valid group and/or user ids." + if !handlers.ValidId(handlers.Id(id), iam.GroupPrefix) && + !handlers.ValidId(handlers.Id(id), iam.UserPrefix) && + !handlers.ValidId(handlers.Id(id), intglobals.OidcManagedGroupPrefix) { + badFields["principal_ids"] = "Must only have valid user, group, and/or managed group ids." break } if id == "u_recovery" { @@ -991,8 +994,10 @@ func validateSetRolePrincipalsRequest(req *pbs.SetRolePrincipalsRequest) error { badFields["version"] = "Required field." } for _, id := range req.GetPrincipalIds() { - if !handlers.ValidId(handlers.Id(id), iam.GroupPrefix) && !handlers.ValidId(handlers.Id(id), iam.UserPrefix) { - badFields["principal_ids"] = "Must only have valid group and/or user ids." + if !handlers.ValidId(handlers.Id(id), iam.GroupPrefix) && + !handlers.ValidId(handlers.Id(id), iam.UserPrefix) && + !handlers.ValidId(handlers.Id(id), intglobals.OidcManagedGroupPrefix) { + badFields["principal_ids"] = "Must only have valid user, group, and/or managed group ids." break } if id == "u_recovery" { @@ -1018,8 +1023,10 @@ func validateRemoveRolePrincipalsRequest(req *pbs.RemoveRolePrincipalsRequest) e badFields["principal_ids"] = "Must be non-empty." } for _, id := range req.GetPrincipalIds() { - if !handlers.ValidId(handlers.Id(id), iam.GroupPrefix) && !handlers.ValidId(handlers.Id(id), iam.UserPrefix) { - badFields["principal_ids"] = "Must only have valid group and/or user ids." + if !handlers.ValidId(handlers.Id(id), iam.GroupPrefix) && + !handlers.ValidId(handlers.Id(id), iam.UserPrefix) && + !handlers.ValidId(handlers.Id(id), intglobals.OidcManagedGroupPrefix) { + badFields["principal_ids"] = "Must only have valid user, group, and/or managed group ids." break } } diff --git a/internal/servers/controller/handlers/roles/role_service_test.go b/internal/servers/controller/handlers/roles/role_service_test.go index c339e6b10..d9cef7986 100644 --- a/internal/servers/controller/handlers/roles/role_service_test.go +++ b/internal/servers/controller/handlers/roles/role_service_test.go @@ -9,15 +9,18 @@ import ( "github.com/google/go-cmp/cmp" "github.com/hashicorp/boundary/internal/auth" + "github.com/hashicorp/boundary/internal/auth/oidc" "github.com/hashicorp/boundary/internal/db" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/roles" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/perms" "github.com/hashicorp/boundary/internal/servers/controller/handlers" "github.com/hashicorp/boundary/internal/servers/controller/handlers/roles" "github.com/hashicorp/boundary/internal/types/scope" + "github.com/kr/pretty" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -1010,10 +1013,23 @@ func TestAddPrincipal(t *testing.T) { repoFn := func() (*iam.Repository, error) { return iamRepo, nil } + o, p := iam.TestScopes(t, iamRepo) s, err := roles.NewService(repoFn) require.NoError(t, err, "Error when getting new role service.") - o, p := iam.TestScopes(t, iamRepo) + ctx := context.Background() + kmsCache := kms.TestKms(t, conn, wrap) + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + users := []*iam.User{ iam.TestUser(t, iamRepo, o.GetPublicId()), iam.TestUser(t, iamRepo, o.GetPublicId()), @@ -1024,15 +1040,22 @@ func TestAddPrincipal(t *testing.T) { iam.TestGroup(t, conn, o.GetPublicId()), iam.TestGroup(t, conn, o.GetPublicId()), } + managedGroups := []*oidc.ManagedGroup{ + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + } addCases := []struct { - name string - setup func(*iam.Role) - addUsers []string - addGroups []string - resultUsers []string - resultGroups []string - wantErr bool + name string + setup func(*iam.Role) + addUsers []string + addGroups []string + addManagedGroups []string + resultUsers []string + resultGroups []string + resultManagedGroups []string + wantErr bool }{ { name: "Add user on empty role", @@ -1078,6 +1101,28 @@ func TestAddPrincipal(t *testing.T) { addGroups: []string{groups[1].GetPublicId(), groups[1].GetPublicId()}, resultGroups: []string{groups[0].GetPublicId(), groups[1].GetPublicId()}, }, + { + name: "Add managed group on empty role", + setup: func(r *iam.Role) {}, + addManagedGroups: []string{managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[1].GetPublicId()}, + }, + { + name: "Add managed group on populated role", + setup: func(r *iam.Role) { + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[0].GetPublicId()) + }, + addManagedGroups: []string{managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[0].GetPublicId(), managedGroups[1].GetPublicId()}, + }, + { + name: "Add duplicate managed group on populated role", + setup: func(r *iam.Role) { + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[0].GetPublicId()) + }, + addManagedGroups: []string{managedGroups[1].GetPublicId(), managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[0].GetPublicId(), managedGroups[1].GetPublicId()}, + }, { name: "Add invalid u_recovery on role", setup: func(r *iam.Role) {}, @@ -1094,7 +1139,7 @@ func TestAddPrincipal(t *testing.T) { req := &pbs.AddRolePrincipalsRequest{ Id: role.GetPublicId(), Version: role.GetVersion(), - PrincipalIds: append(tc.addUsers, tc.addGroups...), + PrincipalIds: append(tc.addUsers, append(tc.addGroups, tc.addManagedGroups...)...), } got, err := s.AddRolePrincipals(auth.DisabledAuthTestContext(repoFn, o.GetPublicId()), req) @@ -1103,10 +1148,10 @@ func TestAddPrincipal(t *testing.T) { return } s, ok := status.FromError(err) - require.True(t, ok) + require.True(t, ok, fmt.Sprintf("Could not run FromError; input was %s", pretty.Sprint(err))) require.NoError(t, err, "Got error: %v", s) - assert.True(t, equalPrincipals(got.GetItem(), append(tc.resultUsers, tc.resultGroups...))) + assert.True(t, equalPrincipals(got.GetItem(), append(tc.resultUsers, append(tc.resultGroups, tc.resultManagedGroups...)...))) }) } } @@ -1168,6 +1213,20 @@ func TestSetPrincipal(t *testing.T) { require.NoError(t, err, "Error when getting new role service.") o, p := iam.TestScopes(t, iamRepo) + + ctx := context.Background() + kmsCache := kms.TestKms(t, conn, wrap) + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + users := []*iam.User{ iam.TestUser(t, iamRepo, o.GetPublicId()), iam.TestUser(t, iamRepo, o.GetPublicId()), @@ -1178,15 +1237,22 @@ func TestSetPrincipal(t *testing.T) { iam.TestGroup(t, conn, o.GetPublicId()), iam.TestGroup(t, conn, o.GetPublicId()), } + managedGroups := []*oidc.ManagedGroup{ + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + } setCases := []struct { - name string - setup func(*iam.Role) - setUsers []string - setGroups []string - resultUsers []string - resultGroups []string - wantErr bool + name string + setup func(*iam.Role) + setUsers []string + setGroups []string + setManagedGroups []string + resultUsers []string + resultGroups []string + resultManagedGroups []string + wantErr bool }{ { name: "Set user on empty role", @@ -1233,6 +1299,20 @@ func TestSetPrincipal(t *testing.T) { setGroups: []string{groups[1].GetPublicId()}, resultGroups: []string{groups[1].GetPublicId()}, }, + { + name: "Set managed group on empty role", + setup: func(r *iam.Role) {}, + setManagedGroups: []string{managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[1].GetPublicId()}, + }, + { + name: "Set managed group on populated role", + setup: func(r *iam.Role) { + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[0].GetPublicId()) + }, + setManagedGroups: []string{managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[1].GetPublicId()}, + }, { name: "Set invalid u_recovery on role", setup: func(r *iam.Role) {}, @@ -1249,7 +1329,7 @@ func TestSetPrincipal(t *testing.T) { req := &pbs.SetRolePrincipalsRequest{ Id: role.GetPublicId(), Version: role.GetVersion(), - PrincipalIds: append(tc.setUsers, tc.setGroups...), + PrincipalIds: append(tc.setUsers, append(tc.setGroups, tc.setManagedGroups...)...), } got, err := s.SetRolePrincipals(auth.DisabledAuthTestContext(repoFn, o.GetPublicId()), req) @@ -1258,10 +1338,10 @@ func TestSetPrincipal(t *testing.T) { return } s, ok := status.FromError(err) - require.True(t, ok) + require.True(t, ok, fmt.Sprintf("Could not run FromError; input was %s", pretty.Sprint(err))) require.NoError(t, err, "Got error: %v", s) - assert.True(t, equalPrincipals(got.GetItem(), append(tc.resultUsers, tc.resultGroups...))) + assert.True(t, equalPrincipals(got.GetItem(), append(tc.resultUsers, append(tc.resultGroups, tc.resultManagedGroups...)...))) }) } } @@ -1323,6 +1403,20 @@ func TestRemovePrincipal(t *testing.T) { require.NoError(t, err, "Error when getting new role service.") o, p := iam.TestScopes(t, iamRepo) + + ctx := context.Background() + kmsCache := kms.TestKms(t, conn, wrap) + databaseWrapper, err := kmsCache.GetWrapper(ctx, o.PublicId, kms.KeyPurposeDatabase) + require.NoError(t, err) + + authMethod := oidc.TestAuthMethod( + t, conn, databaseWrapper, o.GetPublicId(), oidc.ActivePrivateState, + "alice-rp", "fido", + oidc.WithSigningAlgs(oidc.RS256), + oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://www.alice.com")[0]), + oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://www.alice.com/callback")[0]), + ) + users := []*iam.User{ iam.TestUser(t, iamRepo, o.GetPublicId()), iam.TestUser(t, iamRepo, o.GetPublicId()), @@ -1333,15 +1427,22 @@ func TestRemovePrincipal(t *testing.T) { iam.TestGroup(t, conn, o.GetPublicId()), iam.TestGroup(t, conn, o.GetPublicId()), } + managedGroups := []*oidc.ManagedGroup{ + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + oidc.TestManagedGroup(t, conn, authMethod, oidc.TestFakeManagedGroupFilter), + } addCases := []struct { - name string - setup func(*iam.Role) - removeUsers []string - removeGroups []string - resultUsers []string - resultGroups []string - wantErr bool + name string + setup func(*iam.Role) + removeUsers []string + removeGroups []string + removeManagedGroups []string + resultUsers []string + resultGroups []string + resultManagedGroups []string + wantErr bool }{ { name: "Remove user on empty role", @@ -1416,6 +1517,39 @@ func TestRemovePrincipal(t *testing.T) { removeGroups: []string{groups[0].GetPublicId(), groups[1].GetPublicId()}, resultGroups: []string{}, }, + { + name: "Remove managed group on empty role", + setup: func(r *iam.Role) {}, + removeGroups: []string{groups[1].GetPublicId()}, + wantErr: true, + }, + { + name: "Remove 1 of 2 managed groups from role", + setup: func(r *iam.Role) { + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[0].GetPublicId()) + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[1].GetPublicId()) + }, + removeManagedGroups: []string{managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[0].GetPublicId()}, + }, + { + name: "Remove 1 duplicate managed group of 2 managed groups from role", + setup: func(r *iam.Role) { + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[0].GetPublicId()) + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[1].GetPublicId()) + }, + removeManagedGroups: []string{managedGroups[1].GetPublicId(), managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{managedGroups[0].GetPublicId()}, + }, + { + name: "Remove all managed groups from role", + setup: func(r *iam.Role) { + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[0].GetPublicId()) + iam.TestManagedGroupRole(t, conn, r.GetPublicId(), managedGroups[1].GetPublicId()) + }, + removeManagedGroups: []string{managedGroups[0].GetPublicId(), managedGroups[1].GetPublicId()}, + resultManagedGroups: []string{}, + }, } for _, tc := range addCases { @@ -1426,7 +1560,7 @@ func TestRemovePrincipal(t *testing.T) { req := &pbs.RemoveRolePrincipalsRequest{ Id: role.GetPublicId(), Version: role.GetVersion(), - PrincipalIds: append(tc.removeUsers, tc.removeGroups...), + PrincipalIds: append(tc.removeUsers, append(tc.removeGroups, tc.removeManagedGroups...)...), } got, err := s.RemoveRolePrincipals(auth.DisabledAuthTestContext(repoFn, o.GetPublicId()), req) @@ -1438,7 +1572,7 @@ func TestRemovePrincipal(t *testing.T) { require.True(t, ok) require.NoError(t, err, "Got error: %v", s) - assert.True(t, equalPrincipals(got.GetItem(), append(tc.resultUsers, tc.resultGroups...))) + assert.True(t, equalPrincipals(got.GetItem(), append(tc.resultUsers, append(tc.resultGroups, tc.resultManagedGroups...)...))) }) } } diff --git a/internal/servers/controller/handlers/users/user_service.go b/internal/servers/controller/handlers/users/user_service.go index 5e29132d5..e5aaba272 100644 --- a/internal/servers/controller/handlers/users/user_service.go +++ b/internal/servers/controller/handlers/users/user_service.go @@ -7,12 +7,12 @@ import ( "github.com/hashicorp/boundary/globals" "github.com/hashicorp/boundary/internal/auth" "github.com/hashicorp/boundary/internal/auth/oidc" - "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/users" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/iam/store" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/perms" "github.com/hashicorp/boundary/internal/requests" "github.com/hashicorp/boundary/internal/servers/controller/common" @@ -714,7 +714,11 @@ func validateAddUserAccountsRequest(req *pbs.AddUserAccountsRequest) error { } for _, a := range req.GetAccountIds() { // TODO: Increase the type of auth accounts that can be added to a user. - if !handlers.ValidId(handlers.Id(a), password.AccountPrefix, oidc.AccountPrefix) { + if !handlers.ValidId(handlers.Id(a), + intglobals.OldPasswordAccountPrefix, + intglobals.NewPasswordAccountPrefix, + oidc.AccountPrefix, + ) { badFields["account_ids"] = "Values must be valid account ids." break } @@ -735,7 +739,11 @@ func validateSetUserAccountsRequest(req *pbs.SetUserAccountsRequest) error { } for _, a := range req.GetAccountIds() { // TODO: Increase the type of auth accounts that can be added to a user. - if !handlers.ValidId(handlers.Id(a), password.AccountPrefix, oidc.AccountPrefix) { + if !handlers.ValidId(handlers.Id(a), + intglobals.OldPasswordAccountPrefix, + intglobals.NewPasswordAccountPrefix, + oidc.AccountPrefix, + ) { badFields["account_ids"] = "Values must be valid account ids." break } @@ -759,7 +767,11 @@ func validateRemoveUserAccountsRequest(req *pbs.RemoveUserAccountsRequest) error } for _, a := range req.GetAccountIds() { // TODO: Increase the type of auth accounts that can be added to a user. - if !handlers.ValidId(handlers.Id(a), password.AccountPrefix, oidc.AccountPrefix) { + if !handlers.ValidId(handlers.Id(a), + intglobals.OldPasswordAccountPrefix, + intglobals.NewPasswordAccountPrefix, + oidc.AccountPrefix, + ) { badFields["account_ids"] = "Values must be valid account ids." break } diff --git a/internal/servers/controller/testing.go b/internal/servers/controller/testing.go index ebbcd10f3..9c3ae8529 100644 --- a/internal/servers/controller/testing.go +++ b/internal/servers/controller/testing.go @@ -17,6 +17,7 @@ import ( "github.com/hashicorp/boundary/internal/cmd/config" "github.com/hashicorp/boundary/internal/db/schema" "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/servers" "github.com/hashicorp/boundary/sdk/strutil" @@ -27,11 +28,16 @@ import ( ) const ( - DefaultTestAuthMethodId = "ampw_1234567890" - DefaultTestLoginName = "admin" - DefaultTestUnprivilegedLoginName = "user" - DefaultTestPassword = "passpass" - DefaultTestUserId = "u_1234567890" + DefaultTestPasswordAuthMethodId = "ampw_1234567890" + DefaultTestOidcAuthMethodId = "amoidc_1234567890" + DefaultTestLoginName = "admin" + DefaultTestUnprivilegedLoginName = "user" + DefaultTestPassword = "passpass" + DefaultTestUserId = "u_1234567890" + DefaultTestPasswordAccountId = intglobals.NewPasswordAccountPrefix + "_1234567890" + DefaultTestOidcAccountId = "acctoidc_1234567890" + DefaultTestUnprivilegedPasswordAccountId = intglobals.NewPasswordAccountPrefix + "_0987654321" + DefaultTestUnprivilegedOidcAccountId = "acctoidc_0987654321" ) // TestController wraps a base.Server and Controller to provide a @@ -280,8 +286,11 @@ type TestControllerOpts struct { // set. Config *config.Config - // DefaultAuthMethodId is the default auth method ID to use, if set. - DefaultAuthMethodId string + // DefaultPasswordAuthMethodId is the default password method ID to use, if set. + DefaultPasswordAuthMethodId string + + // DefaultOidcAuthMethodId is the default OIDC method ID to use, if set. + DefaultOidcAuthMethodId string // DefaultLoginName is the login name used when creating the default admin account. DefaultLoginName string @@ -300,6 +309,10 @@ type TestControllerOpts struct { // method automatically. DisableAuthMethodCreation bool + // DisableOidcAuthMethodCreation can be set true to disable the built-in + // OIDC listener. Useful for e.g. unix listener tests. + DisableOidcAuthMethodCreation bool + // DisableScopesCreation can be set true to disable creating scopes // automatically. DisableScopesCreation bool @@ -394,10 +407,15 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController { opts.Config.Controller.Name = opts.Name } - if opts.DefaultAuthMethodId != "" { - tc.b.DevPasswordAuthMethodId = opts.DefaultAuthMethodId + if opts.DefaultPasswordAuthMethodId != "" { + tc.b.DevPasswordAuthMethodId = opts.DefaultPasswordAuthMethodId } else { - tc.b.DevPasswordAuthMethodId = DefaultTestAuthMethodId + tc.b.DevPasswordAuthMethodId = DefaultTestPasswordAuthMethodId + } + if opts.DefaultOidcAuthMethodId != "" { + tc.b.DevOidcAuthMethodId = opts.DefaultOidcAuthMethodId + } else { + tc.b.DevOidcAuthMethodId = DefaultTestOidcAuthMethodId } if opts.DefaultLoginName != "" { tc.b.DevLoginName = opts.DefaultLoginName @@ -416,6 +434,10 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController { tc.b.DevPassword = DefaultTestPassword tc.b.DevUnprivilegedPassword = DefaultTestPassword } + tc.b.DevPasswordAccountId = DefaultTestPasswordAccountId + tc.b.DevOidcAccountId = DefaultTestOidcAccountId + tc.b.DevUnprivilegedPasswordAccountId = DefaultTestUnprivilegedPasswordAccountId + tc.b.DevUnprivilegedOidcAccountId = DefaultTestUnprivilegedOidcAccountId // Start a logger tc.b.Logger = opts.Logger @@ -440,6 +462,7 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController { if opts.InitialResourcesSuffix != "" { suffix := opts.InitialResourcesSuffix tc.b.DevPasswordAuthMethodId = "ampw_" + suffix + tc.b.DevOidcAuthMethodId = "amoidc_" + suffix tc.b.DevHostCatalogId = "hcst_" + suffix tc.b.DevHostId = "hst_" + suffix tc.b.DevHostSetId = "hsst_" + suffix @@ -500,6 +523,11 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController { if _, _, err := tc.b.CreateInitialPasswordAuthMethod(ctx); err != nil { t.Fatal(err) } + if !opts.DisableOidcAuthMethodCreation { + if err := tc.b.CreateDevOidcAuthMethod(ctx); err != nil { + t.Fatal(err) + } + } if !opts.DisableScopesCreation { if _, _, err := tc.b.CreateInitialScopes(ctx); err != nil { t.Fatal(err) @@ -523,6 +551,9 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController { if opts.DisableAuthMethodCreation { createOpts = append(createOpts, base.WithSkipAuthMethodCreation()) } + if opts.DisableOidcAuthMethodCreation { + createOpts = append(createOpts, base.WithSkipOidcAuthMethodCreation()) + } if err := tc.b.CreateDevDatabase(ctx, createOpts...); err != nil { t.Fatal(err) } @@ -557,17 +588,18 @@ func (tc *TestController) AddClusterControllerMember(t *testing.T, opts *TestCon opts = new(TestControllerOpts) } nextOpts := &TestControllerOpts{ - DatabaseUrl: tc.c.conf.DatabaseUrl, - DefaultAuthMethodId: tc.c.conf.DevPasswordAuthMethodId, - RootKms: tc.c.conf.RootKms, - WorkerAuthKms: tc.c.conf.WorkerAuthKms, - RecoveryKms: tc.c.conf.RecoveryKms, - Name: opts.Name, - Logger: tc.c.conf.Logger, - DefaultLoginName: tc.b.DevLoginName, - DefaultPassword: tc.b.DevPassword, - DisableKmsKeyCreation: true, - DisableAuthMethodCreation: true, + DatabaseUrl: tc.c.conf.DatabaseUrl, + DefaultPasswordAuthMethodId: tc.c.conf.DevPasswordAuthMethodId, + DefaultOidcAuthMethodId: tc.c.conf.DevOidcAuthMethodId, + RootKms: tc.c.conf.RootKms, + WorkerAuthKms: tc.c.conf.WorkerAuthKms, + RecoveryKms: tc.c.conf.RecoveryKms, + Name: opts.Name, + Logger: tc.c.conf.Logger, + DefaultLoginName: tc.b.DevLoginName, + DefaultPassword: tc.b.DevPassword, + DisableKmsKeyCreation: true, + DisableAuthMethodCreation: true, } if opts.Logger != nil { nextOpts.Logger = opts.Logger diff --git a/internal/tests/api/accounts/account_test.go b/internal/tests/api/accounts/account_test.go index a5cc28e7e..ee84c2704 100644 --- a/internal/tests/api/accounts/account_test.go +++ b/internal/tests/api/accounts/account_test.go @@ -9,8 +9,8 @@ import ( "github.com/hashicorp/boundary/api/accounts" "github.com/hashicorp/boundary/api/authmethods" "github.com/hashicorp/boundary/internal/auth/oidc" - "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/intglobals" "github.com/hashicorp/boundary/internal/servers/controller" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -298,7 +298,13 @@ func TestErrors(t *testing.T) { apiErr = api.AsServerError(err) require.NotNil(apiErr) - _, err = accountClient.Read(tc.Context(), password.AccountPrefix+"_doesntexis") + _, err = accountClient.Read(tc.Context(), intglobals.OldPasswordAccountPrefix+"_doesntexis") + require.Error(err) + apiErr = api.AsServerError(err) + require.NotNil(apiErr) + assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode()) + + _, err = accountClient.Read(tc.Context(), intglobals.NewPasswordAccountPrefix+"_doesntexis") require.Error(err) apiErr = api.AsServerError(err) require.NotNil(apiErr) diff --git a/internal/tests/cluster/unix_listener_test.go b/internal/tests/cluster/unix_listener_test.go index 92d3101ed..d3e5473ce 100644 --- a/internal/tests/cluster/unix_listener_test.go +++ b/internal/tests/cluster/unix_listener_test.go @@ -47,8 +47,9 @@ func TestUnixListener(t *testing.T) { } c1 := controller.NewTestController(t, &controller.TestControllerOpts{ - Config: conf, - Logger: logger.Named("c1"), + Config: conf, + Logger: logger.Named("c1"), + DisableOidcAuthMethodCreation: true, }) defer c1.Shutdown() diff --git a/internal/types/resource/resource.go b/internal/types/resource/resource.go index b7d3f38c1..834e0b567 100644 --- a/internal/types/resource/resource.go +++ b/internal/types/resource/resource.go @@ -4,22 +4,23 @@ package resource type Type uint const ( - Unknown Type = 0 - All Type = 1 - Scope Type = 2 - User Type = 3 - Group Type = 4 - Role Type = 5 - AuthMethod Type = 6 - Account Type = 7 - AuthToken Type = 8 - HostCatalog Type = 9 - HostSet Type = 10 - Host Type = 11 - Target Type = 12 - Controller Type = 13 - Worker Type = 14 - Session Type = 15 + Unknown Type = 0 + All Type = 1 + Scope Type = 2 + User Type = 3 + Group Type = 4 + Role Type = 5 + AuthMethod Type = 6 + Account Type = 7 + AuthToken Type = 8 + HostCatalog Type = 9 + HostSet Type = 10 + Host Type = 11 + Target Type = 12 + Controller Type = 13 + Worker Type = 14 + Session Type = 15 + ManagedGroup Type = 16 ) func (r Type) String() string { @@ -40,24 +41,26 @@ func (r Type) String() string { "controller", "worker", "session", + "managed-group", }[r] } var Map = map[string]Type{ - Unknown.String(): Unknown, - All.String(): All, - Scope.String(): Scope, - User.String(): User, - Group.String(): Group, - Role.String(): Role, - AuthMethod.String(): AuthMethod, - Account.String(): Account, - AuthToken.String(): AuthToken, - HostCatalog.String(): HostCatalog, - HostSet.String(): HostSet, - Host.String(): Host, - Target.String(): Target, - Controller.String(): Controller, - Worker.String(): Worker, - Session.String(): Session, + Unknown.String(): Unknown, + All.String(): All, + Scope.String(): Scope, + User.String(): User, + Group.String(): Group, + Role.String(): Role, + AuthMethod.String(): AuthMethod, + Account.String(): Account, + AuthToken.String(): AuthToken, + HostCatalog.String(): HostCatalog, + HostSet.String(): HostSet, + Host.String(): Host, + Target.String(): Target, + Controller.String(): Controller, + Worker.String(): Worker, + Session.String(): Session, + ManagedGroup.String(): ManagedGroup, } diff --git a/internal/types/resource/resource_test.go b/internal/types/resource/resource_test.go index 9f242d2bd..b7485a8f3 100644 --- a/internal/types/resource/resource_test.go +++ b/internal/types/resource/resource_test.go @@ -75,6 +75,10 @@ func Test_Resource(t *testing.T) { typeString: "session", want: Session, }, + { + typeString: "managed-group", + want: ManagedGroup, + }, } for _, tt := range tests { t.Run(tt.typeString, func(t *testing.T) { diff --git a/internal/website/permstable/permstable.go b/internal/website/permstable/permstable.go index a57834434..9dbff369e 100644 --- a/internal/website/permstable/permstable.go +++ b/internal/website/permstable/permstable.go @@ -70,6 +70,7 @@ func main() { host, hostCatalog, hostSet, + managedGroup, role, scope, session, @@ -190,11 +191,11 @@ func (e *Endpoint) Marshal() (ret []string) { for _, v := range sortedKeys(e.Params) { ret = append(ret, fmt.Sprintf(`%s
  • %s
  • `, indent(10), v), - fmt.Sprintf(`%s
      `, indent(12)), - fmt.Sprintf(`%s
    • `, indent(14)), - fmt.Sprintf(`%s%s`, indent(16), escape(e.Params[v])), - fmt.Sprintf(`%s
    • `, indent(14)), - fmt.Sprintf(`%s
    `, indent(12)), + fmt.Sprintf(`%s
      `, indent(10)), + fmt.Sprintf(`%s
    • `, indent(12)), + fmt.Sprintf(`%s%s`, indent(14), escape(e.Params[v])), + fmt.Sprintf(`%s
    • `, indent(12)), + fmt.Sprintf(`%s
    `, indent(10)), ) } @@ -212,15 +213,17 @@ func (e *Endpoint) Marshal() (ret []string) { fmt.Sprintf(`%s`, indent(10)), ) ret = append(ret, - fmt.Sprintf(`%s
      `, indent(12)), + fmt.Sprintf(`%s
        `, indent(10)), ) for _, x := range v.Examples { ret = append(ret, - fmt.Sprintf(`%s
      • %s
      • `, indent(14), escape(x)), + fmt.Sprintf(`%s
      • `, indent(12)), + fmt.Sprintf(`%s%s`, indent(14), escape(x)), + fmt.Sprintf(`%s
      • `, indent(12)), ) } ret = append(ret, - fmt.Sprintf(`%s
      `, indent(12)), + fmt.Sprintf(`%s
    `, indent(10)), ) } @@ -522,7 +525,7 @@ var hostSet = &Resource{ Actions: clActions("a host set"), }, { - Path: "/targets/", + Path: "/host-sets/", Params: map[string]string{ "ID": "", "Type": "host-set", @@ -559,6 +562,29 @@ var hostSet = &Resource{ }, } +var managedGroup = &Resource{ + Type: "Managed Group", + Scopes: iamScopes, + Endpoints: []*Endpoint{ + { + Path: "/managed-groups", + Params: map[string]string{ + "Type": "managed-group", + }, + Actions: clActions("a managed group"), + }, + { + Path: "/managed-groups/", + Params: map[string]string{ + "ID": "", + "Type": "managed-group", + "Pin": "", + }, + Actions: rudActions("a managed group", true), + }, + }, +} + var role = &Resource{ Type: "Role", Scopes: append(iamScopes, infraScope...), diff --git a/testing/controller/controller.go b/testing/controller/controller.go index 9a4198de2..cdd432d63 100644 --- a/testing/controller/controller.go +++ b/testing/controller/controller.go @@ -22,7 +22,7 @@ func getOpts(opt ...Option) (*controller.TestControllerOpts, error) { return nil, fmt.Errorf("Cannot provide both WithConfigFile and WithConfigText") } var setDbParams bool - if opts.setDefaultAuthMethodId || opts.setDefaultLoginName || opts.setDefaultPassword { + if opts.setDefaultPasswordAuthMethodId || opts.setDefaultOidcAuthMethodId || opts.setDefaultLoginName || opts.setDefaultPassword { setDbParams = true } if opts.setDisableAuthMethodCreation { @@ -39,19 +39,20 @@ func getOpts(opt ...Option) (*controller.TestControllerOpts, error) { } type option struct { - tcOptions *controller.TestControllerOpts - setWithConfigFile bool - setWithConfigText bool - setDisableAuthMethodCreation bool - setDisableDatabaseCreation bool - setDisableDatabaseDestruction bool - setDefaultAuthMethodId bool - setDefaultLoginName bool - setDefaultPassword bool - setRootKms bool - setWorkerAuthKms bool - setRecoveryKms bool - setDatabaseUrl bool + tcOptions *controller.TestControllerOpts + setWithConfigFile bool + setWithConfigText bool + setDisableAuthMethodCreation bool + setDisableDatabaseCreation bool + setDisableDatabaseDestruction bool + setDefaultPasswordAuthMethodId bool + setDefaultOidcAuthMethodId bool + setDefaultLoginName bool + setDefaultPassword bool + setRootKms bool + setWorkerAuthKms bool + setRecoveryKms bool + setDatabaseUrl bool } type Option func(*option) error @@ -119,10 +120,18 @@ func DisableDatabaseDestruction() Option { } } -func WithDefaultAuthMethodId(id string) Option { +func WithDefaultPasswordAuthMethodId(id string) Option { return func(c *option) error { - c.setDefaultAuthMethodId = true - c.tcOptions.DefaultAuthMethodId = id + c.setDefaultPasswordAuthMethodId = true + c.tcOptions.DefaultPasswordAuthMethodId = id + return nil + } +} + +func WithDefaultOidcAuthMethodId(id string) Option { + return func(c *option) error { + c.setDefaultOidcAuthMethodId = true + c.tcOptions.DefaultOidcAuthMethodId = id return nil } } diff --git a/website/content/docs/common-workflows/manage-users-groups.mdx b/website/content/docs/common-workflows/manage-users-groups.mdx index 4785e2d3c..9b7d5a920 100644 --- a/website/content/docs/common-workflows/manage-users-groups.mdx +++ b/website/content/docs/common-workflows/manage-users-groups.mdx @@ -117,7 +117,7 @@ Account information: Auth Method ID: ampw_PbE6nNT72a Created Time: Tue, 29 Sep 2020 08:35:02 PDT Description: My password account - ID: apw_BOn3EcqQfe + ID: acctpw_BOn3EcqQfe Name: my_account Type: password Updated Time: Tue, 29 Sep 2020 08:35:02 PDT @@ -195,7 +195,7 @@ User information: Then associate the user with the account previously created: ```bash -$ boundary users set-accounts -id u_yXhZpt5PX3 -account apw_BOn3EcqQfe +$ boundary users set-accounts -id u_yXhZpt5PX3 -account acctpw_BOn3EcqQfe User information: Created Time: Tue, 29 Sep 2020 08:43:43 PDT @@ -212,7 +212,7 @@ User information: Type: org Accounts: - ID: apw_BOn3EcqQfe + ID: acctpw_BOn3EcqQfe Scope ID: o_1234567890 ``` diff --git a/website/content/docs/concepts/security/permissions.mdx b/website/content/docs/concepts/security/permissions.mdx index d8d866a1e..9af023072 100644 --- a/website/content/docs/concepts/security/permissions.mdx +++ b/website/content/docs/concepts/security/permissions.mdx @@ -1017,7 +1017,7 @@ documentation](https://www.boundaryproject.io/api-docs) for guidance. - /targets/<id> + /host-sets/<id>
      @@ -1112,6 +1112,112 @@ documentation](https://www.boundaryproject.io/api-docs) for guidance.
    + + Managed Group + +
      +
    • Global
    • +
    • Org
    • +
    + + + /managed-groups + + +
      +
    • Type
    • +
        +
      • + managed-group +
      • +
      +
    + + +
      +
    • + create: Create a managed group +
    • +
        +
      • + type=<type>;actions=create +
      • +
      +
    • + list: List managed groups +
    • +
        +
      • + type=<type>;actions=list +
      • +
      +
    + + + + + /managed-groups/<id> + + +
      +
    • ID
    • +
        +
      • + <id> +
      • +
      +
    • Pin
    • +
        +
      • + <auth-method-id> +
      • +
      +
    • Type
    • +
        +
      • + managed-group +
      • +
      +
    + + +
      +
    • + read: Read a managed group +
    • +
        +
      • + id=<id>;actions=read +
      • +
      • + id=<pin>;type=<type>;actions=read +
      • +
      +
    • + update: Update a managed group +
    • +
        +
      • + id=<id>;actions=update +
      • +
      • + id=<pin>;type=<type>;actions=update +
      • +
      +
    • + delete: Delete a managed group +
    • +
        +
      • + id=<id>;actions=delete +
      • +
      • + id=<pin>;type=<type>;actions=delete +
      • +
      +
    + + Role