Auth token pagination (#4113)

* Add pagination support for auth tokens

* change analyze count estimate comment

* adjust queries for efficiency and security

* even more efficient queries
This commit is contained in:
Michael Milton authored and Johan Brandhorst-Satzkorn committed 2024-01-05 07:43:20 -08:00
1 parent 48e8d454a4
commit 6ba3676c37
18 files changed
+2222 -176

No files matched your search

+1 -1
View File
@@ -171,7 +171,7 @@ func (c *Controller) registerGrpcServices(s *grpc.Server) error {
services.RegisterAuthMethodServiceServer(s, authMethods)
}
if _, ok := currentServices[services.AuthTokenService_ServiceDesc.ServiceName]; !ok {
authtoks, err := authtokens.NewService(c.baseContext, c.AuthTokenRepoFn, c.IamRepoFn)
authtoks, err := authtokens.NewService(c.baseContext, c.AuthTokenRepoFn, c.IamRepoFn, c.conf.RawConfig.Controller.MaxPageSize)
if err != nil {
return fmt.Errorf("failed to create auth token handler service: %w", err)
}
@@ -15,12 +15,15 @@ import (
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
"github.com/hashicorp/boundary/internal/errors"
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
"github.com/hashicorp/boundary/internal/listtoken"
"github.com/hashicorp/boundary/internal/pagination"
"github.com/hashicorp/boundary/internal/perms"
"github.com/hashicorp/boundary/internal/requests"
"github.com/hashicorp/boundary/internal/types/action"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/internal/types/scope"
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authtokens"
"github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes"
"google.golang.org/grpc/codes"
)
@@ -51,14 +54,15 @@ func init() {
type Service struct {
pbs.UnsafeAuthTokenServiceServer
repoFn common.AuthTokenRepoFactory
iamRepoFn common.IamRepoFactory
repoFn common.AuthTokenRepoFactory
iamRepoFn common.IamRepoFactory
maxPageSize uint
}
var _ pbs.AuthTokenServiceServer = (*Service)(nil)
// NewService returns a user service which handles user related requests to boundary.
func NewService(ctx context.Context, repo common.AuthTokenRepoFactory, iamRepoFn common.IamRepoFactory) (Service, error) {
func NewService(ctx context.Context, repo common.AuthTokenRepoFactory, iamRepoFn common.IamRepoFactory, maxPageSize uint) (Service, error) {
const op = "authtoken.NewService"
if repo == nil {
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing auth token repository")
@@ -66,14 +70,20 @@ func NewService(ctx context.Context, repo common.AuthTokenRepoFactory, iamRepoFn
if iamRepoFn == nil {
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing iam repository")
}
return Service{repoFn: repo, iamRepoFn: iamRepoFn}, nil
if maxPageSize == 0 {
maxPageSize = uint(globals.DefaultMaxPageSize)
}
return Service{repoFn: repo, iamRepoFn: iamRepoFn, maxPageSize: maxPageSize}, nil
}
// ListAuthTokens implements the interface pbs.AuthTokenServiceServer.
func (s Service) ListAuthTokens(ctx context.Context, req *pbs.ListAuthTokensRequest) (*pbs.ListAuthTokensResponse, error) {
const op = "authtokens.(Service).ListAuthTokens"
if err := validateListRequest(ctx, req); err != nil {
return nil, err
return nil, errors.Wrap(ctx, err, op)
}
authResults := s.authResult(ctx, req.GetScopeId(), action.List)
if authResults.Error != nil {
// If it's forbidden, and it's a recursive request, and they're
@@ -84,69 +94,131 @@ func (s Service) ListAuthTokens(ctx context.Context, req *pbs.ListAuthTokensRequ
req.GetRecursive() &&
authResults.AuthenticationFinished {
} else {
return nil, authResults.Error
return nil, errors.Wrap(ctx, authResults.Error, op)
}
}
scopeIds, scopeInfoMap, err := scopeids.GetListingScopeIds(
ctx, s.iamRepoFn, authResults, req.GetScopeId(), resource.AuthToken, req.GetRecursive())
if err != nil {
return nil, err
return nil, errors.Wrap(ctx, err, op)
}
// If no scopes match, return an empty response
if len(scopeIds) == 0 {
return &pbs.ListAuthTokensResponse{}, nil
}
ul, err := s.listFromRepo(ctx, scopeIds)
if err != nil {
return nil, err
}
if len(ul) == 0 {
return &pbs.ListAuthTokensResponse{}, nil
pageSize := int(s.maxPageSize)
// Use the requested page size only if it is smaller than
// the configured max.
if req.GetPageSize() != 0 && uint(req.GetPageSize()) < s.maxPageSize {
pageSize = int(req.GetPageSize())
}
filter, err := handlers.NewFilter(ctx, req.GetFilter())
if err != nil {
return nil, err
}
finalItems := make([]*pb.AuthToken, 0, len(ul))
res := perms.Resource{
Type: resource.AuthToken,
}
for _, at := range ul {
res.Id = at.GetPublicId()
res.ScopeId = at.GetScopeId()
authorizedActions := authResults.FetchActionSetForId(ctx, at.GetPublicId(), IdActions, auth.WithResource(&res))
if len(authorizedActions) == 0 {
continue
}
if authorizedActions.OnlySelf() && at.GetIamUserId() != authResults.UserId {
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(scopeInfoMap[at.GetScopeId()]))
}
if outputFields.Has(globals.AuthorizedActionsField) {
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions.Strings()))
}
item, err := toProto(ctx, at, outputOpts...)
var filterItemFn func(ctx context.Context, item *authtoken.AuthToken) (bool, error)
switch {
case req.GetFilter() != "":
// Only use a filter if we need to
filter, err := handlers.NewFilter(ctx, req.GetFilter())
if err != nil {
return nil, err
}
if filter.Match(item) {
finalItems = append(finalItems, item)
filterItemFn = func(ctx context.Context, item *authtoken.AuthToken) (bool, error) {
outputOpts, ok := newOutputOpts(ctx, item, scopeInfoMap, authResults)
if !ok {
return false, nil
}
pbItem, err := toProto(ctx, item, outputOpts...)
if err != nil {
return false, err
}
return filter.Match(pbItem), nil
}
default:
filterItemFn = func(ctx context.Context, item *authtoken.AuthToken) (bool, error) {
return true, nil
}
}
return &pbs.ListAuthTokensResponse{Items: finalItems}, nil
grantsHash, err := authResults.GrantsHash(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
repo, err := s.repoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var listResp *pagination.ListResponse[*authtoken.AuthToken]
var sortBy string
if req.GetListToken() == "" {
sortBy = "created_time"
listResp, err = authtoken.List(ctx, grantsHash, pageSize, filterItemFn, repo, scopeIds)
if err != nil {
return nil, err
}
} else {
listToken, err := handlers.ParseListToken(ctx, req.GetListToken(), resource.AuthToken, grantsHash)
if err != nil {
return nil, err
}
switch st := listToken.Subtype.(type) {
case *listtoken.PaginationToken:
sortBy = "created_time"
listResp, err = authtoken.ListPage(ctx, grantsHash, pageSize, filterItemFn, listToken, repo, scopeIds)
if err != nil {
return nil, err
}
case *listtoken.StartRefreshToken:
sortBy = "updated_time"
listResp, err = authtoken.ListRefresh(ctx, grantsHash, pageSize, filterItemFn, listToken, repo, scopeIds)
if err != nil {
return nil, err
}
case *listtoken.RefreshToken:
sortBy = "updated_time"
listResp, err = authtoken.ListRefreshPage(ctx, grantsHash, pageSize, filterItemFn, listToken, repo, scopeIds)
if err != nil {
return nil, err
}
default:
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "unexpected list token subtype: %T", st)
}
}
finalItems := make([]*pb.AuthToken, 0, len(listResp.Items))
for _, item := range listResp.Items {
outputOpts, ok := newOutputOpts(ctx, item, scopeInfoMap, authResults)
if !ok {
continue
}
item, err := toProto(ctx, item, outputOpts...)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
finalItems = append(finalItems, item)
}
respType := "delta"
if listResp.CompleteListing {
respType = "complete"
}
resp := &pbs.ListAuthTokensResponse{
Items: finalItems,
EstItemCount: uint32(listResp.EstimatedItemCount),
RemovedIds: listResp.DeletedIds,
ResponseType: respType,
SortBy: sortBy,
SortDir: "desc",
}
if listResp.ListToken != nil {
resp.ListToken, err = handlers.MarshalListToken(ctx, listResp.ListToken, pbs.ResourceType_RESOURCE_TYPE_AUTH_TOKEN)
if err != nil {
return nil, err
}
}
return resp, nil
}
// GetAuthToken implements the interface pbs.AuthTokenServiceServer.
@@ -266,19 +338,6 @@ func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) {
return rows > 0, nil
}
func (s Service) listFromRepo(ctx context.Context, scopeIds []string) ([]*authtoken.AuthToken, error) {
repo, err := s.repoFn()
_ = repo
if err != nil {
return nil, err
}
ul, err := repo.ListAuthTokens(ctx, scopeIds, authtoken.WithLimit(-1))
if err != nil {
return nil, err
}
return ul, nil
}
func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.VerifyResults {
res := auth.VerifyResults{}
@@ -395,3 +454,30 @@ func validateListRequest(ctx context.Context, req *pbs.ListAuthTokensRequest) er
}
return nil
}
func newOutputOpts(ctx context.Context, item *authtoken.AuthToken, scopeInfoMap map[string]*scopes.ScopeInfo, authResults auth.VerifyResults) ([]handlers.Option, bool) {
res := perms.Resource{
Type: resource.AuthToken,
}
res.Id = item.GetPublicId()
res.ScopeId = item.GetScopeId()
authorizedActions := authResults.FetchActionSetForId(ctx, item.GetPublicId(), IdActions, auth.WithResource(&res))
if len(authorizedActions) == 0 {
return nil, false
}
if authorizedActions.OnlySelf() && item.GetIamUserId() != authResults.UserId {
return nil, false
}
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(scopeInfoMap[item.GetScopeId()]))
}
if outputFields.Has(globals.AuthorizedActionsField) {
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions.Strings()))
}
return outputOpts, true
}
@@ -8,11 +8,13 @@ import (
"errors"
"fmt"
"net/http/httptest"
"slices"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
@@ -34,7 +36,10 @@ import (
"github.com/stretchr/testify/require"
)
var testAuthorizedActions = []string{"no-op", "read", "read:self", "delete", "delete:self"}
var (
fullAuthorizedActions = []string{"no-op", "read", "read:self", "delete", "delete:self"}
selfAuthorizedActions = []string{"read:self", "delete:self"}
)
func TestGetSelf(t *testing.T) {
ctx := context.Background()
@@ -53,7 +58,7 @@ func TestGetSelf(t *testing.T) {
return server.NewRepository(ctx, rw, rw, kms)
}
a, err := authtokens.NewService(ctx, tokenRepoFn, iamRepoFn)
a, err := authtokens.NewService(ctx, tokenRepoFn, iamRepoFn, 1000)
require.NoError(t, err, "Couldn't create new auth token service.")
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
@@ -132,7 +137,7 @@ func TestGet(t *testing.T) {
return authtoken.NewRepository(ctx, rw, rw, kms)
}
s, err := authtokens.NewService(ctx, repoFn, iamRepoFn)
s, err := authtokens.NewService(ctx, repoFn, iamRepoFn, 1000)
require.NoError(t, err, "Couldn't create new auth token service.")
org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
@@ -149,7 +154,7 @@ func TestGet(t *testing.T) {
ApproximateLastUsedTime: at.GetApproximateLastAccessTime().GetTimestamp(),
ExpirationTime: at.GetExpirationTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: org.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
AuthorizedActions: testAuthorizedActions,
AuthorizedActions: fullAuthorizedActions,
}
cases := []struct {
@@ -232,19 +237,22 @@ func TestList_Self(t *testing.T) {
cases := []struct {
name string
requester *authtoken.AuthToken
req *pbs.ListAuthTokensRequest
count int
}{
{
name: "First token sees only self",
req: &pbs.ListAuthTokensRequest{ScopeId: o.GetPublicId()},
requester: at,
},
{
name: "Second token sees only self",
req: &pbs.ListAuthTokensRequest{ScopeId: o.GetPublicId()},
requester: otherAt,
},
}
a, err := authtokens.NewService(testCtx, tokenRepoFn, iamRepoFn)
a, err := authtokens.NewService(testCtx, tokenRepoFn, iamRepoFn, 1000)
require.NoError(t, err)
for _, tc := range cases {
@@ -261,7 +269,7 @@ func TestList_Self(t *testing.T) {
}
ctx := auth.NewVerifierContext(testCtx, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
got, err := a.ListAuthTokens(ctx, &pbs.ListAuthTokensRequest{ScopeId: o.GetPublicId()})
got, err := a.ListAuthTokens(ctx, tc.req)
require.NoError(err)
require.Len(got.Items, 1)
assert.Equal(got.Items[0].GetId(), tc.requester.GetPublicId())
@@ -273,6 +281,8 @@ func TestList_Self(t *testing.T) {
func TestList(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
sqlDB, err := conn.SqlDB(context.Background())
require.NoError(t, err)
rw := db.New(conn)
wrap := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrap)
@@ -287,9 +297,10 @@ func TestList(t *testing.T) {
orgNoTokens, _ := iam.TestScopes(t, iamRepo)
var globalTokens []*pb.AuthToken
var allTokens []*pb.AuthToken
for i := 0; i < 3; i++ {
at := authtoken.TestAuthToken(t, conn, kms, scope.Global.String())
globalTokens = append(globalTokens, &pb.AuthToken{
pbat := &pb.AuthToken{
Id: at.GetPublicId(),
ScopeId: at.GetScopeId(),
UserId: at.GetIamUserId(),
@@ -300,15 +311,17 @@ func TestList(t *testing.T) {
ApproximateLastUsedTime: at.GetApproximateLastAccessTime().GetTimestamp(),
ExpirationTime: at.GetExpirationTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: scope.Global.String(), Type: scope.Global.String(), Name: scope.Global.String(), Description: "Global Scope"},
AuthorizedActions: testAuthorizedActions,
})
AuthorizedActions: fullAuthorizedActions,
}
globalTokens = append(globalTokens, pbat)
allTokens = append(allTokens, pbat)
}
orgWithSomeTokens, _ := iam.TestScopes(t, iamRepo)
var wantSomeTokens []*pb.AuthToken
for i := 0; i < 3; i++ {
at := authtoken.TestAuthToken(t, conn, kms, orgWithSomeTokens.GetPublicId())
wantSomeTokens = append(wantSomeTokens, &pb.AuthToken{
pbat := &pb.AuthToken{
Id: at.GetPublicId(),
ScopeId: at.GetScopeId(),
UserId: at.GetIamUserId(),
@@ -319,15 +332,17 @@ func TestList(t *testing.T) {
ApproximateLastUsedTime: at.GetApproximateLastAccessTime().GetTimestamp(),
ExpirationTime: at.GetExpirationTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: orgWithSomeTokens.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
AuthorizedActions: testAuthorizedActions,
})
AuthorizedActions: fullAuthorizedActions,
}
wantSomeTokens = append(wantSomeTokens, pbat)
allTokens = append(allTokens, pbat)
}
orgWithOtherTokens, _ := iam.TestScopes(t, iamRepo)
var wantOtherTokens []*pb.AuthToken
for i := 0; i < 3; i++ {
at := authtoken.TestAuthToken(t, conn, kms, orgWithOtherTokens.GetPublicId())
wantOtherTokens = append(wantOtherTokens, &pb.AuthToken{
pbat := &pb.AuthToken{
Id: at.GetPublicId(),
ScopeId: at.GetScopeId(),
UserId: at.GetIamUserId(),
@@ -338,12 +353,21 @@ func TestList(t *testing.T) {
ApproximateLastUsedTime: at.GetApproximateLastAccessTime().GetTimestamp(),
ExpirationTime: at.GetExpirationTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: orgWithOtherTokens.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
AuthorizedActions: testAuthorizedActions,
})
AuthorizedActions: fullAuthorizedActions,
}
wantOtherTokens = append(wantOtherTokens, pbat)
allTokens = append(allTokens, pbat)
}
allTokens := append(globalTokens, wantSomeTokens...)
allTokens = append(allTokens, wantOtherTokens...)
// Reverse slices since response is ordered by created_time descending (newest first)
slices.Reverse(globalTokens)
slices.Reverse(wantSomeTokens)
slices.Reverse(wantOtherTokens)
slices.Reverse(allTokens)
// Run analyze to update postgres estimates
_, err = sqlDB.ExecContext(context.Background(), "analyze")
require.NoError(t, err)
cases := []struct {
name string
@@ -354,17 +378,33 @@ func TestList(t *testing.T) {
{
name: "List Some Tokens",
req: &pbs.ListAuthTokensRequest{ScopeId: orgWithSomeTokens.GetPublicId()},
res: &pbs.ListAuthTokensResponse{Items: wantSomeTokens},
res: &pbs.ListAuthTokensResponse{
Items: wantSomeTokens,
EstItemCount: 3,
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
},
},
{
name: "List Other Tokens",
req: &pbs.ListAuthTokensRequest{ScopeId: orgWithOtherTokens.GetPublicId()},
res: &pbs.ListAuthTokensResponse{Items: wantOtherTokens},
res: &pbs.ListAuthTokensResponse{
Items: wantOtherTokens,
EstItemCount: 3,
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
},
},
{
name: "List No Token",
req: &pbs.ListAuthTokensRequest{ScopeId: orgNoTokens.GetPublicId()},
res: &pbs.ListAuthTokensResponse{},
res: &pbs.ListAuthTokensResponse{
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
},
},
// TODO: When an org doesn't exist, we should return a 404 instead of an empty list.
{
@@ -375,7 +415,24 @@ func TestList(t *testing.T) {
{
name: "List Recursively",
req: &pbs.ListAuthTokensRequest{ScopeId: "global", Recursive: true},
res: &pbs.ListAuthTokensResponse{Items: allTokens},
res: &pbs.ListAuthTokensResponse{
Items: allTokens,
EstItemCount: 9,
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
},
},
{
name: "Paginate listing",
req: &pbs.ListAuthTokensRequest{ScopeId: "global", Recursive: true, PageSize: 2},
res: &pbs.ListAuthTokensResponse{
Items: allTokens[:2],
EstItemCount: 9,
ResponseType: "delta",
SortBy: "created_time",
SortDir: "desc",
},
},
{
name: "Filter to Some Tokens",
@@ -383,12 +440,22 @@ func TestList(t *testing.T) {
ScopeId: "global", Recursive: true,
Filter: fmt.Sprintf(`"/item/scope/id"==%q`, orgWithSomeTokens.GetPublicId()),
},
res: &pbs.ListAuthTokensResponse{Items: wantSomeTokens},
res: &pbs.ListAuthTokensResponse{
Items: wantSomeTokens,
EstItemCount: 3,
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
},
},
{
name: "Filter All Tokens",
req: &pbs.ListAuthTokensRequest{ScopeId: orgWithOtherTokens.GetPublicId(), Filter: `"/item/scope/id"=="thisdoesntmatch"`},
res: &pbs.ListAuthTokensResponse{},
res: &pbs.ListAuthTokensResponse{
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
},
},
{
name: "Filter Bad Format",
@@ -398,7 +465,7 @@ func TestList(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, err := authtokens.NewService(context.Background(), repoFn, iamRepoFn)
s, err := authtokens.NewService(context.Background(), repoFn, iamRepoFn, 1000)
assert, require := assert.New(t), require.New(t)
require.NoError(err, "Couldn't create new user service.")
@@ -419,7 +486,8 @@ func TestList(t *testing.T) {
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
), "ListAuthTokens() with scope %q got response %q, wanted %q", tc.req.GetScopeId(), got, tc.res)
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
))
// Now check anon listing
got, gErr = s.ListAuthTokens(auth.DisabledAuthTestContext(iamRepoFn, tc.req.GetScopeId(), auth.WithUserId(globals.AnonymousUserId)), tc.req)
@@ -435,6 +503,274 @@ func TestList(t *testing.T) {
}
}
func authTokenToProto(at *authtoken.AuthToken, scope *scopes.ScopeInfo, authorizedActions []string) *pb.AuthToken {
return &pb.AuthToken{
Id: at.GetPublicId(),
ScopeId: at.GetScopeId(),
UserId: at.GetIamUserId(),
AuthMethodId: at.GetAuthMethodId(),
AccountId: at.GetAuthAccountId(),
CreatedTime: at.GetCreateTime().GetTimestamp(),
UpdatedTime: at.GetUpdateTime().GetTimestamp(),
ApproximateLastUsedTime: at.GetApproximateLastAccessTime().GetTimestamp(),
ExpirationTime: at.GetExpirationTime().GetTimestamp(),
Scope: scope,
AuthorizedActions: authorizedActions,
}
}
func TestListPagination(t *testing.T) {
// Set database read timeout to avoid duplicates in response
oldReadTimeout := globals.RefreshReadLookbackDuration
globals.RefreshReadLookbackDuration = 0
t.Cleanup(func() {
globals.RefreshReadLookbackDuration = oldReadTimeout
})
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
sqlDB, err := conn.SqlDB(ctx)
require.NoError(t, err)
rw := db.New(conn)
wrap := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrap)
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, conn, wrap), nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(ctx, rw, rw, kms)
}
serversRepoFn := func() (*server.Repository, error) {
return server.NewRepository(ctx, rw, rw, kms)
}
iamRepo := iam.TestRepo(t, conn, wrap)
tokenRepo, _ := tokenRepoFn()
orgWithTokens, pwt := iam.TestScopes(t, iamRepo)
authMethod := password.TestAuthMethods(t, conn, orgWithTokens.GetPublicId(), 1)[0]
// auth account is only used to join auth method to user.
// We don't do anything else with the auth account in the test setup.
acct := password.TestAccount(t, conn, authMethod.GetPublicId(), "test_user")
u := iam.TestUser(t, iamRepo, orgWithTokens.GetPublicId(), iam.WithAccountIds(acct.PublicId))
privProjRole := iam.TestRole(t, conn, pwt.GetPublicId())
iam.TestRoleGrant(t, conn, privProjRole.GetPublicId(), "id=*;type=*;actions=*")
iam.TestUserRole(t, conn, privProjRole.GetPublicId(), u.GetPublicId())
var allTokens []*pb.AuthToken
for i := 0; i < 9; i++ {
at, _ := tokenRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
atp := authTokenToProto(at, &scopes.ScopeInfo{Id: orgWithTokens.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, selfAuthorizedActions)
allTokens = append(allTokens, atp)
}
a, err := authtokens.NewService(ctx, tokenRepoFn, iamRepoFn, 1000)
require.NoError(t, err, "Couldn't create new user service.")
masterToken, _ := tokenRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
mtp := authTokenToProto(masterToken, &scopes.ScopeInfo{Id: orgWithTokens.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, selfAuthorizedActions)
allTokens = append(allTokens, mtp)
slices.Reverse(allTokens)
// Run analyze to update postgres estimates
_, err = sqlDB.ExecContext(context.Background(), "analyze")
require.NoError(t, err)
requestInfo := authpb.RequestInfo{
TokenFormat: uint32(auth.AuthTokenTypeBearer),
Token: masterToken.GetToken(),
PublicId: masterToken.GetPublicId(),
}
requestContext := context.WithValue(ctx, requests.ContextRequestInformationKey, &requests.RequestContext{})
ctx = auth.NewVerifierContext(requestContext, iamRepoFn, tokenRepoFn, serversRepoFn, kms, &requestInfo)
// Start paginating, recursively
req := &pbs.ListAuthTokensRequest{
ScopeId: "global",
Recursive: true,
Filter: "",
ListToken: "",
PageSize: 2,
}
got, err := a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 2)
// Compare without comparing the list token
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: allTokens[0:2],
ResponseType: "delta",
SortBy: "created_time",
SortDir: "desc",
RemovedIds: nil,
EstItemCount: 10,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
// Request second page
req.ListToken = got.ListToken
got, err = a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 2)
// Compare without comparing the list token
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: allTokens[2:4],
ResponseType: "delta",
SortBy: "created_time",
SortDir: "desc",
RemovedIds: nil,
EstItemCount: 10,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
// Request rest of results
req.ListToken = got.ListToken
req.PageSize = 10
got, err = a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 6)
// Compare without comparing the list token
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: allTokens[4:],
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
RemovedIds: nil,
EstItemCount: 10,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
// Create two auth tokens in lieu of updating
at1, _ := tokenRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
atp1 := authTokenToProto(at1, &scopes.ScopeInfo{Id: orgWithTokens.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, selfAuthorizedActions)
// Add to the front since it's most recently updated
allTokens = append([]*pb.AuthToken{atp1}, allTokens...)
at2, _ := tokenRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
atp2 := authTokenToProto(at2, &scopes.ScopeInfo{Id: orgWithTokens.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()}, selfAuthorizedActions)
// Add to the front since it's most recently updated
allTokens = append([]*pb.AuthToken{atp2}, allTokens...)
// Delete one of the other auth tokens
_, err = tokenRepo.DeleteAuthToken(ctx, allTokens[len(allTokens)-1].Id)
require.NoError(t, err)
deletedAuthToken := allTokens[len(allTokens)-1]
allTokens = allTokens[:len(allTokens)-1]
// Run analyze to update postgres estimates
_, err = sqlDB.ExecContext(ctx, "analyze")
require.NoError(t, err)
// Request updated results
req.ListToken = got.ListToken
req.PageSize = 1
got, err = a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 1)
// Compare without comparing the list token
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: []*pb.AuthToken{allTokens[0]},
ResponseType: "delta",
SortBy: "updated_time",
SortDir: "desc",
// Should contain the deleted auth token
RemovedIds: []string{deletedAuthToken.Id},
EstItemCount: 11,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
// Get next page
req.ListToken = got.ListToken
got, err = a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 1)
// Compare without comparing the list token
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: []*pb.AuthToken{allTokens[1]},
ResponseType: "complete",
SortBy: "updated_time",
SortDir: "desc",
RemovedIds: nil,
EstItemCount: 11,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
// Request new page with filter requiring looping
// to fill the page.
req.ListToken = ""
req.PageSize = 1
req.Filter = fmt.Sprintf(`"/item/id"==%q or "/item/id"==%q`, allTokens[len(allTokens)-2].Id, allTokens[len(allTokens)-1].Id)
got, err = a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 1)
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: []*pb.AuthToken{allTokens[len(allTokens)-2]},
ResponseType: "delta",
SortBy: "created_time",
SortDir: "desc",
// Should be empty again
RemovedIds: nil,
EstItemCount: 11,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
req.ListToken = got.ListToken
// Get the second page
got, err = a.ListAuthTokens(ctx, req)
require.NoError(t, err)
require.Len(t, got.GetItems(), 1)
assert.Empty(t,
cmp.Diff(
got,
&pbs.ListAuthTokensResponse{
Items: []*pb.AuthToken{allTokens[len(allTokens)-1]},
ResponseType: "complete",
SortBy: "created_time",
SortDir: "desc",
RemovedIds: nil,
EstItemCount: 11,
},
protocmp.Transform(),
protocmp.IgnoreFields(&pbs.ListAuthTokensResponse{}, "list_token"),
),
)
}
func TestDeleteSelf(t *testing.T) {
testCtx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
@@ -454,7 +790,7 @@ func TestDeleteSelf(t *testing.T) {
return server.NewRepository(testCtx, rw, rw, kms)
}
a, err := authtokens.NewService(testCtx, tokenRepoFn, iamRepoFn)
a, err := authtokens.NewService(testCtx, tokenRepoFn, iamRepoFn, 1000)
require.NoError(t, err, "Couldn't create new auth token service.")
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
@@ -544,7 +880,7 @@ func TestDelete(t *testing.T) {
org, _ := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
s, err := authtokens.NewService(ctx, repoFn, iamRepoFn)
s, err := authtokens.NewService(ctx, repoFn, iamRepoFn, 1000)
require.NoError(t, err, "Error when getting new user service.")
cases := []struct {
@@ -609,7 +945,7 @@ func TestDelete_twice(t *testing.T) {
org, _ := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
s, err := authtokens.NewService(ctx, repoFn, iamRepoFn)
s, err := authtokens.NewService(ctx, repoFn, iamRepoFn, 1000)
require.NoError(err, "Error when getting new user service")
req := &pbs.DeleteAuthTokenRequest{
Id: at.GetPublicId(),