mirror of
https://github.com/andwati/zitadel.git
synced 2026-10-22 23:42:16 +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.
236 lines
10 KiB
Go
236 lines
10 KiB
Go
package oidc
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/zitadel/oidc/v3/pkg/op"
|
|
|
|
"github.com/zitadel/zitadel/internal/api/authz"
|
|
"github.com/zitadel/zitadel/internal/query"
|
|
"github.com/zitadel/zitadel/internal/zerrors"
|
|
)
|
|
|
|
// getDynamicClientRegistration handles GET requests to the client configuration endpoint
|
|
// (RFC 7592 §2.1) and returns the current registration of the client. The read does not
|
|
// rotate the registration access token, so the response omits it; the client keeps the token
|
|
// it authenticated with.
|
|
func (s *Server) getDynamicClientRegistration(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
client, _, ok := s.authorizeClientManagement(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
resp := clientRegistrationResponseFromClient(client)
|
|
resp.RegistrationClientURI = s.registrationClientURI(ctx, client.ClientID)
|
|
s.writeRegistrationJSON(ctx, w, http.StatusOK, resp)
|
|
}
|
|
|
|
// updateDynamicClientRegistration handles PUT requests to the client configuration endpoint
|
|
// (RFC 7592 §2.2). It replaces the client metadata with the submitted values and rotates the
|
|
// registration access token, returning the updated registration with the new token.
|
|
func (s *Server) updateDynamicClientRegistration(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
client, binding, ok := s.authorizeClientManagement(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var req clientRegistrationRequest
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, registrationMaxBodyBytes)).Decode(&req); err != nil {
|
|
var maxBytesErr *http.MaxBytesError
|
|
if errors.As(err, &maxBytesErr) {
|
|
s.writeRegistrationJSON(ctx, w, http.StatusRequestEntityTooLarge, newRegistrationError(registrationErrorInvalidClientMetadata, "the request body is too large"))
|
|
return
|
|
}
|
|
s.writeRegistrationError(ctx, w, newRegistrationError(registrationErrorInvalidClientMetadata, "the request body could not be parsed"))
|
|
return
|
|
}
|
|
|
|
app, regErr := req.toOIDCApp()
|
|
if regErr != nil {
|
|
s.writeRegistrationError(ctx, w, regErr)
|
|
return
|
|
}
|
|
app.AggregateID = client.ProjectID
|
|
app.AppID = client.AppID
|
|
|
|
updated, err := s.command.UpdateDynamicOIDCClient(ctx, app, binding.orgID)
|
|
if err != nil {
|
|
s.writeManagementCommandError(ctx, w, err)
|
|
return
|
|
}
|
|
|
|
// The update response is a client information response (RFC 7592 §3); client_id_issued_at
|
|
// reflects the original registration, which is not echoed back here.
|
|
resp := newClientRegistrationResponse(updated, req.ClientName, 0)
|
|
resp.RegistrationAccessToken, err = s.registrationAccessToken(client.ClientID, binding.orgID, updated.RegistrationAccessToken)
|
|
if err != nil {
|
|
s.writeRegistrationServerError(ctx, w, err)
|
|
return
|
|
}
|
|
resp.RegistrationClientURI = s.registrationClientURI(ctx, client.ClientID)
|
|
s.writeRegistrationJSON(ctx, w, http.StatusOK, resp)
|
|
}
|
|
|
|
// deleteDynamicClientRegistration handles DELETE requests to the client configuration
|
|
// endpoint (RFC 7592 §2.3). It removes the client and answers with 204 No Content.
|
|
func (s *Server) deleteDynamicClientRegistration(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
client, binding, ok := s.authorizeClientManagement(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if _, err := s.command.RemoveDynamicOIDCClient(ctx, client.ProjectID, client.AppID, binding.orgID); err != nil {
|
|
s.writeManagementCommandError(ctx, w, err)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
w.Header().Set("Pragma", "no-cache")
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// registrationAccessTokenBinding holds the values recovered from a registration access token.
|
|
type registrationAccessTokenBinding struct {
|
|
clientID string
|
|
orgID string
|
|
secret string
|
|
}
|
|
|
|
// authorizeClientManagement performs the authorization shared by the RFC 7592 management
|
|
// endpoints. It requires dynamic client registration to be enabled in the instance's security
|
|
// settings, a registration access token that decrypts and is bound to the client_id in the
|
|
// path, an existing client, and a secret that matches the stored token hash. On any failure it
|
|
// writes the appropriate response (404 when registration is disabled or the client does not
|
|
// exist, 401 for token problems, 500 for an unexpected failure) and returns ok=false.
|
|
//
|
|
// The registration access token is the only authorization path here (RFC 7592 §3): it is
|
|
// issued at registration and bound to a single client, so a client manages only itself and
|
|
// needs no user permission. In particular neither project.app.register_dynamic, which gates
|
|
// who may create clients, nor project.app.write applies. Operators manage dynamically
|
|
// registered clients through the Management API and Console as they do any other application.
|
|
func (s *Server) authorizeClientManagement(w http.ResponseWriter, r *http.Request) (*query.OIDCClient, *registrationAccessTokenBinding, bool) {
|
|
ctx := r.Context()
|
|
if !authz.GetInstance(ctx).EnableDynamicClientRegistration() {
|
|
http.NotFound(w, r)
|
|
return nil, nil, false
|
|
}
|
|
|
|
clientID := chi.URLParam(r, "client_id")
|
|
token := bearerToken(r)
|
|
if token == "" {
|
|
s.writeRegistrationUnauthorized(ctx, w)
|
|
return nil, nil, false
|
|
}
|
|
binding, err := s.parseRegistrationAccessToken(token)
|
|
if err != nil || binding.clientID != clientID {
|
|
s.writeRegistrationUnauthorized(ctx, w)
|
|
return nil, nil, false
|
|
}
|
|
|
|
client, err := s.query.ActiveOIDCClientByID(ctx, clientID, false)
|
|
if err != nil {
|
|
// Only a genuinely absent client is a 404. An unexpected failure (a database
|
|
// problem, say) must not be reported as "this client does not exist", which would
|
|
// hide the incident from both the client and whoever is on call.
|
|
if !zerrors.IsNotFound(err) {
|
|
s.writeRegistrationServerError(ctx, w, err)
|
|
return nil, nil, false
|
|
}
|
|
s.writeRegistrationNotFound(ctx, w)
|
|
return nil, nil, false
|
|
}
|
|
if err = s.verifyRegistrationAccessToken(ctx, client, binding.orgID, binding.secret); err != nil {
|
|
// Same reasoning as above: only a token that does not match is a 401.
|
|
if !zerrors.IsUnauthenticated(err) {
|
|
s.writeRegistrationServerError(ctx, w, err)
|
|
return nil, nil, false
|
|
}
|
|
s.writeRegistrationUnauthorized(ctx, w)
|
|
return nil, nil, false
|
|
}
|
|
return client, binding, true
|
|
}
|
|
|
|
// verifyRegistrationAccessToken checks the presented registration access token secret against
|
|
// the client's stored token hash. The hash is served from the projection for an O(1) read on
|
|
// the common path; on a miss (most importantly a token that was just rotated and is not
|
|
// projected yet) it falls back to a strongly consistent read from the eventstore, so a rotated
|
|
// token is accepted immediately.
|
|
//
|
|
// A token that does not match is reported as unauthenticated; any other error is passed
|
|
// through unchanged so the caller can tell a rejected token from a failed lookup.
|
|
func (s *Server) verifyRegistrationAccessToken(ctx context.Context, client *query.OIDCClient, orgID, secret string) error {
|
|
if client.RegistrationTokenHash != "" {
|
|
if _, err := s.hasher.Verify(client.RegistrationTokenHash, secret); err == nil {
|
|
return nil
|
|
}
|
|
}
|
|
return s.command.VerifyDynamicClientRegistrationToken(ctx, client.ProjectID, client.AppID, orgID, secret)
|
|
}
|
|
|
|
// registrationAccessToken builds the opaque registration access token (RFC 7592 §3) handed to
|
|
// a client on registration and rotation. It binds the plain secret to the client and its
|
|
// organization through authenticated encryption with the instance key (the same mechanism as
|
|
// refresh tokens), so the management endpoints can recover the binding before checking the
|
|
// secret against the stored hash.
|
|
func (s *Server) registrationAccessToken(clientID, orgID, secret string) (string, error) {
|
|
return s.encAlg.EncryptToken(strings.Join([]string{clientID, orgID, secret}, ":"))
|
|
}
|
|
|
|
// parseRegistrationAccessToken decrypts a registration access token back into its binding.
|
|
func (s *Server) parseRegistrationAccessToken(token string) (*registrationAccessTokenBinding, error) {
|
|
plain, err := s.encAlg.DecryptToken(token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
parts := strings.SplitN(plain, ":", 3)
|
|
if len(parts) != 3 {
|
|
return nil, ErrInvalidTokenFormat
|
|
}
|
|
return ®istrationAccessTokenBinding{clientID: parts[0], orgID: parts[1], secret: parts[2]}, nil
|
|
}
|
|
|
|
// registrationClientURI builds the RFC 7592 §3 client configuration endpoint URL of a client.
|
|
func (s *Server) registrationClientURI(ctx context.Context, clientID string) string {
|
|
return op.IssuerFromContext(ctx) + s.registrationEndpoint.Relative() + "/" + clientID
|
|
}
|
|
|
|
func (s *Server) writeRegistrationNotFound(ctx context.Context, w http.ResponseWriter) {
|
|
s.writeRegistrationJSON(ctx, w, http.StatusNotFound, newRegistrationError("invalid_client", "the client does not exist or the registration access token is no longer valid"))
|
|
}
|
|
|
|
// writeManagementCommandError maps a command error from the update and delete endpoints. A
|
|
// client that no longer exists (a concurrent or retried delete, or a delete racing an update)
|
|
// is reported as 404, consistent with a read of a missing client; other errors fall back to
|
|
// the shared registration error mapping.
|
|
func (s *Server) writeManagementCommandError(ctx context.Context, w http.ResponseWriter, err error) {
|
|
if zerrors.IsNotFound(err) {
|
|
s.writeRegistrationNotFound(ctx, w)
|
|
return
|
|
}
|
|
s.writeRegistrationCommandError(ctx, w, err)
|
|
}
|
|
|
|
// clientRegistrationResponseFromClient maps a persisted OIDC client to an RFC 7592 read
|
|
// response. The client secret is not returned because only its hash is stored; the original
|
|
// client name and issuance time are likewise not persisted in this version.
|
|
func clientRegistrationResponseFromClient(client *query.OIDCClient) *clientRegistrationResponse {
|
|
return &clientRegistrationResponse{
|
|
ClientID: client.ClientID,
|
|
RedirectURIs: client.RedirectURIs,
|
|
ResponseTypes: responseTypesToRegistration(client.ResponseTypes),
|
|
GrantTypes: grantTypesToRegistration(client.GrantTypes),
|
|
ApplicationType: applicationTypeToRegistration(client.ApplicationType),
|
|
TokenEndpointAuthMethod: authMethodToRegistration(client.AuthMethodType),
|
|
PostLogoutRedirectURIs: client.PostLogoutRedirectURIs,
|
|
}
|
|
}
|