Skip to content

[public-api] Implement list personal access tokens #14834

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

Merged
merged 1 commit into from
Nov 22, 2022
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
96 changes: 96 additions & 0 deletions components/gitpod-db/go/dbtest/personal_access_token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package dbtest

import (
"context"
"testing"
"time"

db "github.com/gitpod-io/gitpod/components/gitpod-db/go"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)

func NewPersonalAccessToken(t *testing.T, record db.PersonalAccessToken) db.PersonalAccessToken {
t.Helper()

now := time.Now().UTC().Round(time.Millisecond)
tokenID := uuid.New()

result := db.PersonalAccessToken{
ID: tokenID,
UserID: uuid.New(),
Hash: "some-secure-hash",
Name: "some-name",
Description: "some-description",
Scopes: []string{"read", "write"},
ExpirationTime: now.Add(5 * time.Hour),
CreatedAt: now,
LastModified: now,
}

if record.ID != uuid.Nil {
result.ID = record.ID
}

if record.UserID != uuid.Nil {
result.UserID = record.UserID
}

if record.Hash != "" {
result.Hash = record.Hash
}

if record.Name != "" {
result.Name = record.Name
}

if record.Description != "" {
result.Description = record.Description
}

if len(record.Scopes) == 0 {
result.Scopes = record.Scopes
}

if !record.ExpirationTime.IsZero() {
result.ExpirationTime = record.ExpirationTime
}

if !record.CreatedAt.IsZero() {
result.CreatedAt = record.CreatedAt
}

if !record.LastModified.IsZero() {
result.LastModified = record.LastModified
}

return result
}

func CreatePersonalAccessTokenRecords(t *testing.T, conn *gorm.DB, entries ...db.PersonalAccessToken) []db.PersonalAccessToken {
t.Helper()

var records []db.PersonalAccessToken
var ids []string
for _, tokenEntry := range entries {
record := NewPersonalAccessToken(t, tokenEntry)
records = append(records, record)
ids = append(ids, record.ID.String())

_, err := db.CreateToken(context.Background(), conn, tokenEntry)
require.NoError(t, err)
}

t.Cleanup(func() {
if len(ids) > 0 {
require.NoError(t, conn.Where(ids).Delete(&db.PersonalAccessToken{}).Error)
}
})

return records
}
36 changes: 36 additions & 0 deletions components/gitpod-db/go/pagination.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package db

import (
"gorm.io/gorm"
)

type Pagination struct {
Page int
PageSize int
}

func Paginate(pagination Pagination) func(*gorm.DB) *gorm.DB {
return func(conn *gorm.DB) *gorm.DB {
page := 1
if pagination.Page > 0 {
page = pagination.Page
}

pageSize := 25
if pagination.PageSize >= 0 {
pageSize = pagination.PageSize
}

offset := (page - 1) * pageSize
return conn.Offset(offset).Limit(pageSize)
}
}

type PaginatedResult[T any] struct {
Results []T
Total int64
}
49 changes: 45 additions & 4 deletions components/gitpod-db/go/personal_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ type PersonalAccessToken struct {
_ bool `gorm:"column:deleted;type:tinyint;default:0;" json:"deleted"`
}

type Scopes []string

