keycloak-admin 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -0
  3. data/MIT-LICENSE +18 -17
  4. data/README.md +102 -5
  5. data/keycloak-admin.gemspec +15 -6
  6. data/lib/keycloak-admin/client/attack_detection_client.rb +2 -1
  7. data/lib/keycloak-admin/client/client.rb +36 -11
  8. data/lib/keycloak-admin/client/client_authz_permission_client.rb +5 -4
  9. data/lib/keycloak-admin/client/client_authz_policy_client.rb +4 -3
  10. data/lib/keycloak-admin/client/client_authz_resource_client.rb +15 -11
  11. data/lib/keycloak-admin/client/client_authz_scope_client.rb +5 -4
  12. data/lib/keycloak-admin/client/client_client.rb +6 -2
  13. data/lib/keycloak-admin/client/client_role_client.rb +2 -1
  14. data/lib/keycloak-admin/client/client_role_mappings_client.rb +3 -2
  15. data/lib/keycloak-admin/client/client_scope_client.rb +2 -1
  16. data/lib/keycloak-admin/client/client_scope_protocol_mapper_client.rb +3 -2
  17. data/lib/keycloak-admin/client/configurable_token_client.rb +2 -1
  18. data/lib/keycloak-admin/client/group_client.rb +15 -9
  19. data/lib/keycloak-admin/client/identity_provider_client.rb +2 -1
  20. data/lib/keycloak-admin/client/organization_client.rb +12 -11
  21. data/lib/keycloak-admin/client/realm_client.rb +3 -2
  22. data/lib/keycloak-admin/client/resource.rb +8 -6
  23. data/lib/keycloak-admin/client/response.rb +1 -0
  24. data/lib/keycloak-admin/client/role_client.rb +3 -6
  25. data/lib/keycloak-admin/client/role_mapper_client.rb +2 -1
  26. data/lib/keycloak-admin/client/token_client.rb +1 -0
  27. data/lib/keycloak-admin/client/user_client.rb +70 -47
  28. data/lib/keycloak-admin/configuration.rb +37 -2
  29. data/lib/keycloak-admin/error.rb +63 -0
  30. data/lib/keycloak-admin/path_encoding.rb +24 -0
  31. data/lib/keycloak-admin/representation/attack_detection_representation.rb +1 -0
  32. data/lib/keycloak-admin/representation/camel_json.rb +7 -3
  33. data/lib/keycloak-admin/representation/client_authz_policy_config_representation.rb +1 -0
  34. data/lib/keycloak-admin/representation/client_authz_policy_representation.rb +1 -0
  35. data/lib/keycloak-admin/representation/client_authz_resource_representation.rb +1 -0
  36. data/lib/keycloak-admin/representation/client_authz_scope_representation.rb +1 -0
  37. data/lib/keycloak-admin/representation/client_representation.rb +4 -5
  38. data/lib/keycloak-admin/representation/client_scope_representation.rb +1 -0
  39. data/lib/keycloak-admin/representation/credential_representation.rb +1 -0
  40. data/lib/keycloak-admin/representation/federated_identity_representation.rb +1 -0
  41. data/lib/keycloak-admin/representation/group_representation.rb +1 -0
  42. data/lib/keycloak-admin/representation/identity_provider_mapper_representation.rb +1 -0
  43. data/lib/keycloak-admin/representation/identity_provider_representation.rb +1 -0
  44. data/lib/keycloak-admin/representation/impersonation_redirection_representation.rb +1 -0
  45. data/lib/keycloak-admin/representation/impersonation_representation.rb +1 -0
  46. data/lib/keycloak-admin/representation/member_representation.rb +1 -0
  47. data/lib/keycloak-admin/representation/organization_domain_representation.rb +1 -0
  48. data/lib/keycloak-admin/representation/organization_representation.rb +1 -1
  49. data/lib/keycloak-admin/representation/protocol_mapper_representation.rb +1 -0
  50. data/lib/keycloak-admin/representation/realm_representation.rb +1 -0
  51. data/lib/keycloak-admin/representation/representation.rb +7 -5
  52. data/lib/keycloak-admin/representation/role_representation.rb +2 -1
  53. data/lib/keycloak-admin/representation/session_representation.rb +2 -1
  54. data/lib/keycloak-admin/representation/token_representation.rb +1 -0
  55. data/lib/keycloak-admin/representation/user_representation.rb +1 -0
  56. data/lib/keycloak-admin/resource/base_role_containing_resource.rb +4 -1
  57. data/lib/keycloak-admin/resource/group_resource.rb +1 -0
  58. data/lib/keycloak-admin/resource/user_resource.rb +1 -0
  59. data/lib/keycloak-admin/version.rb +2 -1
  60. data/lib/keycloak-admin.rb +4 -0
  61. metadata +36 -56
  62. data/.github/workflows/Dockerfile +0 -24
  63. data/.github/workflows/ci.yml +0 -94
  64. data/.github/workflows/release.yml +0 -112
  65. data/.gitignore +0 -10
  66. data/.rspec +0 -2
  67. data/Dockerfile +0 -13
  68. data/Gemfile +0 -3
  69. data/Gemfile.lock +0 -54
  70. data/Rakefile +0 -6
  71. data/bin/console +0 -9
  72. data/spec/client/attack_detection_client_spec.rb +0 -102
  73. data/spec/client/client_authz_permission_client_spec.rb +0 -170
  74. data/spec/client/client_authz_policy_client_spec.rb +0 -170
  75. data/spec/client/client_authz_resource_client_spec.rb +0 -150
  76. data/spec/client/client_authz_scope_client_spec.rb +0 -134
  77. data/spec/client/client_client_spec.rb +0 -133
  78. data/spec/client/client_role_mappings_client_spec.rb +0 -83
  79. data/spec/client/client_scope_client_spec.rb +0 -220
  80. data/spec/client/client_scope_protocol_mapper_client_spec.rb +0 -230
  81. data/spec/client/client_spec.rb +0 -101
  82. data/spec/client/configurable_token_client_spec.rb +0 -34
  83. data/spec/client/group_client_spec.rb +0 -328
  84. data/spec/client/identity_provider_client_spec.rb +0 -92
  85. data/spec/client/organization_client_spec.rb +0 -595
  86. data/spec/client/realm_client_spec.rb +0 -155
  87. data/spec/client/resource_spec.rb +0 -223
  88. data/spec/client/response_spec.rb +0 -68
  89. data/spec/client/role_client_spec.rb +0 -79
  90. data/spec/client/role_mapper_client_spec.rb +0 -113
  91. data/spec/client/token_client_spec.rb +0 -68
  92. data/spec/client/user_client_spec.rb +0 -418
  93. data/spec/configuration_spec.rb +0 -150
  94. data/spec/gemspec_spec.rb +0 -25
  95. data/spec/integration/client_authorization_spec.rb +0 -93
  96. data/spec/representation/attack_detection_representation_spec.rb +0 -16
  97. data/spec/representation/client_authz_permission_representation_spec.rb +0 -52
  98. data/spec/representation/client_authz_policy_representation_spec.rb +0 -47
  99. data/spec/representation/client_authz_resource_representation_spec.rb +0 -33
  100. data/spec/representation/client_authz_scope_representation_spec.rb +0 -19
  101. data/spec/representation/client_representation_spec.rb +0 -119
  102. data/spec/representation/client_scope_representation_spec.rb +0 -125
  103. data/spec/representation/credential_representation_spec.rb +0 -68
  104. data/spec/representation/group_representation_spec.rb +0 -22
  105. data/spec/representation/identity_provider_mapper_representation_spec.rb +0 -24
  106. data/spec/representation/identity_provider_representation_spec.rb +0 -113
  107. data/spec/representation/impersonation_representation_spec.rb +0 -163
  108. data/spec/representation/organization_representation_spec.rb +0 -64
  109. data/spec/representation/protocol_mapper_representation_spec.rb +0 -57
  110. data/spec/representation/role_representation_spec.rb +0 -37
  111. data/spec/representation/session_representation_spec.rb +0 -16
  112. data/spec/representation/user_representation_spec.rb +0 -15
  113. data/spec/resource/group_resource_spec.rb +0 -14
  114. data/spec/resource/user_resource_spec.rb +0 -14
  115. data/spec/spec_helper.rb +0 -36
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4a9c09a6765355416960bbc5c4564ad5dd5f526f65093b43d46ac10fc39d0ae7
4
- data.tar.gz: b2dd1762448fad5a096b94adc3d18b30640235fe02efa1e77269797bfa3f9464
3
+ metadata.gz: c5abdd787b09a456ad094161dd8d61d1908937d1461086481059ae40cc064eea
4
+ data.tar.gz: f01144dcf8ab3e193f22644e979c36a88f7cd9738bc98cda7465a88c3d05d3c7
5
5
  SHA512:
