mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-21 20:38:47 +00:00
feat: ListSessions to relational (#11987)
# Which Problems Are Solved This PR introduces the possibility of using the relational DB when calling the ListSession gRPC endpoint. # How the Problems Are Solved - Implement the Querier interface for ListSession: - Create a `domain` model for the Session object to be able to map the gRPC session into it. - Match the permission filters on ES side to be sure the same sessions are returned - Implement converter methods to go from `gRPC` to `domain` models (both ways) - Fix the session sql relational migration: rework the trigger to update the `expiration` field to perform the update only when the input `lifetime` has a non-zero value. - Link the Querier implementation with the gRPC endpoint - Run the same integration tests against the relational DB, making sure the outcome is the same. ⚠️ Due to missing permission checks, some divergence is expected. Hence, specific code to circumvent the differences has been put in place # Additional Context - Closes #11039
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
objpb "github.com/zitadel/zitadel/pkg/grpc/object"
|
||||
)
|
||||
|
||||
var grpcTimestampOpToDomain = map[objpb.TimestampQueryMethod]database.NumberOperation{
|
||||
objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_EQUALS: database.NumberOperationEqual,
|
||||
objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_GREATER: database.NumberOperationGreaterThan,
|
||||
objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_GREATER_OR_EQUALS: database.NumberOperationGreaterThanOrEqual,
|
||||
objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_LESS: database.NumberOperationLessThan,
|
||||
objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_LESS_OR_EQUALS: database.NumberOperationLessThanOrEqual,
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/internal/api/authz"
|
||||
"github.com/zitadel/zitadel/internal/zerrors"
|
||||
session_grpc "github.com/zitadel/zitadel/pkg/grpc/session/v2"
|
||||
)
|
||||
|
||||
// ListSessionsRequestGRPCToDomain converts a gRPC [session_grpc.ListSessionsRequest] to
|
||||
// the domain [domain.ListSessionsRequest]. It validates the request and returns an error
|
||||
// for any invalid filter values.
|
||||
func ListSessionsRequestGRPCToDomain(ctx context.Context, req *session_grpc.ListSessionsRequest) (*domain.ListSessionsRequest, error) {
|
||||
filters, err := searchQueriesGRPCToDomain(ctx, req.GetQueries())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sortCol := domain.SessionSortColumnUnspecified
|
||||
if req.GetSortingColumn() == session_grpc.SessionFieldName_SESSION_FIELD_NAME_CREATION_DATE {
|
||||
sortCol = domain.SessionSortColumnCreationDate
|
||||
}
|
||||
|
||||
return &domain.ListSessionsRequest{
|
||||
Filters: filters,
|
||||
SortColumn: sortCol,
|
||||
Ascending: req.GetQuery().GetAsc(),
|
||||
Limit: req.GetQuery().GetLimit(),
|
||||
Offset: uint32(req.GetQuery().GetOffset()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func searchQueriesGRPCToDomain(ctx context.Context, queries []*session_grpc.SearchQuery) ([]domain.SessionFilter, error) {
|
||||
if len(queries) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
filters := make([]domain.SessionFilter, 0, len(queries))
|
||||
for _, q := range queries {
|
||||
f, err := searchQueryGRPCToDomain(ctx, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filters = append(filters, f)
|
||||
}
|
||||
return filters, nil
|
||||
}
|
||||
|
||||
func searchQueryGRPCToDomain(ctx context.Context, q *session_grpc.SearchQuery) (domain.SessionFilter, error) {
|
||||
switch typedQuery := q.GetQuery().(type) {
|
||||
case *session_grpc.SearchQuery_IdsQuery:
|
||||
return domain.SessionIDsFilter{IDs: typedQuery.IdsQuery.GetIds()}, nil
|
||||
|
||||
case *session_grpc.SearchQuery_UserIdQuery:
|
||||
return domain.SessionUserIDFilter{UserID: typedQuery.UserIdQuery.GetId()}, nil
|
||||
|
||||
case *session_grpc.SearchQuery_CreationDateQuery:
|
||||
return domain.SessionCreationDateFilter{
|
||||
Op: grpcTimestampOpToDomain[typedQuery.CreationDateQuery.GetMethod()],
|
||||
Date: typedQuery.CreationDateQuery.GetCreationDate().AsTime(),
|
||||
}, nil
|
||||
|
||||
case *session_grpc.SearchQuery_CreatorQuery:
|
||||
id := authz.GetCtxData(ctx).UserID
|
||||
if typedQuery.CreatorQuery != nil && typedQuery.CreatorQuery.Id != nil {
|
||||
if typedQuery.CreatorQuery.GetId() == "" {
|
||||
return nil, zerrors.ThrowInvalidArgument(nil, "DOM-x8n24uh", "List.Query.Invalid")
|
||||
}
|
||||
id = typedQuery.CreatorQuery.GetId()
|
||||
}
|
||||
return domain.SessionCreatorFilter{ID: id}, nil
|
||||
|
||||
case *session_grpc.SearchQuery_UserAgentQuery:
|
||||
fp := authz.GetCtxData(ctx).AgentID
|
||||
if typedQuery.UserAgentQuery != nil && typedQuery.UserAgentQuery.FingerprintId != nil {
|
||||
if typedQuery.UserAgentQuery.GetFingerprintId() == "" {
|
||||
return nil, zerrors.ThrowInvalidArgument(nil, "DOM-x8n23uh", "List.Query.Invalid")
|
||||
}
|
||||
fp = typedQuery.UserAgentQuery.GetFingerprintId()
|
||||
}
|
||||
return domain.SessionUserAgentFilter{FingerprintID: fp}, nil
|
||||
|
||||
case *session_grpc.SearchQuery_ExpirationDateQuery:
|
||||
return domain.SessionExpirationDateFilter{
|
||||
Op: grpcTimestampOpToDomain[typedQuery.ExpirationDateQuery.GetMethod()],
|
||||
Date: typedQuery.ExpirationDateQuery.GetExpirationDate().AsTime(),
|
||||
}, nil
|
||||
|
||||
default:
|
||||
return nil, zerrors.ThrowInvalidArgumentf(nil, "CONV-Cz5s3t", "session search query %T not implemented", typedQuery)
|
||||
}
|
||||
}
|
||||
|
||||
// DomainSessionListToGRPCResponse converts a slice of domain sessions to gRPC response sessions.
|
||||
func DomainSessionListToGRPCResponse(sessions []*domain.Session) []*session_grpc.Session {
|
||||
out := make([]*session_grpc.Session, len(sessions))
|
||||
for i, s := range sessions {
|
||||
out[i] = DomainSessionToGRPCResponse(s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DomainSessionToGRPCResponse converts a single domain session to its gRPC representation.
|
||||
func DomainSessionToGRPCResponse(session *domain.Session) *session_grpc.Session {
|
||||
pb := &session_grpc.Session{
|
||||
Id: session.ID,
|
||||
CreationDate: timestamppb.New(session.CreatedAt),
|
||||
ChangeDate: timestamppb.New(session.UpdatedAt),
|
||||
Factors: domainFactorsToGRPC(session),
|
||||
UserAgent: domainUserAgentToGRPC(session.UserAgent),
|
||||
}
|
||||
|
||||
if len(session.Metadata) > 0 {
|
||||
pb.Metadata = make(map[string][]byte, len(session.Metadata))
|
||||
for _, m := range session.Metadata {
|
||||
pb.Metadata[m.Key] = m.Value
|
||||
}
|
||||
}
|
||||
|
||||
if !session.Expiration.IsZero() {
|
||||
pb.ExpirationDate = timestamppb.New(session.Expiration)
|
||||
}
|
||||
|
||||
return pb
|
||||
}
|
||||
|
||||
func domainFactorsToGRPC(session *domain.Session) *session_grpc.Factors {
|
||||
userFactor := session.Factors.GetUserFactor()
|
||||
if userFactor == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
pb := &session_grpc.Factors{
|
||||
User: &session_grpc.UserFactor{
|
||||
VerifiedAt: timestamppb.New(userFactor.LastVerifiedAt),
|
||||
Id: userFactor.UserID,
|
||||
},
|
||||
}
|
||||
|
||||
pb.User.LoginName = session.UserPreferredLoginName
|
||||
if session.UserOrganizationID != nil {
|
||||
pb.User.OrganizationId = *session.UserOrganizationID
|
||||
}
|
||||
if session.UserDisplayName != nil {
|
||||
pb.User.DisplayName = *session.UserDisplayName
|
||||
}
|
||||
|
||||
if f := session.Factors.GetPasswordFactor(); f != nil {
|
||||
pb.Password = &session_grpc.PasswordFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
}
|
||||
}
|
||||
if f := session.Factors.GetPasskeyFactor(); f != nil {
|
||||
pb.WebAuthN = &session_grpc.WebAuthNFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
UserVerified: f.UserVerified,
|
||||
}
|
||||
}
|
||||
if f := session.Factors.GetIDPIntentFactor(); f != nil {
|
||||
pb.Intent = &session_grpc.IntentFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
}
|
||||
}
|
||||
if f := session.Factors.GetTOTPFactor(); f != nil {
|
||||
pb.Totp = &session_grpc.TOTPFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
}
|
||||
}
|
||||
if f := session.Factors.GetOTPSMSFactor(); f != nil {
|
||||
pb.OtpSms = &session_grpc.OTPFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
}
|
||||
}
|
||||
if f := session.Factors.GetOTPEmailFactor(); f != nil {
|
||||
pb.OtpEmail = &session_grpc.OTPFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
}
|
||||
}
|
||||
if f := session.Factors.GetRecoveryCodeFactor(); f != nil {
|
||||
pb.RecoveryCode = &session_grpc.RecoveryCodeFactor{
|
||||
VerifiedAt: timestamppb.New(f.LastVerifiedAt),
|
||||
}
|
||||
}
|
||||
|
||||
return pb
|
||||
}
|
||||
|
||||
func domainUserAgentToGRPC(ua *domain.SessionUserAgent) *session_grpc.UserAgent {
|
||||
if ua == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
pb := &session_grpc.UserAgent{
|
||||
FingerprintId: ua.FingerprintID,
|
||||
Description: ua.Description,
|
||||
}
|
||||
|
||||
if ua.IP != nil {
|
||||
ip := ua.IP.String()
|
||||
pb.Ip = &ip
|
||||
}
|
||||
if len(ua.Header) > 0 {
|
||||
pb.Header = make(map[string]*session_grpc.UserAgent_HeaderValues, len(ua.Header))
|
||||
for k, v := range ua.Header {
|
||||
pb.Header[k] = &session_grpc.UserAgent_HeaderValues{Values: v}
|
||||
}
|
||||
}
|
||||
|
||||
return pb
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/muhlemmer/gu"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
"github.com/zitadel/zitadel/internal/api/authz"
|
||||
"github.com/zitadel/zitadel/internal/zerrors"
|
||||
objpb "github.com/zitadel/zitadel/pkg/grpc/object"
|
||||
objv2 "github.com/zitadel/zitadel/pkg/grpc/object/v2"
|
||||
session_grpc "github.com/zitadel/zitadel/pkg/grpc/session/v2"
|
||||
)
|
||||
|
||||
func TestSearchQueryGRPCToDomain(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
nowPB := timestamppb.New(now)
|
||||
creatorID := "creator-123"
|
||||
fingerprintID := "fp-123"
|
||||
userID := "user-1"
|
||||
agentID := "agent-1"
|
||||
emptyStr := ""
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input *session_grpc.SearchQuery
|
||||
want domain.SessionFilter
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "IdsQuery maps to SessionIDsFilter",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_IdsQuery{
|
||||
IdsQuery: &session_grpc.IDsQuery{Ids: []string{"id1", "id2"}},
|
||||
},
|
||||
},
|
||||
want: domain.SessionIDsFilter{IDs: []string{"id1", "id2"}},
|
||||
},
|
||||
{
|
||||
name: "UserIdQuery maps to SessionUserIDFilter",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_UserIdQuery{
|
||||
UserIdQuery: &session_grpc.UserIDQuery{Id: "user-123"},
|
||||
},
|
||||
},
|
||||
want: domain.SessionUserIDFilter{UserID: "user-123"},
|
||||
},
|
||||
{
|
||||
name: "CreationDateQuery with EQUALS method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreationDateQuery{
|
||||
CreationDateQuery: &session_grpc.CreationDateQuery{
|
||||
CreationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_EQUALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreationDateFilter{Op: database.NumberOperationEqual, Date: now},
|
||||
},
|
||||
{
|
||||
name: "CreationDateQuery with GREATER method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreationDateQuery{
|
||||
CreationDateQuery: &session_grpc.CreationDateQuery{
|
||||
CreationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_GREATER,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreationDateFilter{Op: database.NumberOperationGreaterThan, Date: now},
|
||||
},
|
||||
{
|
||||
name: "CreationDateQuery with GREATER_OR_EQUALS method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreationDateQuery{
|
||||
CreationDateQuery: &session_grpc.CreationDateQuery{
|
||||
CreationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_GREATER_OR_EQUALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreationDateFilter{Op: database.NumberOperationGreaterThanOrEqual, Date: now},
|
||||
},
|
||||
{
|
||||
name: "CreationDateQuery with LESS method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreationDateQuery{
|
||||
CreationDateQuery: &session_grpc.CreationDateQuery{
|
||||
CreationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_LESS,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreationDateFilter{Op: database.NumberOperationLessThan, Date: now},
|
||||
},
|
||||
{
|
||||
name: "CreationDateQuery with LESS_OR_EQUALS method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreationDateQuery{
|
||||
CreationDateQuery: &session_grpc.CreationDateQuery{
|
||||
CreationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_LESS_OR_EQUALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreationDateFilter{Op: database.NumberOperationLessThanOrEqual, Date: now},
|
||||
},
|
||||
{
|
||||
name: "CreatorQuery with nil ID uses userID from context",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreatorQuery{
|
||||
CreatorQuery: &session_grpc.CreatorQuery{},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreatorFilter{ID: userID},
|
||||
},
|
||||
{
|
||||
name: "CreatorQuery with empty ID returns error",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreatorQuery{
|
||||
CreatorQuery: &session_grpc.CreatorQuery{Id: &emptyStr},
|
||||
},
|
||||
},
|
||||
wantErr: zerrors.ThrowInvalidArgument(nil, "DOM-x8n24uh", "List.Query.Invalid"),
|
||||
},
|
||||
{
|
||||
name: "CreatorQuery with valid ID uses it",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_CreatorQuery{
|
||||
CreatorQuery: &session_grpc.CreatorQuery{Id: &creatorID},
|
||||
},
|
||||
},
|
||||
want: domain.SessionCreatorFilter{ID: creatorID},
|
||||
},
|
||||
{
|
||||
name: "UserAgentQuery with nil FingerprintID uses agentID in context",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_UserAgentQuery{
|
||||
UserAgentQuery: &session_grpc.UserAgentQuery{},
|
||||
},
|
||||
},
|
||||
want: domain.SessionUserAgentFilter{FingerprintID: agentID},
|
||||
},
|
||||
{
|
||||
name: "UserAgentQuery with empty FingerprintID returns error",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_UserAgentQuery{
|
||||
UserAgentQuery: &session_grpc.UserAgentQuery{FingerprintId: &emptyStr},
|
||||
},
|
||||
},
|
||||
wantErr: zerrors.ThrowInvalidArgument(nil, "DOM-x8n23uh", "List.Query.Invalid"),
|
||||
},
|
||||
{
|
||||
name: "UserAgentQuery with valid FingerprintID uses it",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_UserAgentQuery{
|
||||
UserAgentQuery: &session_grpc.UserAgentQuery{FingerprintId: &fingerprintID},
|
||||
},
|
||||
},
|
||||
want: domain.SessionUserAgentFilter{FingerprintID: fingerprintID},
|
||||
},
|
||||
{
|
||||
name: "ExpirationDateQuery with EQUALS method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_ExpirationDateQuery{
|
||||
ExpirationDateQuery: &session_grpc.ExpirationDateQuery{
|
||||
ExpirationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_EQUALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionExpirationDateFilter{Op: database.NumberOperationEqual, Date: now},
|
||||
},
|
||||
{
|
||||
name: "ExpirationDateQuery with GREATER method",
|
||||
input: &session_grpc.SearchQuery{
|
||||
Query: &session_grpc.SearchQuery_ExpirationDateQuery{
|
||||
ExpirationDateQuery: &session_grpc.ExpirationDateQuery{
|
||||
ExpirationDate: nowPB,
|
||||
Method: objpb.TimestampQueryMethod_TIMESTAMP_QUERY_METHOD_GREATER,
|
||||
},
|
||||
},
|
||||
},
|
||||
want: domain.SessionExpirationDateFilter{Op: database.NumberOperationGreaterThan, Date: now},
|
||||
},
|
||||
{
|
||||
name: "unknown query type returns error",
|
||||
input: &session_grpc.SearchQuery{},
|
||||
wantErr: zerrors.ThrowInvalidArgumentf(nil, "CONV-Cz5s3t", "session search query %T not implemented", nil),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := authz.NewMockContextWithAgent("instance-1", "org-1", userID, agentID)
|
||||
|
||||
got, err := searchQueryGRPCToDomain(ctx, tc.input)
|
||||
|
||||
assert.ErrorIs(t, err, tc.wantErr)
|
||||
assert.Equal(t, tc.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchQueriesGRPCToDomain(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
emptyStr := ""
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input []*session_grpc.SearchQuery
|
||||
want []domain.SessionFilter
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "nil slice returns nil",
|
||||
input: nil,
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "empty slice returns nil",
|
||||
input: []*session_grpc.SearchQuery{},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "valid queries are converted to filters",
|
||||
input: []*session_grpc.SearchQuery{
|
||||
{Query: &session_grpc.SearchQuery_IdsQuery{IdsQuery: &session_grpc.IDsQuery{Ids: []string{"id1"}}}},
|
||||
{Query: &session_grpc.SearchQuery_UserIdQuery{UserIdQuery: &session_grpc.UserIDQuery{Id: "user-1"}}},
|
||||
},
|
||||
want: []domain.SessionFilter{
|
||||
domain.SessionIDsFilter{IDs: []string{"id1"}},
|
||||
domain.SessionUserIDFilter{UserID: "user-1"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid query inside list propagates error",
|
||||
input: []*session_grpc.SearchQuery{
|
||||
{
|
||||
Query: &session_grpc.SearchQuery_CreatorQuery{
|
||||
CreatorQuery: &session_grpc.CreatorQuery{Id: &emptyStr},
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := authz.NewMockContext("instance-1", "org-1", "user-1")
|
||||
|
||||
got, err := searchQueriesGRPCToDomain(ctx, tc.input)
|
||||
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, got)
|
||||
return
|
||||
}
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListSessionsRequestGRPCToDomain(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
emptyStr := ""
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input *session_grpc.ListSessionsRequest
|
||||
want *domain.ListSessionsRequest
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "nil request returns empty domain request",
|
||||
input: nil,
|
||||
want: &domain.ListSessionsRequest{
|
||||
SortColumn: domain.SessionSortColumnUnspecified,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid query propagates error",
|
||||
input: &session_grpc.ListSessionsRequest{
|
||||
Queries: []*session_grpc.SearchQuery{
|
||||
{
|
||||
Query: &session_grpc.SearchQuery_CreatorQuery{
|
||||
CreatorQuery: &session_grpc.CreatorQuery{Id: &emptyStr},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "SESSION_FIELD_NAME_CREATION_DATE maps to SessionSortColumnCreationDate",
|
||||
input: &session_grpc.ListSessionsRequest{
|
||||
SortingColumn: session_grpc.SessionFieldName_SESSION_FIELD_NAME_CREATION_DATE,
|
||||
},
|
||||
want: &domain.ListSessionsRequest{
|
||||
SortColumn: domain.SessionSortColumnCreationDate,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "SESSION_FIELD_NAME_UNSPECIFIED maps to SessionSortColumnUnspecified",
|
||||
input: &session_grpc.ListSessionsRequest{
|
||||
SortingColumn: session_grpc.SessionFieldName_SESSION_FIELD_NAME_UNSPECIFIED,
|
||||
},
|
||||
want: &domain.ListSessionsRequest{
|
||||
SortColumn: domain.SessionSortColumnUnspecified,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "query limit, offset and ascending are mapped",
|
||||
input: &session_grpc.ListSessionsRequest{
|
||||
Query: &objv2.ListQuery{Limit: 20, Offset: 5, Asc: true},
|
||||
},
|
||||
want: &domain.ListSessionsRequest{
|
||||
SortColumn: domain.SessionSortColumnUnspecified,
|
||||
Limit: 20,
|
||||
Offset: 5,
|
||||
Ascending: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "valid queries are included in result",
|
||||
input: &session_grpc.ListSessionsRequest{
|
||||
Queries: []*session_grpc.SearchQuery{
|
||||
{Query: &session_grpc.SearchQuery_UserIdQuery{UserIdQuery: &session_grpc.UserIDQuery{Id: "user-1"}}},
|
||||
},
|
||||
},
|
||||
want: &domain.ListSessionsRequest{
|
||||
SortColumn: domain.SessionSortColumnUnspecified,
|
||||
Filters: []domain.SessionFilter{domain.SessionUserIDFilter{UserID: "user-1"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := authz.NewMockContext("instance-1", "org-1", "user-2")
|
||||
|
||||
got, err := ListSessionsRequestGRPCToDomain(ctx, tc.input)
|
||||
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, got)
|
||||
return
|
||||
}
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainSessionListToGRPCResponse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("empty slice returns empty response slice", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := DomainSessionListToGRPCResponse([]*domain.Session{})
|
||||
assert.Empty(t, got)
|
||||
})
|
||||
|
||||
t.Run("each session is converted", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
sessions := []*domain.Session{
|
||||
{ID: "sess-1"},
|
||||
{ID: "sess-2"},
|
||||
}
|
||||
got := DomainSessionListToGRPCResponse(sessions)
|
||||
assert.Len(t, got, 2)
|
||||
assert.Equal(t, "sess-1", got[0].Id)
|
||||
assert.Equal(t, "sess-2", got[1].Id)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDomainSessionToGRPCResponse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
createdAt := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC)
|
||||
updatedAt := time.Date(2026, 1, 2, 10, 0, 0, 0, time.UTC)
|
||||
expiration := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
t.Run("basic fields are mapped", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lsr := &domain.Session{
|
||||
ID: "sess-abc",
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: updatedAt,
|
||||
}
|
||||
|
||||
got := DomainSessionToGRPCResponse(lsr)
|
||||
assert.Equal(t, "sess-abc", got.Id)
|
||||
assert.Equal(t, timestamppb.New(createdAt), got.CreationDate)
|
||||
assert.Equal(t, timestamppb.New(updatedAt), got.ChangeDate)
|
||||
assert.EqualValues(t, 0, got.Sequence)
|
||||
assert.Nil(t, got.ExpirationDate)
|
||||
assert.Nil(t, got.Metadata)
|
||||
})
|
||||
|
||||
t.Run("expiration is set when non-zero", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lsr := &domain.Session{Expiration: expiration}
|
||||
got := DomainSessionToGRPCResponse(lsr)
|
||||
assert.Equal(t, timestamppb.New(expiration), got.ExpirationDate)
|
||||
})
|
||||
|
||||
t.Run("zero expiration is not set", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lsr := &domain.Session{}
|
||||
got := DomainSessionToGRPCResponse(lsr)
|
||||
assert.Nil(t, got.ExpirationDate)
|
||||
})
|
||||
|
||||
t.Run("metadata is mapped to key-value pairs", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lsr := &domain.Session{
|
||||
Metadata: []*domain.SessionMetadata{
|
||||
{Metadata: domain.Metadata{Key: "k1", Value: []byte("v1")}},
|
||||
{Metadata: domain.Metadata{Key: "k2", Value: []byte("v2")}},
|
||||
},
|
||||
}
|
||||
got := DomainSessionToGRPCResponse(lsr)
|
||||
assert.Equal(t, map[string][]byte{"k1": []byte("v1"), "k2": []byte("v2")}, got.Metadata)
|
||||
})
|
||||
|
||||
t.Run("empty metadata is not set", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
lsr := &domain.Session{
|
||||
Metadata: []*domain.SessionMetadata{},
|
||||
}
|
||||
got := DomainSessionToGRPCResponse(lsr)
|
||||
assert.Nil(t, got.Metadata)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDomainFactorsToGRPC(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
verifiedAt := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
verifiedAtPB := timestamppb.New(verifiedAt)
|
||||
|
||||
t.Run("no user factor returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainFactorsToGRPC(&domain.Session{Factors: domain.SessionFactors{}})
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
|
||||
t.Run("no factors returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainFactorsToGRPC(&domain.Session{})
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
|
||||
t.Run("only user factor maps User field with nil user", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
factors := domain.SessionFactors{
|
||||
&domain.SessionFactorUser{UserID: "user-1", LastVerifiedAt: verifiedAt},
|
||||
}
|
||||
got := domainFactorsToGRPC(&domain.Session{Factors: factors})
|
||||
assert.NotNil(t, got)
|
||||
assert.Equal(t, verifiedAtPB, got.User.VerifiedAt)
|
||||
assert.Equal(t, "user-1", got.User.Id)
|
||||
assert.Zero(t, got.User.LoginName)
|
||||
assert.Zero(t, got.User.OrganizationId)
|
||||
assert.Zero(t, got.User.DisplayName)
|
||||
assert.Nil(t, got.Password)
|
||||
assert.Nil(t, got.WebAuthN)
|
||||
assert.Nil(t, got.Intent)
|
||||
assert.Nil(t, got.Totp)
|
||||
assert.Nil(t, got.OtpSms)
|
||||
assert.Nil(t, got.OtpEmail)
|
||||
assert.Nil(t, got.RecoveryCode)
|
||||
})
|
||||
|
||||
t.Run("only user factor maps User field", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
factors := domain.SessionFactors{
|
||||
&domain.SessionFactorUser{UserID: "user-1", LastVerifiedAt: verifiedAt},
|
||||
}
|
||||
|
||||
got := domainFactorsToGRPC(&domain.Session{
|
||||
Factors: factors,
|
||||
UserPreferredLoginName: "preferred ln",
|
||||
UserOrganizationID: gu.Ptr("org-1"),
|
||||
UserDisplayName: gu.Ptr("displayed name"),
|
||||
})
|
||||
assert.NotNil(t, got)
|
||||
assert.Equal(t, "user-1", got.User.Id)
|
||||
assert.Equal(t, verifiedAtPB, got.User.VerifiedAt)
|
||||
assert.Equal(t, "preferred ln", got.User.LoginName)
|
||||
assert.Equal(t, "org-1", got.User.OrganizationId)
|
||||
assert.Equal(t, "displayed name", got.User.DisplayName)
|
||||
assert.Nil(t, got.Password)
|
||||
assert.Nil(t, got.WebAuthN)
|
||||
assert.Nil(t, got.Intent)
|
||||
assert.Nil(t, got.Totp)
|
||||
assert.Nil(t, got.OtpSms)
|
||||
assert.Nil(t, got.OtpEmail)
|
||||
assert.Nil(t, got.RecoveryCode)
|
||||
})
|
||||
|
||||
t.Run("all factors are mapped", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
factors := domain.SessionFactors{
|
||||
&domain.SessionFactorUser{UserID: "user-1", LastVerifiedAt: verifiedAt},
|
||||
&domain.SessionFactorPassword{LastVerifiedAt: verifiedAt},
|
||||
&domain.SessionFactorPasskey{LastVerifiedAt: verifiedAt, UserVerified: true},
|
||||
&domain.SessionFactorIdentityProviderIntent{LastVerifiedAt: verifiedAt},
|
||||
&domain.SessionFactorTOTP{LastVerifiedAt: verifiedAt},
|
||||
&domain.SessionFactorOTPSMS{LastVerifiedAt: verifiedAt},
|
||||
&domain.SessionFactorOTPEmail{LastVerifiedAt: verifiedAt},
|
||||
&domain.SessionFactorRecoveryCode{LastVerifiedAt: verifiedAt},
|
||||
}
|
||||
session := &domain.Session{
|
||||
Factors: factors,
|
||||
UserPreferredLoginName: "preferred ln",
|
||||
UserOrganizationID: gu.Ptr("org-1"),
|
||||
UserDisplayName: gu.Ptr("displayed name"),
|
||||
}
|
||||
got := domainFactorsToGRPC(session)
|
||||
assert.NotNil(t, got)
|
||||
assert.Equal(t, "user-1", got.User.Id)
|
||||
assert.Equal(t, verifiedAtPB, got.User.VerifiedAt)
|
||||
assert.Equal(t, "preferred ln", got.User.LoginName)
|
||||
assert.Equal(t, "org-1", got.User.OrganizationId)
|
||||
assert.Equal(t, "displayed name", got.User.DisplayName)
|
||||
assert.Equal(t, verifiedAtPB, got.User.VerifiedAt)
|
||||
assert.Equal(t, verifiedAtPB, got.Password.VerifiedAt)
|
||||
assert.Equal(t, verifiedAtPB, got.WebAuthN.VerifiedAt)
|
||||
assert.True(t, got.WebAuthN.UserVerified)
|
||||
assert.Equal(t, verifiedAtPB, got.Intent.VerifiedAt)
|
||||
assert.Equal(t, verifiedAtPB, got.Totp.VerifiedAt)
|
||||
assert.Equal(t, verifiedAtPB, got.OtpSms.VerifiedAt)
|
||||
assert.Equal(t, verifiedAtPB, got.OtpEmail.VerifiedAt)
|
||||
assert.Equal(t, verifiedAtPB, got.RecoveryCode.VerifiedAt)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDomainUserAgentToGRPC(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fpID := "fp-abc"
|
||||
desc := "Chrome on macOS"
|
||||
ip := net.ParseIP("192.168.1.1")
|
||||
ipStr := ip.String()
|
||||
|
||||
t.Run("nil user agent returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainUserAgentToGRPC(nil)
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
|
||||
t.Run("empty user agent returns empty proto", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainUserAgentToGRPC(&domain.SessionUserAgent{})
|
||||
assert.NotNil(t, got)
|
||||
assert.Nil(t, got.FingerprintId)
|
||||
assert.Nil(t, got.Description)
|
||||
assert.Nil(t, got.Ip)
|
||||
assert.Nil(t, got.Header)
|
||||
})
|
||||
|
||||
t.Run("fingerprint ID is mapped", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainUserAgentToGRPC(&domain.SessionUserAgent{FingerprintID: &fpID})
|
||||
assert.Equal(t, &fpID, got.FingerprintId)
|
||||
})
|
||||
|
||||
t.Run("description is mapped", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainUserAgentToGRPC(&domain.SessionUserAgent{Description: &desc})
|
||||
assert.Equal(t, &desc, got.Description)
|
||||
})
|
||||
|
||||
t.Run("IP is mapped as string", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := domainUserAgentToGRPC(&domain.SessionUserAgent{IP: ip})
|
||||
assert.Equal(t, &ipStr, got.Ip)
|
||||
})
|
||||
|
||||
t.Run("headers are mapped", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ua := &domain.SessionUserAgent{
|
||||
Header: http.Header{"Accept": []string{"application/json", "text/html"}},
|
||||
}
|
||||
got := domainUserAgentToGRPC(ua)
|
||||
assert.Equal(t, []string{"application/json", "text/html"}, got.Header["Accept"].Values)
|
||||
})
|
||||
}
|
||||
@@ -6,12 +6,37 @@ import (
|
||||
"connectrpc.com/connect"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/api/session/v2/convert"
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database/repository"
|
||||
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
|
||||
"github.com/zitadel/zitadel/pkg/grpc/session/v2"
|
||||
object "github.com/zitadel/zitadel/pkg/grpc/object/v2"
|
||||
session "github.com/zitadel/zitadel/pkg/grpc/session/v2"
|
||||
)
|
||||
|
||||
func ListSessions(ctx context.Context, request *connect.Request[session.ListSessionsRequest]) (*connect.Response[session.ListSessionsResponse], error) {
|
||||
req, err := convert.ListSessionsRequestGRPCToDomain(ctx, request.Msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
q := domain.NewListSessionsQuery(req)
|
||||
err = domain.Invoke(ctx, q, domain.WithSessionRepo(repository.SessionRepository()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sessions := convert.DomainSessionListToGRPCResponse(q.Result())
|
||||
return connect.NewResponse(&session.ListSessionsResponse{
|
||||
Sessions: sessions,
|
||||
Details: &object.ListDetails{
|
||||
TotalResult: uint64(len(sessions)),
|
||||
|
||||
// TODO(IAM-Marco): Put something meaningful once we have a reliable timestamp from DB
|
||||
Timestamp: timestamppb.Now(),
|
||||
},
|
||||
}), nil
|
||||
}
|
||||
|
||||
func DeleteSession(ctx context.Context, request *connect.Request[session.DeleteSessionRequest]) (*connect.Response[session.DeleteSessionResponse], error) {
|
||||
sessionDeleteCmd := domain.NewDeleteSessionCommand(request.Msg.GetSessionId(), request.Msg.GetSessionToken(), true)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user