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

Feat: Add a public token type that has only READ access to calling deployments #647

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
20 changes: 19 additions & 1 deletion pkg/api/v1/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,32 @@ func NewTokenGroup(g *echo.Group, backendRepo repository.BackendRepository, conf
return group
}

type CreateTokenRequest struct {
TokenType string `json:"token_type"`
}

func (g *TokenGroup) CreateWorkspaceToken(ctx echo.Context) error {
workspaceId := ctx.Param("workspaceId")

workspace, err := g.backendRepo.GetWorkspaceByExternalId(ctx.Request().Context(), workspaceId)
if err != nil {
return HTTPBadRequest("Invalid workspace ID")
}

token, err := g.backendRepo.CreateToken(ctx.Request().Context(), workspace.Id, types.TokenTypeWorkspace, true)
var req CreateTokenRequest
if err := ctx.Bind(&req); err != nil {
return HTTPBadRequest("Invalid request")
}

if req.TokenType == "" {
req.TokenType = types.TokenTypeWorkspace
}

if req.TokenType != types.TokenTypeWorkspace && req.TokenType != types.TokenTypePublic {
return HTTPBadRequest("Invalid token type")
}

token, err := g.backendRepo.CreateToken(ctx.Request().Context(), workspace.Id, req.TokenType, true)
if err != nil {
return HTTPInternalServerError("Unable to create token")
}
Expand Down
6 changes: 6 additions & 0 deletions pkg/auth/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ func (ai *AuthInterceptor) validateToken(md metadata.MD) (*AuthInfo, bool) {
return nil, false
}

if token.TokenType == types.TokenTypePublic {
// For now disable public tokens
return nil, false
}

return &AuthInfo{
Token: token,
Workspace: workspace,
Expand Down Expand Up @@ -101,6 +106,7 @@ func (ai *AuthInterceptor) Stream() grpc.StreamServerInterceptor {
if !ai.isAuthRequired(info.FullMethod) {
return handler(srv, stream)
}

return status.Errorf(codes.Unauthenticated, "invalid or missing token")
}

Expand Down
70 changes: 70 additions & 0 deletions pkg/auth/grpc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package auth

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
)

func TestGRPCValidateToken(t *testing.T) {
mockDetails := mockBackendWithValidToken()

tests := []struct {
name string
tokenKey string
prepares func()
success bool
}{
{
name: "valid token",
tokenKey: mockDetails.tokenForTest.Key,
prepares: func() {
mockDetails.mockRedis.FlushAll(context.Background())
addTokenRow(mockDetails.mock, *mockDetails.tokenForTest.Workspace, mockDetails.tokenForTest)
},
success: true,
},
{
name: "invalid token",
tokenKey: mockDetails.tokenForTest.Key,
prepares: func() {
mockDetails.mockRedis.FlushAll(context.Background())
},
success: false,
},
{
name: "no token",
tokenKey: "",
prepares: func() {},
success: false,
},
{
name: "workspace public token should fail",
tokenKey: mockDetails.publicTokenForTest.Key,
prepares: func() {
mockDetails.mockRedis.FlushAll(context.Background())
addTokenRow(mockDetails.mock, *mockDetails.publicTokenForTest.Workspace, mockDetails.publicTokenForTest)
},
success: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.prepares()
ai := NewAuthInterceptor(mockDetails.backendRepo, mockDetails.workspaceRepo)

md := map[string][]string{
"authorization": {tt.tokenKey},
}
authInfo, ok := ai.validateToken(md)

assert.Equal(t, tt.success, ok)
if tt.success {
assert.Equal(t, mockDetails.tokenForTest.Key, authInfo.Token.Key)
assert.Equal(t, mockDetails.tokenForTest.Workspace.ExternalId, authInfo.Workspace.ExternalId)
}
})
}
}
3 changes: 2 additions & 1 deletion pkg/auth/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ func WithWorkspaceAuth(next func(ctx echo.Context) error) func(ctx echo.Context)
return echo.NewHTTPError(http.StatusUnauthorized)
}

