package v1 import ( "context" "crypto/hmac" "errors" "fmt" "github.com/ogen-go/ogen/ogenerrors" "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" "lincodex/backend/internal/usecase/identity" ) var errCsrfCheckFailed = errors.New("CSRF check failed") type SessionAuthenticator interface { Authenticate(ctx context.Context, rawToken string) (identity.AuthenticatedSession, error) } // SessionSecurity authenticates only the three session operations enabled in // this implementation. All other protected operations remain unavailable until their // handlers are implemented. type SessionSecurity struct { authenticator SessionAuthenticator publicOrigin string } var _ api.SecurityHandler = (*SessionSecurity)(nil) func NewSessionSecurity(authenticator SessionAuthenticator, publicOrigin string) *SessionSecurity { return &SessionSecurity{authenticator: authenticator, publicOrigin: publicOrigin} } func (handler *IdentityHandler) SessionSecurity() *SessionSecurity { if handler == nil || handler.sessions == nil { return NewSessionSecurity(nil, "") } return NewSessionSecurity(handler.sessions, handler.sessionOrigin) } func (security *SessionSecurity) HandleSessionCookie( ctx context.Context, operation api.OperationName, cookie api.SessionCookie, ) (context.Context, error) { if !sessionOperationAllowed(operation) || security == nil || security.authenticator == nil || !httpmiddleware.SessionCookieMatches(ctx, cookie.APIKey) { return ctx, ogenerrors.ErrSkipServerSecurity } authenticated, err := security.authenticator.Authenticate(ctx, cookie.APIKey) if errors.Is(err, identity.ErrUnauthenticated) { return ctx, ogenerrors.ErrSkipServerSecurity } if err != nil { return ctx, fmt.Errorf("SessionSecurity.HandleSessionCookie - authenticate session: %w", err) } return withAuthenticatedSession(ctx, authenticated), nil } func (security *SessionSecurity) HandleSessionCsrf( ctx context.Context, operation api.OperationName, csrf api.SessionCsrf, ) (context.Context, error) { if operation != api.LogoutOperation { return ctx, ogenerrors.ErrSkipServerSecurity } authenticated, ok := sessionFromContext(ctx) if !ok { return ctx, ogenerrors.ErrSkipServerSecurity } origin, hasOrigin := httpmiddleware.RequestOrigin(ctx) if security == nil || !hasOrigin || origin != security.publicOrigin || authenticated.CSRFToken == "" || !hmac.Equal([]byte(authenticated.CSRFToken), []byte(csrf.APIKey)) { return ctx, errCsrfCheckFailed } return ctx, nil } func sessionOperationAllowed(operation api.OperationName) bool { switch operation { case api.GetCurrentSessionOperation, api.GetCurrentAccountOperation, api.LogoutOperation: return true default: return false } }