Add Output Fields support (#1192)
This commit is contained in:
1 parent
1948984ca2
commit
22d5c88a0b
84 files changed
+5688
-2122
No files matched your search
@@ -2,16 +2,23 @@ package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/boundary/api/authmethods"
|
||||
"github.com/hashicorp/boundary/api/authtokens"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller"
|
||||
authmethodsservice "github.com/hashicorp/boundary/internal/servers/controller/handlers/authmethods"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -106,3 +113,182 @@ func TestFetchActionSetForId(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecursiveListingDifferentOutputFields(t *testing.T) {
|
||||
require, assert := require.New(t), assert.New(t)
|
||||
tc := controller.NewTestController(t, nil)
|
||||
defer tc.Shutdown()
|
||||
|
||||
conn := tc.DbConn()
|
||||
client := tc.Client()
|
||||
token := tc.Token()
|
||||
client.SetToken(token.Token)
|
||||
|
||||
// Set some global permissions so we can read the auth method there. Here we
|
||||
// will expect the defaults.
|
||||
globalRole := iam.TestRole(t, conn, scope.Global.String())
|
||||
iam.TestUserRole(t, conn, globalRole.PublicId, token.UserId)
|
||||
iam.TestUserRole(t, conn, globalRole.PublicId, auth.AnonymousUserId)
|
||||
iam.TestRoleGrant(t, conn, globalRole.PublicId, "id=*;type=auth-method;actions=list,no-op")
|
||||
|
||||
// Create some users at the org level, and some role grants for them
|
||||
org, _ := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId), iam.WithSkipAdminRoleCreation(true), iam.WithSkipDefaultRoleCreation(true))
|
||||
orgAm1 := password.TestAuthMethod(t, conn, org.GetPublicId(), password.WithName("orgam1"), password.WithDescription("orgam1"))
|
||||
orgAm2 := password.TestAuthMethod(t, conn, org.GetPublicId(), password.WithName("orgam2"), password.WithDescription("orgam2"))
|
||||
orgRole := iam.TestRole(t, conn, org.GetPublicId())
|
||||
iam.TestUserRole(t, conn, orgRole.PublicId, token.UserId)
|
||||
// The first and second will actually not take effect for output
|
||||
// grantsbecause it's a list and output fields are scoped by action. So we
|
||||
// expect only name and scope_id for the auth methods in the scope, using
|
||||
// two patterns below. However, since you need an action on the resource for
|
||||
// list to return anything, those grants allow us to list the items, while
|
||||
// also verifying that those output fields don't take effect for the wrong
|
||||
// action.
|
||||
iam.TestRoleGrant(t, conn, orgRole.PublicId, fmt.Sprintf("id=%s;actions=read;output_fields=id,version", orgAm1.GetPublicId()))
|
||||
iam.TestRoleGrant(t, conn, orgRole.PublicId, fmt.Sprintf("id=%s;actions=read;output_fields=description", orgAm2.GetPublicId()))
|
||||
iam.TestRoleGrant(t, conn, orgRole.PublicId, "id=*;type=auth-method;output_fields=name")
|
||||
iam.TestRoleGrant(t, conn, orgRole.PublicId, "id=*;type=auth-method;actions=list;output_fields=scope_id")
|
||||
|
||||
amClient := authmethods.NewClient(tc.Client())
|
||||
resp, err := amClient.List(tc.Context(), scope.Global.String(), authmethods.WithRecursive(true))
|
||||
// Basic sanity checks
|
||||
require.NoError(err)
|
||||
require.NotNil(resp)
|
||||
require.NotNil(resp.GetItems())
|
||||
assert.Len(resp.GetItems().([]*authmethods.AuthMethod), 3)
|
||||
items := resp.GetResponse().Map["items"].([]interface{})
|
||||
require.NotNil(items)
|
||||
|
||||
// The default generated roles don't have output field definitions for them,
|
||||
// so we look for "scope" and if it's there we skip. Otherwise, we look for
|
||||
// "version" and if found expect that we will see a global auth method also
|
||||
// containing name and description. Otherwise it's an org role and we expect
|
||||
// to see name and scope_id. At the end we verify we've seen the exact
|
||||
// numbers of each we expect. Note that we expect 3 at global because of the
|
||||
// auto generated one.
|
||||
var globalAms, orgAms int
|
||||
for _, item := range items {
|
||||
m := item.(map[string]interface{})
|
||||
require.NotNil(m)
|
||||
switch m["scope_id"].(string) {
|
||||
case scope.Global.String():
|
||||
// Validate that it contains fields anon shouldn't; we'll check anon
|
||||
// later
|
||||
assert.Contains(m, "created_time")
|
||||
assert.Contains(m, "attributes")
|
||||
globalAms++
|
||||
|
||||
default:
|
||||
assert.Len(m, 2)
|
||||
assert.Contains(m, "name")
|
||||
assert.Contains(m, "scope_id")
|
||||
orgAms++
|
||||
}
|
||||
}
|
||||
assert.Equal(1, globalAms)
|
||||
assert.Equal(2, orgAms)
|
||||
|
||||
// Now act as the anonymous user and ensure that the fields we checked for
|
||||
// before are not available
|
||||
tc.Client().SetToken("")
|
||||
amClient = authmethods.NewClient(tc.Client())
|
||||
resp, err = amClient.List(tc.Context(), scope.Global.String(), authmethods.WithRecursive(true))
|
||||
require.NoError(err)
|
||||
require.NotNil(resp)
|
||||
require.NotNil(resp.GetItems())
|
||||
assert.Len(resp.GetItems().([]*authmethods.AuthMethod), 1)
|
||||
item := resp.GetResponse().Map["items"].([]interface{})[0].(map[string]interface{})
|
||||
assert.NotContains(item, "created_time")
|
||||
assert.NotContains(item, "attributes")
|
||||
}
|
||||
|
||||
func TestSelfReadingDifferentOutputFields(t *testing.T) {
|
||||
tc := controller.NewTestController(t, nil)
|
||||
defer tc.Shutdown()
|
||||
|
||||
conn := tc.DbConn()
|
||||
|
||||
s, err := authmethodsservice.NewService(tc.Kms(),
|
||||
tc.Controller().PasswordAuthRepoFn,
|
||||
tc.Controller().OidcRepoFn,
|
||||
tc.Controller().IamRepoFn,
|
||||
tc.Controller().AuthTokenRepoFn)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create two auth tokens belonging to different users in the org. Each will
|
||||
// have grants below and should be able to read the other token but see more
|
||||
// fields for its own.
|
||||
org, _ := iam.TestScopes(t, tc.IamRepo(), iam.WithSkipAdminRoleCreation(true), iam.WithSkipDefaultRoleCreation(true))
|
||||
am := password.TestAuthMethod(t, conn, org.GetPublicId())
|
||||
acct1 := password.TestAccount(t, conn, am.GetPublicId(), "acct1")
|
||||
acct2 := password.TestAccount(t, conn, am.GetPublicId(), "acct2")
|
||||
user1 := iam.TestUser(t, tc.IamRepo(), org.GetPublicId(), iam.WithAccountIds(acct1.GetPublicId()))
|
||||
user2 := iam.TestUser(t, tc.IamRepo(), org.GetPublicId(), iam.WithAccountIds(acct2.GetPublicId()))
|
||||
at1, err := tc.AuthTokenRepo().CreateAuthToken(tc.Context(), user1, acct1.GetPublicId())
|
||||
require.NoError(t, err)
|
||||
token1, err := s.ConvertInternalAuthTokenToApiAuthToken(tc.Context(), at1)
|
||||
require.NoError(t, err)
|
||||
at2, err := tc.AuthTokenRepo().CreateAuthToken(tc.Context(), user2, acct2.GetPublicId())
|
||||
require.NoError(t, err)
|
||||
token2, err := s.ConvertInternalAuthTokenToApiAuthToken(tc.Context(), at2)
|
||||
require.NoError(t, err)
|
||||
|
||||
orgRole := iam.TestRole(t, conn, org.GetPublicId())
|
||||
iam.TestUserRole(t, conn, orgRole.PublicId, user1.GetPublicId())
|
||||
iam.TestUserRole(t, conn, orgRole.PublicId, user2.GetPublicId())
|
||||
iam.TestRoleGrant(t, conn, orgRole.PublicId, "id=*;type=auth-token;actions=read:self;output_fields=account_id")
|
||||
iam.TestRoleGrant(t, conn, orgRole.PublicId, "id=*;type=auth-token;actions=read;output_fields=id,scope_id")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
token string
|
||||
lookupId string
|
||||
keys []string
|
||||
}{
|
||||
{
|
||||
name: "at1 self",
|
||||
token: token1.GetToken(),
|
||||
lookupId: token1.GetId(),
|
||||
keys: []string{"id", "scope_id", "account_id"},
|
||||
},
|
||||
{
|
||||
name: "at2 self",
|
||||
token: token2.GetToken(),
|
||||
lookupId: token2.GetId(),
|
||||
keys: []string{"id", "scope_id", "account_id"},
|
||||
},
|
||||
{
|
||||
name: "at1 other",
|
||||
token: token1.GetToken(),
|
||||
lookupId: token2.GetId(),
|
||||
keys: []string{"id", "scope_id"},
|
||||
},
|
||||
{
|
||||
name: "at2 other",
|
||||
token: token2.GetToken(),
|
||||
lookupId: token1.GetId(),
|
||||
keys: []string{"id", "scope_id"},
|
||||
},
|
||||
}
|
||||
for _, test := range cases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
client := tc.Client().Clone()
|
||||
client.SetToken(test.token)
|
||||
atClient := authtokens.NewClient(client)
|
||||
resp, err := atClient.Read(tc.Context(), test.lookupId)
|
||||
require.NoError(err)
|
||||
require.NotNil(resp)
|
||||
require.NotNil(resp.GetItem())
|
||||
item := resp.GetResponse().Map
|
||||
require.NotNil(item)
|
||||
keys := make([]string, 0, len(item))
|
||||
for k := range item {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(test.keys)
|
||||
sort.Strings(keys)
|
||||
assert.Equal(test.keys, keys)
|
||||
})
|
||||
}
|
||||
}
|
||||
+36
-3
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/tokens"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"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"
|
||||
@@ -158,6 +159,19 @@ func Verify(ctx context.Context, opt ...Option) (ret VerifyResults) {
|
||||
|
||||
ret.Scope = new(scopes.ScopeInfo)
|
||||
|
||||
// Note: we don't call RequestContextFromCtx here because that performs a
|
||||
// SelfOrDefault. That's useful in the handlers, but here we don't want to
|
||||
// do anything if it's nil. That's mainly useful in tests where
|
||||
// DisableAuthEntirely is set. Later, if we don't have the value set at all,
|
||||
// we have some safeguards to ensure we fail safe (e.g. no output fields at
|
||||
// all). So it provides a good indication as well whether we have set this
|
||||
// where and when needed.
|
||||
var reqInfo *requests.RequestContext
|
||||
reqInfoRaw := ctx.Value(requests.ContextRequestInformationKey)
|
||||
if reqInfoRaw != nil {
|
||||
reqInfo = reqInfoRaw.(*requests.RequestContext)
|
||||
}
|
||||
|
||||
// In tests we often simply disable auth so we can test the service handlers
|
||||
// without fuss
|
||||
if v.requestInfo.DisableAuthEntirely {
|
||||
@@ -203,6 +217,9 @@ func Verify(ctx context.Context, opt ...Option) (ret VerifyResults) {
|
||||
}
|
||||
}
|
||||
ret.UserId = v.requestInfo.userIdOverride
|
||||
if reqInfo != nil {
|
||||
reqInfo.UserId = ret.UserId
|
||||
}
|
||||
ret.Error = nil
|
||||
return
|
||||
}
|
||||
@@ -249,6 +266,11 @@ func Verify(ctx context.Context, opt ...Option) (ret VerifyResults) {
|
||||
}
|
||||
}
|
||||
|
||||
if reqInfo != nil {
|
||||
reqInfo.UserId = ret.UserId
|
||||
reqInfo.OutputFields = authResults.OutputFields
|
||||
}
|
||||
|
||||
ret.Error = nil
|
||||
return
|
||||
}
|
||||
@@ -513,16 +535,16 @@ func (v verifier) performAuthCheck() (aclResults perms.ACLResults, userId string
|
||||
// FetchActionSetForId returns the allowed actions for a given ID using the
|
||||
// current set of ACLs and all other parameters the same (user, etc.)
|
||||
func (r *VerifyResults) FetchActionSetForId(ctx context.Context, id string, availableActions action.ActionSet, opt ...Option) action.ActionSet {
|
||||
return r.fetchActions(ctx, id, resource.Unknown, availableActions, opt...)
|
||||
return r.fetchActions(id, resource.Unknown, availableActions, opt...)
|
||||
}
|
||||
|
||||
// FetchActionSetForType returns the allowed actions for a given collection type
|
||||
// using the current set of ACLs and all other parameters the same (user, etc.)
|
||||
func (r *VerifyResults) FetchActionSetForType(ctx context.Context, typ resource.Type, availableActions action.ActionSet, opt ...Option) action.ActionSet {
|
||||
return r.fetchActions(ctx, "", typ, availableActions, opt...)
|
||||
return r.fetchActions("", typ, availableActions, opt...)
|
||||
}
|
||||
|
||||
func (r *VerifyResults) fetchActions(ctx context.Context, id string, typ resource.Type, availableActions action.ActionSet, opt ...Option) action.ActionSet {
|
||||
func (r *VerifyResults) fetchActions(id string, typ resource.Type, availableActions action.ActionSet, opt ...Option) action.ActionSet {
|
||||
switch {
|
||||
case r.v.requestInfo.DisableAuthEntirely,
|
||||
r.v.requestInfo.TokenFormat == AuthTokenTypeRecoveryKms:
|
||||
@@ -560,6 +582,17 @@ func (r *VerifyResults) fetchActions(ctx context.Context, id string, typ resourc
|
||||
return ret
|
||||
}
|
||||
|
||||
func (r *VerifyResults) FetchOutputFields(res perms.Resource, act action.Type) perms.OutputFieldsMap {
|
||||
switch {
|
||||
case r.v.requestInfo.TokenFormat == AuthTokenTypeRecoveryKms:
|
||||
return perms.OutputFieldsMap{"*": true}
|
||||
case r.v.requestInfo.DisableAuthEntirely:
|
||||
return nil
|
||||
}
|
||||
|
||||
return r.v.acl.Allowed(res, act).OutputFields
|
||||
}
|
||||
|
||||
// GetTokenFromRequest pulls the token from either the Authorization header or
|
||||
// split cookies and parses it. If it cannot be parsed successfully, the issue
|
||||
// is logged and we return blank, so logic will continue as the anonymous user.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/perms"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/boundary/sdk/strutil"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
// CalculateAuthorizedCollectionActions returns authorized actions for the given
|
||||
// inputs.
|
||||
//
|
||||
// NOTE: Eventually we should unit test this, but for now every service handler
|
||||
// is validating the results of this (as it was pulled out of the service
|
||||
// handlers).
|
||||
func CalculateAuthorizedCollectionActions(ctx context.Context,
|
||||
authResults VerifyResults,
|
||||
mapToRange map[resource.Type]action.ActionSet,
|
||||
scopeId, pin string) (map[string]*structpb.ListValue, error) {
|
||||
res := &perms.Resource{
|
||||
ScopeId: scopeId,
|
||||
Pin: pin,
|
||||
}
|
||||
// Range over the defined collections and check permissions against those
|
||||
// collections.
|
||||
var ret map[string]*structpb.ListValue
|
||||
for k, v := range mapToRange {
|
||||
res.Type = k
|
||||
acts := authResults.FetchActionSetForType(ctx, k, v, WithResource(res)).Strings()
|
||||
if len(acts) > 0 {
|
||||
if ret == nil {
|
||||
ret = make(map[string]*structpb.ListValue)
|
||||
}
|
||||
lv, err := structpb.NewList(strutil.StringListToInterfaceList(acts))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret[k.String()+"s"] = lv
|
||||
}
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
@@ -33,9 +33,7 @@ type options struct {
|
||||
}
|
||||
|
||||
func getDefaultOptions() options {
|
||||
return options{
|
||||
withUserId: AnonymousUserId,
|
||||
}
|
||||
return options{}
|
||||
}
|
||||
|
||||
func WithScopeId(id string) Option {
|
||||
|
||||
@@ -13,15 +13,11 @@ import (
|
||||
// Test_GetOpts provides unit tests for GetOpts and all the options
|
||||
func Test_GetOpts(t *testing.T) {
|
||||
t.Parallel()
|
||||
opts := getOpts()
|
||||
assert.Equal(t, options{
|
||||
withUserId: AnonymousUserId,
|
||||
}, opts)
|
||||
|
||||
withKms := new(kms.Kms)
|
||||
res := new(perms.Resource)
|
||||
|
||||
opts = getOpts(
|
||||
opts := getOpts(
|
||||
WithScopeId("foo"),
|
||||
WithPin("bar"),
|
||||
WithId("zip"),
|
||||
|
||||
@@ -11,40 +11,48 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestAuthMethod creates a password auth methods to the provided DB with the
|
||||
// provided scope id. If any errors are encountered during the creation of the
|
||||
// auth methods, the test will fail.
|
||||
func TestAuthMethod(t *testing.T, conn *gorm.DB, scopeId string, opt ...Option) *AuthMethod {
|
||||
t.Helper()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
w := db.New(conn)
|
||||
cat, err := NewAuthMethod(scopeId, opt...)
|
||||
assert.NoError(err)
|
||||
require.NotNil(cat)
|
||||
id, err := newAuthMethodId()
|
||||
assert.NoError(err)
|
||||
require.NotEmpty(id)
|
||||
cat.PublicId = id
|
||||
|
||||
conf := NewArgon2Configuration()
|
||||
require.NotNil(conf)
|
||||
conf.PrivateId, err = newArgon2ConfigurationId()
|
||||
require.NoError(err)
|
||||
conf.PasswordMethodId = cat.PublicId
|
||||
cat.PasswordConfId = conf.PrivateId
|
||||
|
||||
ctx := context.Background()
|
||||
_, err2 := w.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
|
||||
func(_ db.Reader, iw db.Writer) error {
|
||||
require.NoError(iw.Create(ctx, conf))
|
||||
return iw.Create(ctx, cat)
|
||||
},
|
||||
)
|
||||
|
||||
require.NoError(err2)
|
||||
return cat
|
||||
}
|
||||
|
||||
// TestAuthMethods creates count number of password auth methods to the provided DB
|
||||
// with the provided scope id. If any errors are encountered during the creation of
|
||||
// the auth methods, the test will fail.
|
||||
func TestAuthMethods(t *testing.T, conn *gorm.DB, scopeId string, count int) []*AuthMethod {
|
||||
t.Helper()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
w := db.New(conn)
|
||||
var auts []*AuthMethod
|
||||
for i := 0; i < count; i++ {
|
||||
cat, err := NewAuthMethod(scopeId)
|
||||
assert.NoError(err)
|
||||
require.NotNil(cat)
|
||||
id, err := newAuthMethodId()
|
||||
assert.NoError(err)
|
||||
require.NotEmpty(id)
|
||||
cat.PublicId = id
|
||||
|
||||
conf := NewArgon2Configuration()
|
||||
require.NotNil(conf)
|
||||
conf.PrivateId, err = newArgon2ConfigurationId()
|
||||
require.NoError(err)
|
||||
conf.PasswordMethodId = cat.PublicId
|
||||
cat.PasswordConfId = conf.PrivateId
|
||||
|
||||
ctx := context.Background()
|
||||
_, err2 := w.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
|
||||
func(_ db.Reader, iw db.Writer) error {
|
||||
require.NoError(iw.Create(ctx, conf))
|
||||
return iw.Create(ctx, cat)
|
||||
},
|
||||
)
|
||||
|
||||
require.NoError(err2)
|
||||
auts = append(auts, cat)
|
||||
auts = append(auts, TestAuthMethod(t, conn, scopeId))
|
||||
}
|
||||
return auts
|
||||
}
|
||||
|
||||
@@ -3,10 +3,13 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/requests"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
)
|
||||
|
||||
// DisabledAuthTestContext is meant for testing, and uses a context that has auth checking entirely disabled
|
||||
// DisabledAuthTestContext is meant for testing, and uses a context that has
|
||||
// auth checking entirely disabled. Supported options: WithScopeId an WithUserId
|
||||
// are used directly; WithKms is passed through into the verifier context.
|
||||
func DisabledAuthTestContext(iamRepoFn common.IamRepoFactory, scopeId string, opt ...Option) context.Context {
|
||||
reqInfo := RequestInfo{DisableAuthEntirely: true}
|
||||
opts := getOpts(opt...)
|
||||
@@ -15,5 +18,9 @@ func DisabledAuthTestContext(iamRepoFn common.IamRepoFactory, scopeId string, op
|
||||
reqInfo.scopeIdOverride = scopeId
|
||||
}
|
||||
reqInfo.userIdOverride = opts.withUserId
|
||||
return NewVerifierContext(context.Background(), nil, iamRepoFn, nil, nil, opts.withKms, reqInfo)
|
||||
if reqInfo.userIdOverride == "" {
|
||||
reqInfo.userIdOverride = "u_auth"
|
||||
}
|
||||
requestContext := context.WithValue(context.Background(), requests.ContextRequestInformationKey, &requests.RequestContext{})
|
||||
return NewVerifierContext(requestContext, nil, iamRepoFn, nil, nil, opts.withKms, reqInfo)
|
||||
}
|
||||
Reference in new issue
Block a user