if cc.AuthInfo.Workspace.ExternalId != workspaceId && cc.AuthInfo.Token.TokenType != types.TokenTypeClusterAdmin {
if (cc.AuthInfo.Workspace.ExternalId != workspaceId && cc.AuthInfo.Token.TokenType != types.TokenTypeClusterAdmin) ||
cc.AuthInfo.Token.TokenType == types.TokenTypePublic {
return echo.NewHTTPError(http.StatusUnauthorized)
}

Expand Down
66 changes: 54 additions & 12 deletions pkg/auth/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ import (
)

type MockDetails struct {
backendRepo repository.BackendRepository
workspaceRepo repository.WorkspaceRepository
mock sqlmock.Sqlmock
tokenForTest types.Token
mockRedis *common.RedisClient
backendRepo repository.BackendRepository
workspaceRepo repository.WorkspaceRepository
mock sqlmock.Sqlmock
tokenForTest types.Token
publicTokenForTest types.Token
mockRedis *common.RedisClient
}

func addTokenRow(
Expand Down Expand Up @@ -67,6 +68,20 @@ func mockBackendWithValidToken() MockDetails {
Workspace: &workspaceForTest,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
TokenType: types.TokenTypeWorkspace,
}

publicTokenForTest := types.Token{
Id: 2,
ExternalId: "public",
Key: "public",
Active: true,
Reusable: true,
WorkspaceId: &workspaceForTest.Id,
Workspace: &workspaceForTest,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
TokenType: types.TokenTypePublic,
}

mockRedis, err := repository.NewRedisClientForTest()
Expand All @@ -76,11 +91,12 @@ func mockBackendWithValidToken() MockDetails {
workspaceRepo := repository.NewWorkspaceRedisRepositoryForTest(mockRedis)

return MockDetails{
backendRepo: backendRepo,
workspaceRepo: workspaceRepo,
mock: mock,
mockRedis: mockRedis,
tokenForTest: tokenForTest,
backendRepo: backendRepo,
workspaceRepo: workspaceRepo,
mock: mock,
mockRedis: mockRedis,
tokenForTest: tokenForTest,
publicTokenForTest: publicTokenForTest,
}
}

Expand Down Expand Up @@ -179,8 +195,6 @@ func TestWithAuth(t *testing.T) {
assert.NotNil(t, cc.AuthInfo.Token)
assert.NotNil(t, cc.AuthInfo.Workspace)
assert.NotNil(t, cc.AuthInfo.Workspace.ExternalId)
assert.Equal(t, cc.AuthInfo.Token.ExternalId, mockDetails.tokenForTest.ExternalId)
assert.Equal(t, cc.AuthInfo.Token.Key, mockDetails.tokenForTest.Key)

return c.String(200, "OK")
}))
Expand Down Expand Up @@ -218,6 +232,15 @@ func TestWithAuth(t *testing.T) {
mockDetails.mockRedis.FlushAll(context.Background())
},
},
{
name: "Test with public token. Should succeed",
tokenKey: mockDetails.publicTokenForTest.Key,
expectedStatus: 200,
prepares: func() {
mockDetails.mockRedis.FlushAll(context.Background())
addTokenRow(mockDetails.mock, *mockDetails.publicTokenForTest.Workspace, mockDetails.publicTokenForTest)
},
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -327,6 +350,16 @@ func TestWithWorkspaceAuth(t *testing.T) {
},
expectedStatus: 401,
},
{
name: "Test with public token",
tokenKey: mockDetails.publicTokenForTest.Key,
workspaceId: mockDetails.publicTokenForTest.Workspace.ExternalId,
prepares: func() {
mockDetails.mockRedis.FlushAll(context.Background())
addTokenRow(mockDetails.mock, *mockDetails.publicTokenForTest.Workspace, mockDetails.publicTokenForTest)
},
expectedStatus: 401,
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -404,6 +437,15 @@ func TestWithClusterAdminAuth(t *testing.T) {
WillReturnError(errors.New("invalid token"))
},
},
{
name: "Test with public token",
tokenKey: mockDetails.publicTokenForTest.Key,
expectedStatus: 401,
prepares: func() {
mockDetails.mockRedis.FlushAll(context.Background())
addTokenRow(mockDetails.mock, *mockDetails.publicTokenForTest.Workspace, mockDetails.publicTokenForTest)
},
},
}

