1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
//! Issuer struct contains the discovered OpenID Connect Issuer Metadata.
use core::fmt::Debug;
use std::collections::HashMap;
use std::fmt::Formatter;
use crate::helpers::{convert_json_to, validate_url, webfinger_normalize};
use crate::http::{default_request_interceptor, request, request_async};
use crate::types::{
IssuerMetadata, OidcClientError, Request, RequestOptions, Response, WebFingerResponse,
};
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{Method, StatusCode};
/// Holds all the discovered values from the OIDC Issuer
pub struct Issuer {
/// Discovered issuer uri.
pub issuer: String,
/// OpenID Connect [Authorization Endpoint](https://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint).
pub authorization_endpoint: Option<String>,
/// OpenID Connect [Token Endpoint](https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint).
pub token_endpoint: Option<String>,
/// URL of the authorization server's JWK Set. [See](https://www.rfc-editor.org/rfc/rfc8414.html#section-2).
pub jwks_uri: Option<String>,
/// OpenID Connect [Userinfo Endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo).
pub userinfo_endpoint: Option<String>,
/// Endpoint for revoking refresh tokes and access tokens. [Authorization Server Metadata](https://www.rfc-editor.org/rfc/rfc8414.html#section-2).
pub revocation_endpoint: Option<String>,
/// Claims supported by the Authorization Server
pub claims_parameter_supported: bool,
/// OAuth 2.0 Grant Types supported by the Authorization Server. [RFC 7591](https://www.rfc-editor.org/rfc/rfc7591).
pub grant_types_supported: Vec<String>,
/// Indicates whether request object is supported by Authorization Server. [OIDC Request Object](https://openid.net/specs/openid-connect-core-1_0.html#RequestObject).
pub request_parameter_supported: bool,
/// Indicates whether request object by reference is supported by Authorization Server. [OIDC Request Object by Reference](https://openid.net/specs/openid-connect-core-1_0.html#RequestUriParameter).
pub request_uri_parameter_supported: bool,
/// Whether a request uri has to be pre registered with Authorization Server.
pub require_request_uri_registration: bool,
/// OAuth 2.0 Response Mode values that Authorization Server supports. [Authorization Server Metadata](https://www.rfc-editor.org/rfc/rfc8414.html#section-2).
pub response_modes_supported: Vec<String>,
/// Claim Types supported. [OIDC Claim types](https://openid.net/specs/openid-connect-core-1_0.html#ClaimTypes).
pub claim_types_supported: Vec<String>,
/// Client Authentication methods supported by Token Endpoint. [Client Authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication)
pub token_endpoint_auth_methods_supported: Vec<String>,
request_interceptor: Box<dyn FnMut(&Request) -> RequestOptions>,
}
impl Issuer {
fn default() -> Self {
Self {
claims_parameter_supported: false,
grant_types_supported: vec![
String::from("authorization_code"),
String::from("implicit"),
],
request_parameter_supported: false,
request_uri_parameter_supported: true,
require_request_uri_registration: false,
response_modes_supported: vec![String::from("query"), String::from("fragment")],
claim_types_supported: vec![String::from("normal")],
token_endpoint_auth_methods_supported: vec![String::from("client_secret_basic")],
issuer: "".to_string(),
authorization_endpoint: None,
token_endpoint: None,
jwks_uri: None,
userinfo_endpoint: None,
revocation_endpoint: None,
request_interceptor: Box::new(default_request_interceptor),
}
}
fn from(metadata: IssuerMetadata) -> Self {
Self {
issuer: metadata.issuer,
authorization_endpoint: metadata.authorization_endpoint,
token_endpoint: metadata.token_endpoint,
jwks_uri: metadata.jwks_uri,
userinfo_endpoint: metadata.userinfo_endpoint,
revocation_endpoint: metadata.revocation_endpoint,
..Issuer::default()
}
}
}
/// OIDC [Issuer Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery)
impl Issuer {
/// # Discover OIDC Issuer
///
/// `This is a blocking method.` Checkout [Issuer::discover_async] for async version.
///
/// Discover an OIDC Issuer using the issuer url method.
///
/// ```
/// # use openid_client::Issuer;
///
/// fn main(){
/// let issuer = Issuer::discover("https://auth.example.com").unwrap();
/// }
/// ```
/// Only an absolute urls are accepted, passing in `auth.example.com` will result in an error.
///
/// Urls with `.well-known/openid-configuration` can also be used to discover issuer.
///
/// ```
/// # use openid_client::Issuer;
///
/// fn main(){
/// let issuer = Issuer::discover("https://auth.example.com/.well-known/openid-configurtaion").unwrap();
/// }
/// ```
pub fn discover(issuer: &str) -> Result<Issuer, OidcClientError> {
Issuer::discover_with_interceptor(issuer, Box::new(default_request_interceptor))
}
/// # Discover OIDC Issuer with a request interceptor
///
/// > `This is a blocking method.` Checkout [Issuer::discover_with_interceptor_async] for async version.
///
/// Allows you to pass in a closure that will be called for every request.
/// First parameter is the actual request that is being processed. See [Request].
/// The expected return type is of type [RequestOptions] with custom headers and the timeout.
///
/// ```
/// # use openid_client::{Issuer, HeaderMap, HeaderValue, RequestOptions, Request};
/// # use std::time::Duration;
///
/// fn main(){
/// let interceptor = |_request: &Request| {
/// let mut headers = HeaderMap::new();
/// headers.append("testHeader", HeaderValue::from_static("testHeaderValue"));
///
/// RequestOptions {
/// headers,
/// timeout: Duration::from_millis(3500),
/// }
/// };
///
/// let issuer = Issuer::discover_with_interceptor("https://auth.example.com", Box::new(request_options)).unwrap();
/// }
/// ```
/// Headers that are returned with request options are appended to the headers of the request.
/// If there are duplicate headers, all values are appended to the header like so:
/// `header: value1, value2, value3 ....`
pub fn discover_with_interceptor(
issuer: &str,
mut interceptor: Box<dyn FnMut(&Request) -> RequestOptions>,
) -> Result<Issuer, OidcClientError> {
let req = Self::build_discover_request(issuer)?;
let res = request(req, &mut interceptor)?;
Self::process_discover_response(res, interceptor)
}
/// # Discover OIDC Issuer
///
/// `This is an async method.` Checkout [Issuer::discover] for blocking version.
///
/// Discover an OIDC Issuer using the issuer url method.
///
/// ```
/// # use openid_client::Issuer;
///
/// #[tokio::main]
///async fn main(){
/// let issuer = Issuer::discover_async("https://auth.example.com").await.unwrap();
/// }
/// ```
/// Only an absolute urls are accepted, passing in `auth.example.com` will result in an error.
///
/// Urls with `.well-known/openid-configuration` can also be used to discover issuer.
///
/// ```
/// # use openid_client::Issuer;
///
///#[tokio::main]
///async fn main(){
/// let issuer = Issuer::discover_async("https://auth.example.com/.well-known/openid-configurtaion").await.unwrap();
/// }
/// ```
pub async fn discover_async(issuer: &str) -> Result<Issuer, OidcClientError> {
Self::discover_with_interceptor_async(issuer, Box::new(default_request_interceptor)).await
}
/// # Discover OIDC Issuer with a request interceptor
///
/// > `This is an async method.` Checkout [Issuer::discover_with_interceptor] for blocking version.
///
/// Allows you to pass in a closure that will be called for every request.
/// First parameter is the actual request that is being processed. See [Request].
/// The expected return type is of type [RequestOptions] with custom headers and the timeout.
///
/// ```
/// # use openid_client::{Issuer, HeaderMap, HeaderValue, RequestOptions, Request};
/// # use std::time::Duration;
///
/// #[tokio::main]
/// fn main(){
/// let interceptor = |_request: &Request| {
/// let mut headers = HeaderMap::new();
/// headers.append("testHeader", HeaderValue::from_static("testHeaderValue"));
///
/// RequestOptions {
/// headers,
/// timeout: Duration::from_millis(3500),
/// }
/// };
///
/// let issuer = Issuer::discover_with_interceptor_async("https://auth.example.com", Box::new(request_options)).unwrap();
/// }
/// ```
/// Headers that are returned with request options are appended to the headers of the request.
/// If there are duplicate headers, all values are appended to the header like so:
/// `header: value1, value2, value3 ....`
pub async fn discover_with_interceptor_async(
issuer: &str,
mut request_interceptor: Box<dyn FnMut(&Request) -> RequestOptions>,
) -> Result<Issuer, OidcClientError> {
let req = Self::build_discover_request(issuer)?;
let res = request_async(req, &mut request_interceptor).await?;
Self::process_discover_response(res, request_interceptor)
}
/// This is a private function that is used to build the discover request.
fn build_discover_request(issuer: &str) -> Result<Request, OidcClientError> {
let mut url = match validate_url(issuer) {
Ok(parsed) => parsed,
Err(err) => return Err(err),
};
let mut path: String = url.path().to_string();
if path.ends_with('/') {
path.pop();
}
if path.ends_with(".well-known") {
path.push_str("/openid-configuration");
} else if !path.contains(".well-known") {
path.push_str("/.well-known/openid-configuration");
}
url.set_path(&path);
let mut headers = HeaderMap::new();
headers.append("accept", HeaderValue::from_static("application/json"));
Ok(Request {
url: url.to_string(),
headers,
..Request::default()
})
}
/// This is a private function that is used to process the discover response.
fn process_discover_response(
response: Response,
request_options: Box<dyn FnMut(&Request) -> RequestOptions>,
) -> Result<Issuer, OidcClientError> {
let issuer_metadata =
match convert_json_to::<IssuerMetadata>(response.body.as_ref().unwrap()) {
Ok(metadata) => metadata,
Err(_) => {
return Err(OidcClientError::new(
"OPError",
"invalid_issuer_metadata",
"invalid issuer metadata",
Some(response),
))
}
};
let mut issuer = Issuer::from(issuer_metadata);
issuer.request_interceptor = request_options;
Ok(issuer)
}
}
/// OIDC [Issuer Webfinger Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery)
impl Issuer {
/// # Webfinger OIDC Issuer Discovery
///
/// `This is a blocking method.` Checkout [Issuer::webfinger_async] for async version.
///
/// Discover an OIDC Issuer using the user email, url, url with port syntax or acct syntax.
///
/// ```
/// # use openid_client::Issuer;
///
/// fn main(){
/// let issuer_email = Issuer::webfinger("joe@auth.example.com").unwrap();
/// let issuer_url = Issuer::webfinger("https://auth.example.com/joe").unwrap();
/// let issuer_url_port = Issuer::webfinger("auth.example.com:3000/joe").unwrap();
/// let issuer_acct_email = Issuer::webfinger("acct:joe@auth.example.com").unwrap();
/// let issuer_acct_host = Issuer::webfinger("acct:auth.example.com").unwrap();
/// }
/// ```
pub fn webfinger(input: &str) -> Result<Issuer, OidcClientError> {
Issuer::webfinger_with_interceptor(input, Box::new(default_request_interceptor))
}
/// # Webfinger OIDC Issuer Discovery with request interceptor
///
/// `This is a blocking method.` Checkout [Issuer::webfinger_with_interceptor_async] for async version.
///
/// Discover an OIDC Issuer using the user email, url, url with port syntax or acct syntax.
///
/// Allows you to pass in a closure as a second argument that will be called for every request.
/// First parameter is the actual request that is being processed. See [Request].
/// The expected return type is of type [RequestOptions] with custom headers and the timeout.
///
/// ```
/// # use openid_client::{Issuer, Request, HeaderMap, HeaderValue, RequestOptions};
/// # use std::time::Duration;
///
/// fn main(){
/// let interceptor = |_request: &Request| {
/// let mut headers = HeaderMap::new();
/// headers.append("testHeader", HeaderValue::from_static("testHeaderValue"));
///
/// RequestOptions {
/// headers,
/// timeout: Duration::from_millis(3500),
/// }
/// };
/// let issuer = Issuer::webfinger_with_interceptor("joe@auth.example.com", Box::new(interceptor)).unwrap();
/// }
/// ```
pub fn webfinger_with_interceptor(
input: &str,
mut request_options: Box<dyn FnMut(&Request) -> RequestOptions>,
) -> Result<Issuer, OidcClientError> {
let req = Self::build_webfinger_request(input)?;
let res = request(req, &mut request_options)?;
let expected_issuer = Self::process_webfinger_response(res)?;
let issuer_result = Issuer::discover_with_interceptor(&expected_issuer, request_options);
Self::process_webfinger_issuer_result(issuer_result, expected_issuer)
}
/// # Webfinger OIDC Issuer Discovery
///
/// `This is an async method.` Checkout [Issuer::webfinger] for blocking version.
///
/// Discover an OIDC Issuer using the user email, url, url with port syntax or acct syntax.
///
/// ```
/// use openid_client::Issuer;
///#[tokio::main]
///async fn main(){
/// let issuer_email = Issuer::webfinger_async("joe@auth.example.com").await.unwrap();
/// let issuer_url = Issuer::webfinger_async("https://auth.example.com/joe").await.unwrap();
/// let issuer_url_port = Issuer::webfinger_async("auth.example.com:3000/joe").await.unwrap();
/// let issuer_acct_email = Issuer::webfinger_async("acct:joe@auth.example.com").await.unwrap();
/// let issuer_acct_host = Issuer::webfinger_async("acct:auth.example.com").await.unwrap();
/// }
/// ```
pub async fn webfinger_async(input: &str) -> Result<Issuer, OidcClientError> {
Issuer::webfinger_with_interceptor_async(input, Box::new(default_request_interceptor)).await
}
/// # Webfinger OIDC Issuer Discovery with request interceptor
///
/// `This is an async method.` Checkout [Issuer::webfinger_with_interceptor] for blocking version.
///
/// Discover an OIDC Issuer using the user email, url, url with port syntax or acct syntax.
///
/// Allows you to pass in a closure as a second argument that will be called for every request.
/// First parameter is the actual request that is being processed. See [Request].
/// The expected return type is of type [RequestOptions] with custom headers and the timeout.
///
/// ```
/// use openid_client::{Issuer, Request, HeaderMap, HeaderValue, RequestOptions};
/// use std::time::Duration;
///
///#[tokio::main]
///async fn main(){
/// let interceptor = |_request: &Request| {
/// let mut headers = HeaderMap::new();
/// headers.append("testHeader", HeaderValue::from_static("testHeaderValue"));
///
/// RequestOptions {
/// headers,
/// timeout: Duration::from_millis(3500),
/// }
/// };
/// let issuer = Issuer::webfinger_with_interceptor_async("joe@auth.example.com", Box::new(interceptor)).await.unwrap();
/// }
/// ```
pub async fn webfinger_with_interceptor_async(
input: &str,
mut request_options: Box<dyn FnMut(&Request) -> RequestOptions>,
) -> Result<Issuer, OidcClientError> {
let req = Self::build_webfinger_request(input)?;
let res = request_async(req, &mut request_options).await?;
let expected_issuer = Self::process_webfinger_response(res)?;
let issuer_result =
Issuer::discover_with_interceptor_async(&expected_issuer, request_options).await;
Self::process_webfinger_issuer_result(issuer_result, expected_issuer)
}
/// Private function that builds the webfinger request
fn build_webfinger_request(input: &str) -> Result<Request, OidcClientError> {
let resource = webfinger_normalize(input);
let mut host: Option<String> = None;
if resource.starts_with("acct:") {
let split: Vec<&str> = resource.split('@').collect();
host = Some(split[1].to_string());
} else if resource.starts_with("https://") {
let url = match validate_url(&resource) {
Ok(parsed) => parsed,
Err(err) => return Err(err),
};
if let Some(host_str) = url.host_str() {
host = match url.port() {
Some(port) => Some(host_str.to_string() + &format!(":{}", port)),
None => Some(host_str.to_string()),
}
}
}
if host.is_none() {
return Err(OidcClientError::new(
"TypeError",
"invalid_resource",
"given input was invalid",
None,
));
}
let web_finger_url = format!("https://{}/.well-known/webfinger", host.unwrap());
let mut headers = HeaderMap::new();
headers.append("accept", HeaderValue::from_static("application/json"));
let mut search_params = HashMap::new();
search_params.insert("resource".to_string(), vec![resource]);
search_params.insert(
"rel".to_string(),
vec!["http://openid.net/specs/connect/1.0/issuer".to_string()],
);
Ok(Request {
url: web_finger_url,
method: Method::GET,
headers,
expected: StatusCode::OK,
expect_body: true,
search_params,
})
}
/// Private function that process the webfinger response
fn process_webfinger_response(response: Response) -> Result<String, OidcClientError> {
let webfinger_response =
match convert_json_to::<WebFingerResponse>(response.body.as_ref().unwrap()) {
Ok(res) => res,
Err(_) => {
return Err(OidcClientError::new(
"OPError",
"invalid_webfinger_response",
"invalid webfinger response",
Some(response),
))
}
};
let location_link_result = webfinger_response
.links
.iter()
.find(|x| x.rel == "http://openid.net/specs/connect/1.0/issuer" && x.href.is_some());
let expected_issuer = match location_link_result {
Some(link) => link.href.as_ref().unwrap(),
None => {
return Err(OidcClientError::new(
"OPError",
"empty_location_link",
"no issuer found in webfinger response",
Some(response),
))
}
};
if !expected_issuer.starts_with("https://") {
return Err(OidcClientError::new(
"OPError",
"invalid_location",
&format!("invalid issuer location {}", expected_issuer),
Some(response),
));
}
Ok(expected_issuer.to_string())
}
/// Private function that process the issuer response
fn process_webfinger_issuer_result(
issuer_result: Result<Issuer, OidcClientError>,
expected_issuer: String,
) -> Result<Issuer, OidcClientError> {
let issuer = match issuer_result {
Ok(i) => i,
Err(err) => match err.response {
Some(err_response) if err_response.status == StatusCode::NOT_FOUND => {
return Err(OidcClientError::new(
&err.name,
"no_issuer",
&format!("invalid issuer location {}", expected_issuer),
Some(err_response),
))
}
_ => return Err(err),
},
};
if issuer.issuer != expected_issuer {
return Err(OidcClientError::new(
"OPError",
"issuer_mismatch",
&format!(
"discovered issuer mismatch, expected {}, got: {}",
expected_issuer, issuer.issuer
),
None,
));
}
Ok(issuer)
}
}
impl Debug for Issuer {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Issuer")
.field("issuer", &self.issuer)
.field("authorization_endpoint", &self.authorization_endpoint)
.field("token_endpoint", &self.token_endpoint)
.field("jwks_uri", &self.jwks_uri)
.field("userinfo_endpoint", &self.userinfo_endpoint)
.field("revocation_endpoint", &self.revocation_endpoint)
.field(
"claims_parameter_supported",
&self.claims_parameter_supported,
)
.field("grant_types_supported", &self.grant_types_supported)
.field(
"request_parameter_supported",
&self.request_parameter_supported,
)
.field(
"request_uri_parameter_supported",
&self.request_uri_parameter_supported,
)
.field(
"require_request_uri_registration",
&self.require_request_uri_registration,
)
.field("response_modes_supported", &self.response_modes_supported)
.field("claim_types_supported", &self.claim_types_supported)
.field(
"token_endpoint_auth_methods_supported",
&self.token_endpoint_auth_methods_supported,
)
.field("request_options", &"fn(&String) -> RequestOptions")
.finish()
}
}
#[cfg(test)]
#[path = "./tests/issuer_test.rs"]
mod issuer_test;