Skip to content

Commit bbf3751

Browse files
fix: Encode user ids and names as single URL path segments in UIF (#909)
* fix: Encode user ids and names as single URL path segments in UIF The Keycloak and Entra backends joined request-supplied user ids and names onto the base URL as text, so `/`, `?`, `#` and `..` in them changed which URL was requested. Both now append them as one percent-encoded path segment through `append_path_segments`, and the Keycloak backend sends the username as a query parameter. An empty, `.` or `..` segment and one containing a line break are rejected with `400`, as the url crate would drop or strip them and look up a different user. A Keycloak `rootPath` without a trailing slash is now kept, which `Url::join` dropped. * chore: Regenerate Cargo.nix * chore: Bump rustls-webpki to 0.103.16 * chore: Use UrlExt::join_safe from stackable-operator * chore: Upgrade serde-saphyr * chore: Add ConstructUserGroupsUrl error case * test: Remove unnecessary test case * chore: Remove the dependency to percent-encoding * test(keycloak-user-info): Serve Keycloak below a subpath * chore: Improve comments --------- Co-authored-by: Siegfried Weber <mail@siegfriedweber.net>
1 parent 73667ee commit bbf3751

8 files changed

Lines changed: 485 additions & 66 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,15 @@ All notable changes to this project will be documented in this file.
9292
See [our internal issue](https://github.com/stackabletech/hdfs-operator/issues/626) and [the fix](https://github.com/kube-rs/kube/pull/2042) for details ([#871]).
9393
- The reconciler now applies resources and derives the cluster status in discrete
9494
apply and update_status steps for the `opa_controller` ([#872]).
95+
- The user-info-fetcher Entra backend now encodes the user id and the username as a single URL path
96+
segment. An empty, `.` or `..` id or username, or one containing a line break, is rejected with
97+
`400` ([#909]).
98+
- The user-info-fetcher Keycloak backend now encodes the user id as a single URL path segment, and
99+
sends the username as a query parameter instead of appending it to the URL as text, so that a
100+
username can no longer add or override search parameters. An empty, `.` or `..` id, or one
101+
containing a line break, is rejected with `400` ([#909]).
102+
- The user-info-fetcher Keycloak backend no longer drops a configured `rootPath` from the URLs it
103+
requests, so a Keycloak served below a sub-path, like `/auth`, can now be reached ([#909]).
95104

96105
[#873]: https://github.com/stackabletech/opa-operator/pull/873
97106
[#852]: https://github.com/stackabletech/opa-operator/pull/852
@@ -113,6 +122,7 @@ All notable changes to this project will be documented in this file.
113122
[#905]: https://github.com/stackabletech/opa-operator/pull/905
114123
[#906]: https://github.com/stackabletech/opa-operator/pull/906
115124
[#908]: https://github.com/stackabletech/opa-operator/pull/908
125+
[#909]: https://github.com/stackabletech/opa-operator/pull/909
116126

117127
## [26.7.0] - 2026-07-21
118128

‎Cargo.lock‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.nix‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/user-info-fetcher/src/backend/entra.rs‎

Lines changed: 143 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ use info_fetcher_commons::utils::{
1111
use serde::Deserialize;
1212
use snafu::{ResultExt, Snafu};
1313
use stackable_opa_operator::crd::user_info_fetcher::v1alpha2;
14-
use stackable_operator::commons::{networking::HostName, tls_verification::TlsClientDetails};
14+
use stackable_operator::{
15+
commons::{networking::HostName, tls_verification::TlsClientDetails},
16+
utils::UrlExt,
17+
};
1518
use url::Url;
1619

1720
use crate::{UserInfo, UserInfoRequest, http_error};
@@ -54,6 +57,20 @@ pub enum Error {
5457
endpoint: String,
5558
},
5659

60+
#[snafu(display("failed to construct the Graph URL for user {user:?}"))]
61+
ConstructUserUrl {
62+
source: stackable_operator::utils::UrlError,
63+
user: String,
64+
},
65+
66+
#[snafu(display(
67+
"failed to construct the Graph groups URL for user id {user_id:?} returned by Entra"
68+
))]
69+
ConstructUserGroupsUrl {
70+
source: stackable_operator::utils::UrlError,
71+
user_id: String,
72+
},
73+
5774
#[snafu(display("failed to construct HTTP client"))]
5875
ConstructHttpClient { source: reqwest::Error },
5976

@@ -77,6 +94,18 @@ impl http_error::Error for Error {
7794
Self::UserNotFoundByName { .. } => StatusCode::NOT_FOUND,
7895
Self::RequestUserGroups { .. } => StatusCode::BAD_GATEWAY,
7996
Self::BuildEntraEndpoint { .. } => StatusCode::BAD_REQUEST,
97+
Self::ConstructUserUrl {
98+
source: stackable_operator::utils::UrlError::InvalidSegments { .. },
99+
..
100+
} => StatusCode::BAD_REQUEST,
101+
Self::ConstructUserUrl { .. } => StatusCode::INTERNAL_SERVER_ERROR,
102+
// The groups URL is built from the user id in Graph's own response, so an id that
103+
// cannot be a path segment is a fault of the backend and not of the caller.
104+
Self::ConstructUserGroupsUrl {
105+
source: stackable_operator::utils::UrlError::InvalidSegments { .. },
106+
..
107+
} => StatusCode::BAD_GATEWAY,
108+
Self::ConstructUserGroupsUrl { .. } => StatusCode::INTERNAL_SERVER_ERROR,
80109
Self::ConstructHttpClient { .. } => StatusCode::SERVICE_UNAVAILABLE,
81110
Self::ConfigureTls { .. } => StatusCode::SERVICE_UNAVAILABLE,
82111
Self::ReadClientId { .. } => StatusCode::SERVICE_UNAVAILABLE,
@@ -243,7 +272,7 @@ impl ResolvedEntraBackend {
243272
let user_id = req.id.clone();
244273
send_json_request::<UserMetadata>(
245274
self.http_client
246-
.get(entra_backend.user_info(&user_id))
275+
.get(entra_backend.user_info(&user_id)?)
247276
.bearer_auth(access_token.expose()),
248277
)
249278
.await
@@ -260,7 +289,7 @@ impl ResolvedEntraBackend {
260289
let username = req.username.clone();
261290
send_json_request::<UserMetadata>(
262291
self.http_client
263-
.get(entra_backend.user_info(&username))
292+
.get(entra_backend.user_info(&username)?)
264293
.bearer_auth(access_token.expose()),
265294
)
266295
.await
@@ -274,7 +303,7 @@ impl ResolvedEntraBackend {
274303
};
275304

276305
let mut groups = Vec::new();
277-
let mut next_url = Some(entra_backend.group_info(&user_info.id));
306+
let mut next_url = Some(entra_backend.group_info(&user_info.id)?);
278307
let mut pages_remaining = MAX_GROUP_PAGES;
279308

280309
while let Some(url) = next_url {
@@ -356,22 +385,24 @@ impl EntraBackend {
356385
}
357386

358387
// Works both with id/oid and userPrincipalName
359-
pub fn user_info(&self, user: &str) -> Url {
360-
let mut user_info_url = self.user_info_endpoint_url.clone();
361-
user_info_url.set_path(&format!("/v1.0/users/{user}"));
362-
user_info_url
388+
pub fn user_info(&self, user: &str) -> Result<Url, Error> {
389+
self.user_info_endpoint_url
390+
.join_safe(&["v1.0", "users", user])
391+
.context(ConstructUserUrlSnafu { user })
363392
}
364393

365394
/// Requests the first page of the user's directory memberships.
366395
///
367396
/// `memberOf` returns every directory object the user belongs to: groups as well as directory
368397
/// roles and administrative units.
369-
pub fn group_info(&self, user: &str) -> Url {
370-
let mut user_info_url = self.user_info_endpoint_url.clone();
371-
user_info_url.set_path(&format!("/v1.0/users/{user}/memberOf"));
398+
pub fn group_info(&self, user_id: &str) -> Result<Url, Error> {
399+
let mut group_info_url = self
400+
.user_info_endpoint_url
401+
.join_safe(&["v1.0", "users", user_id, "memberOf"])
402+
.context(ConstructUserGroupsUrlSnafu { user_id })?;
372403
// 999 is the largest page size Graph accepts, and keeps the number of round-trips down.
373-
user_info_url.set_query(Some("$select=displayName&$top=999"));
374-
user_info_url
404+
group_info_url.set_query(Some("$select=displayName&$top=999"));
405+
Ok(group_info_url)
375406
}
376407

377408
/// Rebases an `@odata.nextLink` onto the configured user info endpoint.
@@ -402,7 +433,10 @@ mod tests {
402433
};
403434

404435
use super::*;
405-
use crate::UserInfoRequestById;
436+
use crate::{
437+
UserInfoRequestById,
438+
backend::test_mocks::{HOSTILE_PATH_USERS, assert_looked_up_below, received_lookups},
439+
};
406440

407441
const TENANT_ID: &str = "1234-5678-1234-5678";
408442
const USER_ID: &str = "8765-4321-8765-4321";
@@ -479,10 +513,13 @@ mod tests {
479513
.await;
480514
}
481515

482-
async fn look_up_by_id(backend: &ResolvedEntraBackend) -> Result<UserInfo, super::Error> {
516+
async fn look_up_by_id(
517+
backend: &ResolvedEntraBackend,
518+
id: &str,
519+
) -> Result<UserInfo, super::Error> {
483520
backend
484521
.get_user_info(&UserInfoRequest::UserInfoRequestById(UserInfoRequestById {
485-
id: USER_ID.to_owned(),
522+
id: id.to_owned(),
486523
}))
487524
.await
488525
}
@@ -507,7 +544,7 @@ mod tests {
507544
let mock_server = MockServer::start().await;
508545
mock_token_and_failing_user(&mock_server, USER_ID, 404).await;
509546

510-
let error = look_up_by_id(&backend_for(&mock_server))
547+
let error = look_up_by_id(&backend_for(&mock_server), USER_ID)
511548
.await
512549
.expect_err("a user Entra does not have cannot be looked up");
513550

@@ -527,7 +564,7 @@ mod tests {
527564
let mock_server = MockServer::start().await;
528565
mock_token_and_failing_user(&mock_server, USER_ID, status).await;
529566

530-
let error = look_up_by_id(&backend_for(&mock_server))
567+
let error = look_up_by_id(&backend_for(&mock_server), USER_ID)
531568
.await
532569
.expect_err("a failing lookup surfaces as an error");
533570

@@ -560,6 +597,90 @@ mod tests {
560597
);
561598
}
562599

600+
/// Mounts the token endpoint plus an answer of `404` to every lookup.
601+
async fn mock_token_and_no_users(mock_server: &MockServer) {
602+
mock_token(mock_server, Some(3600), 1).await;
603+
Mock::given(method("GET"))
604+
.respond_with(ResponseTemplate::new(404))
605+
.mount(mock_server)
606+
.await;
607+
}
608+
609+
/// A request-supplied id stays one segment under `/v1.0/users/`, so `../` cannot reach another
610+
/// Graph endpoint with the access token. A username needs no test of its own: Graph addresses
611+
/// the user by id or by principal name in that very same segment.
612+
#[tokio::test]
613+
async fn entra_keeps_a_hostile_id_inside_the_users_endpoint() {
614+
for &user_id in HOSTILE_PATH_USERS {
615+
let mock_server = MockServer::start().await;
616+
mock_token_and_no_users(&mock_server).await;
617+
618+
let error = look_up_by_id(&backend_for(&mock_server), user_id)
619+
.await
620+
.expect_err("Entra does not have the user");
621+
622+
assert!(
623+
matches!(error, Error::UserNotFoundById { .. }),
624+
"for {user_id:?} got {error}"
625+
);
626+
assert_looked_up_below(&mock_server, "/v1.0/users/", user_id).await;
627+
}
628+
}
629+
630+
/// An empty, `.` or `..` user would be dropped from the path, turning the lookup of one user
631+
/// into a listing of all of them, and a line break would be stripped, looking up another user.
632+
#[tokio::test]
633+
async fn entra_rejects_a_user_that_cannot_be_a_path_segment() {
634+
for username in ["", ".", "..", "ad\nmin"] {
635+
let mock_server = MockServer::start().await;
636+
mock_token(&mock_server, Some(3600), 1).await;
637+
638+
let error = look_up_by_name(&backend_for(&mock_server), username)
639+
.await
640+
.expect_err("the user is rejected before Entra is asked");
641+
642+
assert!(
643+
matches!(error, Error::ConstructUserUrl { .. }),
644+
"for {username:?} got {error}"
645+
);
646+
assert_eq!(
647+
http_error::Error::status_code(&error),
648+
StatusCode::BAD_REQUEST
649+
);
650+
assert!(received_lookups(&mock_server).await.is_empty());
651+
}
652+
}
653+
654+
/// The group memberships are requested for the id in Graph's own answer, so an id that cannot be
655+
/// a path segment is a fault of the backend and must not be reported as a bad request of the
656+
/// caller.
657+
#[tokio::test]
658+
async fn entra_reports_an_unusable_id_in_its_own_answer_as_a_backend_fault() {
659+
let mock_server = MockServer::start().await;
660+
mock_token(&mock_server, Some(3600), 1).await;
661+
Mock::given(method("GET"))
662+
.and(path(format!("/v1.0/users/{USER_ID}")))
663+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
664+
"id": "",
665+
"userPrincipalName": "alice@example.com",
666+
})))
667+
.mount(&mock_server)
668+
.await;
669+
670+
let error = look_up_by_id(&backend_for(&mock_server), USER_ID)
671+
.await
672+
.expect_err("the group memberships of a user without an id cannot be requested");
673+
674+
assert!(
675+
matches!(error, Error::ConstructUserGroupsUrl { .. }),
676+
"{error}"
677+
);
678+
assert_eq!(
679+
http_error::Error::status_code(&error),
680+
StatusCode::BAD_GATEWAY
681+
);
682+
}
683+
563684
async fn get_user_info_by_id(backend: &ResolvedEntraBackend) -> UserInfo {
564685
backend
565686
.get_user_info(&UserInfoRequest::UserInfoRequestById(UserInfoRequestById {
@@ -723,11 +844,11 @@ mod tests {
723844
.unwrap()
724845
);
725846
assert_eq!(
726-
entra.user_info(user),
847+
entra.user_info(user).expect("valid user"),
727848
Url::parse(&format!("https://graph.microsoft.com/v1.0/users/{user}")).unwrap()
728849
);
729850
assert_eq!(
730-
entra.group_info(user),
851+
entra.group_info(user).expect("valid user"),
731852
Url::parse(&format!(
732853
"https://graph.microsoft.com/v1.0/users/{user}/memberOf?$select=displayName&$top=999"
733854
))
@@ -763,11 +884,11 @@ mod tests {
763884
.unwrap()
764885
);
765886
assert_eq!(
766-
entra.user_info(user),
887+
entra.user_info(user).expect("valid user"),
767888
Url::parse(&format!("http://graph.mock.com:8080/v1.0/users/{user}")).unwrap()
768889
);
769890
assert_eq!(
770-
entra.group_info(user),
891+
entra.group_info(user).expect("valid user"),
771892
Url::parse(&format!(
772893
"http://graph.mock.com:8080/v1.0/users/{user}/memberOf?$select=displayName&$top=999"
773894
))

0 commit comments

Comments
 (0)