Change Authentification
Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
import { graphql } from 'react-relay';
|
||||
import { useLazyLoadQuery } from 'react-relay';
|
||||
import type {
|
||||
TrustCenterAccessGraphQuery,
|
||||
TrustCenterAccessGraphQuery$data
|
||||
} from "./__generated__/TrustCenterAccessGraphQuery.graphql";
|
||||
|
||||
export const trustCenterAccessesQuery = graphql`
|
||||
query TrustCenterAccessGraphQuery($trustCenterId: ID!) {
|
||||
@@ -90,6 +94,6 @@ export const deleteTrustCenterAccessMutation = graphql`
|
||||
}
|
||||
`;
|
||||
|
||||
export function useTrustCenterAccesses(trustCenterId: string) {
|
||||
return useLazyLoadQuery(trustCenterAccessesQuery, { trustCenterId });
|
||||
export function useTrustCenterAccesses(trustCenterId: string): TrustCenterAccessGraphQuery$data {
|
||||
return useLazyLoadQuery<TrustCenterAccessGraphQuery>(trustCenterAccessesQuery, { trustCenterId });
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
deleteTrustCenterAccessMutation
|
||||
} from "/hooks/graph/TrustCenterAccessGraph";
|
||||
import { useMutation } from "react-relay";
|
||||
import type { TrustCenterAccessGraphQuery$data } from "/hooks/graph/__generated__/TrustCenterAccessGraphQuery.graphql";
|
||||
|
||||
type ContextType = {
|
||||
organization: {
|
||||
@@ -41,7 +40,7 @@ export default function TrustCenterAccessTab() {
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
const data = useTrustCenterAccesses(organization.trustCenter?.id || "");
|
||||
const trustCenterData = useTrustCenterAccesses(organization.trustCenter?.id || "");
|
||||
|
||||
if (!organization.trustCenter?.id) {
|
||||
return (
|
||||
@@ -63,7 +62,6 @@ export default function TrustCenterAccessTab() {
|
||||
);
|
||||
}
|
||||
|
||||
const trustCenterData = data as TrustCenterAccessGraphQuery$data | null;
|
||||
const accesses: AccessType[] = trustCenterData?.node?.accesses?.edges ?
|
||||
trustCenterData.node.accesses.edges.map(edge => ({
|
||||
id: edge.node.id,
|
||||
@@ -343,13 +341,6 @@ export default function TrustCenterAccessTab() {
|
||||
</DialogContent>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => dialogRef.current?.close()}
|
||||
disabled={isCreating}
|
||||
>
|
||||
{__("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={handleInvite} disabled={isCreating}>
|
||||
{isCreating && <Spinner />}
|
||||
{__("Send Invitation")}
|
||||
|
||||
@@ -103,10 +103,6 @@ func NewService(
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetEncryptionKey() cipher.EncryptionKey {
|
||||
return s.encryptionKey
|
||||
}
|
||||
|
||||
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
||||
tenantService := &TenantService{
|
||||
pg: s.pg,
|
||||
|
||||
@@ -331,10 +331,12 @@ func (s TrustCenterAccessService) sendAccessEmail(ctx context.Context, access *c
|
||||
}
|
||||
|
||||
accessURL := url.URL{
|
||||
Scheme: "https",
|
||||
Host: s.svc.hostname,
|
||||
Path: "/trust/" + trustCenter.Slug + "/access",
|
||||
RawQuery: "token=" + url.QueryEscape(accessToken),
|
||||
Scheme: "https",
|
||||
Host: s.svc.hostname,
|
||||
Path: "/trust/" + trustCenter.Slug + "/access",
|
||||
RawQuery: url.Values{
|
||||
"token": []string{accessToken},
|
||||
}.Encode(),
|
||||
}
|
||||
|
||||
return s.usrmgr.SendTrustCenterAccessEmail(ctx, access.Name, access.Email, organization.Name, accessURL.String())
|
||||
|
||||
@@ -7174,7 +7174,6 @@ type Mutation {
|
||||
input: UpdateTrustCenterInput!
|
||||
): UpdateTrustCenterPayload!
|
||||
|
||||
|
||||
revokeTrustCenterAccess(
|
||||
input: RevokeTrustCenterAccessInput!
|
||||
): RevokeTrustCenterAccessPayload!
|
||||
@@ -7364,8 +7363,6 @@ input UpdateTrustCenterInput {
|
||||
slug: String
|
||||
}
|
||||
|
||||
|
||||
|
||||
input RevokeTrustCenterAccessInput {
|
||||
accessId: ID!
|
||||
}
|
||||
|
||||
59
pkg/server/api/trust/v1/auth/auth.go
Normal file
59
pkg/server/api/trust/v1/auth/auth.go
Normal file
@@ -0,0 +1,59 @@
|
||||
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/getprobo/probo/pkg/coredata"
|
||||
"github.com/getprobo/probo/pkg/gid"
|
||||
"github.com/getprobo/probo/pkg/server/api/trust/v1/types"
|
||||
)
|
||||
|
||||
type TokenAccessData struct {
|
||||
TrustCenterID gid.GID
|
||||
Email string
|
||||
TenantID gid.TenantID
|
||||
Scope string
|
||||
}
|
||||
|
||||
type ContextAccessor interface {
|
||||
UserFromContext(ctx context.Context) *coredata.User
|
||||
TokenAccessFromContext(ctx context.Context) *TokenAccessData
|
||||
}
|
||||
|
||||
func GetCurrentUserRole(ctx context.Context, accessor ContextAccessor) types.Role {
|
||||
user := accessor.UserFromContext(ctx)
|
||||
tokenAccess := accessor.TokenAccessFromContext(ctx)
|
||||
|
||||
if user != nil || tokenAccess != nil {
|
||||
return types.RoleUser
|
||||
}
|
||||
return types.RoleNone
|
||||
}
|
||||
|
||||
func MustBeAuthenticatedDirective(accessor ContextAccessor) func(ctx context.Context, obj interface{}, next graphql.Resolver, role *types.Role) (interface{}, error) {
|
||||
return func(ctx context.Context, obj interface{}, next graphql.Resolver, role *types.Role) (interface{}, error) {
|
||||
currentRole := GetCurrentUserRole(ctx, accessor)
|
||||
|
||||
if role != nil && *role == types.RoleUser && currentRole == types.RoleNone {
|
||||
return nil, fmt.Errorf("access denied: authentication required")
|
||||
}
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,15 +16,12 @@ package trust_v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/getprobo/probo/pkg/crypto/cipher"
|
||||
"github.com/getprobo/probo/pkg/probo"
|
||||
"github.com/getprobo/probo/pkg/securecookie"
|
||||
"github.com/getprobo/probo/pkg/statelesstoken"
|
||||
"github.com/getprobo/probo/pkg/trust"
|
||||
"go.gearno.de/kit/httpserver"
|
||||
@@ -42,7 +39,7 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig, encryptionKey cipher.EncryptionKey) http.HandlerFunc {
|
||||
func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req AuthTokenRequest
|
||||
// Limit request body size to 1KB to prevent DoS attacks
|
||||
@@ -69,43 +66,28 @@ func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig, encryptionKey
|
||||
return
|
||||
}
|
||||
|
||||
tokenData := TrustCenterTokenData{
|
||||
TrustCenterID: accessData.TrustCenterID,
|
||||
Email: accessData.Email,
|
||||
TenantID: accessData.TrustCenterID.TenantID(),
|
||||
Scope: TokenScopeTrustCenterReadOnly,
|
||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||
}
|
||||
|
||||
tokenBytes, err := json.Marshal(tokenData)
|
||||
tokenString, err := statelesstoken.NewToken(
|
||||
authCfg.CookieSecret,
|
||||
probo.TokenTypeTrustCenterAccess,
|
||||
24*time.Hour,
|
||||
*accessData,
|
||||
)
|
||||
if err != nil {
|
||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to serialize token data: %w", err))
|
||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to create token: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
encryptedTokenData, err := cipher.Encrypt(tokenBytes, encryptionKey)
|
||||
if err != nil {
|
||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to encrypt token data: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
encryptedTokenString := base64.StdEncoding.EncodeToString(encryptedTokenData)
|
||||
|
||||
cookieConfig := securecookie.Config{
|
||||
cookie := &http.Cookie{
|
||||
Name: TokenCookieName,
|
||||
Secret: authCfg.CookieSecret,
|
||||
Value: tokenString,
|
||||
Domain: authCfg.CookieDomain,
|
||||
Path: "/",
|
||||
MaxAge: int(24 * time.Hour / time.Second), // 24 hours
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
}
|
||||
|
||||
if err := securecookie.Set(w, cookieConfig, encryptedTokenString); err != nil {
|
||||
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("failed to set cookie: %w", err))
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, cookie)
|
||||
|
||||
httpserver.RenderJSON(w, http.StatusOK, AuthTokenResponse{
|
||||
Success: true,
|
||||
@@ -117,7 +99,7 @@ func authTokenHandler(trustSvc *trust.Service, authCfg AuthConfig, encryptionKey
|
||||
|
||||
func validateTrustCenterAccessToken(ctx context.Context, trustSvc *trust.Service, authCfg AuthConfig, tokenString string) (*probo.TrustCenterAccessData, error) {
|
||||
token, err := statelesstoken.ValidateToken[probo.TrustCenterAccessData](
|
||||
authCfg.CookieSecret,
|
||||
trustSvc.GetTokenSecret(),
|
||||
probo.TokenTypeTrustCenterAccess,
|
||||
tokenString,
|
||||
)
|
||||
@@ -133,18 +115,17 @@ func validateTrustCenterAccessToken(ctx context.Context, trustSvc *trust.Service
|
||||
|
||||
func trustCenterLogoutHandler(authCfg AuthConfig) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
cookieConfig := securecookie.Config{
|
||||
// Clear cookie directly
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: TokenCookieName,
|
||||
Secret: authCfg.CookieSecret,
|
||||
Value: "",
|
||||
Domain: authCfg.CookieDomain,
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
}
|
||||
|
||||
securecookie.Clear(w, cookieConfig)
|
||||
})
|
||||
|
||||
w.Header().Set("Clear-Site-Data", "*")
|
||||
|
||||
|
||||
@@ -78,10 +78,6 @@ func NewService(
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) GetEncryptionKey() cipher.EncryptionKey {
|
||||
return s.encryptionKey
|
||||
}
|
||||
|
||||
func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
||||
tenantService := &TenantService{
|
||||
pg: s.pg,
|
||||
@@ -106,3 +102,7 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
|
||||
|
||||
return tenantService
|
||||
}
|
||||
|
||||
func (s *Service) GetTokenSecret() string {
|
||||
return s.tokenSecret
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user