feat: add delete session on relation tables (#11334)

# Which Problems Are Solved

As part of moving the session API to the relational database, this PR
adds the functionality to delete sessions through the session API v2 and
the OIDC end_session endpoint.

# How the Problems Are Solved

- added `SessionDeleteCommand` in domain package
- added possibility to pass the session token verifier to the domain
package
- use feature flag to switch API and OIDC usage from CQRS to relation
table
- added a `permissionCheck` condition to let permissions be checked
directly in the repository / sql
- part of it is still a placeholder until actual permission tables are
done
- added a `session_deleted` table to store (recently) deleted sessions
to handle necessary checks / cases like delete my own session, which
needs to be idempotent

# Additional Changes

Fixed `Matches` function of `existsCondition` (as missing an
implementation)

# Additional Context

- closes #11037

---------

Co-authored-by: Stefan Benz <[email protected]>
This commit is contained in:
Livio Spring
2026-03-19 08:35:53 +01:00
committed by GitHub
co-authored by Stefan Benz
parent ae32508225
commit ca4bba3992
26 changed files with 1221 additions and 222 deletions
@@ -2,6 +2,7 @@ package repository
import (
"context"
"errors"
"fmt"
"time"
@@ -228,14 +229,40 @@ func sessionCTE(change database.Change, i, j int, builder *database.StatementBui
}
// Delete implements [domain.SessionRepository].
func (s session) Delete(ctx context.Context, client database.QueryExecutor, condition database.Condition) (int64, error) {
func (s session) Delete(ctx context.Context, client database.QueryExecutor, condition database.Condition, permissionCondition database.Condition) (int64, time.Time, error) {
if !condition.IsRestrictingColumn(s.InstanceIDColumn()) {
return 0, database.NewMissingConditionError(s.InstanceIDColumn())
return 0, time.Time{}, database.NewMissingConditionError(s.InstanceIDColumn())
}
var builder database.StatementBuilder
builder.WriteString("DELETE FROM zitadel.sessions")
builder.WriteString("WITH gatekeeper AS (SELECT count(*) as total_found, MAX(sessions.deleted_at) as deleted_at FROM (SELECT instance_id, user_id, token_id, now() as deleted_at FROM zitadel.sessions")
writeCondition(&builder, condition)
return client.Exec(ctx, builder.String(), builder.Args()...)
// In case the deletion is intended for a specific session,
// we'll also include already deleted session to check the permission against,
// and to return the deleted_at timestamp from the previous deletion in case the session was already deleted.
if condition.IsRestrictingColumn(s.IDColumn()) {
builder.WriteString(" UNION ALL SELECT instance_id, user_id, token_id, deleted_at FROM zitadel.archived_sessions as sessions")
writeCondition(&builder, condition)
}
// join the users table to get the user's organization, which will be needed for checking the permission
builder.WriteString(") as sessions")
if permissionCondition != nil {
builder.WriteString(" LEFT JOIN zitadel.users ON users.instance_id = sessions.instance_id AND users.id = sessions.user_id HAVING (bool_and(")
permissionCondition.Write(&builder)
builder.WriteString(") AND count(*) > 0) or zitadel.throw_not_permitted()") //TODO: change throw_not_permitted to actual permission check
}
builder.WriteString("), execution AS (DELETE FROM zitadel.sessions")
writeCondition(&builder, condition)
builder.WriteString(" and exists (SELECT 1 FROM gatekeeper) RETURNING 1 AS rows_affected) SELECT (CASE WHEN gatekeeper.total_found = 1 THEN gatekeeper.deleted_at END) as deleted_at, (SELECT count(*) FROM execution) as rows_affected FROM gatekeeper")
var deletedAt database.Null[time.Time]
var deletedSessions int64
if err := client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&deletedAt, &deletedSessions); err != nil {
// If the criteria did not match any session, ignore the error since the user would have had the permission to delete the session,
if errors.Is(err, new(database.NoRowFoundError)) {
return 0, time.Time{}, nil
}
return 0, time.Time{}, err
}
return deletedSessions, deletedAt.V, nil
}
// -------------------------------------------------------------
@@ -427,6 +454,11 @@ func (s session) UserIDCondition(userID string) database.Condition {
return database.NewTextCondition(s.UserIDColumn(), database.TextOperationEqual, userID)
}
// TokenIDCondition implements [domain.sessionConditions].
func (s session) TokenIDCondition(tokenID string) database.Condition {
return database.NewTextCondition(s.TokenIDColumn(), database.TextOperationEqual, tokenID)
}
// CreatorIDCondition implements [domain.sessionConditions].
func (s session) CreatorIDCondition(creatorID string) database.Condition {
return database.NewTextCondition(s.CreatorIDColumn(), database.TextOperationEqual, creatorID)
@@ -918,6 +918,7 @@ func TestSession_Update(t *testing.T) {
}
func TestSession_Delete(t *testing.T) {
start := time.Now()
tx, err := pool.Begin(t.Context(), nil)
require.NoError(t, err)
defer func() {
@@ -944,59 +945,207 @@ func TestSession_Delete(t *testing.T) {
err = instanceRepo.Create(t.Context(), tx, &instance)
require.NoError(t, err)
type test struct {
name string
testFunc func(t *testing.T) *domain.Session
type fields struct {
testFunc func(t *testing.T) []*domain.Session
}
type args struct {
condition func([]*domain.Session) database.Condition
permissionCondition func([]*domain.Session) database.Condition
}
type res struct {
noOfDeletedRows int64
deletedAt time.Time
err error
}
type test struct {
name string
fields fields
args args
res res
}
tests := []test{
{
name: "delete existent session",
testFunc: func(t *testing.T) *domain.Session {
session := &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
err := sessionRepo.Create(t.Context(), tx, session)
require.NoError(t, err)
return session
fields: fields{
testFunc: func(t *testing.T) []*domain.Session {
session := &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
err := sessionRepo.Create(t.Context(), tx, session)
require.NoError(t, err)
return []*domain.Session{session}
},
},
args: args{
condition: func(sessions []*domain.Session) database.Condition {
return sessionRepo.PrimaryKeyCondition(instanceId, sessions[0].ID)
},
},
res: res{
noOfDeletedRows: 1,
deletedAt: time.Now(),
},
noOfDeletedRows: 1,
},
{
name: "delete non existent session",
testFunc: func(t *testing.T) *domain.Session {
return &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
fields: fields{
testFunc: func(t *testing.T) []*domain.Session {
return []*domain.Session{}
},
},
args: args{
condition: func(sessions []*domain.Session) database.Condition {
return sessionRepo.PrimaryKeyCondition(instanceId, gofakeit.UUID())
},
},
res: res{
noOfDeletedRows: 0,
},
},
{
name: "delete previously existent session",
fields: fields{
testFunc: func(t *testing.T) []*domain.Session {
session := &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
err := sessionRepo.Create(t.Context(), tx, session)
require.NoError(t, err)
_, _, err = sessionRepo.Delete(t.Context(), tx, sessionRepo.PrimaryKeyCondition(session.InstanceID, session.ID), nil)
require.NoError(t, err)
return []*domain.Session{session}
},
},
args: args{
condition: func(sessions []*domain.Session) database.Condition {
return sessionRepo.PrimaryKeyCondition(instanceId, sessions[0].ID)
},
},
res: res{
noOfDeletedRows: 0,
deletedAt: time.Now(),
},
},
{
name: "delete multiple sessions",
fields: fields{
testFunc: func(t *testing.T) []*domain.Session {
session := &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
err := sessionRepo.Create(t.Context(), tx, session)
require.NoError(t, err)
session2 := &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
err = sessionRepo.Create(t.Context(), tx, session2)
require.NoError(t, err)
return []*domain.Session{session, session2}
},
},
args: args{
condition: func(sessions []*domain.Session) database.Condition {
return sessionRepo.InstanceIDCondition(instanceId)
},
},
res: res{
noOfDeletedRows: 2,
deletedAt: time.Time{},
},
},
{
name: "delete without permission",
fields: fields{
testFunc: func(t *testing.T) []*domain.Session {
session := &domain.Session{
InstanceID: instanceId,
ID: gofakeit.Name(),
TokenID: gofakeit.UUID(),
Lifetime: time.Hour * 24,
CreatorID: gofakeit.Name(),
}
err := sessionRepo.Create(t.Context(), tx, session)
require.NoError(t, err)
return []*domain.Session{session}
},
},
args: args{
condition: func(sessions []*domain.Session) database.Condition {
return sessionRepo.InstanceIDCondition(instanceId)
},
permissionCondition: func(sessions []*domain.Session) database.Condition {
return sessionRepo.TokenIDCondition("invalid")
},
},
res: res{
noOfDeletedRows: 0,
deletedAt: time.Time{},
err: database.NewPermissionError(nil),
},
noOfDeletedRows: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
session := tt.testFunc(t)
var sessions []*domain.Session
if tt.fields.testFunc != nil {
sessions = tt.fields.testFunc(t)
}
var condition, permissionCondition database.Condition
if tt.args.condition != nil {
condition = tt.args.condition(sessions)
}
if tt.args.permissionCondition != nil {
permissionCondition = tt.args.permissionCondition(sessions)
}
// let's create a snapshot before deletion to make sure we could rollback in case of error
snapshot, err := tx.Begin(t.Context())
require.NoError(t, err)
// delete session
deletedRows, err := sessionRepo.Delete(t.Context(), tx,
sessionRepo.PrimaryKeyCondition(session.InstanceID, session.ID),
deletedRows, deletedAt, err := sessionRepo.Delete(t.Context(), tx,
condition, permissionCondition,
)
require.NoError(t, err)
assert.Equal(t, tt.noOfDeletedRows, deletedRows)
require.ErrorIs(t, err, tt.res.err)
assert.Equal(t, tt.res.noOfDeletedRows, deletedRows)
if tt.res.deletedAt.IsZero() {
assert.Zero(t, deletedAt)
} else {
assert.WithinRange(t, deletedAt, start, time.Now())
}
if err != nil {
err = snapshot.Rollback(t.Context())
require.NoError(t, err)
}
// verify session deletion
deletedSession, err := sessionRepo.Get(t.Context(), tx,
database.WithCondition(
sessionRepo.PrimaryKeyCondition(session.InstanceID, session.ID),
),
deletedSessions, err := sessionRepo.List(t.Context(), tx,
database.WithCondition(condition),
)
require.Error(t, err, new(database.NoRowFoundError))
assert.Nil(t, deletedSession)
require.NoError(t, err)
expectedSessions := 0
// in case of permission error, sessions are not deleted,
// so expectedSessions should be equal to the number of created sessions
if tt.res.err != nil {
expectedSessions = len(sessions)
}
assert.Len(t, deletedSessions, expectedSessions)
})
}
}