mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-25 13:58:46 +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:
@@ -33,11 +33,17 @@ BEGIN
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER set_expiration
|
||||
BEFORE INSERT OR UPDATE OF lifetime ON zitadel.sessions
|
||||
CREATE TRIGGER set_expiration_on_update
|
||||
BEFORE UPDATE OF lifetime ON zitadel.sessions
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION zitadel.update_expiration();
|
||||
|
||||
CREATE TRIGGER set_expiration_on_insert
|
||||
BEFORE INSERT ON zitadel.sessions
|
||||
FOR EACH ROW
|
||||
WHEN (NEW.lifetime <> '0'::interval)
|
||||
EXECUTE FUNCTION zitadel.update_expiration();
|
||||
|
||||
CREATE TYPE zitadel.session_factor_type AS ENUM (
|
||||
'user',
|
||||
'password',
|
||||
|
||||
@@ -19,9 +19,13 @@ import (
|
||||
var _ domain.SessionRepository = (*session)(nil)
|
||||
|
||||
type session struct {
|
||||
factorRepo sessionFactor
|
||||
metadataRepo sessionMetadata
|
||||
userAgentRepo sessionUserAgent
|
||||
factorRepo sessionFactor
|
||||
metadataRepo sessionMetadata
|
||||
userAgentRepo sessionUserAgent
|
||||
userRepo user
|
||||
loginNamesRepo userLoginName
|
||||
// shouldLoadUser loads a part of the user data (display name, organization ID and login names)
|
||||
shouldLoadUser bool
|
||||
}
|
||||
|
||||
func (s session) qualifiedTableName() string {
|
||||
@@ -78,6 +82,9 @@ SELECT
|
||||
, 'headers', session_user_agents.headers
|
||||
)
|
||||
END as user_agent
|
||||
, users.organization_id
|
||||
, jsonb_agg(DISTINCT jsonb_build_object('loginName', login_names.login_name, 'isPreferred', login_names.is_preferred)) FILTER (WHERE login_names.user_id IS NOT NULL) AS login_names
|
||||
, users.display_name
|
||||
FROM zitadel.sessions`
|
||||
|
||||
// Get implements [domain.SessionRepository].
|
||||
@@ -86,6 +93,8 @@ func (s session) Get(ctx context.Context, client database.QueryExecutor, opts ..
|
||||
s.joinFactors(),
|
||||
s.joinMetadata(),
|
||||
s.joinUserAgent(),
|
||||
s.joinUser(),
|
||||
s.joinLoginNames(),
|
||||
database.WithGroupBy(
|
||||
s.InstanceIDColumn(),
|
||||
s.IDColumn(),
|
||||
@@ -93,6 +102,8 @@ func (s session) Get(ctx context.Context, client database.QueryExecutor, opts ..
|
||||
s.userAgentRepo.descriptionColumn(),
|
||||
s.userAgentRepo.ipColumn(),
|
||||
s.userAgentRepo.headersColumn(),
|
||||
s.userRepo.organizationIDColumn(),
|
||||
s.userRepo.Human().DisplayNameColumn(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -118,6 +129,8 @@ func (s session) List(ctx context.Context, client database.QueryExecutor, opts .
|
||||
s.joinFactors(),
|
||||
s.joinMetadata(),
|
||||
s.joinUserAgent(),
|
||||
s.joinUser(),
|
||||
s.joinLoginNames(),
|
||||
database.WithGroupBy(
|
||||
s.InstanceIDColumn(),
|
||||
s.IDColumn(),
|
||||
@@ -125,6 +138,8 @@ func (s session) List(ctx context.Context, client database.QueryExecutor, opts .
|
||||
s.userAgentRepo.descriptionColumn(),
|
||||
s.userAgentRepo.ipColumn(),
|
||||
s.userAgentRepo.headersColumn(),
|
||||
s.userRepo.organizationIDColumn(),
|
||||
s.userRepo.Human().DisplayNameColumn(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -265,6 +280,11 @@ func (s session) Delete(ctx context.Context, client database.QueryExecutor, cond
|
||||
return deletedSessions, deletedAt.V, nil
|
||||
}
|
||||
|
||||
// LoadUserData implements [domain.SessionRepository].
|
||||
func (s session) LoadUserData() domain.SessionRepository {
|
||||
return &session{shouldLoadUser: true}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
@@ -588,6 +608,7 @@ type rawSession struct {
|
||||
CreatorID *string `json:"creatorID" db:"creator_id"`
|
||||
Factors JSONArray[*rawFactor] `json:"factors,omitempty" db:"factors"`
|
||||
Metadata JSONArray[*domain.SessionMetadata] `json:"metadata,omitempty" db:"metadata"`
|
||||
LoginNames JSONArray[*domain.LoginName] `json:"login_names,omitempty" db:"login_names"`
|
||||
}
|
||||
|
||||
func scanSession(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) (*domain.Session, error) {
|
||||
@@ -632,6 +653,13 @@ func rawSessionToDomain(raw *rawSession) (*domain.Session, error) {
|
||||
raw.Session.UserID = gu.Value(raw.UserID)
|
||||
raw.Session.CreatorID = gu.Value(raw.CreatorID)
|
||||
|
||||
for _, ln := range raw.LoginNames {
|
||||
if ln.IsPreferred {
|
||||
raw.UserPreferredLoginName = ln.LoginName
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for _, factor := range raw.Factors {
|
||||
f, ch, err := factor.ToDomain()
|
||||
if err != nil {
|
||||
@@ -687,3 +715,33 @@ func (s session) joinMetadata() database.QueryOption {
|
||||
database.And(columns...),
|
||||
)
|
||||
}
|
||||
|
||||
func (s session) joinUser() database.QueryOption {
|
||||
columns := make([]database.Condition, 2, 3)
|
||||
columns[0] = database.NewColumnCondition(s.InstanceIDColumn(), s.userRepo.InstanceIDColumn())
|
||||
columns[1] = database.NewColumnCondition(s.UserIDColumn(), s.userRepo.IDColumn())
|
||||
|
||||
if !s.shouldLoadUser {
|
||||
columns = append(columns, database.IsNull(s.userRepo.IDColumn()))
|
||||
}
|
||||
|
||||
return database.WithLeftJoin(
|
||||
s.userRepo.qualifiedTableName(),
|
||||
database.And(columns...),
|
||||
)
|
||||
}
|
||||
|
||||
func (s session) joinLoginNames() database.QueryOption {
|
||||
columns := make([]database.Condition, 2, 3)
|
||||
columns[0] = database.NewColumnCondition(s.InstanceIDColumn(), s.loginNamesRepo.instanceIDColumn())
|
||||
columns[1] = database.NewColumnCondition(s.UserIDColumn(), s.loginNamesRepo.userIDColumn())
|
||||
|
||||
if !s.shouldLoadUser {
|
||||
columns = append(columns, database.IsNull(s.loginNamesRepo.loginNameColumn()))
|
||||
}
|
||||
|
||||
return database.WithLeftJoin(
|
||||
s.loginNamesRepo.qualifiedTableName(),
|
||||
database.And(columns...),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/muhlemmer/gu"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/text/language"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
@@ -195,7 +196,11 @@ func TestSession_Create(t *testing.T) {
|
||||
assert.Equal(t, tt.session.ID, createdSession.ID)
|
||||
assert.Equal(t, tt.session.InstanceID, createdSession.InstanceID)
|
||||
assert.Equal(t, tt.session.Lifetime, createdSession.Lifetime)
|
||||
assert.Equal(t, createdSession.UpdatedAt.Add(tt.session.Lifetime), createdSession.Expiration)
|
||||
if tt.session.Lifetime != 0 {
|
||||
assert.Equal(t, createdSession.UpdatedAt.Add(tt.session.Lifetime), createdSession.Expiration)
|
||||
} else {
|
||||
assert.Zero(t, createdSession.Expiration)
|
||||
}
|
||||
assert.Equal(t, tt.session.CreatorID, createdSession.CreatorID)
|
||||
assert.Equal(t, tt.session.UserAgent, createdSession.UserAgent)
|
||||
assert.WithinRange(t, createdSession.CreatedAt, beforeCreate.Add(-time.Second), afterCreate.Add(time.Second))
|
||||
@@ -1159,9 +1164,12 @@ func TestSession_Get(t *testing.T) {
|
||||
t.Logf("error during rollback: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository()
|
||||
sessionRepo := repository.SessionRepository()
|
||||
sessionRepo := repository.SessionRepository().LoadUserData()
|
||||
orgRepo := repository.OrganizationRepository()
|
||||
orgDomainRepo := repository.OrganizationDomainRepository()
|
||||
userRepo := repository.UserRepository()
|
||||
settingsRepo := repository.DomainSettingsRepository()
|
||||
|
||||
// create instance
|
||||
instanceId := gofakeit.Name()
|
||||
@@ -1177,6 +1185,62 @@ func TestSession_Get(t *testing.T) {
|
||||
err = instanceRepo.Create(t.Context(), tx, &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Organization
|
||||
orgID := gofakeit.UUID()
|
||||
org := domain.Organization{
|
||||
ID: orgID,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceId,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
err = orgRepo.Create(t.Context(), tx, &org)
|
||||
require.NoError(t, err)
|
||||
|
||||
domainName := gofakeit.DomainName()
|
||||
err = orgDomainRepo.Add(t.Context(), tx, &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceId,
|
||||
OrgID: orgID,
|
||||
Domain: domainName,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
err = settingsRepo.Set(t.Context(), tx, &domain.DomainSettings{
|
||||
Settings: domain.Settings{
|
||||
InstanceID: instanceId,
|
||||
OrganizationID: &orgID,
|
||||
Type: domain.SettingTypeDomain,
|
||||
State: domain.SettingStateActive,
|
||||
},
|
||||
DomainSettingsAttributes: domain.DomainSettingsAttributes{
|
||||
LoginNameIncludesDomain: gu.Ptr(false),
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
preferredLoginName := gofakeit.Name()
|
||||
userID := gofakeit.UUID()
|
||||
displayName := gofakeit.Username()
|
||||
user := domain.User{
|
||||
InstanceID: instanceId,
|
||||
OrganizationID: orgID,
|
||||
ID: userID,
|
||||
Username: preferredLoginName,
|
||||
State: domain.UserStateActive,
|
||||
Human: &domain.HumanUser{
|
||||
FirstName: gofakeit.Name(),
|
||||
LastName: gofakeit.Name(),
|
||||
Nickname: gofakeit.Username(),
|
||||
DisplayName: displayName,
|
||||
PreferredLanguage: language.English,
|
||||
Gender: domain.HumanGenderMale,
|
||||
},
|
||||
}
|
||||
|
||||
err = userRepo.Create(t.Context(), tx, &user)
|
||||
require.NoError(t, err)
|
||||
|
||||
session := &domain.Session{
|
||||
InstanceID: instanceId,
|
||||
ID: gofakeit.Name(),
|
||||
@@ -1185,6 +1249,11 @@ func TestSession_Get(t *testing.T) {
|
||||
}
|
||||
err = sessionRepo.Create(t.Context(), tx, session)
|
||||
require.NoError(t, err)
|
||||
_, err = sessionRepo.Update(t.Context(), tx, sessionRepo.PrimaryKeyCondition(instanceId, session.ID), sessionRepo.SetFactor(&domain.SessionFactorUser{
|
||||
UserID: userID,
|
||||
LastVerifiedAt: time.Now(),
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -1222,6 +1291,11 @@ func TestSession_Get(t *testing.T) {
|
||||
assert.Equal(t, session.InstanceID, got.InstanceID)
|
||||
assert.Equal(t, session.Lifetime, got.Lifetime)
|
||||
assert.Equal(t, session.CreatorID, got.CreatorID)
|
||||
require.NotNil(t, got.UserOrganizationID)
|
||||
assert.Equal(t, orgID, *got.UserOrganizationID)
|
||||
assert.Equal(t, preferredLoginName, got.UserPreferredLoginName)
|
||||
require.NotNil(t, got.UserDisplayName)
|
||||
assert.Equal(t, displayName, *got.UserDisplayName)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,6 +195,13 @@ func (u user) unqualifiedTableName() string {
|
||||
return "users"
|
||||
}
|
||||
|
||||
func (u user) qualifiedTableName() string {
|
||||
if u.tableName != "" {
|
||||
return "zitadel." + u.tableName
|
||||
}
|
||||
return "zitadel.users"
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user