// TableName sets the insert table name for this struct type
func (d *PersonalAccessToken) TableName() string {
return "d_b_personal_access_token"
Expand Down Expand Up @@ -77,23 +75,66 @@ func CreateToken(ctx context.Context, conn *gorm.DB, req PersonalAccessToken) (P
LastModified: time.Now().UTC(),
}

db := conn.WithContext(ctx).Create(req)
if db.Error != nil {
tx := conn.WithContext(ctx).Create(req)
if tx.Error != nil {
return PersonalAccessToken{}, fmt.Errorf("Failed to create token for user %s", req.UserID)
}

return token, nil
}

func ListPersonalAccessTokensForUser(ctx context.Context, conn *gorm.DB, userID uuid.UUID, pagination Pagination) (*PaginatedResult[PersonalAccessToken], error) {
if userID == uuid.Nil {
return nil, fmt.Errorf("user ID is a required argument to list personal access tokens for user, got nil")
}

var results []PersonalAccessToken

tx := conn.
WithContext(ctx).
Table((&PersonalAccessToken{}).TableName()).
Where("userId = ?", userID).
Order("createdAt").
Scopes(Paginate(pagination)).
Find(&results)
if tx.Error != nil {
return nil, fmt.Errorf("failed to list personal access tokens for user %s: %w", userID.String(), tx.Error)
}

var count int64
tx = conn.
WithContext(ctx).
Table((&PersonalAccessToken{}).TableName()).
Where("userId = ?", userID).
Count(&count)
if tx.Error != nil {
return nil, fmt.Errorf("failed to count total number of personal access tokens for user %s: %w", userID.String(), tx.Error)
}

return &PaginatedResult[PersonalAccessToken]{
Results: results,
Total: count,
}, nil
}

type Scopes []string

// Scan() and Value() allow having a list of strings as a type for Scopes
func (s *Scopes) Scan(src any) error {
bytes, ok := src.([]byte)
if !ok {
return errors.New("src value cannot cast to []byte")
}

if len(bytes) == 0 {
*s = nil
return nil
}

*s = strings.Split(string(bytes), ",")
return nil
}

func (s Scopes) Value() (driver.Value, error) {
if len(s) == 0 {
return "", nil
Expand Down
83 changes: 83 additions & 0 deletions components/gitpod-db/go/personal_access_token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package db_test

import (
"context"
"strconv"
"testing"
"time"

Expand Down Expand Up @@ -58,3 +59,85 @@ func TestPersonalAccessToken_Create(t *testing.T) {

require.Equal(t, request.ID, result.ID)
}

func TestListPersonalAccessTokensForUser(t *testing.T) {
ctx := context.Background()
conn := dbtest.ConnectForTests(t)
pagination := db.Pagination{
Page: 1,
PageSize: 10,
}

userA := uuid.New()
userB := uuid.New()

now := time.Now().UTC()

dbtest.CreatePersonalAccessTokenRecords(t, conn,
dbtest.NewPersonalAccessToken(t, db.PersonalAccessToken{
UserID: userA,
CreatedAt: now.Add(-1 * time.Minute),
}),
dbtest.NewPersonalAccessToken(t, db.PersonalAccessToken{
UserID: userA,
CreatedAt: now,
}),
dbtest.NewPersonalAccessToken(t, db.PersonalAccessToken{
UserID: userB,
}),
)

tokensForUserA, err := db.ListPersonalAccessTokensForUser(ctx, conn, userA, pagination)
require.NoError(t, err)
require.Len(t, tokensForUserA.Results, 2)

tokensForUserB, err := db.ListPersonalAccessTokensForUser(ctx, conn, userB, pagination)
require.NoError(t, err)
require.Len(t, tokensForUserB.Results, 1)

tokensForUserWithNoData, err := db.ListPersonalAccessTokensForUser(ctx, conn, uuid.New(), pagination)
require.NoError(t, err)
require.Len(t, tokensForUserWithNoData.Results, 0)
}

func TestListPersonalAccessTokensForUser_PaginateThroughResults(t *testing.T) {
ctx := context.Background()
conn := dbtest.ConnectForTests(t).Debug()

userA := uuid.New()

total := 11
var toCreate []db.PersonalAccessToken
for i := 0; i < total; i++ {
toCreate = append(toCreate, dbtest.NewPersonalAccessToken(t, db.PersonalAccessToken{
UserID: userA,
Name: strconv.Itoa(i),
}))
}

dbtest.CreatePersonalAccessTokenRecords(t, conn, toCreate...)

batch1, err := db.ListPersonalAccessTokensForUser(ctx, conn, userA, db.Pagination{
Page: 1,
PageSize: 5,
})
require.NoError(t, err)
require.Len(t, batch1.Results, 5)
require.EqualValues(t, batch1.Total, total)

batch2, err := db.ListPersonalAccessTokensForUser(ctx, conn, userA, db.Pagination{
Page: 2,
PageSize: 5,
})
require.NoError(t, err)
require.Len(t, batch2.Results, 5)
require.EqualValues(t, batch2.Total, total)

batch3, err := db.ListPersonalAccessTokensForUser(ctx, conn, userA, db.Pagination{
Page: 3,
PageSize: 5,
})
require.NoError(t, err)
require.Len(t, batch3.Results, 1)
require.EqualValues(t, batch3.Total, total)
}
1 change: 1 addition & 0 deletions components/public-api-server/BUILD.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ packages:
- components/usage-api/go:lib
- components/gitpod-protocol/go:lib
- components/gitpod-db/go:lib
- components/gitpod-db/go:init-testdb
env:
- CGO_ENABLED=0
- GOOS=linux
Expand Down
38 changes: 38 additions & 0 deletions components/public-api-server/pkg/apiv1/pagination.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package apiv1

import (
db "github.com/gitpod-io/gitpod/components/gitpod-db/go"
v1 "github.com/gitpod-io/gitpod/components/public-api/go/experimental/v1"
)

func validatePagination(p *v1.Pagination) *v1.Pagination {
pagination := &v1.Pagination{
PageSize: 25,
Page: 1,
}

if p == nil {
return pagination
}

if p.Page > 0 {
pagination.Page = p.Page
}
if p.PageSize > 0 && p.PageSize <= 100 {
pagination.PageSize = p.PageSize
}

return pagination
}

func paginationToDB(p *v1.Pagination) db.Pagination {
validated := validatePagination(p)
return db.Pagination{
Page: int(validated.GetPage()),
PageSize: int(validated.GetPageSize()),
}
}
Loading