mirror of
https://github.com/andwati/zitadel.git
synced 2026-10-24 00:02:15 +00:00
# Which Problems Are Solved #12313 lets clients register themselves as OIDC applications (RFC 7591), but a dynamically registered client has no way to manage itself afterwards: - The registration response returns no `registration_access_token` and no `registration_client_uri`, which RFC 7591 and 7592 clients (including the MCP SDKs) expect in order to manage their own registration. - There is no way to read back, update or delete a registration without an operator acting on the client's behalf through the Console or the Management API. A client that needs to rotate a redirect URI has to ask a human. # How the Problems Are Solved Implement the [OAuth 2.0 Dynamic Client Registration Management Protocol (RFC 7592)](https://datatracker.ietf.org/doc/html/rfc7592): `GET`, `PUT` and `DELETE` on `/oauth/v2/register/{client_id}`, wired through the same `op.WithSetRouter` hook as the registration endpoint. ## Control plane: the same security settings, no new switch The management endpoints are gated on the `DynamicClientRegistrationSettings.enabled` introduced in #12313. No new setting, no feature flag: a client that may register may manage what it registered. When registration is disabled the endpoints answer `404`, exactly as `POST /oauth/v2/register` does. `allow_unauthenticated` selects the registration mode and does not apply here, because the registration access token authorizes these endpoints in both modes. ## Authorization: the registration access token, and nothing else RFC 7592 §3 defines the credential as the registration access token issued at registration and bound to a single client, not a user credential. So a client manages only itself, proving it with the token it was handed: | | Registration (`POST`) | Management (`GET` / `PUT` / `DELETE`) | | --- | --- | --- | | Credential | Access token, or none in open mode | Registration access token | | Permission | `project.app.register_dynamic` in token mode | None | Neither `project.app.register_dynamic`, which governs who may *create* clients, nor `project.app.write` applies to the management endpoints. One authorization path per endpoint is easier to reason about than two, and there is no user identity to check against in the first place. Operators keep managing dynamically registered clients through the Management API and the Console, like any other application; they cannot obtain a client's registration access token, by design. Status codes: a missing, malformed or non matching token is `401`; a client that no longer exists is `404`. The token's `client_id` is checked against the path before any lookup, so a token bound to another client is rejected without touching the database. ## The token itself - **Stored like a client secret.** Only its passwap hash is persisted, through a new `project.application.config.oidc.registration_token.changed` event; the plain token leaves the server exactly once, in the response that issues it. - **Bound to its client and organization** through authenticated encryption with the instance key, the same mechanism as refresh tokens. The opaque token handed to the client encrypts `client_id:org_id:secret`, so the endpoint recovers the binding before checking the secret against the stored hash. - **Verified in O(1)** against the hash on the projection, folded into the client lookup the handler already does, with a strongly consistent fallback to the eventstore so a token that was just rotated is accepted before it is projected. - **Rotated on update** (RFC 7592 §4.4) and invalidated implicitly when the client is deleted. A read does not rotate it. Every update rotates, including one that changes no metadata, so a client always gets a usable token back. ## Reusing the existing persistence A small refactor extracts the shared OIDC application creation and update logic (`pushOIDCApplication` gains a variadic `extraEvents`, and `oidcApplicationChangeEvent` is lifted out of `UpdateOIDCApplication`), so the dynamic commands reuse it without the permission check. The registration token event is pushed atomically with the application, so a registered client is never left unmanageable. # Additional Changes - Setup step **74** adds the `registration_token` column to the `apps7_oidc_configs` projection, with a reducer for the new event modelled on the client secret. Applications are not part of the relational storage projection, so there is no second write path to keep in sync. - The registration response (`POST`) now also carries `registration_access_token` and `registration_client_uri`. - Docs: a "Manage a registration" section in the dynamic client registration guide covering the three operations, the authorization model, token rotation and the new limitations, plus the management endpoints on the OIDC endpoints page. - Unit tests for the command layer (issue, verify, rotate, update, delete), the projection reducer, and the token binding and response mapping. An integration test covers the full lifecycle (register, read, update with rotation, delete, read again with `404`), a token bound to another client, and the endpoints not being served when registration is disabled. None of the integration calls carries a user access token, which pins down that the management endpoints require no permission of their own. # Additional Context - Part of the MCP authorization effort in #9810. Follow-up to #12313 (RFC 7591), which is now merged; this branch has been rebased on `main` and carries the settings and authorization model agreed there. - **Open question for the review**: the authorization model above (registration access token only, no operator path through these endpoints) is the one I proposed when #12313 was reviewed, but it was never explicitly confirmed. If you would rather have `project.app.write` also grant access to a client in the operator's own organization, that is a contained change in `authorizeClientManagement`. - Rotation is eventually consistent: right after an update the previous token may keep working for a brief moment until the rotation is projected, while the new token works immediately through the eventstore fallback. This matches how ZITADEL validates access tokens, where revocation is likewise eventually consistent. It is documented in the guide and asserted as such in the integration test. - A database migration is introduced for the new projection column. No proto change and no new feature flag. - Verified locally: full build, `go vet` including `-tags integration`, `golangci-lint` with 0 issues, and the unit suites for every touched package. As before, I cannot run the integration suite here, so CI remains the check on it.
169 lines
7.1 KiB
Go
169 lines
7.1 KiB
Go
//go:build integration
|
|
|
|
package oidc_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/zitadel/zitadel/internal/integration"
|
|
)
|
|
|
|
// TestServer_DynamicClientRegistration_Management covers the OAuth 2.0 Dynamic Client
|
|
// Registration Management Protocol (RFC 7592): read, update and delete of a dynamically
|
|
// registered client, authenticated with the registration access token issued at registration.
|
|
//
|
|
// The registration access token is the only credential involved: none of the calls below
|
|
// carries a user access token, so the test also pins down that the management endpoints
|
|
// require no permission of their own.
|
|
func TestServer_DynamicClientRegistration_Management(t *testing.T) {
|
|
// Open registration, so the client below can register itself without a token; the
|
|
// management endpoints are gated on Enabled alone.
|
|
enableDynamicClientRegistration(t, CTXIAM, Instance, true)
|
|
|
|
issuer := Instance.OIDCIssuer()
|
|
|
|
status, reg := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"client_name": "lifecycle client",
|
|
"redirect_uris": []string{redirectURI},
|
|
"token_endpoint_auth_method": "none",
|
|
})
|
|
require.Equal(t, http.StatusCreated, status)
|
|
clientID, _ := reg["client_id"].(string)
|
|
require.NotEmpty(t, clientID)
|
|
token, _ := reg["registration_access_token"].(string)
|
|
require.NotEmpty(t, token)
|
|
clientURI, _ := reg["registration_client_uri"].(string)
|
|
require.Equal(t, issuer+"/oauth/v2/register/"+clientID, clientURI)
|
|
|
|
// The client and its dedicated project were just created, so wait for the projection to
|
|
// catch up before the first read.
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(CTX, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
getStatus, body := manageDynamicClient(t, http.MethodGet, clientURI, token, nil)
|
|
assert.Equal(tt, http.StatusOK, getStatus)
|
|
assert.Equal(tt, clientID, body["client_id"])
|
|
assert.Equal(tt, []any{redirectURI}, body["redirect_uris"])
|
|
// A read does not rotate the token, so it is not returned again.
|
|
assert.Empty(tt, body["registration_access_token"])
|
|
}, retryDuration, tick, "registered client not readable")
|
|
|
|
t.Run("missing or wrong registration access token is unauthorized", func(t *testing.T) {
|
|
noToken, _ := manageDynamicClient(t, http.MethodGet, clientURI, "", nil)
|
|
assert.Equal(t, http.StatusUnauthorized, noToken)
|
|
|
|
wrongToken, _ := manageDynamicClient(t, http.MethodGet, clientURI, token+"tampered", nil)
|
|
assert.Equal(t, http.StatusUnauthorized, wrongToken)
|
|
})
|
|
|
|
var rotatedToken string
|
|
t.Run("update replaces metadata and rotates the token", func(t *testing.T) {
|
|
putStatus, body := manageDynamicClient(t, http.MethodPut, clientURI, token, map[string]any{
|
|
"redirect_uris": []string{redirectURI + "/updated"},
|
|
"token_endpoint_auth_method": "none",
|
|
})
|
|
require.Equal(t, http.StatusOK, putStatus)
|
|
assert.Equal(t, clientID, body["client_id"])
|
|
assert.Equal(t, []any{redirectURI + "/updated"}, body["redirect_uris"])
|
|
rotatedToken, _ = body["registration_access_token"].(string)
|
|
require.NotEmpty(t, rotatedToken)
|
|
assert.NotEqual(t, token, rotatedToken)
|
|
})
|
|
|
|
t.Run("the previous token is eventually rejected after rotation", func(t *testing.T) {
|
|
// Rotation invalidates the previous token, but verification is served from the
|
|
// eventually consistent projection (the new token is accepted immediately through a
|
|
// strongly consistent fallback). The previous token therefore stops working once the
|
|
// rotation has been projected.
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(CTX, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
oldStatus, _ := manageDynamicClient(t, http.MethodGet, clientURI, token, nil)
|
|
assert.Equal(tt, http.StatusUnauthorized, oldStatus)
|
|
}, retryDuration, tick, "previous token still accepted after rotation")
|
|
})
|
|
|
|
t.Run("read reflects the update with the rotated token", func(t *testing.T) {
|
|
// The update is read back from the projection, which is eventually consistent, so
|
|
// retry until the changed redirect_uris show up.
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(CTX, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
getStatus, body := manageDynamicClient(t, http.MethodGet, clientURI, rotatedToken, nil)
|
|
assert.Equal(tt, http.StatusOK, getStatus)
|
|
assert.Equal(tt, []any{redirectURI + "/updated"}, body["redirect_uris"])
|
|
}, retryDuration, tick, "update not reflected in read")
|
|
})
|
|
|
|
t.Run("a token bound to another client is rejected", func(t *testing.T) {
|
|
_, other := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"redirect_uris": []string{redirectURI},
|
|
"token_endpoint_auth_method": "none",
|
|
})
|
|
otherURI, _ := other["registration_client_uri"].(string)
|
|
require.NotEmpty(t, otherURI)
|
|
// Using the first client's token against another client's endpoint must be rejected
|
|
// before any lookup: the token's client_id does not match the path.
|
|
status, _ := manageDynamicClient(t, http.MethodGet, otherURI, rotatedToken, nil)
|
|
assert.Equal(t, http.StatusUnauthorized, status)
|
|
})
|
|
|
|
t.Run("delete removes the client", func(t *testing.T) {
|
|
delStatus, _ := manageDynamicClient(t, http.MethodDelete, clientURI, rotatedToken, nil)
|
|
require.Equal(t, http.StatusNoContent, delStatus)
|
|
|
|
// After deletion the client is gone; wait for the projection to catch up.
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(CTX, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
getStatus, _ := manageDynamicClient(t, http.MethodGet, clientURI, rotatedToken, nil)
|
|
assert.Equal(tt, http.StatusNotFound, getStatus)
|
|
}, retryDuration, tick, "client still readable after deletion")
|
|
})
|
|
}
|
|
|
|
// TestServer_DynamicClientRegistration_Management_disabled verifies that the management
|
|
// endpoints are not served on an instance where dynamic client registration is disabled,
|
|
// which is the default.
|
|
func TestServer_DynamicClientRegistration_Management_disabled(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
defer cancel()
|
|
instance := integration.NewInstance(ctx)
|
|
issuer := instance.OIDCIssuer()
|
|
|
|
status, _ := manageDynamicClient(t, http.MethodGet, issuer+"/oauth/v2/register/whatever", "sometoken", nil)
|
|
assert.Equal(t, http.StatusNotFound, status)
|
|
}
|
|
|
|
func manageDynamicClient(t testing.TB, method, uri, token string, body map[string]any) (int, map[string]any) {
|
|
t.Helper()
|
|
var reader io.Reader
|
|
if body != nil {
|
|
raw, err := json.Marshal(body)
|
|
require.NoError(t, err)
|
|
reader = bytes.NewReader(raw)
|
|
}
|
|
req, err := http.NewRequest(method, uri, reader)
|
|
require.NoError(t, err)
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
resp, err := http.DefaultClient.Do(req)
|
|
require.NoError(t, err)
|
|
defer func() {
|
|
_, _ = io.Copy(io.Discard, resp.Body)
|
|
resp.Body.Close()
|
|
}()
|
|
var respBody map[string]any
|
|
_ = json.NewDecoder(resp.Body).Decode(&respBody)
|
|
return resp.StatusCode, respBody
|
|
}
|