mirror of
https://github.com/andwati/zitadel.git
synced 2026-10-25 00:32:15 +00:00
feat(oidc): add RFC 7592 dynamic client management (#12315)
# 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.
This commit is contained in:
@@ -196,9 +196,13 @@ func (c *Commands) addOIDCApplicationWithID(ctx context.Context, oidcApp *domain
|
||||
// pushOIDCApplication writes the application-added and oidc-config-added events for a new
|
||||
// OIDC application onto the project aggregate. Authorization must already have been
|
||||
// performed by the caller: either through an app.write permission check (see
|
||||
// addOIDCApplicationWithID) or, for dynamic client registration, through the feature flag
|
||||
// and registration mode (see AddDynamicOIDCClient).
|
||||
func (c *Commands) pushOIDCApplication(ctx context.Context, addedApplication *OIDCApplicationWriteModel, oidcApp *domain.OIDCApp, appID string) (_ *domain.OIDCApp, err error) {
|
||||
// addOIDCApplicationWithID) or, for dynamic client registration, at the registration endpoint
|
||||
// through the instance's security settings and registration mode (see AddDynamicOIDCClient).
|
||||
//
|
||||
// extraEvents are appended to the same push, so callers can persist additional state about
|
||||
// the application atomically with its creation (dynamic client registration uses this to
|
||||
// store the registration access token hash).
|
||||
func (c *Commands) pushOIDCApplication(ctx context.Context, addedApplication *OIDCApplicationWriteModel, oidcApp *domain.OIDCApp, appID string, extraEvents ...eventstore.Command) (_ *domain.OIDCApp, err error) {
|
||||
projectAgg := ProjectAggregateFromWriteModel(&addedApplication.WriteModel)
|
||||
|
||||
oidcApp.AppID = appID
|
||||
@@ -249,6 +253,8 @@ func (c *Commands) pushOIDCApplication(ctx context.Context, addedApplication *OI
|
||||
strings.TrimSpace(gu.Value(oidcApp.LoginBaseURI)),
|
||||
))
|
||||
|
||||
events = append(events, extraEvents...)
|
||||
|
||||
addedApplication.AppID = oidcApp.AppID
|
||||
postCommit, err := c.applicationCreatedMilestone(ctx, &events)
|
||||
if err != nil {
|
||||
@@ -305,12 +311,40 @@ func (c *Commands) UpdateOIDCApplication(ctx context.Context, oidc *domain.OIDCA
|
||||
return nil, err
|
||||
}
|
||||
|
||||
projectAgg := ProjectAggregateFromWriteModel(&existingOIDC.WriteModel)
|
||||
changedEvent, hasChanged, err := c.oidcApplicationChangeEvent(ctx, existingOIDC, oidc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasChanged {
|
||||
return nil, zerrors.ThrowPreconditionFailed(nil, "COMMAND-1m88i", "Errors.NoChangesFound")
|
||||
}
|
||||
|
||||
pushedEvents, err := c.eventstore.Push(ctx, changedEvent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = AppendAndReduce(existingOIDC, pushedEvents...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := oidcWriteModelToOIDCConfig(existingOIDC)
|
||||
result.FillCompliance()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// oidcApplicationChangeEvent builds the oidc-config-changed event that brings an existing
|
||||
// OIDC application to the desired state. It assumes the existing write model has been loaded
|
||||
// and reduced and that authorization has already been performed by the caller (an app.write
|
||||
// permission check for UpdateOIDCApplication, the registration access token for
|
||||
// UpdateDynamicOIDCClient). It reports whether anything actually changed.
|
||||
func (c *Commands) oidcApplicationChangeEvent(ctx context.Context, existingOIDC *OIDCApplicationWriteModel, oidc *domain.OIDCApp) (*project_repo.OIDCConfigChangedEvent, bool, error) {
|
||||
projectAgg := ProjectAggregateFromWriteModelWithCTX(ctx, &existingOIDC.WriteModel)
|
||||
var backChannelLogout, loginBaseURI *string
|
||||
if oidc.BackChannelLogoutURI != nil {
|
||||
bcl, err := c.validateBackchannelLogoutURI(oidc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, false, err
|
||||
}
|
||||
backChannelLogout = gu.Ptr(bcl)
|
||||
}
|
||||
@@ -319,7 +353,7 @@ func (c *Commands) UpdateOIDCApplication(ctx context.Context, oidc *domain.OIDCA
|
||||
loginBaseURI = gu.Ptr(strings.TrimSpace(*oidc.LoginBaseURI))
|
||||
}
|
||||
|
||||
changedEvent, hasChanged, err := existingOIDC.NewChangedEvent(
|
||||
return existingOIDC.NewChangedEvent(
|
||||
ctx,
|
||||
projectAgg,
|
||||
oidc.AppID,
|
||||
@@ -342,25 +376,6 @@ func (c *Commands) UpdateOIDCApplication(ctx context.Context, oidc *domain.OIDCA
|
||||
oidc.LoginVersion,
|
||||
loginBaseURI,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasChanged {
|
||||
return nil, zerrors.ThrowPreconditionFailed(nil, "COMMAND-1m88i", "Errors.NoChangesFound")
|
||||
}
|
||||
|
||||
pushedEvents, err := c.eventstore.Push(ctx, changedEvent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = AppendAndReduce(existingOIDC, pushedEvents...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := oidcWriteModelToOIDCConfig(existingOIDC)
|
||||
result.FillCompliance()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Deprecated: use [ChangeApplicationSecret], which supports both OIDC and API applications.
|
||||
|
||||
@@ -192,7 +192,107 @@ func (c *Commands) AddDynamicOIDCClient(ctx context.Context, projectID, resource
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c.pushOIDCApplication(ctx, addedApplication, oidcApp, appID)
|
||||
// Persist the registration access token (RFC 7592 §3) atomically with the application,
|
||||
// so a registered client can always be managed and never ends up without a token.
|
||||
projectAgg := ProjectAggregateFromWriteModelWithCTX(ctx, &addedApplication.WriteModel)
|
||||
registrationTokenEvent, registrationToken, err := c.newOIDCRegistrationTokenEvent(ctx, projectAgg, appID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registered, err := c.pushOIDCApplication(ctx, addedApplication, oidcApp, appID, registrationTokenEvent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
registered.RegistrationAccessToken = registrationToken
|
||||
return registered, nil
|
||||
}
|
||||
|
||||
// UpdateDynamicOIDCClient applies an RFC 7592 update to a dynamically registered client and
|
||||
// rotates its registration access token in the same push. Unlike UpdateOIDCApplication it does
|
||||
// not perform an app.write permission check: the caller is authorized through the registration
|
||||
// access token (see VerifyDynamicClientRegistrationToken). The returned application carries the
|
||||
// new registration access token, which the client must use from then on. Updating metadata to
|
||||
// the values it already has is not an error: the token is rotated and the current state is
|
||||
// returned, as RFC 7592 expects a successful read-back from an update.
|
||||
func (c *Commands) UpdateDynamicOIDCClient(ctx context.Context, oidcApp *domain.OIDCApp, resourceOwner string) (_ *domain.OIDCApp, err error) {
|
||||
ctx, span := tracing.NewSpan(ctx)
|
||||
defer func() { span.EndWithError(err) }()
|
||||
|
||||
if oidcApp == nil || !oidcApp.IsValid() || oidcApp.AppID == "" || oidcApp.AggregateID == "" {
|
||||
return nil, zerrors.ThrowInvalidArgument(nil, "COMMAND-Aef8a", "Errors.Project.App.OIDCConfigInvalid")
|
||||
}
|
||||
|
||||
existingOIDC, err := c.getOIDCAppWriteModel(ctx, oidcApp.AggregateID, oidcApp.AppID, resourceOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existingOIDC.State == domain.AppStateUnspecified || existingOIDC.State == domain.AppStateRemoved {
|
||||
return nil, zerrors.ThrowNotFound(nil, "COMMAND-Voo8i", "Errors.Project.App.NotExisting")
|
||||
}
|
||||
if !existingOIDC.IsOIDC() {
|
||||
return nil, zerrors.ThrowInvalidArgument(nil, "COMMAND-Geph9", "Errors.Project.App.IsNotOIDC")
|
||||
}
|
||||
|
||||
changedEvent, hasChanged, err := c.oidcApplicationChangeEvent(ctx, existingOIDC, oidcApp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
projectAgg := ProjectAggregateFromWriteModelWithCTX(ctx, &existingOIDC.WriteModel)
|
||||
rotationEvent, registrationToken, err := c.newOIDCRegistrationTokenEvent(ctx, projectAgg, oidcApp.AppID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := make([]eventstore.Command, 0, 2)
|
||||
if hasChanged {
|
||||
events = append(events, changedEvent)
|
||||
}
|
||||
events = append(events, rotationEvent)
|
||||
|
||||
pushedEvents, err := c.eventstore.Push(ctx, events...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = AppendAndReduce(existingOIDC, pushedEvents...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := oidcWriteModelToOIDCConfig(existingOIDC)
|
||||
result.FillCompliance()
|
||||
result.RegistrationAccessToken = registrationToken
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// RemoveDynamicOIDCClient deletes a dynamically registered client (RFC 7592 §2.3). Unlike
|
||||
// RemoveApplication it does not perform an app.delete permission check: the caller is
|
||||
// authorized through the registration access token. Removing the application also invalidates
|
||||
// its registration access token.
|
||||
func (c *Commands) RemoveDynamicOIDCClient(ctx context.Context, projectID, appID, resourceOwner string) (_ *domain.ObjectDetails, err error) {
|
||||
ctx, span := tracing.NewSpan(ctx)
|
||||
defer func() { span.EndWithError(err) }()
|
||||
|
||||
if projectID == "" || appID == "" {
|
||||
return nil, zerrors.ThrowInvalidArgument(nil, "COMMAND-Eiv0u", "Errors.IDMissing")
|
||||
}
|
||||
existingApp, err := c.getApplicationWriteModel(ctx, projectID, appID, resourceOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existingApp.State == domain.AppStateUnspecified || existingApp.State == domain.AppStateRemoved {
|
||||
return nil, zerrors.ThrowNotFound(nil, "COMMAND-Quu7n", "Errors.Project.App.NotExisting")
|
||||
}
|
||||
|
||||
projectAgg := ProjectAggregateFromWriteModelWithCTX(ctx, &existingApp.WriteModel)
|
||||
pushedEvents, err := c.eventstore.Push(ctx, project.NewApplicationRemovedEvent(ctx, projectAgg, appID, existingApp.Name, ""))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = AppendAndReduce(existingApp, pushedEvents...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return writeModelToObjectDetails(&existingApp.WriteModel), nil
|
||||
}
|
||||
|
||||
// dynamicOIDCClientName builds a per-project unique application name for a dynamically
|
||||
@@ -205,3 +305,93 @@ func dynamicOIDCClientName(requestedName, appID string) string {
|
||||
}
|
||||
return requestedName + " (" + appID + ")"
|
||||
}
|
||||
|
||||
// newOIDCRegistrationTokenEvent generates a fresh registration access token secret for the
|
||||
// application, returning the event that persists its hash and the plain secret to hand back
|
||||
// to the client. Like a client secret, only the hash is ever stored; the plain secret leaves
|
||||
// the server exactly once. The caller is responsible for pushing the event.
|
||||
func (c *Commands) newOIDCRegistrationTokenEvent(ctx context.Context, projectAgg *eventstore.Aggregate, appID string) (eventstore.Command, string, error) {
|
||||
encodedHash, plain, err := c.newHashedSecret(ctx, c.eventstore.Filter) //nolint:staticcheck
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return project.NewOIDCConfigRegistrationTokenChangedEvent(ctx, projectAgg, appID, encodedHash), plain, nil
|
||||
}
|
||||
|
||||
// VerifyDynamicClientRegistrationToken checks a presented registration access token secret
|
||||
// (RFC 7592 §3) against the stored hash of the application's current token. It returns an
|
||||
// unauthenticated error when no token is set or the secret does not match, so the management
|
||||
// endpoints can answer with 401. The hash is read strongly consistently from the eventstore;
|
||||
// the management endpoints serve the common case from the projection and only fall back here,
|
||||
// most importantly for a token that was just rotated and is not projected yet.
|
||||
func (c *Commands) VerifyDynamicClientRegistrationToken(ctx context.Context, projectID, appID, resourceOwner, secret string) (err error) {
|
||||
ctx, span := tracing.NewSpan(ctx)
|
||||
defer func() { span.EndWithError(err) }()
|
||||
|
||||
if projectID == "" || appID == "" || secret == "" {
|
||||
return zerrors.ThrowUnauthenticated(nil, "COMMAND-Ohj6e", "Errors.Token.Invalid")
|
||||
}
|
||||
wm := newOIDCRegistrationTokenWriteModel(projectID, appID, resourceOwner)
|
||||
if err = c.eventstore.FilterToQueryReducer(ctx, wm); err != nil {
|
||||
return err
|
||||
}
|
||||
if wm.hashedToken == "" {
|
||||
return zerrors.ThrowUnauthenticated(nil, "COMMAND-Eereu", "Errors.Token.Invalid")
|
||||
}
|
||||
// The registration access token is short lived (it is rotated on every update), so an
|
||||
// outdated hash is not persisted back; the updated hash from Verify is intentionally
|
||||
// ignored.
|
||||
if _, err = c.secretHasher.Verify(wm.hashedToken, secret); err != nil {
|
||||
return zerrors.ThrowUnauthenticated(err, "COMMAND-Ush2a", "Errors.Token.Invalid")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// oidcRegistrationTokenWriteModel resolves the current registration access token hash of an
|
||||
// application from the eventstore. It tracks the latest token-changed event and clears the
|
||||
// hash when the application is removed.
|
||||
type oidcRegistrationTokenWriteModel struct {
|
||||
eventstore.WriteModel
|
||||
appID string
|
||||
hashedToken string
|
||||
}
|
||||
|
||||
func newOIDCRegistrationTokenWriteModel(projectID, appID, resourceOwner string) *oidcRegistrationTokenWriteModel {
|
||||
return &oidcRegistrationTokenWriteModel{
|
||||
WriteModel: eventstore.WriteModel{
|
||||
AggregateID: projectID,
|
||||
ResourceOwner: resourceOwner,
|
||||
},
|
||||
appID: appID,
|
||||
}
|
||||
}
|
||||
|
||||
func (wm *oidcRegistrationTokenWriteModel) Reduce() error {
|
||||
for _, event := range wm.Events {
|
||||
switch e := event.(type) {
|
||||
case *project.OIDCConfigRegistrationTokenChangedEvent:
|
||||
if e.AppID == wm.appID {
|
||||
wm.hashedToken = e.HashedToken
|
||||
}
|
||||
case *project.ApplicationRemovedEvent:
|
||||
if e.AppID == wm.appID {
|
||||
wm.hashedToken = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
return wm.WriteModel.Reduce()
|
||||
}
|
||||
|
||||
func (wm *oidcRegistrationTokenWriteModel) Query() *eventstore.SearchQueryBuilder {
|
||||
return eventstore.NewSearchQueryBuilder(eventstore.ColumnsEvent).
|
||||
AwaitOpenTransactions().
|
||||
ResourceOwner(wm.ResourceOwner).
|
||||
AddQuery().
|
||||
AggregateTypes(project.AggregateType).
|
||||
AggregateIDs(wm.AggregateID).
|
||||
EventTypes(
|
||||
project.OIDCConfigRegistrationTokenChangedType,
|
||||
project.ApplicationRemovedType,
|
||||
).
|
||||
Builder()
|
||||
}
|
||||
|
||||
@@ -235,6 +235,14 @@ func TestCommandSide_AddDynamicOIDCClient(t *testing.T) {
|
||||
domain.LoginVersionUnspecified,
|
||||
"",
|
||||
),
|
||||
// The registration access token (RFC 7592 §3) is persisted in the same
|
||||
// push as the application, so a registered client is never left
|
||||
// unmanageable.
|
||||
project.NewOIDCConfigRegistrationTokenChangedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate,
|
||||
"app1",
|
||||
"secret",
|
||||
),
|
||||
),
|
||||
),
|
||||
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "app1", "client1"),
|
||||
@@ -264,6 +272,7 @@ func TestCommandSide_AddDynamicOIDCClient(t *testing.T) {
|
||||
AppName: "app (app1)",
|
||||
ClientID: "client1",
|
||||
ClientSecretString: "secret",
|
||||
RegistrationAccessToken: "secret",
|
||||
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeBasic),
|
||||
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
|
||||
RedirectUris: []string{"https://client.example.com/callback"},
|
||||
@@ -328,6 +337,11 @@ func TestCommandSide_AddDynamicOIDCClient(t *testing.T) {
|
||||
domain.LoginVersionUnspecified,
|
||||
"",
|
||||
),
|
||||
project.NewOIDCConfigRegistrationTokenChangedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate,
|
||||
"app1",
|
||||
"secret",
|
||||
),
|
||||
),
|
||||
),
|
||||
idGenerator: id_mock.NewIDGeneratorExpectIDs(t, "app1", "client1"),
|
||||
@@ -356,6 +370,7 @@ func TestCommandSide_AddDynamicOIDCClient(t *testing.T) {
|
||||
AppID: "app1",
|
||||
AppName: "DCR Client app1",
|
||||
ClientID: "client1",
|
||||
RegistrationAccessToken: "secret",
|
||||
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeNone),
|
||||
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
|
||||
RedirectUris: []string{"https://client.example.com/callback"},
|
||||
@@ -493,3 +508,155 @@ func Test_dcrProjectWriteModel_Reduce(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandSide_VerifyDynamicClientRegistrationToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
regToken := func() *project.OIDCConfigRegistrationTokenChangedEvent {
|
||||
return project.NewOIDCConfigRegistrationTokenChangedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate, "app1", "$plain$$secret")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
eventstore func(*testing.T) *eventstore.Eventstore
|
||||
secret string
|
||||
wantErr func(error) bool
|
||||
}{
|
||||
{
|
||||
name: "valid token",
|
||||
eventstore: expectEventstore(expectFilter(eventFromEventPusher(regToken()))),
|
||||
secret: "secret",
|
||||
wantErr: nil,
|
||||
},
|
||||
{
|
||||
name: "wrong secret is unauthenticated",
|
||||
eventstore: expectEventstore(expectFilter(eventFromEventPusher(regToken()))),
|
||||
secret: "wrong",
|
||||
wantErr: zerrors.IsUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "no token set is unauthenticated",
|
||||
eventstore: expectEventstore(expectFilter()),
|
||||
secret: "secret",
|
||||
wantErr: zerrors.IsUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "empty secret is unauthenticated",
|
||||
eventstore: expectEventstore(),
|
||||
secret: "",
|
||||
wantErr: zerrors.IsUnauthenticated,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := &Commands{
|
||||
eventstore: tt.eventstore(t),
|
||||
secretHasher: mockPasswordHasher(""),
|
||||
}
|
||||
err := c.VerifyDynamicClientRegistrationToken(context.Background(), "project1", "app1", "org1", tt.secret)
|
||||
if tt.wantErr == nil {
|
||||
assert.NoError(t, err)
|
||||
return
|
||||
}
|
||||
assert.True(t, tt.wantErr(err), "got wrong err: %v", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandSide_UpdateDynamicOIDCClient(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
existingClient := func() []eventstore.Event {
|
||||
return []eventstore.Event{
|
||||
eventFromEventPusher(project.NewApplicationAddedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate, "app1", "DCR Client app1")),
|
||||
eventFromEventPusher(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, "")),
|
||||
}
|
||||
}
|
||||
sameMetadata := &domain.OIDCApp{
|
||||
ObjectRoot: models.ObjectRoot{AggregateID: "project1"},
|
||||
AppID: "app1",
|
||||
RedirectUris: []string{"https://client.example.com/callback"},
|
||||
ResponseTypes: []domain.OIDCResponseType{domain.OIDCResponseTypeCode},
|
||||
GrantTypes: []domain.OIDCGrantType{domain.OIDCGrantTypeAuthorizationCode},
|
||||
ApplicationType: gu.Ptr(domain.OIDCApplicationTypeWeb),
|
||||
AuthMethodType: gu.Ptr(domain.OIDCAuthMethodTypeNone),
|
||||
OIDCVersion: gu.Ptr(domain.OIDCVersionV1),
|
||||
AccessTokenType: gu.Ptr(domain.OIDCTokenTypeBearer),
|
||||
}
|
||||
|
||||
t.Run("unchanged metadata still rotates the token, no permission required", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := &Commands{
|
||||
eventstore: expectEventstore(
|
||||
// A single filter: getOIDCAppWriteModel already reduces the write model.
|
||||
expectFilter(existingClient()...),
|
||||
expectPush(
|
||||
project.NewOIDCConfigRegistrationTokenChangedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate, "app1", "secret"),
|
||||
),
|
||||
)(t),
|
||||
newHashedSecret: mockHashedSecret("secret"),
|
||||
checkPermission: newMockPermissionCheckNotAllowed(),
|
||||
}
|
||||
got, err := c.UpdateDynamicOIDCClient(context.Background(), sameMetadata, "org1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "client1", got.ClientID)
|
||||
assert.Equal(t, "secret", got.RegistrationAccessToken)
|
||||
})
|
||||
|
||||
t.Run("not existing client is not found", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := &Commands{
|
||||
eventstore: expectEventstore(expectFilter())(t),
|
||||
checkPermission: newMockPermissionCheckNotAllowed(),
|
||||
}
|
||||
_, err := c.UpdateDynamicOIDCClient(context.Background(), sameMetadata, "org1")
|
||||
assert.True(t, zerrors.IsNotFound(err), "got wrong err: %v", err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCommandSide_RemoveDynamicOIDCClient(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("remove existing client, no permission required", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := &Commands{
|
||||
eventstore: expectEventstore(
|
||||
expectFilter(
|
||||
eventFromEventPusher(project.NewApplicationAddedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate, "app1", "DCR Client app1")),
|
||||
),
|
||||
expectPush(
|
||||
project.NewApplicationRemovedEvent(context.Background(),
|
||||
&project.NewAggregate("project1", "org1").Aggregate, "app1", "DCR Client app1", ""),
|
||||
),
|
||||
)(t),
|
||||
checkPermission: newMockPermissionCheckNotAllowed(),
|
||||
}
|
||||
got, err := c.RemoveDynamicOIDCClient(context.Background(), "project1", "app1", "org1")
|
||||
assert.NoError(t, err)
|
||||
assertObjectDetails(t, &domain.ObjectDetails{ResourceOwner: "org1"}, got)
|
||||
})
|
||||
|
||||
t.Run("not existing client is not found", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := &Commands{
|
||||
eventstore: expectEventstore(expectFilter())(t),
|
||||
checkPermission: newMockPermissionCheckNotAllowed(),
|
||||
}
|
||||
_, err := c.RemoveDynamicOIDCClient(context.Background(), "project1", "app1", "org1")
|
||||
assert.True(t, zerrors.IsNotFound(err), "got wrong err: %v", err)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user