Change Authentification
Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
@@ -18,25 +18,23 @@ package trust_v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/99designs/gqlgen/graphql/handler"
|
||||
"github.com/99designs/gqlgen/graphql/handler/extension"
|
||||
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||
"github.com/99designs/gqlgen/graphql/playground"
|
||||
"github.com/getprobo/probo/pkg/coredata"
|
||||
"github.com/getprobo/probo/pkg/crypto/cipher"
|
||||
"github.com/getprobo/probo/pkg/gid"
|
||||
"github.com/getprobo/probo/pkg/probo"
|
||||
"github.com/getprobo/probo/pkg/securecookie"
|
||||
"github.com/getprobo/probo/pkg/server/api/trust/v1/auth"
|
||||
"github.com/getprobo/probo/pkg/server/api/trust/v1/schema"
|
||||
"github.com/getprobo/probo/pkg/server/api/trust/v1/types"
|
||||
"github.com/getprobo/probo/pkg/statelesstoken"
|
||||
"github.com/getprobo/probo/pkg/trust"
|
||||
"github.com/getprobo/probo/pkg/usrmgr"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -58,21 +56,6 @@ type (
|
||||
}
|
||||
|
||||
ctxKey struct{ name string }
|
||||
|
||||
TokenAccessData struct {
|
||||
TrustCenterID gid.GID
|
||||
Email string
|
||||
TenantID gid.TenantID
|
||||
Scope string
|
||||
}
|
||||
|
||||
TrustCenterTokenData struct {
|
||||
TrustCenterID gid.GID `json:"trust_center_id"`
|
||||
Email string `json:"email"`
|
||||
TenantID gid.TenantID `json:"tenant_id"`
|
||||
Scope string `json:"scope"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -97,19 +80,19 @@ func UserFromContext(ctx context.Context) *coredata.User {
|
||||
return user
|
||||
}
|
||||
|
||||
func TokenAccessFromContext(ctx context.Context) *TokenAccessData {
|
||||
tokenAccess, _ := ctx.Value(tokenAccessContextKey).(*TokenAccessData)
|
||||
func TokenAccessFromContext(ctx context.Context) *auth.TokenAccessData {
|
||||
tokenAccess, _ := ctx.Value(tokenAccessContextKey).(*auth.TokenAccessData)
|
||||
return tokenAccess
|
||||
}
|
||||
|
||||
func GetCurrentUserRole(ctx context.Context) types.Role {
|
||||
user := UserFromContext(ctx)
|
||||
tokenAccess := TokenAccessFromContext(ctx)
|
||||
// UserFromContext implements auth.ContextAccessor interface
|
||||
func (r *Resolver) UserFromContext(ctx context.Context) *coredata.User {
|
||||
return UserFromContext(ctx)
|
||||
}
|
||||
|
||||
if user != nil || tokenAccess != nil {
|
||||
return types.RoleUser
|
||||
}
|
||||
return types.RoleNone
|
||||
// TokenAccessFromContext implements auth.ContextAccessor interface
|
||||
func (r *Resolver) TokenAccessFromContext(ctx context.Context) *auth.TokenAccessData {
|
||||
return TokenAccessFromContext(ctx)
|
||||
}
|
||||
|
||||
func NewMux(
|
||||
@@ -120,37 +103,29 @@ func NewMux(
|
||||
) *chi.Mux {
|
||||
r := chi.NewMux()
|
||||
|
||||
encryptionKey := trustSvc.GetEncryptionKey()
|
||||
|
||||
r.Handle("/graphql", graphqlHandler(logger, usrmgrSvc, trustSvc, authCfg, encryptionKey))
|
||||
r.Handle("/graphql", graphqlHandler(logger, usrmgrSvc, trustSvc, authCfg))
|
||||
|
||||
r.Handle("/playground", playground.Handler("GraphQL Playground", "/api/trust/v1/graphql"))
|
||||
|
||||
r.Post("/trust-center-access/authenticate", authTokenHandler(trustSvc, authCfg, encryptionKey))
|
||||
r.Post("/trust-center-access/authenticate", authTokenHandler(trustSvc, authCfg))
|
||||
r.Delete("/trust-center-access/logout", trustCenterLogoutHandler(authCfg))
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func graphqlHandler(logger *log.Logger, usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig, encryptionKey cipher.EncryptionKey) http.HandlerFunc {
|
||||
func graphqlHandler(logger *log.Logger, usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig) http.HandlerFunc {
|
||||
var mb int64 = 1 << 20
|
||||
|
||||
resolver := &Resolver{
|
||||
trustCenterSvc: trustSvc,
|
||||
authCfg: authCfg,
|
||||
}
|
||||
|
||||
c := schema.Config{
|
||||
Resolvers: &Resolver{
|
||||
trustCenterSvc: trustSvc,
|
||||
authCfg: authCfg,
|
||||
},
|
||||
Resolvers: resolver,
|
||||
}
|
||||
|
||||
c.Directives.MustBeAuthenticated = func(ctx context.Context, obj interface{}, next graphql.Resolver, role *types.Role) (interface{}, error) {
|
||||
currentRole := GetCurrentUserRole(ctx)
|
||||
|
||||
if role != nil && *role == types.RoleUser && currentRole == types.RoleNone {
|
||||
return nil, fmt.Errorf("access denied: authentication required")
|
||||
}
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
c.Directives.MustBeAuthenticated = auth.MustBeAuthenticatedDirective(resolver)
|
||||
|
||||
es := schema.NewExecutableSchema(c)
|
||||
|
||||
@@ -175,7 +150,7 @@ func graphqlHandler(logger *log.Logger, usrmgrSvc *usrmgr.Service, trustSvc *tru
|
||||
return errors.New("internal server error")
|
||||
})
|
||||
|
||||
return WithSession(usrmgrSvc, trustSvc, authCfg, encryptionKey, srv.ServeHTTP)
|
||||
return WithSession(usrmgrSvc, trustSvc, authCfg, srv.ServeHTTP)
|
||||
}
|
||||
|
||||
// TrustService returns a trust service scoped to the given tenant
|
||||
@@ -188,90 +163,125 @@ func (r *Resolver) GetTenantService(ctx context.Context, tenantID gid.TenantID)
|
||||
return r.trustCenterSvc.WithTenant(tenantID)
|
||||
}
|
||||
|
||||
func WithSession(usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig, encryptionKey cipher.EncryptionKey, next http.HandlerFunc) http.HandlerFunc {
|
||||
func WithSession(usrmgrSvc *usrmgr.Service, trustSvc *trust.Service, authCfg AuthConfig, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
cookieValue, err := securecookie.Get(r, securecookie.DefaultConfig(
|
||||
authCfg.CookieName,
|
||||
authCfg.CookieSecret,
|
||||
))
|
||||
|
||||
if err == nil {
|
||||
sessionID, err := gid.ParseGID(cookieValue)
|
||||
if err == nil {
|
||||
session, err := usrmgrSvc.GetSession(ctx, sessionID)
|
||||
if err == nil {
|
||||
user, err := usrmgrSvc.GetUserBySession(ctx, sessionID)
|
||||
if err == nil {
|
||||
tenantIDs, err := usrmgrSvc.ListTenantsForUserID(ctx, user.ID)
|
||||
if err == nil {
|
||||
ctx = context.WithValue(ctx, sessionContextKey, session)
|
||||
ctx = context.WithValue(ctx, userContextKey, user)
|
||||
ctx = context.WithValue(ctx, userTenantContextKey, &tenantIDs)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
|
||||
if err := usrmgrSvc.UpdateSession(ctx, session); err != nil {
|
||||
panic(fmt.Errorf("failed to update session: %w", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
securecookie.Clear(w, securecookie.DefaultConfig(
|
||||
authCfg.CookieName,
|
||||
authCfg.CookieSecret,
|
||||
))
|
||||
if authCtx := trySessionAuth(ctx, w, r, usrmgrSvc, authCfg); authCtx != nil {
|
||||
next(w, r.WithContext(authCtx))
|
||||
updateSessionIfNeeded(authCtx, usrmgrSvc)
|
||||
return
|
||||
}
|
||||
|
||||
tokenCookieValue, err := securecookie.Get(r, securecookie.Config{
|
||||
Name: TokenCookieName,
|
||||
Secret: authCfg.CookieSecret,
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
encryptedData, err := base64.StdEncoding.DecodeString(tokenCookieValue)
|
||||
if err == nil {
|
||||
decryptedData, err := cipher.Decrypt(encryptedData, encryptionKey)
|
||||
if err == nil {
|
||||
var tokenData TrustCenterTokenData
|
||||
if err := json.Unmarshal(decryptedData, &tokenData); err == nil {
|
||||
if time.Now().Before(tokenData.ExpiresAt) {
|
||||
tenantSvc := trustSvc.WithTenant(tokenData.TenantID)
|
||||
isActive, err := tenantSvc.TrustCenterAccesses.IsAccessActive(ctx, tokenData.TrustCenterID, tokenData.Email)
|
||||
|
||||
if err == nil && isActive {
|
||||
tokenAccess := &TokenAccessData{
|
||||
TrustCenterID: tokenData.TrustCenterID,
|
||||
Email: tokenData.Email,
|
||||
TenantID: tokenData.TenantID,
|
||||
Scope: tokenData.Scope,
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, tokenAccessContextKey, tokenAccess)
|
||||
next(w, r.WithContext(ctx))
|
||||
return
|
||||
} else {
|
||||
securecookie.Clear(w, securecookie.Config{
|
||||
Name: TokenCookieName,
|
||||
Secret: authCfg.CookieSecret,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
securecookie.Clear(w, securecookie.Config{
|
||||
Name: TokenCookieName,
|
||||
Secret: authCfg.CookieSecret,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if authCtx := tryTokenAuth(ctx, w, r, trustSvc, authCfg); authCtx != nil {
|
||||
next(w, r.WithContext(authCtx))
|
||||
return
|
||||
}
|
||||
|
||||
// Continue without authentication for public access
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func trySessionAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, usrmgrSvc *usrmgr.Service, authCfg AuthConfig) context.Context {
|
||||
cookieValue, err := securecookie.Get(r, securecookie.DefaultConfig(
|
||||
authCfg.CookieName,
|
||||
authCfg.CookieSecret,
|
||||
))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
sessionID, err := gid.ParseGID(cookieValue)
|
||||
if err != nil {
|
||||
clearSessionCookie(w, authCfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
session, err := usrmgrSvc.GetSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
clearSessionCookie(w, authCfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
user, err := usrmgrSvc.GetUserBySession(ctx, sessionID)
|
||||
if err != nil {
|
||||
clearSessionCookie(w, authCfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
tenantIDs, err := usrmgrSvc.ListTenantsForUserID(ctx, user.ID)
|
||||
if err != nil {
|
||||
clearSessionCookie(w, authCfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, sessionContextKey, session)
|
||||
ctx = context.WithValue(ctx, userContextKey, user)
|
||||
ctx = context.WithValue(ctx, userTenantContextKey, &tenantIDs)
|
||||
|
||||
return ctx
|
||||
}
|
||||
|
||||
func tryTokenAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, trustSvc *trust.Service, authCfg AuthConfig) context.Context {
|
||||
cookie, err := r.Cookie(TokenCookieName)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
payload, err := statelesstoken.ValidateToken[probo.TrustCenterAccessData](
|
||||
authCfg.CookieSecret,
|
||||
probo.TokenTypeTrustCenterAccess,
|
||||
cookie.Value,
|
||||
)
|
||||
if err != nil {
|
||||
clearTokenCookie(w, authCfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
tenantID := payload.Data.TrustCenterID.TenantID()
|
||||
tenantSvc := trustSvc.WithTenant(tenantID)
|
||||
isActive, err := tenantSvc.TrustCenterAccesses.IsAccessActive(ctx, payload.Data.TrustCenterID, payload.Data.Email)
|
||||
|
||||
if err != nil || !isActive {
|
||||
clearTokenCookie(w, authCfg)
|
||||
return nil
|
||||
}
|
||||
|
||||
tokenAccess := &auth.TokenAccessData{
|
||||
TrustCenterID: payload.Data.TrustCenterID,
|
||||
Email: payload.Data.Email,
|
||||
TenantID: tenantID,
|
||||
Scope: TokenScopeTrustCenterReadOnly,
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, tokenAccessContextKey, tokenAccess)
|
||||
}
|
||||
|
||||
func clearSessionCookie(w http.ResponseWriter, authCfg AuthConfig) {
|
||||
securecookie.Clear(w, securecookie.DefaultConfig(
|
||||
authCfg.CookieName,
|
||||
authCfg.CookieSecret,
|
||||
))
|
||||
}
|
||||
|
||||
func clearTokenCookie(w http.ResponseWriter, authCfg AuthConfig) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: TokenCookieName,
|
||||
Value: "",
|
||||
Domain: authCfg.CookieDomain,
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
|
||||
func updateSessionIfNeeded(ctx context.Context, usrmgrSvc *usrmgr.Service) {
|
||||
session := SessionFromContext(ctx)
|
||||
if session != nil {
|
||||
if err := usrmgrSvc.UpdateSession(ctx, session); err != nil {
|
||||
panic(fmt.Errorf("failed to update session: %w", err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user