diff --git a/.gitignore b/.gitignore index 55a4f20..54a9d08 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /dist /uploads +/keys .DS_Store diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 398633e..8bf4a02 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -4,26 +4,18 @@ - @@ -199,7 +190,8 @@ - true diff --git a/go.mod b/go.mod index dd68f8b..7d723ce 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ toolchain go1.23.2 require ( git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782 - git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084 + git.solsynth.dev/hypernet/nexus v0.0.0-20241023163829-f51b22f0e880 github.com/dgraph-io/ristretto v0.1.1 github.com/eko/gocache/lib/v4 v4.1.6 github.com/eko/gocache/store/ristretto/v4 v4.2.2 @@ -22,6 +22,7 @@ require ( github.com/sujit-baniya/flash v0.1.8 golang.org/x/crypto v0.28.0 google.golang.org/grpc v1.67.1 + google.golang.org/protobuf v1.35.1 gorm.io/datatypes v1.2.4 gorm.io/driver/postgres v1.5.4 gorm.io/gorm v1.25.12 @@ -41,6 +42,7 @@ require ( github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/goccy/go-json v0.10.3 // indirect github.com/golang/glog v1.2.2 // indirect github.com/golang/mock v1.6.0 // indirect github.com/golang/protobuf v1.5.4 // indirect @@ -101,7 +103,6 @@ require ( golang.org/x/sys v0.26.0 // indirect golang.org/x/text v0.19.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect - google.golang.org/protobuf v1.35.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect gorm.io/driver/mysql v1.5.7 // indirect diff --git a/go.sum b/go.sum index a63c97c..9a139c1 100644 --- a/go.sum +++ b/go.sum @@ -37,6 +37,8 @@ git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782 h1:HUgt8RmDp git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782/go.mod h1:Q51JPkKnV0UoOT/IRmdBh5CyfSlp7s8BRGzgooYHqkI= git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084 h1:e+G3H8Hrzk3VaYwbppxIXATq8I4u/5K/g4BkqWv2L2Y= git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084/go.mod h1:BKF6Fv/TdfMaxiRHoLjT5AxTsbVBU6VKAZbWxGAMxe4= +git.solsynth.dev/hypernet/nexus v0.0.0-20241023163829-f51b22f0e880 h1:l6IKIMfm0XRHQSrCoTVQTrOoE3NxIhd+h/OodXGSz3g= +git.solsynth.dev/hypernet/nexus v0.0.0-20241023163829-f51b22f0e880/go.mod h1:BKF6Fv/TdfMaxiRHoLjT5AxTsbVBU6VKAZbWxGAMxe4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= @@ -126,6 +128,8 @@ github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9 github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofiber/fiber/v2 v2.36.0/go.mod h1:tgCr+lierLwLoVHHO/jn3Niannv34WRkQETU8wiL9fQ= github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo= diff --git a/pkg/internal/grpc/auth.go b/pkg/internal/grpc/auth.go index 56fff64..ea668e9 100644 --- a/pkg/internal/grpc/auth.go +++ b/pkg/internal/grpc/auth.go @@ -2,6 +2,7 @@ package grpc import ( "context" + "git.solsynth.dev/hypernet/nexus/pkg/nex" "git.solsynth.dev/hydrogen/passport/pkg/internal/database" "git.solsynth.dev/hydrogen/passport/pkg/internal/models" @@ -18,56 +19,32 @@ type authenticateServer struct { } func (v *Server) Authenticate(_ context.Context, in *proto.AuthRequest) (*proto.AuthReply, error) { - ctx, perms, atk, rtk, err := services.Authenticate(in.GetAccessToken(), in.GetRefreshToken(), 0) + ticket, perms, err := services.Authenticate(uint(in.GetSessionId())) if err != nil { return &proto.AuthReply{ IsValid: false, }, nil } else { - user := ctx.Account - rawPerms, _ := jsoniter.Marshal(perms) - + user := ticket.Account userinfo := &proto.UserInfo{ - Id: uint64(user.ID), - Name: user.Name, - Nick: user.Nick, - Email: user.GetPrimaryEmail().Content, - Description: &user.Description, - } - - if user.Avatar != nil { - userinfo.Avatar = *user.GetAvatar() - } - if user.Banner != nil { - userinfo.Banner = *user.GetBanner() - } - - if user.AffiliatedID != nil { - userinfo.AffiliatedTo = lo.ToPtr(uint64(*user.AffiliatedID)) - } - if user.AutomatedID != nil { - userinfo.AutomatedBy = lo.ToPtr(uint64(*user.AutomatedID)) + Id: uint64(user.ID), + Name: user.Name, + PermNodes: nex.EncodeMap(perms), + Metadata: nex.EncodeMap(user), } return &proto.AuthReply{ IsValid: true, Info: &proto.AuthInfo{ - NewAccessToken: &atk, - NewRefreshToken: &rtk, - Permissions: rawPerms, - TicketId: uint64(ctx.Ticket.ID), - Info: userinfo, + SessionId: uint64(ticket.ID), + Info: userinfo, }, }, nil } } func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest) (*proto.CheckPermResponse, error) { - claims, err := services.DecodeJwt(in.GetToken()) - if err != nil { - return nil, err - } - ctx, err := services.GetAuthContext(claims.ID) + ctx, err := services.GetAuthContext(uint(in.GetSessionId())) if err != nil { return nil, err } @@ -78,7 +55,7 @@ func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest var value any _ = jsoniter.Unmarshal(in.GetValue(), &value) - perms := services.FilterPermNodes(heldPerms, ctx.Ticket.Claims) + perms := services.FilterPermNodes(heldPerms, ctx.Claims) valid := services.HasPermNode(perms, in.GetKey(), value) return &proto.CheckPermResponse{ @@ -120,18 +97,10 @@ func (v *Server) ListUserFriends(_ context.Context, in *proto.ListUserRelativeRe } return &proto.ListUserRelativeResponse{ - Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.SimpleUserInfo { - val := &proto.SimpleUserInfo{ + Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.UserInfo { + val := &proto.UserInfo{ Id: uint64(item.AccountID), Name: item.Account.Name, - Nick: item.Account.Nick, - } - - if item.Account.AffiliatedID != nil { - val.AffiliatedTo = lo.ToPtr(uint64(*item.Account.AffiliatedID)) - } - if item.Account.AutomatedID != nil { - val.AutomatedBy = lo.ToPtr(uint64(*item.Account.AutomatedID)) } return val @@ -154,18 +123,10 @@ func (v *Server) ListUserBlocklist(_ context.Context, in *proto.ListUserRelative } return &proto.ListUserRelativeResponse{ - Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.SimpleUserInfo { - val := &proto.SimpleUserInfo{ + Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.UserInfo { + val := &proto.UserInfo{ Id: uint64(item.AccountID), Name: item.Account.Name, - Nick: item.Account.Nick, - } - - if item.Account.AffiliatedID != nil { - val.AffiliatedTo = lo.ToPtr(uint64(*item.Account.AffiliatedID)) - } - if item.Account.AutomatedID != nil { - val.AutomatedBy = lo.ToPtr(uint64(*item.Account.AutomatedID)) } return val diff --git a/pkg/internal/server/api/auth_api.go b/pkg/internal/server/api/auth_api.go index 3e51d2d..642e79b 100644 --- a/pkg/internal/server/api/auth_api.go +++ b/pkg/internal/server/api/auth_api.go @@ -151,8 +151,6 @@ func getToken(c *fiber.Ctx) error { idk = atk } - exts.SetAuthCookies(c, atk, rtk) - return c.JSON(fiber.Map{ "id_token": idk, "access_token": atk, diff --git a/pkg/internal/server/exts/auth.go b/pkg/internal/server/exts/auth.go index 9c2de08..a13a134 100644 --- a/pkg/internal/server/exts/auth.go +++ b/pkg/internal/server/exts/auth.go @@ -2,40 +2,11 @@ package exts import ( "fmt" - "git.solsynth.dev/hydrogen/dealer/pkg/hyper" "git.solsynth.dev/hydrogen/passport/pkg/internal/models" "git.solsynth.dev/hydrogen/passport/pkg/internal/services" "github.com/gofiber/fiber/v2" - "strings" ) -func AuthMiddleware(c *fiber.Ctx) error { - var atk string - if cookie := c.Cookies(hyper.CookieAtk); len(cookie) > 0 { - atk = cookie - } - if header := c.Get(fiber.HeaderAuthorization); len(header) > 0 { - tk := strings.Replace(header, "Bearer", "", 1) - atk = strings.TrimSpace(tk) - } - if tk := c.Query("tk"); len(tk) > 0 { - atk = strings.TrimSpace(tk) - } - - c.Locals("p_token", atk) - - rtk := c.Cookies(hyper.CookieRtk) - if ctx, perms, newAtk, newRtk, err := services.Authenticate(atk, rtk, 0); err == nil { - if newAtk != atk { - SetAuthCookies(c, newAtk, newRtk) - } - c.Locals("permissions", perms) - c.Locals("user", ctx.Account) - } - - return c.Next() -} - func EnsureAuthenticated(c *fiber.Ctx) error { if _, ok := c.Locals("user").(models.Account); !ok { return fiber.NewError(fiber.StatusUnauthorized) diff --git a/pkg/internal/server/server.go b/pkg/internal/server/server.go index 98b9bb2..3009acb 100644 --- a/pkg/internal/server/server.go +++ b/pkg/internal/server/server.go @@ -1,12 +1,11 @@ package server import ( + "git.solsynth.dev/hypernet/nexus/pkg/nex/sec" "strings" "git.solsynth.dev/hydrogen/passport/pkg/internal/server/admin" "git.solsynth.dev/hydrogen/passport/pkg/internal/server/api" - "git.solsynth.dev/hydrogen/passport/pkg/internal/server/exts" - "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/idempotency" @@ -20,6 +19,8 @@ type HTTPApp struct { app *fiber.App } +var IReader *sec.InternalTokenReader + func NewServer() *HTTPApp { app := fiber.New(fiber.Config{ DisableStartupMessage: true, @@ -54,7 +55,7 @@ func NewServer() *HTTPApp { Output: log.Logger, })) - app.Use(exts.AuthMiddleware) + app.Use(sec.ContextMiddleware(IReader)) admin.MapAdminAPIs(app, "/api/admin") api.MapAPIs(app, "/api") diff --git a/pkg/internal/services/accounts.go b/pkg/internal/services/accounts.go index 91ba61c..80748fc 100644 --- a/pkg/internal/services/accounts.go +++ b/pkg/internal/services/accounts.go @@ -312,7 +312,7 @@ func DeleteAccount(id uint) error { return err } else { InvalidAuthCacheWithUser(id) - _, _ = proto.NewServiceDirectoryClient(gap.Nx.GetDealerGrpcConn()).BroadcastDeletion(context.Background(), &proto.DeletionRequest{ + _, _ = proto.NewServiceDirectoryClient(gap.Nx.GetNexusGrpcConn()).BroadcastDeletion(context.Background(), &proto.DeletionRequest{ ResourceType: "account", ResourceId: fmt.Sprintf("%d", id), }) diff --git a/pkg/internal/services/auth.go b/pkg/internal/services/auth.go index ab805a4..7b04d42 100644 --- a/pkg/internal/services/auth.go +++ b/pkg/internal/services/auth.go @@ -3,6 +3,7 @@ package services import ( "context" "fmt" + "git.solsynth.dev/hydrogen/passport/pkg/internal/database" "time" "github.com/eko/gocache/lib/v4/cache" @@ -16,13 +17,13 @@ import ( "github.com/rs/zerolog/log" ) -func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[string]any, err error) { - if ctx, err = GetAuthContext(claims.ID); err == nil { +func Authenticate(sessionId uint) (ctx models.AuthTicket, perms map[string]any, err error) { + if ctx, err = GetAuthContext(sessionId); err == nil { var heldPerms map[string]any rawHeldPerms, _ := jsoniter.Marshal(ctx.Account.PermNodes) _ = jsoniter.Unmarshal(rawHeldPerms, &heldPerms) - perms = FilterPermNodes(heldPerms, ctx.Ticket.Claims) + perms = FilterPermNodes(heldPerms, ctx.Claims) return } @@ -30,46 +31,47 @@ func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[s return } -func GetAuthContextCacheKey(jti string) string { - return fmt.Sprintf("auth-context#%s", jti) +func GetAuthContextCacheKey(sessionId uint) string { + return fmt.Sprintf("auth-context#%d", sessionId) } -func GetAuthContext(jti string) (models.AuthContext, error) { +func GetAuthContext(sessionId uint) (models.AuthTicket, error) { var err error - var ctx models.AuthContext + var ctx models.AuthTicket cacheManager := cache.New[any](localCache.S) marshal := marshaler.New(cacheManager) contx := context.Background() - if val, err := marshal.Get(contx, GetAuthContextCacheKey(jti), new(models.AuthContext)); err == nil { - ctx = *val.(*models.AuthContext) + if val, err := marshal.Get(contx, GetAuthContextCacheKey(sessionId), new(models.AuthTicket)); err == nil { + ctx = *val.(*models.AuthTicket) } else { - ctx, err = CacheAuthContext(jti) - log.Debug().Str("jti", jti).Msg("Created a new auth context cache") + ctx, err = CacheAuthContext(sessionId) + log.Debug().Uint("session", sessionId).Msg("Created a new auth context cache") } return ctx, err } -func CacheAuthContext(jti string) (models.AuthContext, error) { - var ctx models.AuthContext - +func CacheAuthContext(sessionId uint) (models.AuthTicket, error) { // Query data from primary database - ticket, err := GetTicketWithToken(jti) - if err != nil { - return ctx, fmt.Errorf("invalid auth ticket: %v", err) + var ticket models.AuthTicket + if err := database.C. + Where("id = ?", sessionId). + Preload("Account"). + First(&ticket).Error; err != nil { + return ticket, fmt.Errorf("invalid auth ticket: %v", err) } else if err := ticket.IsAvailable(); err != nil { - return ctx, fmt.Errorf("unavailable auth ticket: %v", err) + return ticket, fmt.Errorf("unavailable auth ticket: %v", err) } user, err := GetAccount(ticket.AccountID) if err != nil { - return ctx, fmt.Errorf("invalid account: %v", err) + return ticket, fmt.Errorf("invalid account: %v", err) } groups, err := GetUserAccountGroup(user) if err != nil { - return ctx, fmt.Errorf("unable to get account groups: %v", err) + return ticket, fmt.Errorf("unable to get account groups: %v", err) } for _, group := range groups { @@ -80,33 +82,28 @@ func CacheAuthContext(jti string) (models.AuthContext, error) { } } - ctx = models.AuthContext{ - Ticket: ticket, - Account: user, - } - - // Put the data into cache + // Put the data into the cache cacheManager := cache.New[any](localCache.S) marshal := marshaler.New(cacheManager) - contx := context.Background() + ctx := context.Background() - marshal.Set( - contx, - GetAuthContextCacheKey(jti), + _ = marshal.Set( ctx, + GetAuthContextCacheKey(sessionId), + ticket, store.WithExpiration(3*time.Minute), store.WithTags([]string{"auth-context", fmt.Sprintf("user#%d", user.ID)}), ) - return ctx, nil + return ticket, nil } func InvalidAuthCacheWithUser(userId uint) { cacheManager := cache.New[any](localCache.S) - contx := context.Background() + ctx := context.Background() cacheManager.Invalidate( - contx, + ctx, store.WithInvalidateTags([]string{"auth-context", fmt.Sprintf("user#%d", userId)}), ) } diff --git a/pkg/internal/services/factors.go b/pkg/internal/services/factors.go index b5814ae..ddd1634 100644 --- a/pkg/internal/services/factors.go +++ b/pkg/internal/services/factors.go @@ -88,7 +88,7 @@ func GetFactorCode(factor models.AuthFactor) (bool, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - _, err := proto.NewPostmanClient(gap.Nx.GetDealerGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{ + _, err := proto.NewPostmanClient(gap.Nx.GetNexusGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{ To: user.GetPrimaryEmail().Content, Email: &proto.EmailRequest{ Subject: subject, diff --git a/pkg/internal/services/statuses.go b/pkg/internal/services/statuses.go index c83a680..46d672a 100644 --- a/pkg/internal/services/statuses.go +++ b/pkg/internal/services/statuses.go @@ -60,7 +60,7 @@ func CacheUserStatus(uid uint, status models.Status) { } func GetUserOnline(uid uint) bool { - pc := proto.NewStreamControllerClient(gap.Nx.GetDealerGrpcConn()) + pc := proto.NewStreamControllerClient(gap.Nx.GetNexusGrpcConn()) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() resp, err := pc.CountStreamConnection(ctx, &proto.CountConnectionRequest{ diff --git a/pkg/internal/services/tokens.go b/pkg/internal/services/tokens.go index 783f14f..17dcd7d 100644 --- a/pkg/internal/services/tokens.go +++ b/pkg/internal/services/tokens.go @@ -145,7 +145,7 @@ func NotifyMagicToken(token models.MagicToken) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - _, err := proto.NewPostmanClient(gap.Nx.GetDealerGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{ + _, err := proto.NewPostmanClient(gap.Nx.GetNexusGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{ To: user.GetPrimaryEmail().Content, Email: &proto.EmailRequest{ Subject: subject, diff --git a/pkg/main.go b/pkg/main.go index 810a6da..09e6950 100644 --- a/pkg/main.go +++ b/pkg/main.go @@ -1,6 +1,7 @@ package main import ( + "git.solsynth.dev/hypernet/nexus/pkg/nex/sec" "os" "os/signal" "syscall" @@ -42,6 +43,14 @@ func main() { log.Fatal().Err(err).Msg("An error occurred when connecting to nexus...") } + // Load keypair + if reader, err := sec.NewInternalTokenReader(viper.GetString("security.internal_public_key")); err != nil { + log.Error().Err(err).Msg("An error occurred when reading internal public key for jwt. Authentication related features will be disabled.") + } else { + server.IReader = reader + log.Info().Msg("Internal jwt public key loaded.") + } + // Connect to database if err := database.NewGorm(); err != nil { log.Fatal().Err(err).Msg("An error occurred when connect to database.") diff --git a/settings.toml b/settings.toml index 71ff163..fb11621 100644 --- a/settings.toml +++ b/settings.toml @@ -26,3 +26,4 @@ cookie_domain = "localhost" cookie_samesite = "Lax" access_token_duration = 300 refresh_token_duration = 2592000 +internal_public_key = "keys/internal_public_key.pem"