6
- metadata.gz: 3274b863ef8b7d295b82d5dd87a6d3340ac96ac08c1f38c822ad531b204f4fd5755704a905ccc308821e199d17cc8c73959c3dc1d39a5a13079ce133f1ed4854
7
- data.tar.gz: 7c8d7b5f54eb523f27eaaa83893d8b5190d4647ed6d7424a6ac1b55168ffa02fb426171b424330db86d976e00c84e1644d3bab3cf4fd398d1eb9cf4deff2e679
6
+ metadata.gz: 250bf4f4bc7471eee8c96d7b84c413ab608ef0c35b1dfebb301f8838c674ebeed93ec571bf918d3b3837543067d3c151cc3acdf992cbe390da36bf4e761b2570
7
+ data.tar.gz: edcec9055546f2d8ee9a756e2f9fce7a5f29feb8ffc87ce452a98e8f5b554055b1e8dd03df03f6459a93592bf79a6c1d961acb31468db371d395e49f360d6144
data/CHANGELOG.md CHANGED
@@ -5,6 +5,46 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.0.3] - 2026-08-03
9
+
10
+ * [Performance] Added `# frozen_string_literal: true` across all Ruby files to significantly reduce string object allocations and lower memory consumption.
11
+ * [Performance] Refactored `Representation` JSON serialization (`as_json` and `to_json`) to eliminate intermediate Array and Hash allocations, improving CPU performance and memory footprint.
12
+ * [Fix] `Representation#as_json` now strips `nil` values when generating JSON payloads. This fixes `HTTP 400 Bad Request` errors caused by strict API requirements in Keycloak 19+ (such as refusing `null` for `subGroupCount` and other restricted fields).
13
+ * [Chore] Expanded the integration test suite to cover 100% of the REST clients against live Keycloak instances.
14
+ * [Chore] Fixed the integration test suite against Keycloak 25 and 26. The `dummy` realm now enables internationalization and unmanaged user attributes, both required since Keycloak 24 for `locale` and custom attributes to be persisted; authorization permissions are deleted before the policy they depend on, since Keycloak 25 cascades that deletion; and permissions are asserted by name rather than by total count, which Keycloak 25 inflates with a seeded `Default Permission`. Each integration spec now loads the integration helper itself, instead of relying on another spec file having loaded it first.
15
+ * [Fix] `Configuration#inspect` no longer renders `client_secret`, `password` or the cached access token, showing `[FILTERED]` instead. The default `#inspect` printed every attribute, so these credentials travelled into console sessions, `pp` output, and whatever local-variable dump an exception reporter attaches to a crash. A credential that is not set still renders as `nil`, so an inspect stays useful when authentication misbehaves.
16
+ * [Fix] The access token cache introduced in 2.0.1 is now thread-safe.
17
+ * [Fix] Identifiers are now percent-encoded before being interpolated into a URL path.
18
+ * [Feature] `UserClient#update_password` accepts an optional `temporary:` keyword.
19
+ * [Performance] `ClientClient#find_by_client_id` now has Keycloak filter with `?clientId=` instead of listing every client of the realm and comparing in Ruby
20
+ * [Feature] `UserClient#list` and `GroupClient#list` accept optional `first:` and `max:` keywords. Keycloak answers `GET /users` with at most 100 entries when `max` is absent, so `users.list` silently returned a truncated realm with no way to ask for more; `GET /groups` applies no such cap, but both endpoints now page the same way. Calling either `list` with no argument sends no query parameter and is unchanged. `GroupClient#list` pairs a lone `max` with `first=0`, because Keycloak 19 only paginates that endpoint when both bounds are present and ignores `max` on its own; this is a no-op from Keycloak 23 on. Verified against live Keycloak 19.0, 23.0 and 26.7.0.
21
+ * [Feature] `config.faraday_adapter` selects the Faraday adapter requests run through.
22
+ * [Fix] `UserClient#impersonate` now takes part in the `401` replay introduced in 2.0.2. It called `get_redirect_impersonation` outside `execute_http`, so its `Authorization` header was built before the replay cleared the cached token: the second attempt resent the very bearer that had just been rejected and failed with the same `401`. It was the last call in the gem where the replay was inert.
23
+ * [Fix] `CamelJson#camelize` no longer raises `NoMethodError` on an empty word.
24
+ * [Fix] Query parameters built from an Array are now rendered as the key repeated once per element, instead of the array's Ruby `inspect` form: a list value used to be sent as `name=%5B%22a%22%2C%20%22b%22%5D`. An empty array now contributes no parameter at all; a `nil` still renders as `name=`, unchanged.
25
+ * [Breaking] `ClientAuthzResourceClient#update` now replaces the submitted `uris` and `scopes` instead of merging them with the ones already stored. It used to union both, so updating twice with the same uri accumulated duplicates and no uri or scope could ever be removed. A key absent from the submitted hash still leaves the stored value untouched; presence is now what decides, not truthiness, so `uris: []` clears the uris and `owner_managed_access: false` is honoured rather than read as "not submitted". The method also no longer raises a bare `RuntimeError` when a scope has no `:name`, but a `KeycloakAdmin`-consistent `ArgumentError`, and no longer raises `TypeError` when the stored resource has no `uris` at all.
26
+ * [Fix] `ClientRepresentation.from_hash` no longer produces wrongly typed defaults when the payload omits a field.
27
+ * [Fix] `RoleRepresentation` and `SessionRepresentation` no longer define spurious `from_hash` and `from_hash=` instance accessors. A trailing comma after the last symbol of their `attr_accessor` list continued the argument list into the following `def`, which evaluates to a Symbol, so `attr_accessor` also received `:from_hash`. The class method `self.from_hash` was never shadowed, so parsing was unaffected.
28
+
29
+ * [Fix] `UserClient#update`, `#add_group` and `#remove_group` built their request outside `execute_http`. They were the only methods on this client that raised a bare `Faraday::Error` instead of the documented `KeycloakAdmin::ApiError` hierarchy, and the only ones that did not replay a request rejected on a stale `401`.
30
+ * [Fix] `UserClient#create!` could return a different user than the one it had just created. It looked the new user up with `search(email)`, and Keycloak's `search` parameter matches a *substring* of the username, email, first name or last name: creating `pioupioux@email.com` while `vieuxpioupioux@email.com` already existed returned the pre-existing account. The new user's id is now read from the `Location` header of the creation response, like `GroupClient#create!` already did. Two consequences: a creation not answered with `201 Created` now raises `KeycloakAdmin::UnexpectedResponseError` instead of returning `nil`, and the returned representation is fetched by id.
31
+ * [Fix] `UserClient#create!` wrote the `locale` into the very `attributes` hash it was given, mutating the caller's object.
32
+ * [Fix] `UserClient#execute_actions_email` (and `#forgot_password`) ignored `config.faraday_options`. It was the only call in the gem running with no timeout, and any configured SSL or proxy setting was silently dropped. The internal `KeycloakAdmin::Resource.put` shorthand it relied on is removed; its signature could not carry connection options.
33
+ * [Chore] Migrated test suites to use WebMock `stub_request` instead of stubbing `KeycloakAdmin::Resource` directly, ensuring tests validate the actual network payload.
34
+
35
+ ## [2.0.2] - 2026-08-01
36
+
37
+ * [Breaking] HTTP failures now raise a `KeycloakAdmin::ApiError` subclass instead of a bare `RuntimeError`.
38
+ * Messages are unchanged, so code matching on the text keeps working.
39
+ * Code rescuing `RuntimeError` explicitly must be updated.
40
+ * A create call answering something other than `201 Created` now raises `KeycloakAdmin::UnexpectedResponseError`.
41
+ * [Feature] A `401` answer now drops the cached access token and replays the request once with a freshly fetched one, so a token revoked before its advertised expiry no longer fails every call until it lapses.
42
+ * [Fix] `GroupClient#members` called ActiveSupport's `Object#try` and raised `NoMethodError` outside a Rails application.
43
+ * [Fix] `UserClient#execute_actions_email` (and `#forgot_password`) called ActiveSupport's `Numeric#seconds` and raised `NoMethodError` outside a Rails application whenever a `lifespan` was passed.
44
+ * [Fix] `ClientAuthzPolicyClient#find_by` opened a second `?` in its URL, which folded `name`, `type`, `first` and `max` into the value of `permission`; Keycloak silently returned an unfiltered list.
45
+ * [Fix] Query parameters are now percent-encoded everywhere they are built. Search terms, and the `redirect_uri` of `UserClient#execute_actions_email`, containing a space, `&` or `=` used to break the URL or forge extra parameters.
46
+ * [Fix] `OrganizationClient#build` raised `NameError` instead of the intended `ArgumentError` when `domains` was not an `Array`.
47
+
8
48
  ## [2.0.1] - 2026-07-31
