mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-27 06:38:46 +00:00
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:
co-authored by
Stefan Benz
parent
ae32508225
commit
ca4bba3992
@@ -313,8 +313,14 @@ type existsCondition struct {
|
||||
|
||||
// Matches implements [Condition].
|
||||
func (e *existsCondition) Matches(x any) bool {
|
||||
// Unimplemented
|
||||
return false
|
||||
toMatch, ok := x.(*existsCondition)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if e.table != toMatch.table {
|
||||
return false
|
||||
}
|
||||
return e.condition.Matches(toMatch.condition)
|
||||
}
|
||||
|
||||
// String implements [Condition].
|
||||
@@ -364,3 +370,46 @@ func ForceRestrictingColumn(cond Condition, isRestriction bool) Condition {
|
||||
}
|
||||
|
||||
var _ Condition = (*forcedRestrictingColumnCondition)(nil)
|
||||
|
||||
type permissionCheck struct {
|
||||
requiredPermission string
|
||||
throwError bool
|
||||
}
|
||||
|
||||
func (p *permissionCheck) Matches(x any) bool {
|
||||
toMatch, ok := x.(*permissionCheck)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if toMatch.requiredPermission != p.requiredPermission {
|
||||
return false
|
||||
}
|
||||
return toMatch.throwError == p.throwError
|
||||
}
|
||||
|
||||
func (p *permissionCheck) String() string {
|
||||
return "database.permissionCheck"
|
||||
}
|
||||
|
||||
func (p *permissionCheck) Write(builder *StatementBuilder) {
|
||||
// TODO: implement actual permission check once we have the necessary tables and functions in place.
|
||||
// For now, we just write a dummy condition that can be used to verify that the permission check is included in the generated SQL.
|
||||
if p.throwError {
|
||||
builder.WriteString(" zitadel.throw_not_permitted() ")
|
||||
return
|
||||
}
|
||||
builder.WriteString(" true ")
|
||||
}
|
||||
|
||||
func (p *permissionCheck) IsRestrictingColumn(_ Column) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func PermissionCheck(requiredPermission string, throwError bool) *permissionCheck {
|
||||
return &permissionCheck{
|
||||
requiredPermission: requiredPermission,
|
||||
throwError: throwError,
|
||||
}
|
||||
}
|
||||
|
||||
var _ Condition = (*permissionCheck)(nil)
|
||||
|
||||
@@ -10,6 +10,10 @@ import (
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
const (
|
||||
ZIT01 = "ZIT01" // custom error code to express missing permissions by the end-user
|
||||
)
|
||||
|
||||
func wrapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
@@ -54,6 +58,9 @@ func wrapPgError(err *pgconn.PgError) error {
|
||||
// 22P02: integrity violation - A value is being inserted into a enum that is not valid
|
||||
case "22P02":
|
||||
return database.NewCheckError(err.TableName, err.ConstraintName, err)
|
||||
// ZIT01: missing permissions by the end-user
|
||||
case ZIT01:
|
||||
return database.NewPermissionError(err)
|
||||
default:
|
||||
return database.NewUnknownError(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
var (
|
||||
//go:embed 017_archived_sessions_table/up.sql
|
||||
up017ArchivedSessionsTable string
|
||||
//go:embed 017_archived_sessions_table/down.sql
|
||||
down017ArchivedSessionsTable string
|
||||
)
|
||||
|
||||
func init() {
|
||||
registerSQLMigration(17, up017ArchivedSessionsTable, down017ArchivedSessionsTable)
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
DROP TRIGGER IF EXISTS trg_move_to_archived_sessions ON zitadel.sessions;
|
||||
DROP FUNCTION IF EXISTS zitadel.move_to_archived_sessions() CASCADE;
|
||||
DROP TABLE IF EXISTS zitadel.archived_sessions CASCADE;
|
||||
DROP FUNCTION IF EXISTS zitadel.throw_not_permitted();
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
CREATE TABLE zitadel.archived_sessions (
|
||||
instance_id TEXT NOT NULL
|
||||
, id TEXT NOT NULL CHECK (id <> '')
|
||||
, token_id TEXT
|
||||
, user_agent_id TEXT
|
||||
, expiration TIMESTAMPTZ
|
||||
, user_id TEXT
|
||||
, creator_id TEXT
|
||||
, deleted_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
|
||||
|
||||
, PRIMARY KEY (instance_id, id)
|
||||
, FOREIGN KEY (instance_id) REFERENCES zitadel.instances(id)
|
||||
, FOREIGN KEY (instance_id, user_id) REFERENCES zitadel.users(instance_id, id) ON DELETE CASCADE
|
||||
, FOREIGN KEY (instance_id, user_agent_id) REFERENCES zitadel.session_user_agents(instance_id, fingerprint_id) ON DELETE SET NULL (user_agent_id)
|
||||
);
|
||||
|
||||
CREATE OR REPLACE FUNCTION zitadel.move_to_archived_sessions() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
INSERT INTO zitadel.archived_sessions (instance_id, id, token_id, user_agent_id, expiration, user_id, creator_id, deleted_at)
|
||||
VALUES (OLD.instance_id, OLD.id, OLD.token_id, OLD.user_agent_id, OLD.expiration, OLD.user_id, OLD.creator_id, now());
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER trg_move_to_archived_sessions
|
||||
AFTER DELETE ON zitadel.sessions
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION zitadel.move_to_archived_sessions();
|
||||
|
||||
-- placeholder for permissions, will be replaced by actual permission checks in the future,
|
||||
-- respectively will be used to fallback to when permissions are not yet implemented for a specific action
|
||||
CREATE OR REPLACE FUNCTION zitadel.throw_not_permitted() returns boolean AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'Permission denied: User does not have permission'
|
||||
USING ERRCODE = 'ZIT01';
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
@@ -272,3 +272,26 @@ func (e *UnknownError) Is(target error) bool {
|
||||
func (e *UnknownError) Unwrap() error {
|
||||
return e.original
|
||||
}
|
||||
|
||||
type PermissionError struct {
|
||||
original error
|
||||
}
|
||||
|
||||
func NewPermissionError(original error) error {
|
||||
return &PermissionError{
|
||||
original: original,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *PermissionError) Error() string {
|
||||
return fmt.Sprintf("permission error: %v", e.original)
|
||||
}
|
||||
|
||||
func (e *PermissionError) Is(target error) bool {
|
||||
_, ok := target.(*PermissionError)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (e *PermissionError) Unwrap() error {
|
||||
return e.original
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package database
|
||||
|
||||
import "database/sql"
|
||||
|
||||
// Null is a type alias for sql.Null[T] to avoid importing the sql package into repositories.
|
||||
type Null[T any] = sql.Null[T]
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user