diff --git a/docs/docs/admin-journey/features/secret-rotation.md b/docs/docs/admin-journey/features/secret-rotation.md index 03b64f7cd..4b290d187 100644 --- a/docs/docs/admin-journey/features/secret-rotation.md +++ b/docs/docs/admin-journey/features/secret-rotation.md @@ -114,6 +114,13 @@ identity.cp.ei.telekom.de/disable-secret-rotation: "true" This is typically done by the platform team, not by application developers. +The annotation can be added at any time, including to clients that already took part in rotation. Shortly after you set it, the platform removes all rotation state from the client in Keycloak: + +- The current secret no longer expires. +- If a rotation grace period is still active, the **old secret stops working immediately**. Make sure all consumers use the current secret before you opt the client out. + +Removing the annotation opts the client back in. Keycloak then assigns a new expiration date to the current secret. + ## Operational Considerations - **Grace period sizing** — Choose a grace period long enough for teams to update all their consumers. Seven days is a common starting point. diff --git a/docs/docs/architecture/identity.mdx b/docs/docs/architecture/identity.mdx index 519760e99..9975ce021 100644 --- a/docs/docs/architecture/identity.mdx +++ b/docs/docs/architecture/identity.mdx @@ -18,7 +18,7 @@ When a Realm is configured with a `secretRotation` policy, the Identity domain p 2. A new secret is set as the primary credential 3. Both secrets are accepted until the grace period expires -Individual clients can opt out via the `identity.cp.ei.telekom.de/disable-secret-rotation: "true"` annotation. +Individual clients can opt out via the `identity.cp.ei.telekom.de/disable-secret-rotation: "true"` annotation. The annotation can also be added to an existing client. On the next reconciliation, the controller removes the opt-in attribute and all rotation state from the Keycloak client: the secret expiration time and any rotated secret. Keycloak would otherwise still expire the current secret and keep accepting the old one. The client's `SecretRotation` condition and rotation status fields are cleared. ### Realm Attributes diff --git a/identity/internal/handler/client/handler.go b/identity/internal/handler/client/handler.go index fa23cde25..80cb7794d 100644 --- a/identity/internal/handler/client/handler.go +++ b/identity/internal/handler/client/handler.go @@ -125,14 +125,13 @@ func shouldSkipForceRotation(client *identityv1.Client) bool { // syncRotationStatus updates client.Status rotation fields after a successful // CreateOrReplaceClient call. When supportsRotation is false it clears any -// stale fields left from a previous opt-in. +// stale fields and the SecretRotation condition left from a previous opt-in. func syncRotationStatus(ctx context.Context, client *identityv1.Client, realmClient keycloak.KeycloakService, realmName string, clientCopy *identityv1.Client, supportsRotation bool) error { if !supportsRotation { - // Rotation not supported (or was just disabled) — clear any stale - // rotation status fields from a previous opt-in. client.Status.RotatedClientSecret = "" client.Status.RotatedSecretExpiresAt = nil client.Status.SecretExpiresAt = nil + meta.RemoveStatusCondition(&client.Status.Conditions, identityv1.SecretRotationConditionType) return nil } diff --git a/identity/internal/handler/client/handler_test.go b/identity/internal/handler/client/handler_test.go index 2d410ddab..417c210b8 100644 --- a/identity/internal/handler/client/handler_test.go +++ b/identity/internal/handler/client/handler_test.go @@ -1089,6 +1089,7 @@ var _ = Describe("HandlerClient", func() { // Simulate a client that previously had rotation enabled and has stale status fields. cl.Status.RotatedClientSecret = "stale-old-secret" cl.Status.RotatedSecretExpiresAt = &metav1.Time{Time: time.Now()} + cl.SetCondition(identityv1.NewSecretRotatedCondition(time.Now())) realm := newValidRealm() overrideSecretsGet(func(_ context.Context, _ string) (string, error) { @@ -1115,6 +1116,7 @@ var _ = Describe("HandlerClient", func() { Expect(cl.Status.RotatedClientSecret).To(BeEmpty()) Expect(cl.Status.RotatedSecretExpiresAt).To(BeNil()) Expect(cl.Status.SecretExpiresAt).To(BeNil()) + Expect(meta.FindStatusCondition(cl.GetConditions(), identityv1.SecretRotationConditionType)).To(BeNil()) }) }) diff --git a/identity/pkg/keycloak/graceful_secrets.go b/identity/pkg/keycloak/graceful_secrets.go index df3ff7ee1..dbe695031 100644 --- a/identity/pkg/keycloak/graceful_secrets.go +++ b/identity/pkg/keycloak/graceful_secrets.go @@ -44,10 +44,10 @@ type SecretRotationParams struct { } const ( - attrSecretCreationTime = "client.secret.creation.time" - attrSecretExpirationTime = "client.secret.expiration.time" - attrRotatedCreationTime = "client.secret.rotated.creation.time" - attrRotatedExpirationTime = "client.secret.rotated.expiration.time" + attrSecretCreationTime = util.SecretCreationTimeAttribute + attrSecretExpirationTime = util.SecretExpirationTimeAttribute + attrRotatedCreationTime = util.RotatedSecretCreationTimeAttribute + attrRotatedExpirationTime = util.RotatedSecretExpirationTimeAttribute ) // GetSecretCreationTime extracts the epoch-seconds timestamp of the current diff --git a/identity/pkg/keycloak/keycloak_service_test.go b/identity/pkg/keycloak/keycloak_service_test.go index 5e3e4741b..93824ea8a 100644 --- a/identity/pkg/keycloak/keycloak_service_test.go +++ b/identity/pkg/keycloak/keycloak_service_test.go @@ -176,6 +176,34 @@ var _ = Describe("KeycloakService", func() { })).Return(&api.PutRealmClientsIdResponse{HTTPResponse: httpResp(204)}, nil) Expect(svc.CreateOrReplaceClient(ctx, "realm1", client, keycloak.ClientUpdateOptions{})).To(Succeed()) }) + It("should remove rotation attributes from Keycloak when rotation is disabled afterwards", func() { + client := newIdentityClient("my-app", "secret") + existing := util.MapToClientRepresentation(client) + existing.Id = ptr.To("existing-uid") + existing.Attributes = &map[string]interface{}{ + util.SecretRotationClientAttribute: "true", + util.SecretExpirationTimeAttribute: "1800000000", + util.RotatedSecretAttribute: "old-secret", + util.RotatedSecretCreationTimeAttribute: "1700000000", + } + client.Annotations = map[string]string{identityv1.DisableSecretRotationAnnotation: "true"} + + mockClient.EXPECT().GetRealmClientsWithResponse(mock.Anything, "realm1", mock.Anything). + Return(&api.GetRealmClientsResponse{HTTPResponse: httpResp(200), JSON2XX: &[]api.ClientRepresentation{existing}}, nil) + mockClient.EXPECT().PutRealmClientsIdWithResponse(mock.Anything, "realm1", "existing-uid", mock.MatchedBy(func(body api.ClientRepresentation) bool { + if body.Attributes == nil { + return false + } + attrs := *body.Attributes + return attrs[util.SecretRotationClientAttribute] == "" && + attrs[util.SecretExpirationTimeAttribute] == "" && + attrs[util.RotatedSecretAttribute] == "" && + attrs[util.RotatedSecretCreationTimeAttribute] == "" + })).Return(&api.PutRealmClientsIdResponse{HTTPResponse: httpResp(204)}, nil) + + Expect(svc.CreateOrReplaceClient(ctx, "realm1", client, keycloak.ClientUpdateOptions{})).To(Succeed()) + }) + It("should update existing client and set UID in status", func() { client := newIdentityClient("my-app", "new-secret") existing := api.ClientRepresentation{ diff --git a/identity/pkg/keycloak/util/client.go b/identity/pkg/keycloak/util/client.go index e16554844..6a8d35ea9 100644 --- a/identity/pkg/keycloak/util/client.go +++ b/identity/pkg/keycloak/util/client.go @@ -36,6 +36,28 @@ const ( stringTrue = "true" ) +// Client attributes written by Keycloak's secret-rotation executor. +const ( + SecretCreationTimeAttribute = "client.secret.creation.time" + SecretExpirationTimeAttribute = "client.secret.expiration.time" + SecretRemainingExpirationAttribute = "client.secret.remaining.expiration.time" + RotatedSecretAttribute = "client.secret.rotated" + RotatedSecretCreationTimeAttribute = "client.secret.rotated.creation.time" + RotatedSecretExpirationTimeAttribute = "client.secret.rotated.expiration.time" +) + +// secretRotationStateAttributes must be removed when a client opts out of +// rotation. Keycloak enforces them on every client authentication even when no +// rotation policy applies anymore: the current secret is rejected once +// client.secret.expiration.time has passed, and the rotated secret stays valid. +var secretRotationStateAttributes = []string{ + SecretExpirationTimeAttribute, + SecretRemainingExpirationAttribute, + RotatedSecretAttribute, + RotatedSecretCreationTimeAttribute, + RotatedSecretExpirationTimeAttribute, +} + func MapToClientRepresentation(client *identityv1.Client) api.ClientRepresentation { webOrigins := slices.Clone(client.Status.AllowedOrigins) rep := api.ClientRepresentation{ @@ -109,9 +131,36 @@ func compareWebOrigins(left, right *[]string) bool { // compareSecretRotationAttribute returns true when both representations agree // on the controlplane.secret-rotation attribute value. The attribute is -// considered "set" only when its value is the string "true". -func compareSecretRotationAttribute(a, b *api.ClientRepresentation) bool { - return getSecretRotationAttr(a) == getSecretRotationAttr(b) +// considered "set" only when its value is the string "true". When the desired +// client opted out of rotation, any leftover rotation state on the existing +// client counts as drift. +func compareSecretRotationAttribute(existing, desired *api.ClientRepresentation) bool { + if getSecretRotationAttr(existing) != getSecretRotationAttr(desired) { + return false + } + return getSecretRotationAttr(desired) == stringTrue || !hasSecretRotationState(existing) +} + +func hasSecretRotationState(c *api.ClientRepresentation) bool { + if c.Attributes == nil { + return false + } + for _, key := range secretRotationStateAttributes { + if isAttributeSet(*c.Attributes, key) { + return true + } + } + return false +} + +// isAttributeSet mirrors Keycloak, which treats empty values as absent. +func isAttributeSet(attrs map[string]interface{}, key string) bool { + v, ok := attrs[key] + if !ok || v == nil { + return false + } + s, isString := v.(string) + return !isString || s != "" } // getSecretRotationAttr returns "true" when the secret-rotation attribute is @@ -157,10 +206,25 @@ func MergeClientRepresentation(existingClient, newClient *api.ClientRepresentati existingClient.Attributes = &map[string]interface{}{} } (*existingClient.Attributes)[SecretRotationClientAttribute] = (*newClient.Attributes)[SecretRotationClientAttribute] - } else if existingClient.Attributes != nil { - // New client doesn't set the attribute — remove it from existing if present. - delete(*existingClient.Attributes, SecretRotationClientAttribute) + return existingClient } + clearSecretRotationAttributes(existingClient) return existingClient } + +// clearSecretRotationAttributes removes the opt-in attribute and the rotation +// state from a client that opted out of rotation. A Keycloak client PUT only +// updates the attributes it contains, so omitting a key keeps it; an empty +// value is what makes Keycloak remove the attribute. +func clearSecretRotationAttributes(c *api.ClientRepresentation) { + if c.Attributes == nil { + return + } + attrs := *c.Attributes + for _, key := range append([]string{SecretRotationClientAttribute}, secretRotationStateAttributes...) { + if _, ok := attrs[key]; ok { + attrs[key] = "" + } + } +} diff --git a/identity/pkg/keycloak/util/client_test.go b/identity/pkg/keycloak/util/client_test.go index a4501ea84..bc46d6c5e 100644 --- a/identity/pkg/keycloak/util/client_test.go +++ b/identity/pkg/keycloak/util/client_test.go @@ -156,12 +156,17 @@ func TestMergeClientRepresentation_PreservesExistingAttributes(t *testing.T) { } } -func TestMergeClientRepresentation_RemovesAttributeWhenDesiredHasNone(t *testing.T) { +func TestMergeClientRepresentation_ClearsRotationAttributesWhenDesiredHasNone(t *testing.T) { existing := &api.ClientRepresentation{ ClientId: ptr.To("my-app"), Attributes: &map[string]interface{}{ - SecretRotationClientAttribute: "true", - "other-attr": "keep-me", + SecretRotationClientAttribute: "true", + SecretCreationTimeAttribute: "1700000000", + SecretExpirationTimeAttribute: "1800000000", + RotatedSecretAttribute: "old-secret", + RotatedSecretCreationTimeAttribute: "1700000000", + RotatedSecretExpirationTimeAttribute: "1700600000", + "other-attr": "keep-me", }, } desired := &api.ClientRepresentation{ @@ -172,10 +177,51 @@ func TestMergeClientRepresentation_RemovesAttributeWhenDesiredHasNone(t *testing merged := MergeClientRepresentation(existing, desired) attrs := *merged.Attributes - if _, ok := attrs[SecretRotationClientAttribute]; ok { - t.Fatal("secret-rotation attribute should have been removed") + // Keycloak ignores omitted keys on PUT and removes keys with empty values. + for _, key := range []string{ + SecretRotationClientAttribute, + SecretExpirationTimeAttribute, + RotatedSecretAttribute, + RotatedSecretCreationTimeAttribute, + RotatedSecretExpirationTimeAttribute, + } { + if v, ok := attrs[key]; !ok || v != "" { + t.Fatalf("expected attribute %q to be sent as empty value, got %v (present=%t)", key, v, ok) + } + } + if _, ok := attrs[SecretRemainingExpirationAttribute]; ok { + t.Fatal("absent attributes must not be added") + } + if attrs[SecretCreationTimeAttribute] != "1700000000" { + t.Fatal("secret creation time must be preserved") } if attrs["other-attr"] != "keep-me" { t.Fatal("unrelated attribute was removed") } + if !CompareClientRepresentation(merged, desired) { + t.Fatal("merged representation must converge with the desired one") + } +} + +func TestCompareClientRepresentation_DetectsLeftoverRotationStateWhenDisabled(t *testing.T) { + desired := &api.ClientRepresentation{ClientId: ptr.To("my-app")} + existing := &api.ClientRepresentation{ + ClientId: ptr.To("my-app"), + Attributes: &map[string]interface{}{ + SecretExpirationTimeAttribute: "1800000000", + }, + } + + if CompareClientRepresentation(existing, desired) { + t.Fatal("leftover secret expiration must count as drift when rotation is disabled") + } + + enabled := &api.ClientRepresentation{ + ClientId: ptr.To("my-app"), + Attributes: &map[string]interface{}{SecretRotationClientAttribute: "true"}, + } + (*existing.Attributes)[SecretRotationClientAttribute] = "true" + if !CompareClientRepresentation(existing, enabled) { + t.Fatal("rotation state is expected while rotation is enabled") + } }