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

GO-4642: Scoped Auth Tokens #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
2 changes: 1 addition & 1 deletion core/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func (mw *Middleware) AccountEnableLocalNetworkSync(_ context.Context, req *pb.R
func (mw *Middleware) AccountLocalLinkNewChallenge(ctx context.Context, request *pb.RpcAccountLocalLinkNewChallengeRequest) *pb.RpcAccountLocalLinkNewChallengeResponse {
info := getClientInfo(ctx)

challengeId, err := mw.applicationService.LinkLocalStartNewChallenge(&info)
challengeId, err := mw.applicationService.LinkLocalStartNewChallenge(request.Scope, &info)
code := mapErrorCode(err,
errToCode(session.ErrTooManyChallengeRequests, pb.RpcAccountLocalLinkNewChallengeResponseError_TOO_MANY_REQUESTS),
errToCode(application.ErrApplicationIsNotRunning, pb.RpcAccountLocalLinkNewChallengeResponseError_ACCOUNT_IS_NOT_RUNNING),
Expand Down
43 changes: 36 additions & 7 deletions core/api/server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import (
"context"
"fmt"
"net/http"
"strings"

"github.com/anyproto/any-sync/app"
"github.com/didip/tollbooth/v8"
"github.com/didip/tollbooth/v8/limiter"
"github.com/gin-gonic/gin"

"github.com/anyproto/anytype-heart/core/anytype/account"
"github.com/anyproto/anytype-heart/pb"
"github.com/anyproto/anytype-heart/pb/service"
)

// rateLimit is a middleware that limits the number of requests per second.
Expand All @@ -32,15 +35,41 @@ func (s *Server) rateLimit(max float64) gin.HandlerFunc {
}

// ensureAuthenticated is a middleware that ensures the request is authenticated.
func (s *Server) ensureAuthenticated() gin.HandlerFunc {
func (s *Server) ensureAuthenticated(mw service.ClientCommandsServer) gin.HandlerFunc {
return func(c *gin.Context) {
// token := c.GetHeader("Authorization")
// if token == "" {
// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
// return
// }
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing Authorization header"})
return
}

if !strings.HasPrefix(authHeader, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization header format"})
return
}
key := strings.TrimPrefix(authHeader, "Bearer ")

// Validate the key - if the key exists in the KeyToToken map, it is considered valid.
// Otherwise, attempt to create a new session using the key and add it to the map upon successful validation.
s.mu.Lock()
token, exists := s.KeyToToken[key]
s.mu.Unlock()

if !exists {
response := mw.WalletCreateSession(context.Background(), &pb.RpcWalletCreateSessionRequest{Auth: &pb.RpcWalletCreateSessionRequestAuthOfAppKey{AppKey: key}})
if response.Error.Code != pb.RpcWalletCreateSessionResponseError_NULL {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
token = response.Token

s.mu.Lock()
s.KeyToToken[key] = token
s.mu.Unlock()
}

// TODO: Validate the token and retrieve user information; this is mock example
// Add token to request context for downstream services (subscriptions, events, etc.)
c.Set("token", token)
c.Next()
}
}
Expand Down
16 changes: 10 additions & 6 deletions core/api/server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/anyproto/anytype-heart/core/api/services/object"
"github.com/anyproto/anytype-heart/core/api/services/search"
"github.com/anyproto/anytype-heart/core/api/services/space"
"github.com/anyproto/anytype-heart/pb/service"
)

const (
Expand All @@ -23,7 +24,7 @@ const (
)

// NewRouter builds and returns a *gin.Engine with all routes configured.
func (s *Server) NewRouter(a *app.App) *gin.Engine {
func (s *Server) NewRouter(a *app.App, mw service.ClientCommandsServer) *gin.Engine {
router := gin.Default()

paginator := pagination.New(pagination.Config{
Expand All @@ -36,16 +37,19 @@ func (s *Server) NewRouter(a *app.App) *gin.Engine {
// Swagger route
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

// Auth routes (no authentication required)
authGroup := router.Group("/v1/auth")
{
authGroup.POST("/display_code", auth.DisplayCodeHandler(s.authService))
authGroup.POST("/token", auth.TokenHandler(s.authService))
}

// API routes
v1 := router.Group("/v1")
v1.Use(paginator)
v1.Use(s.ensureAuthenticated())
v1.Use(s.ensureAuthenticated(mw))
v1.Use(s.ensureAccountInfo(a))
{
// Auth
v1.POST("/auth/display_code", auth.DisplayCodeHandler(s.authService))
v1.POST("/auth/token", auth.TokenHandler(s.authService))

// Export
v1.POST("/spaces/:space_id/objects/:object_id/export/:format", export.GetObjectExportHandler(s.exportService))

Expand Down
8 changes: 7 additions & 1 deletion core/api/server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package server

import (
"sync"

"github.com/anyproto/any-sync/app"
"github.com/gin-gonic/gin"

Expand All @@ -21,6 +23,9 @@ type Server struct {
objectService *object.ObjectService
spaceService *space.SpaceService
searchService *search.SearchService

mu sync.Mutex
KeyToToken map[string]string // appKey -> token
}

// NewServer constructs a new Server with default config and sets up the routes.
Expand All @@ -33,7 +38,8 @@ func NewServer(a *app.App, mw service.ClientCommandsServer) *Server {

s.objectService = object.NewService(mw, s.spaceService)
s.searchService = search.NewService(mw, s.spaceService, s.objectService)
s.engine = s.NewRouter(a)
s.engine = s.NewRouter(a, mw)
s.KeyToToken = make(map[string]string)

return s
}
Expand Down
4 changes: 1 addition & 3 deletions core/api/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ type apiService struct {
}

func New() Service {
return &apiService{
mw: mwSrv,
}
return &apiService{mw: mwSrv}
}

func (s *apiService) Name() (name string) {
Expand Down
8 changes: 6 additions & 2 deletions core/api/services/auth/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/anyproto/anytype-heart/pb"
"github.com/anyproto/anytype-heart/pb/service"
"github.com/anyproto/anytype-heart/pkg/lib/pb/model"
)

var (
Expand Down Expand Up @@ -34,7 +35,10 @@ func (s *AuthService) NewChallenge(ctx context.Context, appName string) (string,
return "", ErrMissingAppName
}

resp := s.mw.AccountLocalLinkNewChallenge(ctx, &pb.RpcAccountLocalLinkNewChallengeRequest{AppName: appName})
resp := s.mw.AccountLocalLinkNewChallenge(ctx, &pb.RpcAccountLocalLinkNewChallengeRequest{
AppName: appName,
Scope: model.AccountAuth_JsonAPI,
})

if resp.Error.Code != pb.RpcAccountLocalLinkNewChallengeResponseError_NULL {
return "", ErrFailedGenerateChallenge
Expand All @@ -43,7 +47,7 @@ func (s *AuthService) NewChallenge(ctx context.Context, appName string) (string,
return resp.ChallengeId, nil
}

// SolveChallengeForToken calls AccountLocalLinkSolveChallenge and returns the session token + app key, or an error if it fails.
// SolveChallenge calls AccountLocalLinkSolveChallenge and returns the session token + app key, or an error if it fails.
func (s *AuthService) SolveChallenge(ctx context.Context, challengeId string, code string) (sessionToken string, appKey string, err error) {
if challengeId == "" || code == "" {
return "", "", ErrInvalidInput
Expand Down
11 changes: 9 additions & 2 deletions core/api/services/auth/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/anyproto/anytype-heart/pb"
"github.com/anyproto/anytype-heart/pb/service/mock_service"
"github.com/anyproto/anytype-heart/pkg/lib/pb/model"
)

const (
Expand Down Expand Up @@ -40,7 +41,10 @@ func TestAuthService_GenerateNewChallenge(t *testing.T) {
ctx := context.Background()
fx := newFixture(t)

fx.mwMock.On("AccountLocalLinkNewChallenge", mock.Anything, &pb.RpcAccountLocalLinkNewChallengeRequest{AppName: mockedAppName}).
fx.mwMock.On("AccountLocalLinkNewChallenge", mock.Anything, &pb.RpcAccountLocalLinkNewChallengeRequest{
AppName: mockedAppName,
Scope: model.AccountAuth_JsonAPI,
}).
Return(&pb.RpcAccountLocalLinkNewChallengeResponse{
ChallengeId: mockedChallengeId,
Error: &pb.RpcAccountLocalLinkNewChallengeResponseError{Code: pb.RpcAccountLocalLinkNewChallengeResponseError_NULL},
Expand Down Expand Up @@ -73,7 +77,10 @@ func TestAuthService_GenerateNewChallenge(t *testing.T) {
ctx := context.Background()
fx := newFixture(t)

fx.mwMock.On("AccountLocalLinkNewChallenge", mock.Anything, &pb.RpcAccountLocalLinkNewChallengeRequest{AppName: mockedAppName}).
fx.mwMock.On("AccountLocalLinkNewChallenge", mock.Anything, &pb.RpcAccountLocalLinkNewChallengeRequest{
AppName: mockedAppName,
Scope: model.AccountAuth_JsonAPI,
}).
Return(&pb.RpcAccountLocalLinkNewChallengeResponse{
Error: &pb.RpcAccountLocalLinkNewChallengeResponseError{Code: pb.RpcAccountLocalLinkNewChallengeResponseError_UNKNOWN_ERROR},
}).Once()
Expand Down
21 changes: 15 additions & 6 deletions core/application/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/anyproto/anytype-heart/core/session"
walletComp "github.com/anyproto/anytype-heart/core/wallet"
"github.com/anyproto/anytype-heart/pb"
"github.com/anyproto/anytype-heart/pkg/lib/pb/model"
)

func (s *Service) CreateSession(req *pb.RpcWalletCreateSessionRequest) (token string, accountId string, err error) {
Expand All @@ -31,7 +32,8 @@ func (s *Service) CreateSession(req *pb.RpcWalletCreateSessionRequest) (token st
return "", "", err
}
log.Infof("appLink auth %s", appLink.AppName)
token, err := s.sessions.StartSession(s.sessionSigningKey)

token, err := s.sessions.StartSession(s.sessionSigningKey, model.AccountAuthLocalApiScope(appLink.Scope)) // nolint:gosec
if err != nil {
return "", "", err
}
Expand All @@ -46,7 +48,7 @@ func (s *Service) CreateSession(req *pb.RpcWalletCreateSessionRequest) (token st
if s.mnemonic != mnemonic {
return "", "", errors.Join(ErrBadInput, fmt.Errorf("incorrect mnemonic"))
}
token, err = s.sessions.StartSession(s.sessionSigningKey)
token, err = s.sessions.StartSession(s.sessionSigningKey, model.AccountAuth_Full)
if err != nil {
return "", "", err
}
Expand All @@ -61,23 +63,24 @@ func (s *Service) CloseSession(req *pb.RpcWalletCloseSessionRequest) error {
return s.sessions.CloseSession(req.Token)
}

func (s *Service) ValidateSessionToken(token string) error {
func (s *Service) ValidateSessionToken(token string) (model.AccountAuthLocalApiScope, error) {
return s.sessions.ValidateToken(s.sessionSigningKey, token)
}

func (s *Service) LinkLocalStartNewChallenge(clientInfo *pb.EventAccountLinkChallengeClientInfo) (id string, err error) {
func (s *Service) LinkLocalStartNewChallenge(scope model.AccountAuthLocalApiScope, clientInfo *pb.EventAccountLinkChallengeClientInfo) (id string, err error) {
if s.app == nil {
return "", ErrApplicationIsNotRunning
}

id, value, err := s.sessions.StartNewChallenge(clientInfo)
id, value, err := s.sessions.StartNewChallenge(scope, clientInfo)
if err != nil {
return "", err
}
s.eventSender.Broadcast(event.NewEventSingleMessage("", &pb.EventMessageValueOfAccountLinkChallenge{
AccountLinkChallenge: &pb.EventAccountLinkChallenge{
Challenge: value,
ClientInfo: clientInfo,
Scope: scope,
},
}))
return id, nil
Expand All @@ -87,7 +90,7 @@ func (s *Service) LinkLocalSolveChallenge(req *pb.RpcAccountLocalLinkSolveChalle
if s.app == nil {
return "", "", ErrApplicationIsNotRunning
}
clientInfo, token, err := s.sessions.SolveChallenge(req.ChallengeId, req.Answer, s.sessionSigningKey)
clientInfo, token, scope, err := s.sessions.SolveChallenge(req.ChallengeId, req.Answer, s.sessionSigningKey)
if err != nil {
return "", "", err
}
Expand All @@ -96,7 +99,13 @@ func (s *Service) LinkLocalSolveChallenge(req *pb.RpcAccountLocalLinkSolveChalle
AppName: clientInfo.ProcessName,
AppPath: clientInfo.ProcessPath,
CreatedAt: time.Now().Unix(),
Scope: int(scope),
})

s.eventSender.Broadcast(event.NewEventSingleMessage("", &pb.EventMessageValueOfAccountLinkChallengeHide{
AccountLinkChallengeHide: &pb.EventAccountLinkChallengeHide{
Challenge: req.Answer,
},
}))
return
}
26 changes: 24 additions & 2 deletions core/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package core
import (
"context"
"fmt"
"strings"

"github.com/gogo/protobuf/proto"
"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
Expand All @@ -15,8 +16,20 @@ import (
"google.golang.org/grpc/metadata"

"github.com/anyproto/anytype-heart/pb"
"github.com/anyproto/anytype-heart/pkg/lib/pb/model"
)

var limitedScopeMethods = map[string]struct{}{
"ObjectSearch": {},
"ObjectShow": {},
"ObjectCreate": {},
"ObjectCreateFromURL": {},
"BlockPreview": {},
"BlockPaste": {},
"BroadcastPayloadEvent": {},
"AccountSelect": {}, // need to replace with other method to get info
}

func (mw *Middleware) Authorize(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
_, d := descriptor.ForMessage(req.(descriptor.Message))
noAuth := proto.GetBoolExtension(d.GetOptions(), pb.E_NoAuth, false)
Expand All @@ -35,11 +48,20 @@ func (mw *Middleware) Authorize(ctx context.Context, req interface{}, info *grpc
}
tok := v[0]

err = mw.applicationService.ValidateSessionToken(tok)
var scope model.AccountAuthLocalApiScope
scope, err = mw.applicationService.ValidateSessionToken(tok)
if err != nil {
return nil, status.Error(codes.Unauthenticated, err.Error())
}

switch scope {
case model.AccountAuth_Full:
case model.AccountAuth_Limited:
if _, ok := limitedScopeMethods[strings.TrimPrefix(info.FullMethod, "/anytype.ClientCommands/")]; !ok {
return nil, status.Error(codes.PermissionDenied, "method not allowed for limited scope")
}
default:
return nil, status.Error(codes.PermissionDenied, fmt.Sprintf("method not allowed for %s scope", scope.String()))
}
resp, err = handler(ctx, req)
return
}
13 changes: 12 additions & 1 deletion core/grpc_events.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,25 @@ import (
"github.com/anyproto/anytype-heart/core/session"
"github.com/anyproto/anytype-heart/pb"
lib "github.com/anyproto/anytype-heart/pb/service"
"github.com/anyproto/anytype-heart/pkg/lib/pb/model"
)

func (mw *Middleware) ListenSessionEvents(req *pb.StreamRequest, server lib.ClientCommands_ListenSessionEventsServer) {
if err := mw.applicationService.ValidateSessionToken(req.Token); err != nil {
var (
scope model.AccountAuthLocalApiScope
err error
)
if scope, err = mw.applicationService.ValidateSessionToken(req.Token); err != nil {
log.Errorf("ListenSessionEvents: %s", err)
return
}

switch scope {
case model.AccountAuth_Full:
default:
log.Errorf("method not allowed for scope %s", scope.String())
return
}
var srv event.SessionServer
if sender, ok := mw.applicationService.GetEventSender().(*event.GrpcSender); ok {
srv = sender.SetSessionServer(req.Token, server)
Expand Down
Loading
Loading