mirror of
https://github.com/andwati/zitadel.git
synced 2026-10-23 07:52:15 +00:00
# Which Problems Are Solved ZITADEL cannot currently be used as an OAuth 2.0 Authorization Server by clients that need to register themselves at runtime: - There is no [OAuth 2.0 Dynamic Client Registration (RFC 7591)](https://datatracker.ietf.org/doc/html/rfc7591) endpoint, and no `registration_endpoint` is advertised in the discovery document. - This blocks [Model Context Protocol (MCP)](https://modelcontextprotocol.io) clients (Claude Desktop, claude.ai, Cursor, the MCP SDKs), whose OAuth 2.1 authorization profile expects an Authorization Server that supports dynamic client registration. They self-register before any user context exists and only then start the authorization code + PKCE flow. # How the Problems Are Solved ## Control plane: instance security settings No feature flag and no runtime config. A `DynamicClientRegistrationSettings` message is nested under the instance `SecuritySettings` in `settings/v2`, next to `embedded_iframe` and `enable_impersonation`: | `enabled` | `allow_unauthenticated` | Behaviour | | --- | --- | --- | | `false` (default) | — | `POST /oauth/v2/register` returns `404`, `registration_endpoint` absent from discovery | | `true` | `false` (default) | Token-gated registration, client homed in the token's organization | | `true` | `true` | Open registration for MCP hosts, client homed in the instance default organization | Both values are carried on `authz.Instance` and loaded with the instance, exactly like `EnableImpersonation`, so the discovery document and the endpoint read them per request without an extra query. `allow_unauthenticated` implies `enabled` in both implementations, so a single setting closes the endpoint. Adding the two columns bumps the projection table to `projections.security_policies3`, following what the impersonation setting did for `security_policies2`. ## Authorization: a dedicated permission, not `project.app.write` - New org-scoped permission **`project.app.register_dynamic`**, granted by default to `ORG_OWNER`, `IAM_OWNER` and `IAM_ORG_MANAGER` — in both `InternalAuthZ` and `SystemAuthZ`, mirroring where `project.app.write` already lives. - New built-in role **`ORG_DYNAMIC_CLIENT_REGISTRAR`** carrying only that permission, so a service user can self-register clients without gaining write access to the organization's existing applications. - Open mode (`allow_unauthenticated = true`) requires no token and no permission: that is the MCP self-register path. - A valid token whose user lacks the permission is answered with **`403 insufficient_scope`** (RFC 6750 §3.1) rather than `401 invalid_token`, so a caller can tell "your token is bad" from "your token may not do this". `verifyAccessToken` also reports invalid tokens as permission denied, so the authorization failure is marked explicitly to keep the two apart. The check runs once, at the endpoint, right after the token is verified and before any state is created, so it also gates the auto-provisioning of the organization's DCR project. The permission itself lives in the command layer next to the others (`Commands.CheckPermissionRegisterDynamicClient`). As the OIDC endpoints are not behind the authorization interceptor, the caller identity is derived from the verified token, the way token exchange does for the impersonating actor. ## Registration itself - **Registered clients are ordinary OIDC applications.** The endpoint reuses the existing application-creation events (`NewApplicationAddedEvent` and `NewOIDCConfigAddedEvent`), so the whole token, authorization and introspection flow keeps working unchanged. They are stored in a dedicated, auto-provisioned project named `ZITADEL DCR` per organization (name lookup), so they do not pollute the `IAMProject` or other projects. - Input is validated with the existing `GetOIDCV1Compliance` rules; `private_key_jwt` and `jwks`/`jwks_uri` are rejected with `invalid_client_metadata`. - **Endpoint wiring without forking the library.** `NewServer` calls `op.RegisterServer` instead of `op.RegisterLegacyServer`, so the new route can be added through the same `op.WithSetRouter` hook as the authorize callback. `op.RegisterLegacyServer` appends a middleware after the caller options, which chi forbids once a route has been registered; `op.NewIssuerInterceptor` reproduces the issuer middleware it would otherwise add. The `/oauth/v2` routing prefix is unchanged. # Additional Changes - **`application_type` inference for custom-scheme redirects** (last commit, isolated). `application_type` is an OpenID Connect member; RFC 7591 does not define it, so clients that only implement RFC 7591 omit it. Native MCP hosts doing so register custom-scheme redirect URIs, which ZITADEL reserves for native applications, and the OIDC default of `web` rejected them with `invalid_redirect_uri`. Inference is limited to custom schemes and to an absent `application_type`, so every request accepted today keeps its current application type and auth method — an `http` loopback redirect still yields a web application. Happy to drop this commit if you would rather keep it out of this PR. - **Docs**: a Dynamic Client Registration integration guide, a `registration_endpoint` section on the OpenID Connect endpoints page, and the new role in the administrators table (plus its description in the Console translations). # Additional Context - Part of #9810. This is **Phase 1 (DCR)**; #12315 adds RFC 7592 and #12316 adds CIMD, both stacked on this branch and rebased once this lands. - Implements the control-plane and authorization model requested in the review of this PR, itself a refinement of the direction in https://github.com/zitadel/zitadel/issues/9810#issuecomment-4891176997. - **Out of scope (deliberately)**: RFC 7592, CIMD, persisting free-form metadata (`logo_uri`, `contacts`, and similar), and `private_key_jwt` / `jwks_uri` (rejected cleanly). No new event types. - Follow-ups explicitly left out, per the review: DCR client lifecycle and richer audit, consent and custom scopes, JWT / `aud` (RFC 8707), and RFC 8414 AS metadata (currently absent from both ZITADEL and `zitadel/oidc`).
252 lines
9.8 KiB
Go
252 lines
9.8 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/oidc/v3/pkg/oidc"
|
|
|
|
"github.com/zitadel/zitadel/internal/domain"
|
|
"github.com/zitadel/zitadel/internal/integration"
|
|
oidc_pb "github.com/zitadel/zitadel/pkg/grpc/oidc/v2"
|
|
"github.com/zitadel/zitadel/pkg/grpc/settings/v2"
|
|
)
|
|
|
|
// TestServer_DynamicClientRegistration covers the OAuth 2.0 Dynamic Client Registration
|
|
// endpoint (RFC 7591) in open mode, where no access token is required.
|
|
func TestServer_DynamicClientRegistration(t *testing.T) {
|
|
issuer := Instance.OIDCIssuer()
|
|
enableDynamicClientRegistration(t, CTXIAM, Instance, true)
|
|
|
|
t.Run("discovery advertises the registration endpoint", func(t *testing.T) {
|
|
discovery := fetchDiscovery(t, issuer)
|
|
assert.Equal(t, issuer+"/oauth/v2/register", discovery.RegistrationEndpoint)
|
|
})
|
|
|
|
t.Run("public client without secret, usable for authorization code with PKCE", func(t *testing.T) {
|
|
status, body := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"client_name": "integration public client",
|
|
"redirect_uris": []string{redirectURI},
|
|
"token_endpoint_auth_method": "none",
|
|
})
|
|
require.Equal(t, http.StatusCreated, status)
|
|
clientID, _ := body["client_id"].(string)
|
|
require.NotEmpty(t, clientID)
|
|
assert.Empty(t, body["client_secret"])
|
|
|
|
// The returned client_id must be usable for an authorization code + PKCE flow.
|
|
// The client and its dedicated project were just created, so wait for the
|
|
// projection to catch up before starting the authorization flow.
|
|
var authRequestID string
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(CTX, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
_, id, err := Instance.CreateOIDCAuthRequest(CTX, clientID, Instance.Users.Get(integration.UserTypeLogin).ID, redirectURI, oidc.ScopeOpenID)
|
|
assert.NoError(tt, err)
|
|
authRequestID = id
|
|
}, retryDuration, tick, "registered client not usable for authorization")
|
|
|
|
sessionID, sessionToken, _, _ := Instance.CreateVerifiedWebAuthNSession(t, CTXLOGIN, User.GetUserId())
|
|
linkResp, err := Instance.Client.OIDCv2.CreateCallback(CTXLOGIN, &oidc_pb.CreateCallbackRequest{
|
|
AuthRequestId: authRequestID,
|
|
CallbackKind: &oidc_pb.CreateCallbackRequest_Session{
|
|
Session: &oidc_pb.Session{
|
|
SessionId: sessionID,
|
|
SessionToken: sessionToken,
|
|
},
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
code := assertCodeResponse(t, linkResp.GetCallbackUrl())
|
|
tokens, err := exchangeTokens(t, Instance, clientID, code, redirectURI)
|
|
require.NoError(t, err)
|
|
assert.NotEmpty(t, tokens.AccessToken)
|
|
|
|
// An Authorization header is always treated as a registration token, even with open
|
|
// registration enabled: the request must not fall back to anonymous registration.
|
|
// This token belongs to an ordinary user without project.app.register_dynamic, so
|
|
// it is rejected rather than silently registering a client.
|
|
tokenStatus, tokenBody := registerDynamicClient(t, issuer, tokens.AccessToken, map[string]any{
|
|
"client_name": "integration token-mode client",
|
|
"redirect_uris": []string{redirectURI},
|
|
})
|
|
require.Equal(t, http.StatusForbidden, tokenStatus)
|
|
assert.Equal(t, "insufficient_scope", tokenBody["error"])
|
|
assert.Empty(t, tokenBody["client_id"])
|
|
})
|
|
|
|
t.Run("confidential client returns a secret", func(t *testing.T) {
|
|
status, body := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"client_name": "integration confidential client",
|
|
"redirect_uris": []string{redirectURI},
|
|
"token_endpoint_auth_method": "client_secret_basic",
|
|
})
|
|
require.Equal(t, http.StatusCreated, status)
|
|
assert.NotEmpty(t, body["client_id"])
|
|
assert.NotEmpty(t, body["client_secret"])
|
|
})
|
|
|
|
t.Run("invalid redirect uri is rejected", func(t *testing.T) {
|
|
status, body := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"redirect_uris": []string{"myapp://callback"},
|
|
"application_type": "web",
|
|
})
|
|
assert.Equal(t, http.StatusBadRequest, status)
|
|
assert.Equal(t, "invalid_redirect_uri", body["error"])
|
|
})
|
|
|
|
t.Run("malformed request body is rejected", func(t *testing.T) {
|
|
req, err := http.NewRequest(http.MethodPost, issuer+"/oauth/v2/register", bytes.NewReader([]byte("{not valid json")))
|
|
require.NoError(t, err)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
|
})
|
|
|
|
t.Run("missing redirect uri is rejected", func(t *testing.T) {
|
|
status, body := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"client_name": "no redirects",
|
|
})
|
|
assert.Equal(t, http.StatusBadRequest, status)
|
|
assert.Equal(t, "invalid_redirect_uri", body["error"])
|
|
})
|
|
}
|
|
|
|
// TestServer_DynamicClientRegistration_tokenMode covers the default mode, where a caller
|
|
// must present an access token whose user holds project.app.register_dynamic in the token's
|
|
// organization.
|
|
func TestServer_DynamicClientRegistration_tokenMode(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
|
defer cancel()
|
|
instance := integration.NewInstance(ctx)
|
|
iamCTX := instance.WithAuthorization(ctx, integration.UserTypeIAMOwner)
|
|
issuer := instance.OIDCIssuer()
|
|
|
|
enableDynamicClientRegistration(t, iamCTX, instance, false)
|
|
|
|
metadata := map[string]any{
|
|
"client_name": "token mode client",
|
|
"redirect_uris": []string{redirectURI},
|
|
"token_endpoint_auth_method": "none",
|
|
}
|
|
|
|
t.Run("without a token registration is unauthorized", func(t *testing.T) {
|
|
status, body := registerDynamicClient(t, issuer, "", metadata)
|
|
assert.Equal(t, http.StatusUnauthorized, status)
|
|
assert.Equal(t, "invalid_token", body["error"])
|
|
})
|
|
|
|
t.Run("a token without the permission is forbidden", func(t *testing.T) {
|
|
_, pat, err := instance.CreateMachineUserPATWithMembership(iamCTX)
|
|
require.NoError(t, err)
|
|
|
|
status, body := registerDynamicClient(t, issuer, pat, metadata)
|
|
assert.Equal(t, http.StatusForbidden, status)
|
|
assert.Equal(t, "insufficient_scope", body["error"])
|
|
})
|
|
|
|
// The dedicated least-privilege role carries project.app.register_dynamic and nothing
|
|
// else, so it is enough on its own to register a client.
|
|
t.Run("a token with ORG_DYNAMIC_CLIENT_REGISTRAR may register", func(t *testing.T) {
|
|
_, pat, err := instance.CreateMachineUserPATWithMembership(iamCTX, domain.RoleOrgDynamicClientRegistrar)
|
|
require.NoError(t, err)
|
|
|
|
var body map[string]any
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(ctx, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
var status int
|
|
status, body = registerDynamicClient(t, issuer, pat, metadata)
|
|
assert.Equal(tt, http.StatusCreated, status)
|
|
}, retryDuration, tick, "membership not effective for registration")
|
|
assert.NotEmpty(t, body["client_id"])
|
|
})
|
|
}
|
|
|
|
// TestServer_DynamicClientRegistration_disabled verifies that with the setting off the
|
|
// endpoint is neither advertised nor served.
|
|
func TestServer_DynamicClientRegistration_disabled(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
defer cancel()
|
|
instance := integration.NewInstance(ctx)
|
|
issuer := instance.OIDCIssuer()
|
|
|
|
discovery := fetchDiscovery(t, issuer)
|
|
assert.Empty(t, discovery.RegistrationEndpoint)
|
|
|
|
status, _ := registerDynamicClient(t, issuer, "", map[string]any{
|
|
"redirect_uris": []string{redirectURI},
|
|
})
|
|
assert.Equal(t, http.StatusNotFound, status)
|
|
}
|
|
|
|
// enableDynamicClientRegistration turns the endpoint on through the instance's security
|
|
// settings and waits until the change is observable, i.e. until the projection behind the
|
|
// cached instance has caught up and discovery advertises the endpoint.
|
|
func enableDynamicClientRegistration(t *testing.T, ctx context.Context, instance *integration.Instance, allowUnauthenticated bool) {
|
|
t.Helper()
|
|
_, err := instance.Client.SettingsV2.SetSecuritySettings(ctx, &settings.SetSecuritySettingsRequest{
|
|
DynamicClientRegistration: &settings.DynamicClientRegistrationSettings{
|
|
Enabled: true,
|
|
AllowUnauthenticated: allowUnauthenticated,
|
|
},
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
issuer := instance.OIDCIssuer()
|
|
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(ctx, time.Minute)
|
|
require.EventuallyWithT(t, func(tt *assert.CollectT) {
|
|
resp, err := http.Get(issuer + "/.well-known/openid-configuration")
|
|
if !assert.NoError(tt, err) {
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
var discovery oidc.DiscoveryConfiguration
|
|
if !assert.NoError(tt, json.NewDecoder(resp.Body).Decode(&discovery)) {
|
|
return
|
|
}
|
|
assert.Equal(tt, issuer+"/oauth/v2/register", discovery.RegistrationEndpoint)
|
|
}, retryDuration, tick, "registration endpoint not advertised")
|
|
}
|
|
|
|
func registerDynamicClient(t testing.TB, issuer, accessToken string, metadata map[string]any) (int, map[string]any) {
|
|
t.Helper()
|
|
raw, err := json.Marshal(metadata)
|
|
require.NoError(t, err)
|
|
req, err := http.NewRequest(http.MethodPost, issuer+"/oauth/v2/register", bytes.NewReader(raw))
|
|
require.NoError(t, err)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if accessToken != "" {
|
|
req.Header.Set("Authorization", "Bearer "+accessToken)
|
|
}
|
|
resp, err := http.DefaultClient.Do(req)
|
|
require.NoError(t, err)
|
|
defer func() {
|
|
_, _ = io.Copy(io.Discard, resp.Body)
|
|
resp.Body.Close()
|
|
}()
|
|
var body map[string]any
|
|
_ = json.NewDecoder(resp.Body).Decode(&body)
|
|
return resp.StatusCode, body
|
|
}
|
|
|
|
func fetchDiscovery(t testing.TB, issuer string) oidc.DiscoveryConfiguration {
|
|
t.Helper()
|
|
resp, err := http.Get(issuer + "/.well-known/openid-configuration")
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
var discovery oidc.DiscoveryConfiguration
|
|
require.NoError(t, json.NewDecoder(resp.Body).Decode(&discovery))
|
|
return discovery
|
|
}
|