9
49
 
10
50
  * [Feature] Requests are now logged through `config.logger` (method, URL, and response status) via Faraday's `:logger` middleware.
data/MIT-LICENSE CHANGED
@@ -1,20 +1,21 @@
1
- Copyright 2018
1
+ MIT License
2
2
 
3
- Permission is hereby granted, free of charge, to any person obtaining
4
- a copy of this software and associated documentation files (the
5
- "Software"), to deal in the Software without restriction, including
6
- without limitation the rights to use, copy, modify, merge, publish,
7
- distribute, sublicense, and/or sell copies of the Software, and to
8
- permit persons to whom the Software is furnished to do so, subject to
9
- the following conditions:
3
+ Copyright (c) 2026 Lorent Lempereur
10
4
 
11
- The above copyright notice and this permission notice shall be
12
- included in all copies or substantial portions of the Software.
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
13
11
 
14
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md CHANGED
@@ -16,7 +16,7 @@ This gem *does not* require Rails.
16
16
  For example, using `bundle`, add this line to your Gemfile.
17
17
 
18
18
  ```ruby
19
- gem "keycloak-admin", "2.0.1"
19
+ gem "keycloak-admin", "2.0.3"
20
20
  ```
21
21
 
22
22
  ## Login
@@ -107,7 +107,67 @@ All options have a default value. However, all of them can be changed in your in
107
107
  | `password` | `nil`| String | Optional | Clear password to access the Admin REST API. Recommended if `user_service_account` is set to `false`. | `bobby` |