for _, tt := range tests {
Expand Down
4 changes: 3 additions & 1 deletion pkg/gateway/gateway.proto
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,9 @@ message ListTokensResponse {
repeated Token tokens = 3;
}

message CreateTokenRequest {}
message CreateTokenRequest {
string token_type = 1;
}

message CreateTokenResponse {
bool ok = 1;
Expand Down
15 changes: 14 additions & 1 deletion pkg/gateway/services/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,20 @@ func (gws *GatewayService) ListTokens(ctx context.Context, req *pb.ListTokensReq
func (gws *GatewayService) CreateToken(ctx context.Context, req *pb.CreateTokenRequest) (*pb.CreateTokenResponse, error) {
authInfo, _ := auth.AuthInfoFromContext(ctx)

token, err := gws.backendRepo.CreateToken(ctx, authInfo.Workspace.Id, types.TokenTypeWorkspace, true)
tokenType := req.TokenType
if tokenType == "" {
tokenType = types.TokenTypeWorkspace
}

if tokenType != types.TokenTypeWorkspace && tokenType != types.TokenTypePublic {
return &pb.CreateTokenResponse{
Token: &pb.Token{},
Ok: false,
ErrMsg: "Invalid token type.",
}, nil
}

token, err := gws.backendRepo.CreateToken(ctx, authInfo.Workspace.Id, tokenType, true)
if err != nil {
return &pb.CreateTokenResponse{
Token: &pb.Token{},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package backend_postgres_migrations

import (
"context"
"database/sql"
"fmt"

"github.com/pressly/goose/v3"
)

func init() {
goose.AddMigrationContext(upAddPublicTokenType, downAddPublicTokenType)
}

func upAddPublicTokenType(ctx context.Context, tx *sql.Tx) error {
newTokenTypes := []string{"public"}

for _, tokenType := range newTokenTypes {
addEnumSQL := fmt.Sprintf(`
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_type t
JOIN pg_enum e ON t.oid = e.enumtypid
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'public' AND t.typname = 'token_type' AND e.enumlabel = '%s'
) THEN
EXECUTE 'ALTER TYPE token_type ADD VALUE ' || quote_literal('%s');
END IF;
END
$$;`, tokenType, tokenType)

if _, err := tx.Exec(addEnumSQL); err != nil {
return err
}
}

return nil
}

func downAddPublicTokenType(ctx context.Context, tx *sql.Tx) error {
// No need to revert this migration
return nil
}
1 change: 1 addition & 0 deletions pkg/types/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const (
TokenTypeWorkspace string = "workspace"
TokenTypeWorker string = "worker"
TokenTypeMachine string = "machine"
TokenTypePublic string = "public" // TODO: naming could be improved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what should we name it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think TokenTypeReadOnly because its being used as just that. If we decide to have permissions on tokens, then having a "Public" token is redundant with a "Workspace" token. So this feels more like a temporary feature to me until we have something more elaborate.

If we want to get more specific, TokenTypeDeploymentReadOnly. This creates room for other resource types like tasks or volumes, but it could make the auth closure logic more complicated to follow, challenging to add more token types, and difficult to maintain.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about TokenTypeRequestOnly?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or TokenTypeCallAPIOnly

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think those are less clear. Neither "Request" nor "CallAPIOnly" indicate to me that this is a read-only token. In both names, one could still assume they have write permissions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TokenTypeDeploymentReadOnly sounds like they can list deployments as well. I can't think of the perfect name for this.

what about TokenTypeAPIRestricted

)

type Token struct {
Expand Down
Loading
Loading