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
+22
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
@@ -30,3 +31,24 @@ func SessionTokenVerifier(algorithm crypto.EncryptionAlgorithm) func(ctx context
return nil
}
}
func SessionTokenDecryptor(algorithm crypto.EncryptionAlgorithm) func(ctx context.Context, sessionToken string) (sessionID, tokenID string, err error) {
return func(ctx context.Context, sessionToken string) (sessionID, tokenID string, err error) {
decodedToken, err := base64.RawURLEncoding.DecodeString(sessionToken)
if err != nil {
return "", "", zerrors.ThrowInvalidArgument(err, "AUTHZ-hi6Ph", "Errors.Session.Token.Invalid")
}
_, spanPasswordComparison := tracing.NewNamedSpan(ctx, "crypto.CompareHash")
token, err := algorithm.DecryptString(decodedToken, algorithm.EncryptionKeyID())
spanPasswordComparison.EndWithError(err)
if err != nil {
return "", "", zerrors.ThrowPermissionDenied(err, "AUTHZ-sGr42", "Errors.Session.Token.Invalid")
}
n, err := fmt.Sscanf(strings.ReplaceAll(token, ":", " "), strings.ReplaceAll(SessionTokenFormat, ":", " "), &sessionID, &tokenID)
if err != nil || n != 2 {
return "", "", zerrors.ThrowInvalidArgument(err, "AUTHZ-3uike", "Errors.Session.Token.Invalid")
}
return sessionID, tokenID, nil
}
}
@@ -21,6 +21,7 @@ import (
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/internal/integration/sink"
"github.com/zitadel/zitadel/pkg/grpc/feature/v2"
mgmt "github.com/zitadel/zitadel/pkg/grpc/management"
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
"github.com/zitadel/zitadel/pkg/grpc/session/v2"
@@ -897,95 +898,150 @@ func TestServer_SetSession_expired(t *testing.T) {
}
func TestServer_DeleteSession_token(t *testing.T) {
createResp, err := Client.CreateSession(LoginCTX, &session.CreateSessionRequest{})
require.NoError(t, err)
sysAuthZ := integration.WithSystemAuthorization(CTX)
_, err = Client.DeleteSession(CTX, &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
SessionToken: gu.Ptr("invalid"),
})
require.Error(t, err)
relTableState := integration.RelationalTablesEnableMatrix(t, IAMOwnerCTX, sysAuthZ)
for _, stateCase := range relTableState {
t.Run(stateCase.Name, func(t *testing.T) {
loginCTX := stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeLogin)
createResp, err := stateCase.Inst.Client.SessionV2.CreateSession(loginCTX, &session.CreateSessionRequest{})
require.NoError(t, err)
_, err = Client.DeleteSession(CTX, &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
SessionToken: gu.Ptr(createResp.GetSessionToken()),
})
require.NoError(t, err)
//TODO: remove after create session also uses the relational tables directly
if stateCase.Enabled {
time.Sleep(5 * time.Second)
}
_, err = stateCase.Inst.Client.SessionV2.DeleteSession(stateCase.InstOwner, &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
SessionToken: gu.Ptr("invalid"),
})
require.Error(t, err)
_, err = stateCase.Inst.Client.SessionV2.DeleteSession(stateCase.InstOwner, &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
SessionToken: gu.Ptr(createResp.GetSessionToken()),
})
require.NoError(t, err)
})
}
}
func TestServer_DeleteSession_own_session(t *testing.T) {
// create two users for the test and a session each to get tokens for authorization
user1 := Instance.CreateHumanUser(CTX)
Instance.SetUserPassword(CTX, user1.GetUserId(), integration.UserPassword, false)
_, token1, _, _ := Instance.CreatePasswordSession(t, LoginCTX, user1.GetUserId(), integration.UserPassword)
sysAuthZ := integration.WithSystemAuthorization(CTX)
user2 := Instance.CreateHumanUser(CTX)
Instance.SetUserPassword(CTX, user2.GetUserId(), integration.UserPassword, false)
_, token2, _, _ := Instance.CreatePasswordSession(t, LoginCTX, user2.GetUserId(), integration.UserPassword)
relTableState := integration.RelationalTablesEnableMatrix(t, IAMOwnerCTX, sysAuthZ)
for _, stateCase := range relTableState {
t.Run(stateCase.Name, func(t *testing.T) {
loginCTX := stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeLogin)
// create two users for the test and a session each to get tokens for authorization
user1 := stateCase.Inst.CreateUserTypeHuman(stateCase.InstOwner, integration.Email())
stateCase.Inst.SetUserPassword(stateCase.InstOwner, user1.GetId(), integration.UserPassword, false)
_, token1, _, _ := stateCase.Inst.CreatePasswordSession(t, loginCTX, user1.GetId(), integration.UserPassword)
// create a new session for the first user
createResp, err := Client.CreateSession(LoginCTX, &session.CreateSessionRequest{
Checks: &session.Checks{
User: &session.CheckUser{
Search: &session.CheckUser_UserId{
UserId: user1.GetUserId(),
user2 := stateCase.Inst.CreateUserTypeHuman(stateCase.InstOwner, integration.Email())
stateCase.Inst.SetUserPassword(stateCase.InstOwner, user2.GetId(), integration.UserPassword, false)
_, token2, _, _ := stateCase.Inst.CreatePasswordSession(t, loginCTX, user2.GetId(), integration.UserPassword)
// create a new session for the first user
createResp, err := stateCase.Inst.Client.SessionV2.CreateSession(loginCTX, &session.CreateSessionRequest{
Checks: &session.Checks{
User: &session.CheckUser{
Search: &session.CheckUser_UserId{
UserId: user1.GetId(),
},
},
},
},
},
})
require.NoError(t, err)
})
require.NoError(t, err)
// delete the new (user1) session must not be possible with user (has no permission)
_, err = Client.DeleteSession(integration.WithAuthorizationToken(context.Background(), token2), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
})
require.Error(t, err)
//TODO: remove after create session also uses the relational tables directly
if stateCase.Enabled {
time.Sleep(5 * time.Second)
}
// delete the new (user1) session by themselves
_, err = Client.DeleteSession(integration.WithAuthorizationToken(context.Background(), token1), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
})
require.NoError(t, err)
// delete the new (user1) session must not be possible with user (has no permission)
_, err = stateCase.Inst.Client.SessionV2.DeleteSession(integration.WithAuthorizationToken(t.Context(), token2), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
})
require.Error(t, err)
// delete the new (user1) session by themselves
_, err = stateCase.Inst.Client.SessionV2.DeleteSession(integration.WithAuthorizationToken(t.Context(), token1), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
})
require.NoError(t, err)
})
}
}
func TestServer_DeleteSession_with_permission(t *testing.T) {
createResp, err := Client.CreateSession(LoginCTX, &session.CreateSessionRequest{
Checks: &session.Checks{
User: &session.CheckUser{
Search: &session.CheckUser_UserId{
UserId: User.GetUserId(),
},
},
},
})
require.NoError(t, err)
sysAuthZ := integration.WithSystemAuthorization(CTX)
// delete the new session by ORG_OWNER
_, err = Client.DeleteSession(Instance.WithAuthorization(context.Background(), integration.UserTypeOrgOwner), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
})
require.NoError(t, err)
relTableState := integration.RelationalTablesEnableMatrix(t, IAMOwnerCTX, sysAuthZ)
for _, stateCase := range relTableState {
t.Run(stateCase.Name, func(t *testing.T) {
loginCTX := stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeLogin)
user1 := stateCase.Inst.CreateUserTypeHuman(stateCase.InstOwner, integration.Email())
createResp, err := stateCase.Inst.Client.SessionV2.CreateSession(loginCTX, &session.CreateSessionRequest{
Checks: &session.Checks{
User: &session.CheckUser{
Search: &session.CheckUser_UserId{
UserId: user1.GetId(),
},
},
},
})
require.NoError(t, err)
if stateCase.Enabled {
t.Skip("TODO: remove after permission checks are implemented in the relational tables")
}
// delete the new session by ORG_OWNER
_, err = stateCase.Inst.Client.SessionV2.DeleteSession(
stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeOrgOwner),
&session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
},
)
require.NoError(t, err)
})
}
}
func TestServer_DeleteSession_expired(t *testing.T) {
createResp, err := Client.CreateSession(LoginCTX, &session.CreateSessionRequest{
Lifetime: durationpb.New(5 * time.Second),
t.Cleanup(func() {
_, err := Instance.Client.FeatureV2.ResetInstanceFeatures(IAMOwnerCTX, &feature.ResetInstanceFeaturesRequest{})
require.NoError(t, err)
})
require.NoError(t, err)
sysAuthZ := integration.WithSystemAuthorization(CTX)
// wait until the token expires
time.Sleep(10 * time.Second)
_, err = Client.DeleteSession(Instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
SessionToken: gu.Ptr(createResp.GetSessionToken()),
})
require.NoError(t, err)
relTableState := integration.RelationalTablesEnableMatrix(t, IAMOwnerCTX, sysAuthZ)
// get session should return an error
sessionResp, err := Client.GetSession(Instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner),
&session.GetSessionRequest{SessionId: createResp.GetSessionId()})
require.Error(t, err)
require.Nil(t, sessionResp)
for _, stateCase := range relTableState {
t.Run(stateCase.Name, func(t *testing.T) {
loginCTX := stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeLogin)
createResp, err := stateCase.Inst.Client.SessionV2.CreateSession(loginCTX, &session.CreateSessionRequest{
Lifetime: durationpb.New(5 * time.Second),
})
require.NoError(t, err)
// wait until the token expires
time.Sleep(10 * time.Second)
_, err = stateCase.Inst.Client.SessionV2.DeleteSession(stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeOrgOwner), &session.DeleteSessionRequest{
SessionId: createResp.GetSessionId(),
SessionToken: gu.Ptr(createResp.GetSessionToken()),
})
require.NoError(t, err)
// get session should return an error
sessionResp, err := stateCase.Inst.Client.SessionV2.GetSession(stateCase.Inst.WithAuthorizationToken(t.Context(), integration.UserTypeOrgOwner),
&session.GetSessionRequest{SessionId: createResp.GetSessionId()})
require.Error(t, err)
require.Nil(t, sessionResp)
})
}
}
func Test_ZITADEL_API_missing_authentication(t *testing.T) {
+6
View File
@@ -10,6 +10,8 @@ import (
"golang.org/x/text/language"
"google.golang.org/protobuf/types/known/structpb"
sessionv2 "github.com/zitadel/zitadel/backend/v3/api/session/v2"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
@@ -63,6 +65,10 @@ func (s *Server) SetSession(ctx context.Context, req *connect.Request[session.Se
}
func (s *Server) DeleteSession(ctx context.Context, req *connect.Request[session.DeleteSessionRequest]) (*connect.Response[session.DeleteSessionResponse], error) {
if authz.GetFeatures(ctx).EnableRelationalTables {
return sessionv2.DeleteSession(ctx, req)
}
details, err := s.command.TerminateSession(ctx, req.Msg.GetSessionId(), req.Msg.GetSessionToken())
if err != nil {
return nil, err
+12
View File
@@ -16,6 +16,8 @@ import (
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/oidc/v3/pkg/op"
zdomain "github.com/zitadel/zitadel/backend/v3/domain"
"github.com/zitadel/zitadel/backend/v3/storage/database/repository"
"github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/http/middleware"
@@ -350,6 +352,16 @@ func (o *OPStorage) TerminateSessionFromRequest(ctx context.Context, endSessionR
// V2:
// Terminate the v2 session of the id_token_hint
if authz.GetFeatures(ctx).EnableRelationalTables {
if err := zdomain.Invoke(
ctx,
zdomain.NewDeleteSessionCommand(endSessionRequest.IDTokenHintClaims.SessionID, "", false),
zdomain.WithSessionRepo(repository.SessionRepository()),
); err != nil {
return "", err
}
return v2PostLogoutRedirectURI(endSessionRequest.RedirectURI), nil
}
_, err = o.command.TerminateSessionWithoutTokenCheck(ctx, endSessionRequest.IDTokenHintClaims.SessionID)
if err != nil {
return "", err