108
108
  | `logger` | `Logger.new(STDOUT)`| Logger | Optional | The logger used by `keycloak-admin` | `Rails.logger` | 
109
109
  | `faraday_options` | `{}`| Hash | Optional | Options to pass to `Faraday.new` (e.g. `request:`, `ssl:`, `proxy:`) | `{ request: { timeout: 5 } }` | 
110
+ | `faraday_adapter` | `nil`| Symbol or Array | Optional | Faraday adapter to run requests through. `nil` uses `Faraday.default_adapter`. See _Connection reuse_ below. | `:net_http_persistent` |
110
111
 
112
+ ### Connection reuse
113
+
114
+ By default this gem runs on `Faraday.default_adapter` (`net_http`), which wraps every request in `Net::HTTP#start`: the TCP connection is opened and closed again for each call. On a loop of admin calls, that handshake dominates the time spent.
115
+
116
+ Set `faraday_adapter` to a pooling adapter to keep connections alive between calls. The adapter is not bundled, so add its gem to your own `Gemfile` alongside this one:
117
+
118
+ ```ruby
119
+ # Gemfile
120
+ gem "faraday-net_http_persistent"
121
+ ```
122
+
123
+ ```ruby
124
+ KeycloakAdmin.configure do |config|
125
+ config.faraday_adapter = :net_http_persistent
126
+ end
127
+ ```
128
+
129
+ An adapter needing arguments is given as an array, splatted into Faraday's `adapter` call:
130
+
131
+ ```ruby
132
+ config.faraday_adapter = [:net_http_persistent, { pool_size: 5 }]
133
+ ```
134
+
135
+
136
+ ## Error handling
137
+
138
+ Every HTTP failure raises a `KeycloakAdmin::ApiError` carrying the `status`, `body` and `headers`
139
+ of the response, so you never have to parse the message. Rescue as narrowly or as broadly as you need:
140
+
141
+ ```ruby
142
+ begin
143
+ KeycloakAdmin.realm("a-realm").users.get(user_id)
144
+ rescue KeycloakAdmin::NotFoundError => e # exactly 404
145
+ nil
146
+ rescue KeycloakAdmin::ClientError => e # any 4xx
147
+ logger.warn("Rejected with #{e.status}: #{e.body}")
148
+ raise
149
+ rescue KeycloakAdmin::ServerError => e # any 5xx
150
+ raise
151
+ end
152
+ ```
153
+
154
+ | Class | Raised on |
155
+ | ---- | ---- |
156
+ | `KeycloakAdmin::Error` | Base class of every error this gem raises |
157
+ | `KeycloakAdmin::ApiError` | Any non-2xx answer; parent of the two families below |
158
+ | `KeycloakAdmin::ClientError` | Any 4xx |
159
+ | `KeycloakAdmin::BadRequestError` | 400 |
160
+ | `KeycloakAdmin::UnauthorizedError` | 401 |
161
+ | `KeycloakAdmin::ForbiddenError` | 403 |
162
+ | `KeycloakAdmin::NotFoundError` | 404 |
163
+ | `KeycloakAdmin::ConflictError` | 409 |
164
+ | `KeycloakAdmin::ServerError` | Any 5xx |
165
+ | `KeycloakAdmin::UnexpectedResponseError` | A create call answered something other than `201 Created` |
166
+
167
+ `Faraday::TimeoutError` and the other connection-level Faraday errors are left untouched and propagate as-is, since no response ever came back to describe.
168
+
169
+ A `401` is handled before it reaches you: the cached access token is dropped and the request is replayed once with a freshly fetched one, so a token revoked before its advertised expiry does not fail every call until it lapses `KeycloakAdmin::UnauthorizedError` is raised only if the replay is
170
+ refused too.
111
171
 
