Files
zitadel/internal/command/project_application_oidc_dcr_test.go
T
jmaretteandGitHub f34cc45eac feat(oidc): add RFC 7591 dynamic client registration (#12313)
# 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`).
2026-07-30 14:43:47 +00:00

496 lines
16 KiB
Go

package command
import (
"context"
"net"
"testing"
"time"
"github.com/muhlemmer/gu"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/id"
id_mock "github.com/zitadel/zitadel/internal/id/mock"
"github.com/zitadel/zitadel/internal/repository/project"
"github.com/zitadel/zitadel/internal/zerrors"
)
func TestCommandSide_EnsureDCRProject(t *testing.T) {
t.Parallel()
dcrProjectAdded := func(projectID string) eventstore.Event {
return eventFromEventPusher(project.NewProjectAddedEvent(
context.Background(),
&project.NewAggregate(projectID, "org1").Aggregate,
DCRProjectName,
false,
false,
false,
domain.PrivateLabelingSettingUnspecified,
))
}
t.Run("missing resource owner, invalid argument", func(t *testing.T) {
t.Parallel()
c := &Commands{
eventstore: expectEventstore()(t),
checkPermission: newMockPermissionCheckNotAllowed(),
}
_, err := c.EnsureDCRProject(authz.WithInstanceID(context.Background(), "instanceID"), "")
assert.True(t, zerrors.IsErrorInvalidArgument(err))
})
t.Run("existing project resolved from the eventstore", func(t *testing.T) {
t.Parallel()
c := &Commands{
eventstore: expectEventstore(
expectFilter(dcrProjectAdded("existing")),
)(t),
checkPermission: newMockPermissionCheckNotAllowed(),
}
projectID, err := c.EnsureDCRProject(authz.WithInstanceID(context.Background(), "instanceID"), "org1")
assert.NoError(t, err)
assert.Equal(t, "existing", projectID)
})
t.Run("project created when none exists, without permission check", func(t *testing.T) {
t.Parallel()
c := &Commands{
eventstore: expectEventstore(
expectFilter(), // lookup: no DCR project yet
expectFilter(), // project write model for the new id
expectPush(
project.NewProjectAddedEvent(
context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
DCRProjectName,
false,
false,
false,
domain.PrivateLabelingSettingUnspecified,
),
),
)(t),
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "project1"),
// Provisioning the DCR project must not depend on project.create.
checkPermission: newMockPermissionCheckNotAllowed(),
}
c.setMilestonesCompletedForTest("instanceID")
projectID, err := c.EnsureDCRProject(authz.WithInstanceID(context.Background(), "instanceID"), "org1")
assert.NoError(t, err)
assert.Equal(t, "project1", projectID)
})
t.Run("concurrent creation resolves the winner from the eventstore", func(t *testing.T) {
t.Parallel()
c := &Commands{
eventstore: expectEventstore(
expectFilter(), // lookup: no DCR project yet
expectFilter(), // project write model for the new id
expectPushFailed(
zerrors.ThrowAlreadyExists(nil, "id", "project name already taken"),
project.NewProjectAddedEvent(
context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
DCRProjectName,
false,
false,
false,
domain.PrivateLabelingSettingUnspecified,
),
),
expectFilter(dcrProjectAdded("winner")), // re-resolve: the racing winner
)(t),
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "project1"),
checkPermission: newMockPermissionCheckNotAllowed(),
}
c.setMilestonesCompletedForTest("instanceID")
projectID, err := c.EnsureDCRProject(authz.WithInstanceID(context.Background(), "instanceID"), "org1")
assert.NoError(t, err)
assert.Equal(t, "winner", projectID)
})
}
func TestCommandSide_AddDynamicOIDCClient(t *testing.T) {
t.Parallel()
type fields struct {
eventstore func(t *testing.T) *eventstore.Eventstore
idGenerator id.Generator
}
type args struct {
ctx context.Context
projectID string
resourceOwner string
oidcApp *domain.OIDCApp
}
type res struct {
want *domain.OIDCApp
err func(error) bool
}
tests := []struct {
name string
fields fields
args args
res res
}{
{
name: "missing project id, invalid argument error",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "instanceID"),
projectID: "",
resourceOwner: "org1",
oidcApp: &domain.OIDCApp{AppName: "app"},
},
res: res{
err: zerrors.IsErrorInvalidArgument,
},
},
{
name: "invalid app, invalid argument error",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "instanceID"),
projectID: "project1",
resourceOwner: "org1",
oidcApp: &domain.OIDCApp{AppName: ""},
},
res: res{
err: zerrors.IsErrorInvalidArgument,
},
},
{
name: "project not existing, precondition failed error",
fields: fields{
eventstore: expectEventstore(
expectFilter(),
),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "instanceID"),
projectID: "project1",
resourceOwner: "org1",
oidcApp: &domain.OIDCApp{
AppName: "app",
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeNone),
RedirectUris: []string{"https://client.example.com/callback"},
ResponseTypes: []domain.OIDCResponseType{domain.OIDCResponseTypeCode},
GrantTypes: []domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
},
},
res: res{
err: zerrors.IsPreconditionFailed,
},
},
{
name: "confidential client (client_secret_basic), secret returned, no permission required",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
project.NewProjectAddedEvent(context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
"project", true, true, true,
domain.PrivateLabelingSettingUnspecified),
),
),
expectFilter(),
expectPush(
project.NewApplicationAddedEvent(context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
"app1",
"app (app1)",
),
project.NewOIDCConfigAddedEvent(context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
domain.OIDCVersionV1,
"app1",
"client1",
"secret",
[]string{"https://client.example.com/callback"},
[]domain.OIDCResponseType{domain.OIDCResponseTypeCode},
[]domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
domain.OIDCApplicationTypeWeb,
domain.OIDCAuthMethodTypeBasic,
[]string{},
false,
domain.OIDCTokenTypeBearer,
false,
false,
false,
0,
[]string{},
false,
"",
domain.LoginVersionUnspecified,
"",
),
),
),
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "app1", "client1"),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "instanceID"),
projectID: "project1",
resourceOwner: "org1",
oidcApp: &domain.OIDCApp{
AppName: "app",
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeBasic),
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
RedirectUris: []string{"https://client.example.com/callback"},
ResponseTypes: []domain.OIDCResponseType{domain.OIDCResponseTypeCode},
GrantTypes: []domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
ApplicationType: gu.Ptr(domain.OIDCApplicationTypeWeb),
AccessTokenType: gu.Ptr(domain.OIDCTokenTypeBearer),
},
},
res: res{
want: &domain.OIDCApp{
ObjectRoot: models.ObjectRoot{
AggregateID: "project1",
ResourceOwner: "org1",
},
AppID: "app1",
AppName: "app (app1)",
ClientID: "client1",
ClientSecretString: "secret",
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeBasic),
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
RedirectUris: []string{"https://client.example.com/callback"},
ResponseTypes: []domain.OIDCResponseType{domain.OIDCResponseTypeCode},
GrantTypes: []domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
ApplicationType: gu.Ptr(domain.OIDCApplicationTypeWeb),
AccessTokenType: gu.Ptr(domain.OIDCTokenTypeBearer),
DevMode: gu.Ptr(false),
AccessTokenRoleAssertion: gu.Ptr(false),
IDTokenRoleAssertion: gu.Ptr(false),
IDTokenUserinfoAssertion: gu.Ptr(false),
ClockSkew: gu.Ptr(time.Duration(0)),
SkipNativeAppSuccessPage: gu.Ptr(false),
BackChannelLogoutURI: gu.Ptr(""),
LoginVersion: gu.Ptr(domain.LoginVersionUnspecified),
LoginBaseURI: gu.Ptr(""),
State: domain.AppStateActive,
Compliance: &domain.Compliance{},
},
},
},
{
name: "public client (none), no secret returned, no permission required",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
project.NewProjectAddedEvent(context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
"project", true, true, true,
domain.PrivateLabelingSettingUnspecified),
),
),
expectFilter(),
expectPush(
project.NewApplicationAddedEvent(context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
"app1",
"DCR Client app1",
),
project.NewOIDCConfigAddedEvent(context.Background(),
&project.NewAggregate("project1", "org1").Aggregate,
domain.OIDCVersionV1,
"app1",
"client1",
"",
[]string{"https://client.example.com/callback"},
[]domain.OIDCResponseType{domain.OIDCResponseTypeCode},
[]domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
domain.OIDCApplicationTypeWeb,
domain.OIDCAuthMethodTypeNone,
[]string{},
false,
domain.OIDCTokenTypeBearer,
false,
false,
false,
0,
[]string{},
false,
"",
domain.LoginVersionUnspecified,
"",
),
),
),
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "app1", "client1"),
},
args: args{
ctx: authz.WithInstanceID(context.Background(), "instanceID"),
projectID: "project1",
resourceOwner: "org1",
oidcApp: &domain.OIDCApp{
AppName: "",
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeNone),
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
RedirectUris: []string{"https://client.example.com/callback"},
ResponseTypes: []domain.OIDCResponseType{domain.OIDCResponseTypeCode},
GrantTypes: []domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
ApplicationType: gu.Ptr(domain.OIDCApplicationTypeWeb),
AccessTokenType: gu.Ptr(domain.OIDCTokenTypeBearer),
},
},
res: res{
want: &domain.OIDCApp{
ObjectRoot: models.ObjectRoot{
AggregateID: "project1",
ResourceOwner: "org1",
},
AppID: "app1",
AppName: "DCR Client app1",
ClientID: "client1",
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeNone),
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
RedirectUris: []string{"https://client.example.com/callback"},
ResponseTypes: []domain.OIDCResponseType{domain.OIDCResponseTypeCode},
GrantTypes: []domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
ApplicationType: gu.Ptr(domain.OIDCApplicationTypeWeb),
AccessTokenType: gu.Ptr(domain.OIDCTokenTypeBearer),
DevMode: gu.Ptr(false),
AccessTokenRoleAssertion: gu.Ptr(false),
IDTokenRoleAssertion: gu.Ptr(false),
IDTokenUserinfoAssertion: gu.Ptr(false),
ClockSkew: gu.Ptr(time.Duration(0)),
SkipNativeAppSuccessPage: gu.Ptr(false),
BackChannelLogoutURI: gu.Ptr(""),
LoginVersion: gu.Ptr(domain.LoginVersionUnspecified),
LoginBaseURI: gu.Ptr(""),
State: domain.AppStateActive,
Compliance: &domain.Compliance{},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := &Commands{
eventstore: tt.fields.eventstore(t),
idGenerator: tt.fields.idGenerator,
newHashedSecret: mockHashedSecret("secret"),
defaultSecretGenerators: &SecretGenerators{
ClientSecret: emptyConfig,
},
// Dynamic client registration must NOT depend on app.write: deny all
// permissions and assert the client is still created.
checkPermission: newMockPermissionCheckNotAllowed(),
ipLookupFunction: func(_ string) ([]net.IP, error) {
return []net.IP{net.ParseIP("1.2.3.4")}, nil
},
}
c.setMilestonesCompletedForTest("instanceID")
got, err := c.AddDynamicOIDCClient(tt.args.ctx, tt.args.projectID, tt.args.resourceOwner, tt.args.oidcApp)
if tt.res.err == nil {
assert.NoError(t, err)
}
if tt.res.err != nil && !tt.res.err(err) {
t.Errorf("got wrong err: %v ", err)
}
if tt.res.err == nil {
assert.Equal(t, tt.res.want, got)
}
})
}
}
func Test_dcrProjectWriteModel_Reduce(t *testing.T) {
t.Parallel()
aggregate := func(projectID string) *eventstore.Aggregate {
return &project.NewAggregate(projectID, "org1").Aggregate
}
// The write model type-switches on the repository events, so feed it the typed events
// directly rather than the raw ones eventFromEventPusher builds for the mock eventstore.
added := func(projectID, name string) eventstore.Event {
return project.NewProjectAddedEvent(
context.Background(), aggregate(projectID), name,
false, false, false, domain.PrivateLabelingSettingUnspecified,
)
}
renamed := func(projectID, oldName, newName string) eventstore.Event {
return project.NewProjectChangeEvent(
context.Background(), aggregate(projectID), oldName,
[]project.ProjectChanges{project.ChangeName(newName)},
)
}
removed := func(projectID string) eventstore.Event {
return project.NewProjectRemovedEvent(
context.Background(), aggregate(projectID), DCRProjectName, nil,
)
}
tests := []struct {
name string
events []eventstore.Event
want string
}{
{
name: "no events, no project",
events: nil,
want: "",
},
{
name: "dcr project added",
events: []eventstore.Event{added("p1", DCRProjectName)},
want: "p1",
},
{
name: "unrelated project ignored",
events: []eventstore.Event{added("p1", "Some Other Project")},
want: "",
},
{
// Without reducing ProjectChanged the write model would still return p1, while
// the name-based projection query no longer finds it.
name: "renamed away from the dcr name is dropped",
events: []eventstore.Event{added("p1", DCRProjectName), renamed("p1", DCRProjectName, "Renamed")},
want: "",
},
{
name: "renamed onto the dcr name is picked up",
events: []eventstore.Event{added("p1", "Some Other Project"), renamed("p1", "Some Other Project", DCRProjectName)},
want: "p1",
},
{
name: "rename of an unrelated project does not clear the dcr project",
events: []eventstore.Event{
added("p1", DCRProjectName),
added("p2", "Some Other Project"),
renamed("p2", "Some Other Project", "Still Something Else"),
},
want: "p1",
},
{
name: "removed dcr project is dropped",
events: []eventstore.Event{added("p1", DCRProjectName), removed("p1")},
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
wm := newDCRProjectWriteModel("org1")
wm.AppendEvents(tt.events...)
require.NoError(t, wm.Reduce())
assert.Equal(t, tt.want, wm.projectID)
})
}
}