Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix auth pagination #1755

Merged
merged 4 commits into from
Apr 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pkg/api/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ func (c *Controller) ListGroups(w http.ResponseWriter, r *http.Request, params L
response := GroupList{
Results: make([]Group, 0, len(groups)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -324,6 +325,7 @@ func (c *Controller) ListGroupMembers(w http.ResponseWriter, r *http.Request, gr
response := UserList{
Results: make([]User, 0, len(users)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -397,6 +399,7 @@ func (c *Controller) ListGroupPolicies(w http.ResponseWriter, r *http.Request, g
response := PolicyList{
Results: make([]Policy, 0, len(policies)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -485,6 +488,7 @@ func (c *Controller) ListPolicies(w http.ResponseWriter, r *http.Request, params
response := PolicyList{
Results: make([]Policy, 0, len(policies)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -632,6 +636,7 @@ func (c *Controller) ListUsers(w http.ResponseWriter, r *http.Request, params Li
response := UserList{
Results: make([]User, 0, len(users)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -742,6 +747,7 @@ func (c *Controller) ListUserCredentials(w http.ResponseWriter, r *http.Request,
response := CredentialsList{
Results: make([]Credentials, 0, len(credentials)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -850,6 +856,7 @@ func (c *Controller) ListUserGroups(w http.ResponseWriter, r *http.Request, user
response := GroupList{
Results: make([]Group, 0, len(groups)),
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down Expand Up @@ -892,6 +899,7 @@ func (c *Controller) ListUserPolicies(w http.ResponseWriter, r *http.Request, us

response := PolicyList{
Pagination: Pagination{
HasMore: paginator.NextPageToken != "",
NextOffset: paginator.NextPageToken,
Results: paginator.Amount,
},
Expand Down
1 change: 1 addition & 0 deletions pkg/auth/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ var (
ErrAlreadyExists = db.ErrAlreadyExists
ErrInvalidArn = errors.New("invalid ARN")
ErrInsufficientPermissions = errors.New("insufficient permissions")
ErrNoField = errors.New("no field tagged in struct")
)
1 change: 0 additions & 1 deletion pkg/auth/page.go

This file was deleted.

37 changes: 32 additions & 5 deletions pkg/auth/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,42 @@ type Service interface {

var psql = sq.StatementBuilder.PlaceholderFormat(sq.Dollar)

// fieldNameByTag returns the name of the field of t that is tagged tag on key, or an empty string.
func fieldByTag(t reflect.Type, key, tag string) string {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if l, ok := field.Tag.Lookup(key); ok {
if l == tag {
return field.Name
}
}
}
return ""
}

const maxPage = 1000

func ListPaged(ctx context.Context, db db.Querier, retType reflect.Type, params *model.PaginationParams, tokenColumnName string, queryBuilder sq.SelectBuilder) (*reflect.Value, *model.Paginator, error) {
ptrType := reflect.PtrTo(retType)
tokenField := fieldByTag(retType, "db", tokenColumnName)
if tokenField == "" {
return nil, nil, fmt.Errorf("[I] no field %s: %w", tokenColumnName, ErrNoField)
}
slice := reflect.MakeSlice(reflect.SliceOf(ptrType), 0, 0)
queryBuilder = queryBuilder.OrderBy(tokenColumnName)
amount := 0
if params != nil {
queryBuilder = queryBuilder.Where(sq.Gt{tokenColumnName: params.After})
if params.Amount >= 0 {
queryBuilder = queryBuilder.Limit(uint64(params.Amount) + 1)
amount = params.Amount + 1
}
}
if amount > maxPage {
amount = maxPage
}
if amount > 0 {
queryBuilder = queryBuilder.Limit(uint64(amount))
}
query, args, err := queryBuilder.ToSql()
if err != nil {
return nil, nil, fmt.Errorf("convert to SQL: %w", err)
Expand All @@ -112,7 +138,8 @@ func ListPaged(ctx context.Context, db db.Querier, retType reflect.Type, params
// we have more pages
slice = slice.Slice(0, params.Amount)
p.Amount = params.Amount
p.NextPageToken = slice.Index(slice.Len() - 1).Elem().FieldByName(tokenColumnName).String()
lastElem := slice.Index(slice.Len() - 1).Elem()
p.NextPageToken = lastElem.FieldByName(tokenField).String()
return &slice, p, nil
}
p.Amount = slice.Len()
Expand Down Expand Up @@ -273,7 +300,7 @@ func (s *DBAuthService) ListUsers(ctx context.Context, params *model.PaginationP

func (s *DBAuthService) ListUserCredentials(ctx context.Context, username string, params *model.PaginationParams) ([]*model.Credential, *model.Paginator, error) {
var credential model.Credential
slice, paginator, err := ListPaged(ctx, s.db, reflect.TypeOf(credential), params, "auth_credentials.access_key_id", psql.Select("auth_credentials.*").
slice, paginator, err := ListPaged(ctx, s.db, reflect.TypeOf(credential), params, "access_key_id", psql.Select("auth_credentials.*").
From("auth_credentials").
Join("auth_users ON (auth_credentials.user_id = auth_users.id)").
Where(sq.Eq{"auth_users.display_name": username}))
Expand Down Expand Up @@ -326,7 +353,7 @@ func (s *DBAuthService) DetachPolicyFromUser(ctx context.Context, policyDisplayN

func (s *DBAuthService) ListUserPolicies(ctx context.Context, username string, params *model.PaginationParams) ([]*model.Policy, *model.Paginator, error) {
var policy model.Policy
slice, paginator, err := ListPaged(ctx, s.db, reflect.TypeOf(policy), params, "auth_policies.display_name", psql.Select("auth_policies.*").
slice, paginator, err := ListPaged(ctx, s.db, reflect.TypeOf(policy), params, "display_name", psql.Select("auth_policies.*").
From("auth_policies").
Join("auth_user_policies ON (auth_policies.id = auth_user_policies.policy_id)").
Join("auth_users ON (auth_user_policies.user_id = auth_users.id)").
Expand Down Expand Up @@ -385,7 +412,7 @@ func (s *DBAuthService) ListEffectivePolicies(ctx context.Context, username stri

func (s *DBAuthService) ListGroupPolicies(ctx context.Context, groupDisplayName string, params *model.PaginationParams) ([]*model.Policy, *model.Paginator, error) {
var policy model.Policy
slice, paginator, err := ListPaged(ctx, s.db, reflect.TypeOf(policy), params, "auth_policies.display_name",
slice, paginator, err := ListPaged(ctx, s.db, reflect.TypeOf(policy), params, "display_name",
psql.Select("auth_policies.*").
From("auth_policies").
Join("auth_group_policies ON (auth_policies.id = auth_group_policies.policy_id)").
Expand Down
10 changes: 6 additions & 4 deletions pkg/auth/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,10 @@ func TestDBAuthService_ListPaged(t *testing.T) {
ctx := context.Background()
const chars = "abcdefghijklmnopqrstuvwxyz"
adb, _ := testutil.GetDB(t, databaseURI)
type row struct{ A string }
if _, err := adb.Exec(ctx, `CREATE TABLE test_pages (a text PRIMARY KEY)`); err != nil {
type row struct {
TheKey string `db:"the_key"`
}
if _, err := adb.Exec(ctx, `CREATE TABLE test_pages (the_key text PRIMARY KEY)`); err != nil {
t.Fatalf("CREATE TABLE test_pages: %s", err)
}
insert := psql.Insert("test_pages")
Expand All @@ -131,7 +133,7 @@ func TestDBAuthService_ListPaged(t *testing.T) {
got := ""
for {
values, paginator, err := auth.ListPaged(ctx,
adb, reflect.TypeOf(row{}), pagination, "A", psql.Select("a").From("test_pages"))
adb, reflect.TypeOf(row{}), pagination, "the_key", psql.Select("the_key").From("test_pages"))
if err != nil {
t.Errorf("ListPaged: %s", err)
break
Expand All @@ -141,7 +143,7 @@ func TestDBAuthService_ListPaged(t *testing.T) {
}
letters := values.Interface().([]*row)
for _, c := range letters {
got = got + c.A
got = got + c.TheKey
}
if paginator.NextPageToken == "" {
if size > 0 && len(letters) > size {
Expand Down