112
172
  ## Use Cases
113
173
 
@@ -188,6 +248,13 @@ Returns an array of `KeycloakAdmin::UserRepresentation`.
188
248
  KeycloakAdmin.realm("a_realm").users.list
189
249
  ```
190
250
 
251
+ Keycloak answers this endpoint with **at most 100 users** unless told otherwise, so a bare `list` silently truncates a larger realm. Pass `max` (and `first` to walk the pages) to go past it:
252
+
253
+ ```ruby
254
+ KeycloakAdmin.realm("a_realm").users.list(max: 500)
255
+ KeycloakAdmin.realm("a_realm").users.list(first: 100, max: 100)
256
+ ```
257
+
191
258
  ### Save a user
192
259
 
193
260
  Returns the provided `user`, which must be of type `KeycloakAdmin::UserRepresentation`.
@@ -238,6 +305,14 @@ new_password = "coco"
238
305
  KeycloakAdmin.realm("a_realm").users.update_password(user_id, new_password)
239
306
  ```
240
307
 
308
+ Pass `temporary: true` to force the user to choose a new password at their next login. Keycloak
309
+ records this as an `UPDATE_PASSWORD` required action on the account; a later permanent reset
310
+ clears it.
311
+
312
+ ```ruby
313
+ KeycloakAdmin.realm("a_realm").users.update_password(user_id, new_password, temporary: true)
314
+ ```
315
+
241
316
  ### List credentials
242
317
 
243
318
  ```ruby
@@ -344,11 +419,17 @@ Returns an array of `KeycloakAdmin::GroupRepresentation`.
344
419
  KeycloakAdmin.realm("a_realm").groups.list
345
420
  ```
346
421
 
422
+ This endpoint applies no default cap, so a bare `list` already returns every group. `first` and `max` are still accepted, to page through a realm holding a lot of them:
423
+
424
+ ```ruby
425
+ KeycloakAdmin.realm("a_realm").groups.list(first: 0, max: 100)
426
+ ```
427
+
347
428
  ### Search for a group
348
429
 
349
430
  Returns an array of `KeycloakAdmin::GroupRepresentation`.
350
431
 
