975 Commits

Author SHA1 Message Date
Stefan Benz
0337a861ba
test: correct notifications integration test with eventual consistency (#9569)
# Which Problems Are Solved

Quota notification integration test failed sometimes due to eventual
consistency issues, which resulted in calls which should have been
counted to the quota not being added. This resulted in flaky integration
tests as the expected API calls to be limited were executed normally.

# How the Problems Are Solved

As there is no API call to query the currently applied Quota, there was
a sleep added as a last effort, to give some time that the event gets
processed into the projection.

# Additional Changes

None

# Additional Context

Related to
https://github.com/zitadel/zitadel/actions/runs/13922326003/job/38959595055

Co-authored-by: Livio Spring <livio.a@gmail.com>
(cherry picked from commit 5ca76af7790769273ee0e27375510b78b37e859e)
2025-03-28 07:36:17 +01:00
Harsha Reddy
7c1e211a3c
fix: reduce cardinality in metrics and tracing for unknown paths (#9523)
# Which Problems Are Solved
Zitadel should not record 404 response counts of unknown paths (check
`/debug/metrics`).
This can lead to high cardinality on metrics endpoint and in traces.

```
GOOD http_server_return_code_counter_total{method="GET",otel_scope_name="",otel_scope_version="",return_code="200",uri="/.well-known/openid-configuration"} 2
GOOD http_server_return_code_counter_total{method="GET",otel_scope_name="",otel_scope_version="",return_code="200",uri="/oauth/v2/keys"} 2
BAD http_server_return_code_counter_total{method="GET",otel_scope_name="",otel_scope_version="",return_code="404",uri="/junk"} 2000
```

After
```
GOOD http_server_return_code_counter_total{method="GET",otel_scope_name="",otel_scope_version="",return_code="200",uri="/.well-known/openid-configuration"} 2
GOOD http_server_return_code_counter_total{method="GET",otel_scope_name="",otel_scope_version="",return_code="200",uri="/oauth/v2/keys"} 2
```

# How the Problems Are Solved

This PR makes sure, that any unknown path is recorded as `UNKNOWN_PATH`
instead of the actual path.

# Additional Changes

N/A

# Additional Context

On our production instance, when a penetration test was run, it caused
our metric count to blow up to many thousands due to Zitadel recording
404 response counts.

Next nice to have steps, remove 404 timer recordings which serve no
purpose

---------

Co-authored-by: Livio Spring <livio.a@gmail.com>
Co-authored-by: Silvan <27845747+adlerhurst@users.noreply.github.com>
Co-authored-by: Livio Spring <livio@zitadel.com>
(cherry picked from commit 599850e7e8f2638cbd758f92b8759f4efa4f9ea1)
2025-03-17 17:39:46 +01:00
Livio Spring
5aaaaa2398
fix(login): cache scripts and other assets correctly (#9551)
# Which Problems Are Solved

Scripts and other assets for the hosted login UI are served with a
public cache with `max-age` and `s-maxage`. After changing scripts or
assets, old versions might be still used as they might be cached locally
or in a shared cache (CDN, proxy, ...). This can lead to unwanted
behaviour or even errors.

# How the Problems Are Solved

To ensure the correct file is served a query parameter with the build
time is added to the assets filename dynamically. (`?v=2025-03-17...`)

# Additional Changes

None

# Additional Context

- relates to #9485
- requires backport to at least 2.70.x

(cherry picked from commit 19f022e1cf6c62c1cff03fc1e945c6b8a094c6c6)
2025-03-17 17:39:43 +01:00
Silvan
205229f0d1
fix(perf): simplify eventstore queries by removing or in projection handlers (#9530)
# Which Problems Are Solved

[A recent performance
enhancement]((https://github.com/zitadel/zitadel/pull/9497)) aimed at
optimizing event store queries, specifically those involving multiple
aggregate type filters, has successfully improved index utilization.
While the query planner now correctly selects relevant indexes, it
employs [bitmap index
scans](https://www.postgresql.org/docs/current/indexes-bitmap-scans.html)
to retrieve data.

This approach, while beneficial in many scenarios, introduces a
potential I/O bottleneck. The bitmap index scan first identifies the
required database blocks and then utilizes a bitmap to access the
corresponding rows from the table's heap. This subsequent "bitmap heap
scan" can result in significant I/O overhead, particularly when queries
return a substantial number of rows across numerous data pages.

## Impact:

Under heavy load or with queries filtering for a wide range of events
across multiple aggregate types, this increased I/O activity may lead
to:

- Increased query latency.
- Elevated disk utilization.
- Potential performance degradation of the event store and dependent
systems.

# How the Problems Are Solved

To address this I/O bottleneck and further optimize query performance,
the projection handler has been modified. Instead of employing multiple
OR clauses for each aggregate type, the aggregate and event type filters
are now combined using IN ARRAY filters.

Technical Details:

This change allows the PostgreSQL query planner to leverage [index-only
scans](https://www.postgresql.org/docs/current/indexes-index-only-scans.html).
By utilizing IN ARRAY filters, the database can efficiently retrieve the
necessary data directly from the index, eliminating the need to access
the table's heap. This results in:

* Reduced I/O: Index-only scans significantly minimize disk I/O
operations, as the database avoids reading data pages from the main
table.
* Improved Query Performance: By reducing I/O, query execution times are
substantially improved, leading to lower latency.

# Additional Changes

- rollback of https://github.com/zitadel/zitadel/pull/9497

# Additional Information

## Query Plan of previous query

```sql
SELECT
    created_at, event_type, "sequence", "position", payload, creator, "owner", instance_id, aggregate_type, aggregate_id, revision
FROM
    eventstore.events2
WHERE
    instance_id = '<INSTANCE_ID>'
    AND (
        (
            instance_id = '<INSTANCE_ID>'
            AND "position" > <POSITION>
            AND aggregate_type = 'project'
            AND event_type = ANY(ARRAY[
                                'project.application.added'
                                ,'project.application.changed'
                                ,'project.application.deactivated'
                                ,'project.application.reactivated'
                                ,'project.application.removed'
                                ,'project.removed'
                                ,'project.application.config.api.added'
                                ,'project.application.config.api.changed'
                                ,'project.application.config.api.secret.changed'
                ,'project.application.config.api.secret.updated'
                                ,'project.application.config.oidc.added'
                                ,'project.application.config.oidc.changed'
                                ,'project.application.config.oidc.secret.changed'
                ,'project.application.config.oidc.secret.updated'
                                ,'project.application.config.saml.added'
                                ,'project.application.config.saml.changed'
                        ])
        ) OR (
            instance_id = '<INSTANCE_ID>'
            AND "position" > <POSITION>
            AND aggregate_type = 'org'
            AND event_type = 'org.removed'
        ) OR (
            instance_id = '<INSTANCE_ID>'
            AND "position" > <POSITION>
            AND aggregate_type = 'instance'
            AND event_type = 'instance.removed'
        )
    )
    AND "position" > 1741600905.3495
    AND "position" < (
        SELECT
            COALESCE(EXTRACT(EPOCH FROM min(xact_start)), EXTRACT(EPOCH FROM now()))
        FROM
            pg_stat_activity
        WHERE
            datname = current_database()
            AND application_name = ANY(ARRAY['zitadel_es_pusher_', 'zitadel_es_pusher', 'zitadel_es_pusher_<INSTANCE_ID>'])
            AND state <> 'idle'
    )
ORDER BY "position", in_tx_order LIMIT 200 OFFSET 1;
```

```
Limit  (cost=120.08..120.09 rows=7 width=361) (actual time=2.167..2.172 rows=0 loops=1)
   Output: events2.created_at, events2.event_type, events2.sequence, events2."position", events2.payload, events2.creator, events2.owner, events2.instance_id, events2.aggregate_type, events2.aggregate_id, events2.revision, events2.in_tx_order
   InitPlan 1
     ->  Aggregate  (cost=2.74..2.76 rows=1 width=32) (actual time=1.813..1.815 rows=1 loops=1)
           Output: COALESCE(EXTRACT(epoch FROM min(s.xact_start)), EXTRACT(epoch FROM now()))
           ->  Nested Loop  (cost=0.00..2.74 rows=1 width=8) (actual time=1.803..1.805 rows=0 loops=1)
                 Output: s.xact_start
                 Join Filter: (d.oid = s.datid)
                 ->  Seq Scan on pg_catalog.pg_database d  (cost=0.00..1.07 rows=1 width=4) (actual time=0.016..0.021 rows=1 loops=1)
                       Output: d.oid, d.datname, d.datdba, d.encoding, d.datlocprovider, d.datistemplate, d.datallowconn, d.dathasloginevt, d.datconnlimit, d.datfrozenxid, d.datminmxid, d.dattablespace, d.datcollate, d.datctype, d.datlocale, d.daticurules, d.datcollversion, d.datacl
                       Filter: (d.datname = current_database())
                       Rows Removed by Filter: 4
                 ->  Function Scan on pg_catalog.pg_stat_get_activity s  (cost=0.00..1.63 rows=3 width=16) (actual time=1.781..1.781 rows=0 loops=1)
                       Output: s.datid, s.pid, s.usesysid, s.application_name, s.state, s.query, s.wait_event_type, s.wait_event, s.xact_start, s.query_start, s.backend_start, s.state_change, s.client_addr, s.client_hostname, s.client_port, s.backend_xid, s.backend_xmin, s.backend_type, s.ssl, s.sslversion, s.sslcipher, s.sslbits, s.ssl_client_dn, s.ssl_client_serial, s.ssl_issuer_dn, s.gss_auth, s.gss_princ, s.gss_enc, s.gss_delegation, s.leader_pid, s.query_id
                       Function Call: pg_stat_get_activity(NULL::integer)
                       Filter: ((s.state <> 'idle'::text) AND (s.application_name = ANY ('{zitadel_es_pusher_,zitadel_es_pusher,zitadel_es_pusher_<INSTANCE_ID>}'::text[])))
                       Rows Removed by Filter: 49
   ->  Sort  (cost=117.31..117.33 rows=8 width=361) (actual time=2.167..2.168 rows=0 loops=1)
         Output: events2.created_at, events2.event_type, events2.sequence, events2."position", events2.payload, events2.creator, events2.owner, events2.instance_id, events2.aggregate_type, events2.aggregate_id, events2.revision, events2.in_tx_order
         Sort Key: events2."position", events2.in_tx_order
         Sort Method: quicksort  Memory: 25kB
         ->  Bitmap Heap Scan on eventstore.events2  (cost=84.92..117.19 rows=8 width=361) (actual time=2.088..2.089 rows=0 loops=1)
               Output: events2.created_at, events2.event_type, events2.sequence, events2."position", events2.payload, events2.creator, events2.owner, events2.instance_id, events2.aggregate_type, events2.aggregate_id, events2.revision, events2.in_tx_order
               Recheck Cond: (((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = 'project'::text) AND (events2.event_type = ANY ('{project.application.added,project.application.changed,project.application.deactivated,project.application.reactivated,project.application.removed,project.removed,project.application.config.api.added,project.application.config.api.changed,project.application.config.api.secret.changed,project.application.config.api.secret.updated,project.application.config.oidc.added,project.application.config.oidc.changed,project.application.config.oidc.secret.changed,project.application.config.oidc.secret.updated,project.application.config.saml.added,project.application.config.saml.changed}'::text[])) AND (events2."position" > <POSITION>) AND (events2."position" > 1741600905.3495) AND (events2."position" < (InitPlan 1).col1)) OR ((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = 'org'::text) AND (events2.event_type = 'org.removed'::text) AND (events2."position" > <POSITION>) AND (events2."position" > 1741600905.3495) AND (events2."position" < (InitPlan 1).col1)) OR ((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = 'instance'::text) AND (events2.event_type = 'instance.removed'::text) AND (events2."position" > <POSITION>) AND (events2."position" > 1741600905.3495) AND (events2."position" < (InitPlan 1).col1)))
               ->  BitmapOr  (cost=84.88..84.88 rows=8 width=0) (actual time=2.080..2.081 rows=0 loops=1)
                     ->  Bitmap Index Scan on es_projection  (cost=0.00..75.44 rows=8 width=0) (actual time=2.016..2.017 rows=0 loops=1)
                           Index Cond: ((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = 'project'::text) AND (events2.event_type = ANY ('{project.application.added,project.application.changed,project.application.deactivated,project.application.reactivated,project.application.removed,project.removed,project.application.config.api.added,project.application.config.api.changed,project.application.config.api.secret.changed,project.application.config.api.secret.updated,project.application.config.oidc.added,project.application.config.oidc.changed,project.application.config.oidc.secret.changed,project.application.config.oidc.secret.updated,project.application.config.saml.added,project.application.config.saml.changed}'::text[])) AND (events2."position" > <POSITION>) AND (events2."position" > 1741600905.3495) AND (events2."position" < (InitPlan 1).col1))
                     ->  Bitmap Index Scan on es_projection  (cost=0.00..4.71 rows=1 width=0) (actual time=0.016..0.016 rows=0 loops=1)
                           Index Cond: ((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = 'org'::text) AND (events2.event_type = 'org.removed'::text) AND (events2."position" > <POSITION>) AND (events2."position" > 1741600905.3495) AND (events2."position" < (InitPlan 1).col1))
                     ->  Bitmap Index Scan on es_projection  (cost=0.00..4.71 rows=1 width=0) (actual time=0.045..0.045 rows=0 loops=1)
                           Index Cond: ((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = 'instance'::text) AND (events2.event_type = 'instance.removed'::text) AND (events2."position" > <POSITION>) AND (events2."position" > 1741600905.3495) AND (events2."position" < (InitPlan 1).col1))
 Query Identifier: 3194938266011254479
 Planning Time: 1.295 ms
 Execution Time: 2.832 ms
```

## Query Plan of new query

```sql
SELECT
    created_at, event_type, "sequence", "position", payload, creator, "owner", instance_id, aggregate_type, aggregate_id, revision
FROM
    eventstore.events2
WHERE
    instance_id = '<INSTANCE_ID>'
    AND "position" > <POSITION>
    AND aggregate_type = ANY(ARRAY['project', 'instance', 'org'])
    AND event_type = ANY(ARRAY[
        'project.application.added'
        ,'project.application.changed'
        ,'project.application.deactivated'
        ,'project.application.reactivated'
        ,'project.application.removed'
        ,'project.removed'
        ,'project.application.config.api.added'
        ,'project.application.config.api.changed'
        ,'project.application.config.api.secret.changed'
        ,'project.application.config.api.secret.updated'
        ,'project.application.config.oidc.added'
        ,'project.application.config.oidc.changed'
        ,'project.application.config.oidc.secret.changed'
        ,'project.application.config.oidc.secret.updated'
        ,'project.application.config.saml.added'
        ,'project.application.config.saml.changed'
        ,'org.removed'
        ,'instance.removed'
    ])
    AND "position" < (
        SELECT
            COALESCE(EXTRACT(EPOCH FROM min(xact_start)), EXTRACT(EPOCH FROM now()))
        FROM
            pg_stat_activity
        WHERE
            datname = current_database()
            AND application_name = ANY(ARRAY['zitadel_es_pusher_', 'zitadel_es_pusher', 'zitadel_es_pusher_<INSTANCE_ID>'])
            AND state <> 'idle'
    )
ORDER BY "position", in_tx_order LIMIT 200 OFFSET 1;
```

```
Limit  (cost=293.34..293.36 rows=8 width=361) (actual time=4.686..4.689 rows=0 loops=1)
   Output: events2.created_at, events2.event_type, events2.sequence, events2."position", events2.payload, events2.creator, events2.owner, events2.instance_id, events2.aggregate_type, events2.aggregate_id, events2.revision, events2.in_tx_order
   InitPlan 1
     ->  Aggregate  (cost=2.74..2.76 rows=1 width=32) (actual time=1.717..1.719 rows=1 loops=1)
           Output: COALESCE(EXTRACT(epoch FROM min(s.xact_start)), EXTRACT(epoch FROM now()))
           ->  Nested Loop  (cost=0.00..2.74 rows=1 width=8) (actual time=1.658..1.659 rows=0 loops=1)
                 Output: s.xact_start
                 Join Filter: (d.oid = s.datid)
                 ->  Seq Scan on pg_catalog.pg_database d  (cost=0.00..1.07 rows=1 width=4) (actual time=0.026..0.028 rows=1 loops=1)
                       Output: d.oid, d.datname, d.datdba, d.encoding, d.datlocprovider, d.datistemplate, d.datallowconn, d.dathasloginevt, d.datconnlimit, d.datfrozenxid, d.datminmxid, d.dattablespace, d.datcollate, d.datctype, d.datlocale, d.daticurules, d.datcollversion, d.datacl
                       Filter: (d.datname = current_database())
                       Rows Removed by Filter: 4
                 ->  Function Scan on pg_catalog.pg_stat_get_activity s  (cost=0.00..1.63 rows=3 width=16) (actual time=1.628..1.628 rows=0 loops=1)
                       Output: s.datid, s.pid, s.usesysid, s.application_name, s.state, s.query, s.wait_event_type, s.wait_event, s.xact_start, s.query_start, s.backend_start, s.state_change, s.client_addr, s.client_hostname, s.client_port, s.backend_xid, s.backend_xmin, s.backend_type, s.ssl, s.sslversion, s.sslcipher, s.sslbits, s.ssl_client_dn, s.ssl_client_serial, s.ssl_issuer_dn, s.gss_auth, s.gss_princ, s.gss_enc, s.gss_delegation, s.leader_pid, s.query_id
                       Function Call: pg_stat_get_activity(NULL::integer)
                       Filter: ((s.state <> 'idle'::text) AND (s.application_name = ANY ('{zitadel_es_pusher_,zitadel_es_pusher,zitadel_es_pusher_<INSTANCE_ID>}'::text[])))
                       Rows Removed by Filter: 42
   ->  Sort  (cost=290.58..290.60 rows=9 width=361) (actual time=4.685..4.685 rows=0 loops=1)
         Output: events2.created_at, events2.event_type, events2.sequence, events2."position", events2.payload, events2.creator, events2.owner, events2.instance_id, events2.aggregate_type, events2.aggregate_id, events2.revision, events2.in_tx_order
         Sort Key: events2."position", events2.in_tx_order
         Sort Method: quicksort  Memory: 25kB
         ->  Index Scan using es_projection on eventstore.events2  (cost=0.70..290.43 rows=9 width=361) (actual time=4.616..4.617 rows=0 loops=1)
               Output: events2.created_at, events2.event_type, events2.sequence, events2."position", events2.payload, events2.creator, events2.owner, events2.instance_id, events2.aggregate_type, events2.aggregate_id, events2.revision, events2.in_tx_order
               Index Cond: ((events2.instance_id = '<INSTANCE_ID>'::text) AND (events2.aggregate_type = ANY ('{project,instance,org}'::text[])) AND (events2.event_type = ANY ('{project.application.added,project.application.changed,project.application.deactivated,project.application.reactivated,project.application.removed,project.removed,project.application.config.api.added,project.application.config.api.changed,project.application.config.api.secret.changed,project.application.config.api.secret.updated,project.application.config.oidc.added,project.application.config.oidc.changed,project.application.config.oidc.secret.changed,project.application.config.oidc.secret.updated,project.application.config.saml.added,project.application.config.saml.changed,org.removed,instance.removed}'::text[])) AND (events2."position" > <POSITION>) AND (events2."position" < (InitPlan 1).col1))
 Query Identifier: -8254550537132386499
 Planning Time: 2.864 ms
 Execution Time: 5.414 ms
 ```

(cherry picked from commit e36f402e093f53b9a8ef614da2e3c77c65cb45f5)
2025-03-13 16:51:46 +01:00
Livio Spring
a47f4a30fa
fix(OIDC): back channel logout work for custom UI (#9487)
# Which Problems Are Solved

When using a custom / new login UI and an OIDC application with
registered BackChannelLogoutUI, no logout requests were sent to the URI
when the user signed out.
Additionally, as described in #9427, an error was logged:
`level=error msg="event of type *session.TerminateEvent doesn't
implement OriginEvent"
caller="/home/runner/work/zitadel/zitadel/internal/notification/handlers/origin.go:24"`

# How the Problems Are Solved

- Properly pass `TriggerOrigin` information to session.TerminateEvent
creation and implement `OriginEvent` interface.
- Implemented `RegisterLogout` in `CreateOIDCSessionFromAuthRequest` and
`CreateOIDCSessionFromDeviceAuth`, both used when interacting with the
OIDC v2 API.
- Both functions now receive the `BackChannelLogoutURI` of the client
from the OIDC layer.

# Additional Changes

None

# Additional Context

- closes #9427

(cherry picked from commit ed697bbd69b7e9596e9cd53d8f37aad09403d87a)
2025-03-12 16:05:00 +01:00
Livio Spring
5ad33e717b
fix(token exchange): properly return an error if membership is missing (#9468)
# Which Problems Are Solved

When requesting a JWT (`urn:ietf:params:oauth:token-type:jwt`) to be
returned in a Token Exchange request, ZITADEL would panic if the `actor`
was not granted the necessary permission.

# How the Problems Are Solved

Properly check the error and return it.

# Additional Changes

None

# Additional Context

- closes #9436

(cherry picked from commit e6ce1af0038d4913431aa9de0a688d81d7b09d7e)
2025-03-12 16:04:57 +01:00
Max Peintner
6256908181
fix(login): passkey setup when pressing "Enter" key on login form (#9485)
# Which Problems Are Solved

When registering passkeys or u2f methods as second factor, some users
pressed the "Enter" key, rather than clicking the submit button. This
method has bypassed the execution of the device registration and
encoding scripts, resulting in the form being submitted without the
necessary encoded values.

# How the Problems Are Solved

This PR ensures that device registration is always executed and the
required information are submitted in the form regardless of pressing
"Enter" or clicking the button.

# Additional Changes

None

# Additional Context

- closes #6592
- closes #2910

(cherry picked from commit 27b319bd988f49d2feb6352ea2f2ad21e68646b7)
2025-03-12 16:04:54 +01:00
Max Peintner
52bb9ca3a5
fix(login): improve webauthn error handling (#9474)
This PR improves error handling around webauthn functions in the login.

(cherry picked from commit a82f5805b6acf6e4b22bee927119c326e8bf5df6)
2025-03-06 07:41:17 +01:00
Iraq
122b5f3e0e
fix(actions): Linking external account doesn't trigger flow "External Authentication" on "Post Authentication" on first login (#9397)
# Which Problems Are Solved

When logging in using exeternal idp to Zitadel using SAML with action
setup to override existing Zitadel account attributes (first name/last
name/display name ect) with that of external linked idp account as
described here:
https://zitadel.com/docs/guides/integrate/identity-providers/azure-ad-saml#add-action-to-map-user-attributes,
does not happen until the next time the user logs in using the external
idp

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/9133

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
Co-authored-by: Livio Spring <livio.a@gmail.com>
(cherry picked from commit b0fa974419867a56d3a40dfee715460fd785a119)
2025-03-06 07:41:16 +01:00
Tim Möhlmann
e670b9126c
fix(permissions): chunked synchronization of role permission events (#9403)
# Which Problems Are Solved

Setup fails to push all role permission events when running Zitadel with
CockroachDB. `TransactionRetryError`s were visible in logs which finally
times out the setup job with `timeout: context deadline exceeded`

# How the Problems Are Solved

As suggested in the [Cockroach documentation](timeout: context deadline
exceeded), _"break down larger transactions"_. The commands to be pushed
for the role permissions are chunked in 50 events per push. This
chunking is only done with CockroachDB.

# Additional Changes

- gci run fixed some unrelated imports
- access to `command.Commands` for the setup job, so we can reuse the
sync logic.

# Additional Context

Closes #9293

---------

Co-authored-by: Silvan <27845747+adlerhurst@users.noreply.github.com>
2025-02-26 16:06:50 +00:00
KevinRSI
70bddceda8
fix(user fields): missing creationDate in details (#9250)
# Which Problems Are Solved

The `creationDate` property on user search V2 endpoint was missing

# How the Problems Are Solved

Added property in v2 `object.proto` and in the function creating the
details on each call

# Additional Changes
- none
# Additional Context
closes #8552

---------

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-02-26 13:00:04 +00:00
Livio Spring
8f88c4cf5b
feat: add PKCE option to generic OAuth2 / OIDC identity providers (#9373)
# Which Problems Are Solved

Some OAuth2 and OIDC providers require the use of PKCE for all their
clients. While ZITADEL already recommended the same for its clients, it
did not yet support the option on the IdP configuration.

# How the Problems Are Solved

- A new boolean `use_pkce` is added to the add/update generic OAuth/OIDC
endpoints.
- A new checkbox is added to the generic OAuth and OIDC provider
templates.
- The `rp.WithPKCE` option is added to the provider if the use of PKCE
has been set.
- The `rp.WithCodeChallenge` and `rp.WithCodeVerifier` options are added
to the OIDC/Auth BeginAuth and CodeExchange function.
- Store verifier or any other persistent argument in the intent or auth
request.
- Create corresponding session object before creating the intent, to be
able to store the information.
- (refactored session structs to use a constructor for unified creation
and better overview of actual usage)

Here's a screenshot showing the URI including the PKCE params:


![use_pkce_in_url](https://github.com/zitadel/zitadel/assets/30386061/eaeab123-a5da-4826-b001-2ae9efa35169)

# Additional Changes

None.

# Additional Context

- Closes #6449
- This PR replaces the existing PR (#8228) of @doncicuto. The base he
did was cherry picked. Thank you very much for that!

---------

Co-authored-by: Miguel Cabrerizo <doncicuto@gmail.com>
Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-02-26 12:20:47 +00:00
MAHANTH-wq
32ec7d0aa9
feat(\internal): sorting column on ListIAMMembersRequest (#9203)
# Which Problems Are Solved


SortingColumn functionality on system API ListIAMMembers

SortingColumn functionality on admin API ListIAMMembers

# How the Problems Are Solved

I have added enum MemberFieldColumnName in` member.proto `file ,
consists of names of the columns on which the request can be sorted.
    MEMBER_FIELD_NAME_UNSPECIFIED = 0;
    MEMBER_FIELD_NAME_USER_ID=1;
    MEMBER_FIELD_NAME_CREATION_DATE = 2;
    MEMBER_FIELD_NAME_CHANGE_DATE=3;
    MEMBER_FIELD_NAME_USER_RESOURCE_OWNER=4
I have added field Sorting Column for ListIAMMembersRequest in`
system.proto` file. I have added field Sorting Column for
ListIAMMembersRequest in` admin.proto` file.
I have modified ListIAMMembersRequestToQuery function in file
`internal/api/grpc/system/instance_converter.go `to include sorting
column in the query.SearchRequest{}.
I have modified ListIAMMembersRequestToQuery function in file
`internal/api/grpc/admin/iam_member_converter.go ` to include sorting
column in the query.SearchRequest{}.

# Additional Changes

Replace this example text with a concise list of additional changes that
this PR introduces, that are not directly solving the initial problem
but are related.
For example:
- The docs explicitly describe that the property XY is mandatory
- Adds missing translations for validations.

# Additional Context

Replace this example with links to related issues, discussions, discord
threads, or other sources with more context.
Use the Closing #issue syntax for issues that are resolved with this PR.
- Closes https://github.com/zitadel/zitadel/issues/5063
- Discussion #xxx
- Follow-up for PR #xxx
-
https://discordapp.com/channels/927474939156643850/1329872809488416789/1329872809488416789

---------

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-02-26 11:48:51 +01:00
Livio Spring
911200aa9b
feat(api): allow Device Authorization Grant using custom login UI (#9387)
# Which Problems Are Solved

The OAuth2 Device Authorization Grant could not yet been handled through
the new login UI, resp. using the session API.
This PR adds the ability for the login UI to get the required
information to display the user and handle their decision (approve with
authorization or deny) using the OIDC Service API.

# How the Problems Are Solved

- Added a `GetDeviceAuthorizationRequest` endpoint, which allows getting
the `id`, `client_id`, `scope`, `app_name` and `project_name` of the
device authorization request
- Added a `AuthorizeOrDenyDeviceAuthorization` endpoint, which allows to
approve/authorize with the session information or deny the request. The
identification of the request is done by the `device_authorization_id` /
`id` returned in the previous request.
- To prevent leaking the `device_code` to the UI, but still having an
easy reference, it's encrypted and returned as `id`, resp. decrypted
when used.
- Fixed returned error types for device token responses on token
endpoint:
- Explicitly return `access_denied` (without internal error) when user
denied the request
  - Default to `invalid_grant` instead of `access_denied`
- Explicitly check on initial state when approving the reqeust
- Properly handle done case (also relates to initial check) 
- Documented the flow and handling in custom UIs (according to OIDC /
SAML)

# Additional Changes

- fixed some typos and punctuation in the corresponding OIDC / SAML
guides.
- added some missing translations for auth and saml request

# Additional Context

- closes #6239

---------

Co-authored-by: Tim Möhlmann <tim+github@zitadel.com>
2025-02-25 07:33:13 +01:00
Iraq
f2e82d57ac
fix: adding code to test ListUsers with and without permission_check_v2 flag set (#9383)
# Which Problems Are Solved

Enhancing `v2/ListUsers()` tests by adding code to run all test with and
without `permission_check_v2` flag set

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/9356

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
2025-02-24 16:29:51 +00:00
Iraq
9aad207ee4
fix(permissions): return current user when calling ListUsers() when user does not have permissions (#9374)
# Which Problems Are Solved

When running `ListUsers()` with no permissions, the calling user shoud
be returned

# How the Problems Are Solved

Added additional clause to SQL search statement 

# Additional Changes

n/a

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/9355

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
2025-02-20 15:39:48 +00:00
Stefan Benz
93466055ee
test: add sink functionality for idp intents (#9116)
# Which Problems Are Solved

New integration tests can't use command side to simulate successful
intents.

# How the Problems Are Solved

Add endpoints to only in integration tests available sink to create
already successful intents.

# Additional Changes

None

# Additional Context

Closes #8557

---------

Co-authored-by: Livio Spring <livio.a@gmail.com>
2025-02-20 13:27:20 +01:00
Kenta Yamaguchi
9b35b98cae
fix(i18n): add some missing elements in Japanese (#9353)
# Which Problems Are Solved

Some i18n elements are not translated in Japanese yet.

# How the Problems Are Solved

Add some missing i18n elements to `console/src/assets/i18n/ja.json`,
`internal/api/ui/login/static/i18n/ja.yaml`, and
`internal/static/i18n/ja.yaml`.

More details are following:
- `console/src/assets/i18n/ja.json`
  - `POLICY.PRIVATELABELING.BACKGROUNDCOLOR`
  - `POLICY.PRIVATELABELING.PRIMARYCOLOR`
  - `POLICY.PRIVATELABELING.WARNCOLOR`
  - `POLICY.PRIVATELABELING.FONTCOLOR`
  - `POLICY.LOGIN_TEXTS.MESSAGE_TEXTS.TYPES.IU`
  - `IDP.CREATE.APPLE.TITLE`
  - `IDP.CREATE.APPLE.DESCRIPTION`
  - `IDP.CREATE.SAML.TITLE`
  - `IDP.CREATE.SAML.DESCRIPTION`
  - `IDP.APPLE.TEAMID`
  - `IDP.APPLE.KEYID`
  - `IDP.APPLE.PRIVATEKEY`
  - `IDP.APPLE.UPDATEPRIVATEKEY`
  - `IDP.APPLE.UPLOADPRIVATEKEY`
  - `IDP.KEYMAXSIZEEXCEEDED`
  - `IDP.SAML.METADATAXML`
  - `IDP.SAML.METADATAURL`
  - `IDP.SAML.BIDNING`
  - `IDP.SAML.SIGNEDREQUEST`
  - `IDP.SAML.NAMEIDFORMAT`
  - `IDP.SAML.TRANSIENTMAPPINGATTRIBUTENAME`
  - `IDP.SAML.TRANSIENTMAPPINGATTRIBUTENAME_DESC`
  - `SMTP.LIST.DIALOG.TEST_TITLE`
  - `SMTP.LIST.DIALOG.TEST_DESCRIPTION`
  - `SMTP.LIST.DIALOG.TEST_EMAIL`
  - `SMTP.LIST.DIALOG.TEST_RESULT`
- `internal/api/ui/login/static/i18n/ja.yaml`
  - `LDAP.Title`
  - `LDAP.Description`
  - `LDAP.LoginNameLabel`
  - `LDAP.PasswordLabel`
  - `LDAP.NextButtonText`
  - `PasswordChange.Footer`
  - `Footer.SupportEmail`
  - `Errors.User.AlreadyExists`
  - `Errors.User.Profile.NotFound`
  - `Errors.User.Profile.NotChanged`
  - `Errors.User.Profile.Empty`
  - `Errors.User.Profile.FirstNameEmpty`
  - `Errors.User.Profile.LastNameEmpty`
  - `Errors.User.Profile.IDMissing`
  - `Errors.User.Email.NotFound`
  - `Errors.User.Email.Invalid`
  - `Errors.User.Email.AlreadyVerified`
  - `Errors.User.Email.NotChanged`
  - `Errors.User.Email.Empty`
  - `Errors.User.Email.IDMissing`
  - `Errors.User.Phone.NotFound`
  - `Errors.User.Phone.Invalid`
  - `Errors.User.Phone.AlreadyVerified`
  - `Errors.User.Phone.Empty`
  - `Errors.User.Phone.NotChanged`
  - `Errors.User.Address.NotFound`
  - `Errors.User.Address.NotChanged`
  - `Errors.User.Username.AlreadyExists`
  - `Errors.User.Username.Reserved`
  - `Errors.User.Username.Empty`
  - `Errors.Org.LoginPolicy.RegistrationNotAllowed`
- `internal/static/i18n/ja.yaml`
  - `Errors.SMSConfig.NotExternalVerification`
  - `Errors.User.Profile.Empty`
  - `Errors.User.Profile.FirstNameEmpty`
  - `Errors.User.Profile.LastNameEmpty`
  - `Errors.User.Email.Empty`
  - `Errors.User.Email.IDMissing`
  - `Errors.User.Phone.Empty`
  - `Errors.User.Phone.NotChanged`
  - `Errors.User.Username.Empty`
  - `Errors.Org.LabelPolicy.NotFound`
  - `Errors.Org.LabelPolicy.NotChanged`
  - `EventTypes.project.application.oidc.key.added`
  - `EventTypes.project.application.oidc.key.removed`

# Additional Changes

- Change some order of the elements in `internal/static/i18n/ja.yaml`
  - `EventTypes.user.human.password.change.sent`
  - `EventTypes.user.human.password.hash.updated`
- Remove an element which is not used in the `us.yaml` from
`internal/static/i18n/ja.yaml`
  - `EventTypes.user.phone.removed`
- Correct a translation in `internal/static/i18n/ja.yaml`
  - `EventTypes.user.human.password.change.sent`
2025-02-19 12:51:53 +00:00
Iraq
5bbb953ffb
feat(ldap): adding root ca option to ldap config (#9292)
# Which Problems Are Solved

Adding ability to add a root CA to LDAP configs

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/7888

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
2025-02-18 10:06:50 +00:00
Ramon
3042bbb993
feat: Use V2 API's in Console (#9312)
# Which Problems Are Solved
Solves #8976

# Additional Changes
I have done some intensive refactorings and we are using the new
@zitadel/client package for GRPC access.

# Additional Context
- Closes #8976

---------

Co-authored-by: Max Peintner <peintnerm@gmail.com>
2025-02-17 19:25:46 +01:00
Iraq
0cb0380826
feat: updating eventstore.permitted_orgs sql function (#9309)
# Which Problems Are Solved

Performance issue for GRPC call `zitadel.user.v2.UserService.ListUsers`
due to lack of org filtering on `ListUsers`

# Additional Context

Replace this example with links to related issues, discussions, discord
threads, or other sources with more context.
Use the Closing #issue syntax for issues that are resolved with this PR.
- Closes https://github.com/zitadel/zitadel/issues/9191

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
Co-authored-by: Tim Möhlmann <tim+github@zitadel.com>
2025-02-17 11:55:28 +02:00
Stefan Benz
49de5c61b2
feat: saml application configuration for login version (#9351)
# Which Problems Are Solved

OIDC applications can configure the used login version, which is
currently not possible for SAML applications.

# How the Problems Are Solved

Add the same functionality dependent on the feature-flag for SAML
applications.

# Additional Changes

None

# Additional Context

Closes #9267
Follow up issue for frontend changes #9354

---------

Co-authored-by: Livio Spring <livio.a@gmail.com>
2025-02-13 16:03:05 +00:00
Iraq
66296db971
fix: custom userID not being added when specified in zitadel.org.v2.AddOrganizationRequest.AddOrganization() request (#9334)
# Which Problems Are Solved

When specifying a `user_id` as a human admin in
`zitadel.org.v2.AddOrganizationRequest.AddOrganization()` the `user_id`
specified in the request should have been used, before it was being
ignored, this has been fixed with this PR

# Additional Context
- Closes https://github.com/zitadel/zitadel/issues/9308

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
2025-02-13 09:17:05 +00:00
Stefan Benz
0ea42f1ddf
fix: no project owner at project creation and cleanup (#9317)
# Which Problems Are Solved

Project creation always requires a user as project owner, in case of a
system user creating the project, there is no valid user existing at
that moment.

# How the Problems Are Solved

Remove the initially created project owner membership, as this is
something which was necessary in old versions, and all should work
perfectly without.
The call to add a project automatically designates the calling user as
the project owner, which is irrelevant currently, as this user always
already has higher permissions to be able to even create the project.

# Additional Changes

Cleanup of the existing checks for the project, which can be improved
through the usage of the fields table.

# Additional Context

Closes #9182
2025-02-12 11:48:28 +00:00
Stefan Benz
39a7977e34
test: session v2beta corrected like v2 (#9350)
# Which Problems Are Solved

Ordering of sessions in v2beta is still relevant in the integration
tests.

# How the Problems Are Solved

Correct the integration tests on session service v2beta like in v2.

# Additional Changes

None

# Additional Context

Failing integration tests in pipeline.
2025-02-12 10:46:14 +00:00
Stefan Benz
840da5be2d
feat: permission check on OIDC and SAML service session API (#9304)
# Which Problems Are Solved

Through configuration on projects, there can be additional permission
checks enabled through an OIDC or SAML flow, which were not included in
the OIDC and SAML services.

# How the Problems Are Solved

Add permission check through the query-side of Zitadel in a singular SQL
query, when an OIDC or SAML flow should be linked to a SSO session. That
way it is eventual consistent, but will not impact the performance on
the eventstore. The permission check is defined in the API, which
provides the necessary function to the command side.

# Additional Changes

Added integration tests for the permission check on OIDC and SAML
service for every combination.
Corrected session list integration test, to content checks without
ordering.
Corrected get auth and saml request integration tests, to check for
timestamp of creation, not start of test.

# Additional Context

Closes #9265

---------

Co-authored-by: Livio Spring <livio.a@gmail.com>
2025-02-11 18:45:09 +00:00
Livio Spring
e7a73eb6b1
fix(oidc / login v2): always us login v2 if x-zitadel-login-client header is sent (#9336)
# Which Problems Are Solved

As reported in #9311, even when providing a `x-zitadel-login-client`
header, the auth request would be created as hosted login UI / V1
request.
This is due to a change introduced with #9071, where the login UI
version can be specified using the app configuration.
The configuration set to V1 was not considering if the header was sent.

# How the Problems Are Solved

- Check presence of `x-zitadel-login-client` before the configuration.
Use later only if no header is set.

# Additional Changes

None

# Additional Context

- closes #9311 
- needs back ports to 2.67.x, 2.68.x and 2.69.x
2025-02-10 14:46:28 +01:00
Lars
4dc7a58a25
fix: ensure metadata is projected for scim tests to ensure stable tests (#9305)
# Which Problems Are Solved
- SCIM tests are flaky due to metadata being set by the tests while
shortly after being read by the application, resulting in a race
condition

# How the Problems Are Solved
- whenever metadata is set, the projection is awaited

# Additional Context
Part of #8140

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-02-05 15:40:56 +00:00
Lars
361f7a2edc
fix: relax parsing of SCIM user 'active' flag to improve compatibility (#9296)
# Which Problems Are Solved
- Microsoft Entra invokes the user patch endpoint with `"active":
"True"` / `"active": "False"` when patching a user. This is a well-known
bug in MS Entra (see
[here](https://learn.microsoft.com/en-us/entra/identity/app-provisioning/application-provisioning-config-problem-scim-compatibility)),
but the bug fix has not landed yet and/or the feature flag does not
work.

# How the Problems Are Solved
- To ensure compatibility with MS Entra, the parsing of the the boolean
active flag of the scim user is relaxed and accepts strings in any
casing that resolve to `true` or `false` as well as raw boolean values.

# Additional Context
Part of https://github.com/zitadel/zitadel/issues/8140
2025-02-05 16:17:20 +01:00
Livio Spring
990e1982c7
fix(OTEL): reduce high cardinality in traces and metrics (#9286)
# Which Problems Are Solved

There were multiple issues in the OpenTelemetry (OTEL) implementation
and usage for tracing and metrics, which lead to high cardinality and
potential memory leaks:
- wrongly initiated tracing interceptors
- high cardinality in traces:
  - HTTP/1.1 endpoints containing host names
- HTTP/1.1 endpoints containing object IDs like userID (e.g.
`/management/v1/users/2352839823/`)
- high amount of traces from internal processes (spooler)
- high cardinality in metrics endpoint:
  - GRPC entries containing host names
  - notification metrics containing instanceIDs and error messages

# How the Problems Are Solved

- Properly initialize the interceptors once and update them to use the
grpc stats handler (unary interceptors were deprecated).
- Remove host names from HTTP/1.1 span names and use path as default.
- Set / overwrite the uri for spans on the grpc-gateway with the uri
pattern (`/management/v1/users/{user_id}`). This is used for spans in
traces and metric entries.
- Created a new sampler which will only sample spans in the following
cases:
  - remote was already sampled
- remote was not sampled, root span is of kind `Server` and based on
fraction set in the runtime configuration
- This will prevent having a lot of spans from the spooler back ground
jobs if they were not started by a client call querying an object (e.g.
UserByID).
- Filter out host names and alike from OTEL generated metrics (using a
`view`).
- Removed instance and error messages from notification metrics.

# Additional Changes

Fixed the middleware handling for serving Console. Telemetry and
instance selection are only used for the environment.json, but not on
statically served files.

# Additional Context

- closes #8096 
- relates to #9074
- back ports to at least 2.66.x, 2.67.x and 2.68.x
2025-02-04 09:55:26 +01:00
Livio Spring
04b9e9b144
fix(console): add posthog to CSP if configured (#9284)
# Which Problems Are Solved

PostHog scripts are currently blocked by content security policy (CSP).

# How the Problems Are Solved

Add `https://*.i.posthog.com` to the CSP according to
https://posthog.com/docs/advanced/content-security-policy#enabling-the-toolbar
(they suggest  `https://*.posthog.com`)

# Additional Changes

None

# Additional Context

relates to https://github.com/zitadel/zitadel/issues/9076
2025-02-03 08:08:01 +01:00
Lars
f65db52247
fix: scim create users dont send init emails (#9283)
# Which Problems Are Solved
- when a scim user is provisioned, a init email could be sent

# How the Problems Are Solved
- no init email should be sent => hard code false for the email init
param

# Additional Context

Related to https://github.com/zitadel/zitadel/issues/8140

Co-authored-by: Fabienne Bühler <fabienne@zitadel.com>
2025-01-31 09:36:18 +00:00
Lars
20cff9c70a
fix: scim 2.0 patch ignore op casing (#9282)
# Which Problems Are Solved
- Some SCIM clients send "op" of a patch operation in PascalCase

# How the Problems Are Solved
- Well known "op" values of patch operations are matched
case-insensitive.

# Additional Context
Related to #8140
2025-01-31 09:15:39 +00:00
Lars
563f74640e
fix: scim v2 endpoints enforce user resource owner (#9273)
# Which Problems Are Solved
- If a SCIM endpoint is called with an orgID in the URL that is not the
resource owner, no error is returned, and the action is executed.

# How the Problems Are Solved
- The orgID provided in the SCIM URL path must match the resource owner
of the target user. Otherwise, an error will be returned.

# Additional Context

Part of https://github.com/zitadel/zitadel/issues/8140
2025-01-30 16:43:13 +01:00
Lars
e15094cdea
feat: add scim v2 service provider configuration endpoints (#9258)
# Which Problems Are Solved
* Adds support for the service provider configuration SCIM v2 endpoints

# How the Problems Are Solved
* Adds support for the service provider configuration SCIM v2 endpoints
  * `GET /scim/v2/{orgId}/ServiceProviderConfig`
  * `GET /scim/v2/{orgId}/ResourceTypes`
  * `GET /scim/v2/{orgId}/ResourceTypes/{name}`
  * `GET /scim/v2/{orgId}/Schemas`
  * `GET /scim/v2/{orgId}/Schemas/{id}`

# Additional Context
Part of #8140

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-01-29 18:11:12 +00:00
Tim Möhlmann
b6841251b1
feat(users/v2): return prompt information (#9255)
# Which Problems Are Solved

Add the ability to update the timestamp when MFA initialization was last
skipped.
Get User By ID now also returns the timestamps when MFA setup was last
skipped.

# How the Problems Are Solved

- Add a `HumanMFAInitSkipped` method to the `users/v2` API.
- MFA skipped was already projected in the `auth.users3` table. In this
PR the same column is added to the users projection. Event handling is
kept the same as in the `UserView`:

<details>


62804ca45f/internal/user/repository/view/model/user.go (L243-L377)

</details>

# Additional Changes

- none

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/9197
2025-01-29 15:12:31 +00:00
Lars
df8bac8a28
feat: bulk scim v2 endpoint (#9256)
# Which Problems Are Solved
* Adds support for the bulk SCIM v2 endpoint

# How the Problems Are Solved
* Adds support for the bulk SCIM v2 endpoint under `POST
/scim/v2/{orgID}/Bulk`

# Additional Context
Part of #8140

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-01-29 14:23:56 +00:00
Lars
accfb7525a
fix: scim 2 filter: the username should be treated case-insensitive (#9257)
# Which Problems Are Solved
- when listing users via scim v2.0 filters applied to the username are
applied case-sensitive

# How the Problems Are Solved
- when a query filter is appleid on the username it is applied
case-insensitive

# Additional Context
Part of https://github.com/zitadel/zitadel/issues/8140
2025-01-29 15:22:22 +02:00
kkrime
5eeff97ffe
feat(session/v2): user password lockout error response (#9233)
# Which Problems Are Solved

Adds `failed attempts` field to the grpc response when a user enters
wrong password when logging in

FYI:

this only covers the senario above; other senarios where this is not
applied are:
SetPasswordWithVerifyCode
setPassword
ChangPassword
setPasswordWithPermission

# How the Problems Are Solved 

Created new grpc message `CredentialsCheckError` -
`proto/zitadel/message.proto` to include `failed_attempts` field.

Had to create a new package -
`github.com/zitadel/zitadel/internal/command/errors` to resolve cycle
dependency between `github.com/zitadel/zitadel/internal/command` and
`github.com/zitadel/zitadel/internal/command`.

# Additional Changes

- none

# Additional Context

- Closes https://github.com/zitadel/zitadel/issues/9198

---------

Co-authored-by: Iraq Jaber <IraqJaber@gmail.com>
2025-01-29 10:29:00 +00:00
Lars
21f00c1e6b
fix: scim use first email or phone if no primary is set (#9236)
# Which Problems Are Solved
- scim v2 only maps the primary phone/email to the zitadel user, this
does not work if no primary is set

# How the Problems Are Solved
- the first phone / email is mapped if no primary is available

# Additional Context
Part of #8140

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-01-29 09:18:00 +00:00
Lars
30a54fc1eb
fix: scim user query endpoint don't allow SortBy custom field (#9235)
# Which Problems Are Solved
- scim list users endpoint (`GET /scim/v2/{orgId}/Users`): handle
unsupported `SortBy` columns correctly

# How the Problems Are Solved
- throw an error if sorting by an unsupported column is requested

# Additional Context
Part of #8140
2025-01-27 17:30:27 +00:00
Lars
b19333726c
fix: allow scim content type wildcards (#9245)
# Which Problems Are Solved
- requests to the scim interface with content type `*/*` are rejected

# How the Problems Are Solved
- `*/*` is accepted as content type

# Additional Context
Part of #8140
2025-01-27 16:10:30 +00:00
Lars
741434806a
fix: unified scim metadata key casing (#9244)
# Which Problems Are Solved
- SCIM user metadata mapping keys have differing case styles.

# How the Problems Are Solved
- key casing style is unified to strict camelCase

# Additional Context
Part of #8140

Although this is technically a breaking change, it is considered
acceptable because the SCIM feature is still in the preview stage and
not fully implemented yet.

Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2025-01-27 13:51:58 +00:00
Lars
189f9770c6
feat: patch user scim v2 endpoint (#9219)
# Which Problems Are Solved
* Adds support for the patch user SCIM v2 endpoint

# How the Problems Are Solved
* Adds support for the patch user SCIM v2 endpoint under `PATCH
/scim/v2/{orgID}/Users/{id}`

# Additional Context
Part of #8140
2025-01-27 13:36:07 +01:00
Lars
1915d35605
feat: list users scim v2 endpoint (#9187)
# Which Problems Are Solved
- Adds support for the list users SCIM v2 endpoint

# How the Problems Are Solved
- Adds support for the list users SCIM v2 endpoints under `GET
/scim/v2/{orgID}/Users` and `POST /scim/v2/{orgID}/Users/.search`

# Additional Changes
- adds a new function `SearchUserMetadataForUsers` to the query layer to
query a metadata keyset for given user ids
- adds a new function `NewUserMetadataExistsQuery` to the query layer to
query a given metadata key value pair exists
- adds a new function `CountUsers` to the query layer to count users
without reading any rows
- handle `ErrorAlreadyExists` as scim errors `uniqueness`
- adds `NumberLessOrEqual` and `NumberGreaterOrEqual` query comparison
methods
- adds `BytesQuery` with `BytesEquals` and `BytesNotEquals` query
comparison methods

# Additional Context
Part of #8140
Supported fields for scim filters:
* `meta.created`
* `meta.lastModified`
* `id`
* `username`
* `name.familyName`
* `name.givenName`
* `emails` and `emails.value`
* `active` only eq and ne
* `externalId` only eq and ne
2025-01-21 13:31:54 +01:00
Tim Möhlmann
94cbf97534
fix(permissions_v2): add membership fields migration (#9199)
# Which Problems Are Solved

Memberships did not have a fields table fill migration.

# How the Problems Are Solved

Add filling of membership fields to the repeatable steps.

# Additional Changes

- Use the same repeatable step for multiple fill fields handlers.
- Fix an error for PostgreSQL 15 where a subquery in a `FROM` clause
needs an alias ing the `permitted_orgs` function.

# Additional Context

- Part of https://github.com/zitadel/zitadel/issues/9188
- Introduced in https://github.com/zitadel/zitadel/pull/9152
2025-01-17 16:16:26 +01:00
Lars
07f74730ac
fix: include tzdata to validate timezones in scim (#9195)
# Which Problems Are Solved
- include tzdata in the binary to correctly validate time zones in the
scim layer if the os doesn't have timezone data available.

# How the Problems Are Solved
- by importing the go pkg `"time/tzdata"`

# Additional Context
Part of https://github.com/zitadel/zitadel/issues/8140
2025-01-16 10:34:52 +00:00
Tim Möhlmann
3f6ea78c87
perf: role permissions in database (#9152)
# Which Problems Are Solved

Currently ZITADEL defines organization and instance member roles and
permissions in defaults.yaml. The permission check is done on API call
level. For example: "is this user allowed to make this call on this
org". This makes sense on the V1 API where the API is permission-level
shaped. For example, a search for users always happens in the context of
the organization. (Either the organization the calling user belongs to,
or through member ship and the x-zitadel-orgid header.

However, for resource based APIs we must be able to resolve permissions
by object. For example, an IAM_OWNER listing users should be able to get
all users in an instance based on the query filters. Alternatively a
user may have user.read permissions on one or more orgs. They should be
able to read just those users.

# How the Problems Are Solved

## Role permission mapping

The role permission mappings defined from `defaults.yaml` or local
config override are synchronized to the database on every run of
`zitadel setup`:

- A single query per **aggregate** builds a list of `add` and `remove`
actions needed to reach the desired state or role permission mappings
from the config.
- The required events based on the actions are pushed to the event
store.
- Events define search fields so that permission checking can use the
indices and is strongly consistent for both query and command sides.

The migration is split in the following aggregates:

- System aggregate for for roles prefixed with `SYSTEM`
- Each instance for roles not prefixed with `SYSTEM`. This is in
anticipation of instance level management over the API.

## Membership

Current instance / org / project membership events now have field table
definitions. Like the role permissions this ensures strong consistency
while still being able to use the indices of the fields table. A
migration is provided to fill the membership fields.

## Permission check

I aimed keeping the mental overhead to the developer to a minimal. The
provided implementation only provides a permission check for list
queries for org level resources, for example users. In the `query`
package there is a simple helper function `wherePermittedOrgs` which
makes sure the underlying database function is called as part of the
`SELECT` query and the permitted organizations are part of the `WHERE`
clause. This makes sure results from non-permitted organizations are
omitted. Under the hood:

- A Pg/PlSQL function searches for a list of organization IDs the passed
user has the passed permission.
- When the user has the permission on instance level, it returns early
with all organizations.
- The functions uses a number of views. The views help mapping the
fields entries into relational data and simplify the code use for the
function. The views provide some pre-filters which allow proper index
usage once the final `WHERE` clauses are set by the function.

# Additional Changes



# Additional Context

Closes #9032
Closes https://github.com/zitadel/zitadel/issues/9014

https://github.com/zitadel/zitadel/issues/9188 defines follow-ups for
the new permission framework based on this concept.
2025-01-16 10:09:15 +00:00
Livio Spring
40082745f4
fix(login): allow fallback to local auth in case of IdP errors (#9178)
# Which Problems Are Solved

The current login will always prefer external authentication (through an
IdP) over local authentication. So as soon as either the user had
connected to an IdP or even when the login policy was just set up to
have an IdP allowed, users would be redirected to that IdP for
(re)authentication.
This could lead to problems, where the IdP was not available or any
other error occurred in the process (such as secret expired for
EntraID).
Even when local authentication (passkeys or password) was allowed for
the corresponding user, they would always be redirected to the IdP
again, preventing any authentication. If admins were affected, they
might not even be able to update the client secret of the IdP.

# How the Problems Are Solved

Errors during the external IdP flow are handled in an
`externalAuthFailed` function, which will check if the organisation
allows local authentication and if the user has set up such.
If either password or passkeys is set up, the corresponding login page
will be presented to the user. As already with local auth passkeys is
preferred over password authentication.
The user is informed that the external login failed and fail back to
local auth as an error on the corresponding page in a focused mode. Any
interaction or after 5 second the focus mode is disabled.

# Additional Changes

None.

# Additional Context

closes #6466
2025-01-15 10:39:28 +00:00
MAHANTH-wq
b664ffe993
feat(/internal): Add User Resource Owner (#9168)
Update the  ../proto/zitadel/member.proto to
include the UserResourceOwner as part of member.

Update the queries to include UserResourceOwner
for the following :
zitadel/internal/query/iam_member.go
zitadel/internal/query/org_member.go
zitadel/internal/query/project_member.go
zitadel/internal/query/project_grant_member.go

Non Breaking Changes

# Which Problems Are Solved

https://github.com/zitadel/zitadel/issues/5062

# How the Problems Are Solved

- Updated the member.proto file to include user_resource_owner. I have
compiled using` make compile` command .
- Changed the queries to include the userResourceOwner as part of
Member.
- Then, updated the converter to map the userResourceOwner.

# Additional Changes

Replace this example text with a concise list of additional changes that
this PR introduces, that are not directly solving the initial problem
but are related.
For example:
- The docs explicitly describe that the property XY is mandatory
- Adds missing translations for validations.

# Additional Context


- Closes #5062 
-
https://discordapp.com/channels/927474939156643850/1326245856193544232/1326476710752948316
2025-01-15 09:40:30 +01:00