351
- According to [the documentation](https://www.keycloak.org/docs-api/22.0.1/rest-api/index.html#_groups):
432
+ According to [the documentation](https://www.keycloak.org/docs-api/latest/rest-api/index.html#_groups):
352
433
  * When providing a `String` parameter, this produces an arbitrary search string
353
434
  * When providing a `Hash`, you can specify other fields (_e.g_ q, max, first)
354
435
 
@@ -879,7 +960,23 @@ KeycloakAdmin.realm("a_realm").client_scope_protocol_mappers(client_scope_id).de
879
960
 
880
961
  ## How to execute library tests
881
962
 
882
- From the `keycloak-admin-api` directory:
963
+ Unit tests need nothing but the gems:
964
+
965
+ ```
966
+ $ bundle install
967
+ $ bundle exec rake spec
968
+ ```
969
+
970
+ Integration tests run against a real Keycloak. `docker-compose.yml` boots one configured like the one CI uses, so a green run locally means the same thing as a green run in CI:
971
+
972
+ ```
973
+ $ docker compose up -d
974
+ $ bundle exec rake integration
975
+ ```
976
+
977
+ To reproduce a failure specific to an older Keycloak, pin `image:` in `docker-compose.yml` to that version and start over with `docker compose down -v && docker compose up -d`. The suite is exercised in CI against Keycloak 19.0, 21.0, 23.0, 25.0 and 26.7.0.
978
+
979
+ Everything can also run inside a container:
883
980
 
884
981
  ```
885
982
  $ docker build . -t keycloak-admin:test
@@ -898,6 +995,6 @@ scoped RubyGems credential.
898
995
  3. Tag the commit and push the tag:
899
996
 
900
997
  ```
901
- $ git tag -a v2.0.1 -m "Version 2.0.1"
902
- $ git push origin v2.0.1
998
+ $ git tag -a v2.0.3 -m "Version 2.0.3"
999
+ $ git push origin v2.0.3
903
1000
  ```
@@ -12,15 +12,24 @@ Gem::Specification.new do |spec|
12
12
  spec.description = "Keycloak Admin REST API client written in Ruby"
13
13
  spec.license = "MIT"
14
14
 
15
- spec.files = `git ls-files -z`.split("\x0")
15
+ spec.files = Dir.glob(["lib/**/*.rb", "CHANGELOG.md", "MIT-LICENSE", "README.md", "keycloak-admin.gemspec"]).sort
16
16
  spec.require_paths = ["lib"]
17
17
 
18
- spec.required_ruby_version = '>= 3.1'
18
+ spec.required_ruby_version = ">= 3.1"
19
+
20
+ spec.metadata = {
21
+ "source_code_uri" => spec.homepage,
22
+ "changelog_uri" => "#{spec.homepage}/blob/main/CHANGELOG.md",
23
+ "bug_tracker_uri" => "#{spec.homepage}/issues",
24
+ "rubygems_mfa_required" => "true"
25
+ }
19
26
 
20
27
  spec.add_dependency "http-cookie", "~> 1.0", ">= 1.0.3"
21
28
  spec.add_dependency "faraday", "~> 2.0"
22
29
  spec.add_dependency "base64"
23
- spec.add_development_dependency "rspec", "3.13.2"
24
- spec.add_development_dependency "byebug", "12.0.0"
25
- spec.add_development_dependency "rake", ">= 13.0"
26
- end
30
+ spec.add_development_dependency "rspec", "3.13.2"
31
+ spec.add_development_dependency "byebug", "12.0.0"
32
+ spec.add_development_dependency "rake", ">= 13.0"
33
+ spec.add_development_dependency "webmock", "~> 3.0"
34
+ spec.add_development_dependency "bundler-audit", "~> 0.9"
35
+ end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class AttackDetectionClient < Client
3
4
  def initialize(configuration, realm_client)
@@ -33,7 +34,7 @@ module KeycloakAdmin
33
34
 
34
35
  def brute_force_url(user_id = nil)
35
36
  if user_id
36
- "#{@realm_client.realm_admin_url}/attack-detection/brute-force/users/#{user_id}"
37
+ "#{@realm_client.realm_admin_url}/attack-detection/brute-force/users/#{encode_segment(user_id)}"
37
38
  else
38
39
  "#{@realm_client.realm_admin_url}/attack-detection/brute-force/users"
39
40
  end
@@ -1,5 +1,9 @@
1
+ # frozen_string_literal: true
2
+ require "uri"
3
+
1
4
  module KeycloakAdmin
2
5
  class Client
6
+ include PathEncoding
3
7
 
4
8
  def initialize(configuration)
5
9
  @configuration = configuration
@@ -13,7 +17,7 @@ module KeycloakAdmin
13
17
  # created for nearly every call (e.g. KeycloakAdmin.realm(x).users creates a fresh
14
18
  # UserClient) - caching here alone would fetch a new token on almost every request.
15
19
  def current_token
16
- @configuration.cached_token || @configuration.cache_token(fetch_token)
20
+ @configuration.fetch_token_once { fetch_token }
17
21
  end
18
22
 
19
23
  def headers
@@ -25,16 +29,24 @@ module KeycloakAdmin
25
29
  end
26
30
 
27
31
  def execute_http
28
- yield
29
- rescue Faraday::TimeoutError
30
- raise
31
- rescue Faraday::ClientError, Faraday::ServerError => e
32
- http_error(e.response)
32
+ replayed = false
33
+ begin
34
+ yield
35
+ rescue Faraday::TimeoutError
36
+ raise
37
+ rescue Faraday::ClientError, Faraday::ServerError => e
38
+ if !replayed && e.response && e.response[:status] == 401 && !@configuration.cached_token.nil?
39
+ @configuration.clear_cached_token!
40
+ replayed = true
41
+ retry
42
+ end
43
+ raise ApiError.from_response(e.response)
44
+ end
33
45
  end
34
46
 
35
47
  def created_id(response)
36
48
  unless response.status == 201
37
- raise "Create method returned status #{response.reason_phrase} (Code: #{response.status}); expected status: Created (201)"
49
+ raise UnexpectedResponseError.new(response.status, response.reason_phrase)
38
50
  end
39
51
  (_head, _separator, id) = response.headers[:location].rpartition("/")
40
52
  id
@@ -52,16 +64,29 @@ module KeycloakAdmin
52
64
 
53
65
  private
54
66
 
67
+ def build_query(parameters)
68
+ parameters.flat_map do |name, value|
69
+ encoded_name = URI.encode_uri_component(name.to_s)
70
+ values = value.is_a?(Array) ? value : [value]
71
+ values.map { |single_value| "#{encoded_name}=#{URI.encode_uri_component(single_value.to_s)}" }
72
+ end.join("&")
73
+ end
74
+
55
75
  def fetch_token
56
76
  KeycloakAdmin.create_client(@configuration, @configuration.client_realm_name).token.get
57
77
  end
58
78
 
59
- def resource(url)
60
- Resource.new(url, @configuration.faraday_options, @configuration.logger)
79
+ def connection_options
80
+ adapter = @configuration.faraday_adapter
81
+ if adapter.nil?
82
+ @configuration.faraday_options
83
+ else
84
+ @configuration.faraday_options.merge(adapter: adapter)
85
+ end
61
86
  end
62
87
 
63
- def http_error(response)
64
- raise "Keycloak: The request failed with response code #{response[:status]} and message: #{response[:body]}"
88
+ def resource(url)
89
+ Resource.new(url, connection_options, @configuration.logger)
65
90
  end
66
91
  end
67
92
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientAuthzPermissionClient < Client
3
4
  def initialize(configuration, realm_client, client_id, type, resource_id = nil)
@@ -20,7 +21,7 @@ module KeycloakAdmin
20
21
 
21
22
  def find_by(name, resource_param, scope = nil)
22
23
  response = execute_http do
23
- url = "#{authz_permission_url(@client_id)}?name=#{name}&resource=#{resource_param}&type=#{@type}&scope=#{scope}&deep=true&first=0&max=100"
24
+ url = "#{authz_permission_url(@client_id)}?#{build_query(name: name, resource: resource_param, type: @type, scope: scope, deep: true, first: 0, max: 100)}"
24
25
  resource(url).get(headers)
25
26
  end
26
27
  JSON.parse(response).map { |role_as_hash| ClientAuthzPermissionRepresentation.from_hash(role_as_hash) }
@@ -55,11 +56,11 @@ module KeycloakAdmin
55
56
 
56
57
  def authz_permission_url(client_id, resource_id = nil, type = nil, id = nil)
57
58
  if resource_id
58
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/resource/#{resource_id}/permissions"
59
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/resource/#{encode_segment(resource_id)}/permissions"
59
60
  elsif id
60
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/permission/#{type}/#{id}"
61
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/permission/#{encode_segment(type)}/#{encode_segment(id)}"
61
62
  else
62
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/permission/#{type}"
63
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/permission/#{encode_segment(type)}"
63
64
  end
64
65
  end
65
66
 
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientAuthzPolicyClient < Client
3
4
  def initialize(configuration, realm_client, client_id, type)
@@ -33,7 +34,7 @@ module KeycloakAdmin
33
34
 
34
35
  def find_by(name, type)
35
36
  response = execute_http do
36
- url = "#{authz_policy_url(@client_id, @type)}?permission=false&name=#{name}&type=#{type}&first=0&max=11"
37
+ url = "#{authz_policy_url(@client_id, @type)}&#{build_query(name: name, type: type, first: 0, max: 11)}"
37
38
  resource(url).get(headers)
38
39
  end
39
40
  JSON.parse(response).map { |role_as_hash| ClientAuthzPolicyRepresentation.from_hash(role_as_hash) }
@@ -55,9 +56,9 @@ module KeycloakAdmin
55
56
 
56
57
  def authz_policy_url(client_id, type, id = nil)
57
58
  if id
58
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/policy/#{type}/#{id}"
59
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/policy/#{encode_segment(type)}/#{encode_segment(id)}"
59
60
  else
60
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/policy/#{type}?permission=false"
61
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/policy/#{encode_segment(type)}?permission=false"
61
62
  end
62
63
  end
63
64
 
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientAuthzResourceClient < Client
3
4
  def initialize(configuration, realm_client, client_id)
@@ -22,17 +23,20 @@ module KeycloakAdmin
22
23
  end
23
24
 
24
25
  def update(resource_id, client_authz_resource_representation)
25
- raise "scope[:name] is mandatory and the only necessary attribute to add scope to resource" if client_authz_resource_representation[:scopes] && client_authz_resource_representation[:scopes].any?{|a| !a[:name]}
26
+ submitted = client_authz_resource_representation || {}
27
+ if submitted[:scopes]&.any? { |scope| !scope[:name] }
28
+ raise ArgumentError.new("scope[:name] is mandatory and the only necessary attribute to add scope to resource")
29
+ end
26
30
 
27
31
  existing_resource = get(resource_id)
28
32
  new_resource = build(
29
- client_authz_resource_representation[:name] || existing_resource.name,
30
- client_authz_resource_representation[:type] || existing_resource.type,
31
- (client_authz_resource_representation[:uris] || [] ) + existing_resource.uris,
32
- client_authz_resource_representation[:owner_managed_access] || existing_resource.owner_managed_access,
33
- client_authz_resource_representation[:display_name] || existing_resource.display_name,
34
- (client_authz_resource_representation[:scopes] || []) + existing_resource.scopes.map{|s| {name: s.name}},
35
- client_authz_resource_representation[:attributes] || existing_resource.attributes
33
+ submitted.fetch(:name, existing_resource.name),
34
+ submitted.fetch(:type, existing_resource.type),
35
+ submitted.fetch(:uris, existing_resource.uris),
36
+ submitted.fetch(:owner_managed_access, existing_resource.owner_managed_access),
37
+ submitted.fetch(:display_name, existing_resource.display_name),
38
+ submitted.fetch(:scopes, existing_resource.scopes.map { |scope| {name: scope.name} }),
39
+ submitted.fetch(:attributes, existing_resource.attributes)
36
40
  )
37
41
 
38
42
  execute_http do
@@ -47,7 +51,7 @@ module KeycloakAdmin
47
51
 
48
52
  def find_by(name, type, uris, owner, scope)
49
53
  response = execute_http do
50
- url = "#{authz_resources_url(@client_id)}?name=#{name}&type=#{type}&uris=#{uris}&owner=#{owner}&scope=#{scope}&deep=true&first=0&max=100"
54
+ url = "#{authz_resources_url(@client_id)}?#{build_query(name: name, type: type, uris: uris, owner: owner, scope: scope, deep: true, first: 0, max: 100)}"
51
55
  resource(url).get(headers)
52
56
  end
53
57
  JSON.parse(response).map { |role_as_hash| ClientAuthzResourceRepresentation.from_hash(role_as_hash) }
@@ -69,9 +73,9 @@ module KeycloakAdmin
69
73
 
70
74
  def authz_resources_url(client_id, id = nil)
71
75
  if id
72
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/resource/#{id}"
76
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/resource/#{encode_segment(id)}"
73
77
  else
74
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/resource"
78
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/resource"
75
79
  end
76
80
  end
77
81
 
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientAuthzScopeClient < Client
3
4
  def initialize(configuration, realm_client, client_id, resource_id = nil)
@@ -35,7 +36,7 @@ module KeycloakAdmin
35
36
  end
36
37
 
37
38
  def search(name)
38
- url = "#{authz_scopes_url(@client_id)}?first=0&max=11&deep=false&name=#{name}"
39
+ url = "#{authz_scopes_url(@client_id)}?#{build_query(first: 0, max: 11, deep: false, name: name)}"
39
40
  response = execute_http do
40
41
  resource(url).get(headers)
41
42
  end
@@ -44,11 +45,11 @@ module KeycloakAdmin
44
45
 
45
46
  def authz_scopes_url(client_id, resource_id = nil, id = nil)
46
47
  if resource_id
47
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/resource/#{resource_id}/scopes"
48
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/resource/#{encode_segment(resource_id)}/scopes"
48
49
  elsif id
49
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/scope/#{id}"
50
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/scope/#{encode_segment(id)}"
50
51
  else
51
- "#{@realm_client.realm_admin_url}/clients/#{client_id}/authz/resource-server/scope"
52
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(client_id)}/authz/resource-server/scope"
52
53
  end
53
54
  end
54
55
 
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientClient < Client
3
4
  def initialize(configuration, realm_client)
@@ -29,7 +30,10 @@ module KeycloakAdmin
29
30
  end
30
31
 
31
32
  def find_by_client_id(client_id)
32
- list.find { |client| client.client_id == client_id }
33
+ response = execute_http do
34
+ resource("#{clients_url}?#{build_query(clientId: client_id)}").get(headers)
35
+ end
36
+ JSON.parse(response).map { |client_as_hash| ClientRepresentation.from_hash(client_as_hash) }.first
33
37
  end
34
38
 
35
39
  def delete(id)
@@ -58,7 +62,7 @@ module KeycloakAdmin
58
62
 
59
63
  def clients_url(id=nil)
60
64
  if id
61
- "#{@realm_client.realm_admin_url}/clients/#{id}"
65
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(id)}"
62
66
  else
63
67
  "#{@realm_client.realm_admin_url}/clients"
64
68
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientRoleClient < Client
3
4
  def initialize(configuration, realm_client)
@@ -14,7 +15,7 @@ module KeycloakAdmin
14
15
  end
15
16
 
16
17
  def clients_url(id)
17
- "#{@realm_client.realm_admin_url}/clients/#{id}/roles"
18
+ "#{@realm_client.realm_admin_url}/clients/#{encode_segment(id)}/roles"
18
19
  end
19
20
  end
20
21
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientRoleMappingsClient < Client
3
4
  def initialize(configuration, user_resource, client_id)
@@ -22,11 +23,11 @@ module KeycloakAdmin
22
23
  end
23
24
 
24
25
  def list_available_url
25
- "#{@user_resource.resource_url}/role-mappings/clients/#{@client_id}/available"
26
+ "#{@user_resource.resource_url}/role-mappings/clients/#{encode_segment(@client_id)}/available"
26
27
  end
27
28
 
28
29
  def base_url
29
- "#{@user_resource.resource_url}/role-mappings/clients/#{@client_id}"
30
+ "#{@user_resource.resource_url}/role-mappings/clients/#{encode_segment(@client_id)}"
30
31
  end
31
32
  end
32
33
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientScopeClient < Client
3
4
  def initialize(configuration, realm_client)
@@ -59,7 +60,7 @@ module KeycloakAdmin
59
60
  def client_scopes_url(client_scope_id = nil)
60
61
  base = "#{@realm_client.realm_admin_url}/client-scopes"
61
62
 
62
- client_scope_id ? "#{base}/#{client_scope_id}" : base
63
+ client_scope_id ? "#{base}/#{encode_segment(client_scope_id)}" : base
63
64
  end
64
65
  end
65
66
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ClientScopeProtocolMapperClient < Client
3
4
  def initialize(configuration, realm_client, client_scope_id)
@@ -54,9 +55,9 @@ module KeycloakAdmin
54
55
  end
55
56
 
56
57
  def protocol_mappers_url(mapper_id = nil)
57
- base = "#{@realm_client.realm_admin_url}/client-scopes/#{@client_scope_id}/protocol-mappers/models"
58
+ base = "#{@realm_client.realm_admin_url}/client-scopes/#{encode_segment(@client_scope_id)}/protocol-mappers/models"
58
59
 
59
- mapper_id ? "#{base}/#{mapper_id}" : base
60
+ mapper_id ? "#{base}/#{encode_segment(mapper_id)}" : base
60
61
  end
61
62
  end
62
63
  end
@@ -1,3 +1,4 @@
1
+ # frozen_string_literal: true
1
2
  module KeycloakAdmin
2
3
  class ConfigurableTokenClient < Client
3
4
  def initialize(configuration, realm_client)
@@ -17,7 +18,7 @@ module KeycloakAdmin
17
18
  def exchange_with(user_access_token, token_lifespan_in_seconds)
18
19
  response = execute_http do
19
20
  Resource.execute(
20
- @configuration.faraday_options.merge(
21
+ connection_options.merge(
21
22
  method: :post,
22
23
  url: token_url,
23
24
  payload: { tokenLifespanInSeconds: token_lifespan_in_seconds }.to_json,