fix(security): drop expired rsa 0.9.10 advisory exception (#9678)

openidconnect 4.1.0 is the only consumer of rsa 0.9.10 and has no
released rsa 0.10 build. Vendor that crate, retarget JWS verification
to rsa 0.10, and remove the exception that expired on 2026-07-31.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Chris An <overtrue@users.noreply.github.com>
This commit is contained in:
Chris An
2026-11-27 21:27:55 +08:00
committed by GitHub
co-authored by Cursor Agent Chris An
parent 2e5e99a994
commit c3f2636c6b
46 changed files with 19464 additions and 88 deletions
-12
View File
@@ -13,18 +13,6 @@
schema_version = 1
[[exceptions]]
advisory_id = "RUSTSEC-2023-0071"
crate = "rsa"
affected_versions = "=0.9.10"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "Transitive rsa 0.9.10 pulled exclusively via openidconnect 4.1.0 <- rustfs-iam; direct workspace rsa consumers already upgraded to patched rsa 0.10.0 in PR #9492. Historical 2026-07 review window has expired and requires maintainer risk-acceptance sign-off or upstream openidconnect upgrade to rsa >=0.10.0 before promotion."
mitigation = "crates/iam/src/oidc uses openidconnect only for public-key JWS ID-token verification and rejects signed or encrypted UserInfo responses (crates/iam/src/oidc/runtime.rs), exposing no remote RSA private-key decryption oracle on rsa 0.9.10. Track upstream openidconnect migration off rsa 0.9.x."
approved_at = "2026-05-06T07:47:19Z"
expires_at = "2026-07-31T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/2769"
[[exceptions]]
advisory_id = "RUSTSEC-2026-0543"
crate = "chrono"
Generated
+7 -69
View File
@@ -6312,9 +6312,6 @@ name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
dependencies = [
"spin 0.9.9",
]
[[package]]
name = "lexical-core"
@@ -7231,22 +7228,6 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "num-bigint-dig"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
dependencies = [
"lazy_static",
"libm",
"num-integer",
"num-iter",
"num-traits",
"rand 0.8.8",
"smallvec",
"zeroize",
]
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -7271,16 +7252,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
@@ -7659,8 +7630,6 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "openidconnect"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -7675,7 +7644,7 @@ dependencies = [
"p256",
"p384",
"rand 0.8.8",
"rsa 0.9.10",
"rsa",
"serde",
"serde-value",
"serde_json",
@@ -8358,17 +8327,6 @@ dependencies = [
"futures-io",
]
[[package]]
name = "pkcs1"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [
"der 0.7.10",
"pkcs8 0.10.2",
"spki 0.7.3",
]
[[package]]
name = "pkcs1"
version = "0.8.0"
@@ -9672,26 +9630,6 @@ dependencies = [
"xmlparser",
]
[[package]]
name = "rsa"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
dependencies = [
"const-oid 0.9.6",
"digest 0.10.7",
"num-bigint-dig",
"num-integer",
"num-traits",
"pkcs1 0.7.5",
"pkcs8 0.10.2",
"rand_core 0.6.4",
"signature 2.2.0",
"spki 0.7.3",
"subtle",
"zeroize",
]
[[package]]
name = "rsa"
version = "0.10.0"
@@ -9704,7 +9642,7 @@ dependencies = [
"crypto-primes",
"digest 0.11.3",
"hmac 0.13.0",
"pkcs1 0.8.0",
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.1",
@@ -9808,13 +9746,13 @@ dependencies = [
"p521",
"pageant",
"pbkdf2 0.13.0",
"pkcs1 0.8.0",
"pkcs1",
"pkcs5 0.8.1",
"pkcs8 0.11.0",
"polyval",
"rand 0.10.4",
"rand_core 0.10.1",
"rsa 0.10.0",
"rsa",
"russh-cryptovec",
"russh-util",
"salsa20 0.11.0",
@@ -10007,7 +9945,7 @@ dependencies = [
"regex",
"reqwest 0.13.5",
"rmp-serde",
"rsa 0.10.0",
"rsa",
"rust-embed",
"rustfs-audit",
"rustfs-common",
@@ -10216,7 +10154,7 @@ dependencies = [
"jsonwebtoken 12.0.0",
"pbkdf2 0.13.0",
"rand 0.10.4",
"rsa 0.10.0",
"rsa",
"serde",
"serde_json",
"sha2 0.11.1",
@@ -12908,7 +12846,7 @@ dependencies = [
"p384",
"p521",
"rand_core 0.10.1",
"rsa 0.10.0",
"rsa",
"sec1",
"serde",
"sha1 0.11.0",
+4 -1
View File
@@ -73,7 +73,7 @@ members = [
"crates/zip", # ZIP file handling and compression
"crates/zstd-compat", # Fixed codec for dependencies requiring zstd 0.13
]
exclude = ["vendor/hyper"]
exclude = ["vendor/hyper", "vendor/openidconnect"]
resolver = "3"
[workspace.package]
@@ -243,6 +243,7 @@ chacha20poly1305 = { version = "0.11.0" }
crc-fast = "1.10.0"
hmac = { version = "0.13.0" }
jsonwebtoken = { version = "12.0.0" }
# Patched onto rsa 0.10 in vendor/openidconnect until upstream releases that dependency.
openidconnect = { default-features = false, version = "4.1.0" }
pbkdf2 = "0.13.0"
p256 = { version = "0.14.0", features = ["ecdsa", "pkcs8"] }
@@ -460,4 +461,6 @@ strip = "none"
[patch.crates-io]
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
# Remove after openidconnect releases an rsa >= 0.10 build (ramosbugs/openidconnect-rs#140).
openidconnect = { path = "vendor/openidconnect" }
zstd = { path = "crates/zstd-compat" }
-6
View File
@@ -21,12 +21,6 @@ no-default-features = false
version = 2
yanked = "deny"
ignore = [
# `rsa` Marvin timing sidechannel (RUSTSEC-2023-0071, patched in >= 0.10.0).
# Direct workspace consumers migrated to `rsa 0.10.0` in PR #9492; only
# transitive `rsa 0.9.10` remains via `openidconnect 4.1.0` (`rustfs-iam`).
# Machine-enforced expiry and approval metadata live in `.config/advisory-exceptions.toml`.
# owner: rustfs-maintainers review: 2026-07
{ id = "RUSTSEC-2023-0071", reason = "rsa 0.9.10 Marvin timing sidechannel via openidconnect 4.1.0; tracked in .config/advisory-exceptions.toml" },
# `chrono` is retained only at compatibility boundaries while the project
# migrates its internal time model to jiff. The advisory reports no safe
# upgrade for any chrono release. Tracked in `.config/advisory-exceptions.toml`.
+193
View File
@@ -0,0 +1,193 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.88"
name = "openidconnect"
version = "4.1.0"
authors = ["David A. Ramos <ramos@cs.stanford.edu>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "OpenID Connect library"
readme = "README.md"
keywords = [
"openid",
"oidc",
"oauth2",
"authentication",
"auth",
]
license = "MIT"
repository = "https://github.com/ramosbugs/openidconnect-rs"
[package.metadata.docs.rs]
all-features = true
[badges.maintenance]
status = "actively-developed"
[features]
accept-rfc3339-timestamps = []
accept-string-booleans = []
curl = ["oauth2/curl"]
default = [
"reqwest",
"rustls-tls",
]
native-tls = ["oauth2/native-tls"]
reqwest = ["oauth2/reqwest"]
reqwest-blocking = ["oauth2/reqwest-blocking"]
rustls-tls = ["oauth2/rustls-tls"]
timing-resistant-secret-traits = ["oauth2/timing-resistant-secret-traits"]
ureq = ["oauth2/ureq"]
[lib]
name = "openidconnect"
path = "src/lib.rs"
[[example]]
name = "gitlab"
path = "examples/gitlab.rs"
required-features = ["reqwest-blocking"]
[[example]]
name = "google"
path = "examples/google.rs"
required-features = ["reqwest-blocking"]
[[example]]
name = "okta_device_grant"
path = "examples/okta_device_grant.rs"
required-features = ["reqwest-blocking"]
[[test]]
name = "rp_certification_code"
path = "tests/rp_certification_code.rs"
[[test]]
name = "rp_certification_dynamic"
path = "tests/rp_certification_dynamic.rs"
[[test]]
name = "rp_common"
path = "tests/rp_common.rs"
[dependencies.base64]
version = "0.22"
[dependencies.chrono]
version = "0.4"
features = [
"clock",
"std",
"wasmbind",
]
default-features = false
[dependencies.dyn-clone]
version = "1.0.10"
[dependencies.ed25519-dalek]
version = "3"
features = ["pem"]
[dependencies.getrandom]
version = "0.4"
features = ["wasm_js"]
[dependencies.hmac]
version = "0.12.1"
[dependencies.http]
version = "1.0"
[dependencies.itertools]
version = "0.14"
[dependencies.log]
version = "0.4"
[dependencies.oauth2]
version = "5.0.0"
default-features = false
[dependencies.p256]
version = "0.14"
[dependencies.p384]
version = "0.14"
[dependencies.rand]
version = "0.8.5"
[dependencies.rsa]
version = "0.10.0"
features = ["pkcs1v15"]
[dependencies.serde]
version = "1.0"
[dependencies.serde-value]
version = "0.7"
[dependencies.serde_json]
version = "1.0"
[dependencies.serde_path_to_error]
version = "0.1"
[dependencies.serde_plain]
version = "1.0"
[dependencies.serde_with]
version = "3"
[dependencies.sha2]
version = "0.10.6"
features = ["oid"]
[dependencies.subtle]
version = "2.4"
[dependencies.thiserror]
version = "1.0"
[dependencies.url]
version = "2.4"
features = ["serde"]
[dev-dependencies.anyhow]
version = "1.0"
[dev-dependencies.color-backtrace]
version = "0.5"
[dev-dependencies.env_logger]
version = "0.9"
[dev-dependencies.pretty_assertions]
version = "1.0"
[dev-dependencies.reqwest]
version = "0.12"
features = [
"blocking",
"rustls-tls",
]
default-features = false
[dev-dependencies.retry]
version = "1.0"
+83
View File
@@ -0,0 +1,83 @@
[package]
name = "openidconnect"
version = "4.1.0"
authors = ["David A. Ramos <ramos@cs.stanford.edu>"]
description = "OpenID Connect library"
keywords = ["openid", "oidc", "oauth2", "authentication", "auth"]
license = "MIT"
repository = "https://github.com/ramosbugs/openidconnect-rs"
edition = "2021"
readme = "README.md"
rust-version = "1.88"
[package.metadata.docs.rs]
all-features = true
[badges]
maintenance = { status = "actively-developed" }
[features]
accept-rfc3339-timestamps = []
accept-string-booleans = []
curl = ["oauth2/curl"]
default = ["reqwest", "rustls-tls"]
native-tls = ["oauth2/native-tls"]
reqwest = ["oauth2/reqwest"]
reqwest-blocking = ["oauth2/reqwest-blocking"]
rustls-tls = ["oauth2/rustls-tls"]
timing-resistant-secret-traits = ["oauth2/timing-resistant-secret-traits"]
ureq = ["oauth2/ureq"]
[[example]]
name = "gitlab"
required-features = ["reqwest-blocking"]
[[example]]
name = "google"
required-features = ["reqwest-blocking"]
[[example]]
name = "okta_device_grant"
required-features = ["reqwest-blocking"]
[dependencies]
base64 = "0.22"
# Disable 'time' dependency since it triggers RUSTSEC-2020-0071 and we don't need it.
chrono = { version = "0.4", default-features = false, features = [
"clock",
"std",
"wasmbind"
] }
thiserror = "1.0"
http = "1.0"
itertools = "0.14"
log = "0.4"
oauth2 = { version = "5.0.0", default-features = false }
rand = "0.8.5"
hmac = "0.12.1"
rsa = { version = "0.10.0", features = ["pkcs1v15"] }
sha2 = { version = "0.10.6", features = ["oid"] } # Object ID needed for pkcs1v15 padding
p256 = "0.14"
p384 = "0.14"
dyn-clone = "1.0.10"
serde = "1.0"
serde_json = "1.0"
serde_path_to_error = "0.1"
serde_plain = "1.0"
serde_with = "3"
serde-value = "0.7"
url = { version = "2.4", features = ["serde"] }
subtle = "2.4"
ed25519-dalek = { version = "3", features = ["pem"] }
# For backward compatibility with earlier 4.x releases, enables the `wasm_js` feature on WASM
# targets.
getrandom = { version = "0.4", features = ["wasm_js"] }
[dev-dependencies]
color-backtrace = { version = "0.5" }
env_logger = "0.9"
pretty_assertions = "1.0"
reqwest = { version = "0.12", features = ["blocking", "rustls-tls"], default-features = false }
retry = "1.0"
anyhow = "1.0"
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 David Ramos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+61
View File
@@ -0,0 +1,61 @@
# [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html) Library for Rust
[![crates.io](https://img.shields.io/crates/v/openidconnect.svg)](https://crates.io/crates/openidconnect)
[![docs.rs](https://docs.rs/openidconnect/badge.svg)](https://docs.rs/openidconnect)
[![Build Status](https://github.com/ramosbugs/openidconnect-rs/actions/workflows/main.yml/badge.svg)](https://github.com/ramosbugs/openidconnect-rs/actions/workflows/main.yml)
[![codecov](https://codecov.io/gh/ramosbugs/openidconnect-rs/branch/main/graph/badge.svg)](https://codecov.io/gh/ramosbugs/openidconnect-rs)
This library provides extensible, strongly-typed interfaces for the OpenID
Connect protocol, which can be used to authenticate users via
[Google](https://developers.google.com/identity/openid-connect/openid-connect),
[GitLab](https://docs.gitlab.com/ee/integration/openid_connect_provider.html),
[Microsoft](https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc),
and [many other providers](https://openid.net/certification/#OPENID-OP-P).
API documentation and examples are available on [docs.rs](https://docs.rs/openidconnect).
## Minimum Supported Rust Version (MSRV)
The MSRV for *4.1* and newer releases of this crate is Rust **1.88**.
The MSRV for *3.3* to *4.0* releases of this crate is Rust **1.65**.
The MSRV for *3.0* to *3.2* releases of this crate is Rust **1.57**.
The MSRV for *2.x* releases of this crate is Rust 1.45.
Since the 3.0.0 release, this crate maintains a policy of supporting
Rust releases going back at least 6 months. Changes that break compatibility with Rust releases
older than 6 months will no longer be considered SemVer breaking changes and will not result in a
new major version number for this crate. MSRV changes will coincide with minor version updates
and will not happen in patch releases.
## Standards
* [OpenID Connect Core](https://openid.net/specs/openid-connect-core-1_0.html)
* Supported features:
* Relying Party flows: code, implicit, hybrid
* Standard claims
* UserInfo endpoint
* RSA, HMAC, ECDSA (P-256/P-384 curves) and EdDSA (Ed25519 curve) ID token verification
* Unsupported features:
* Aggregated and distributed claims
* Passing request parameters as JWTs
* Verification of the `azp` claim (see [discussion](https://bitbucket.org/openid/connect/issues/973/))
* ECDSA-based ID token verification using the P-521 curve
* JSON Web Encryption (JWE)
* [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)
* Supported features:
* Provider Metadata
* Unsupported features:
* WebFinger
* [OpenID Connect Dynamic Client Registration](https://openid.net/specs/openid-connect-registration-1_0.html)
* Supported features:
* Client Metadata
* Client Registration endpoint
* Unsupported features:
* Client Configuration endpoint
* [OpenID Connect RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html)
* [OAuth 2.0 Token Introspection](https://tools.ietf.org/html/rfc7662)
* [OAuth 2.0 Token Revocation](https://tools.ietf.org/html/rfc7009)
* [OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628)
+9
View File
@@ -0,0 +1,9 @@
# openidconnect rsa 0.10
This directory contains the published `openidconnect` 4.1.0 crate (crates.io SHA-256 `df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c`) with the dependency moved from `rsa` 0.9.2 to `rsa` 0.10.0. Upstream 4.1.0 is still the latest release and still requires `rsa ^0.9.2`, which cargo-deny reports as `RUSTSEC-2023-0071` (Marvin timing sidechannel, patched in `rsa >= 0.10.0`). Tracking issue: [ramosbugs/openidconnect-rs#140](https://github.com/ramosbugs/openidconnect-rs/issues/140).
The patch keeps ID-token verification on the same JWS algorithms. PKCS#1 v1.5 and PSS padding now use `rsa`'s own SHA-2 types, while the hashed message bytes are still produced by this crate's `sha2` 0.10 dependency. JWK modulus and exponent values are decoded as unsigned big-endian integers with leading `0x00` octets removed, matching the previous `num-bigint` decode. RSA signing adapts the existing `rand` 0.8 generator to `rand_core` 0.10 because `rsa` 0.10 requires that trait for blinding and PSS salt. RustFS calls this crate for public-key ID-token verification and confidential-client secrets; it does not use the RSA private signing type on the request path.
No registry, git, or example files from the published crate are omitted except VCS metadata and the upstream lockfiles. One trailing-whitespace line in `UPGRADE.md` was removed so the tree passes whitespace checks. The workspace lockfile is authoritative. Remove this directory and the `openidconnect` Cargo patch when a released `openidconnect` depends on `rsa >= 0.10.0`.
The upstream MIT license is retained in `LICENSE`.
+310
View File
@@ -0,0 +1,310 @@
# Upgrade Guide
## Upgrading from 3.x to 4.x
The 4.0 release includes breaking changes to address several long-standing API issues, along with
a few minor improvements. Consider following the tips below to help ensure a smooth upgrade
process. This document is not exhaustive but covers the breaking changes most likely to affect
typical uses of this crate.
### Add typestate generic types to `Client`
Each auth flow depends on one or more server endpoints. For example, the
authorization code flow depends on both an authorization endpoint and a token endpoint, while the
client credentials flow only depends on a token endpoint. Previously, it was possible to instantiate
a `Client` without a token endpoint and then attempt to use an auth flow that required a token
endpoint, leading to errors at runtime. Also, the authorization endpoint was always required, even
for auth flows that do not use it.
In the 4.0 release, all endpoints are optional.
[Typestates](https://cliffle.com/blog/rust-typestate/) are used to statically track, at compile
time, which endpoints' setters (e.g., `set_auth_uri()`) have been called. Auth flows that depend on
an endpoint cannot be used without first calling the corresponding setter, which is enforced by the
compiler's type checker. This guarantees that certain errors will not arise at runtime.
When using [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)
(i.e., `Client::from_provider_metadata()`),
each discoverable endpoint is set to a conditional typestate (`EndpointMaybeSet`). This is because
it cannot be determined at compile time whether each of these endpoints will be returned by the
OpenID Provider. When the conditional typestate is set, endpoints can be used via fallible methods
that return `Err(ConfigurationError::MissingUrl(_))` if an endpoint has not been set.
There are three possible typestates, each implementing the `EndpointState` trait:
* `EndpointNotSet`: the corresponding endpoint has **not** been set and cannot be used.
* `EndpointSet`: the corresponding endpoint **has** been set and is ready to be used.
* `EndpointMaybeSet`: the corresponding endpoint **may have** been set and can be used via fallible
methods that return `Result<_, ConfigurationError>`.
The following code changes are required to support the new interface:
1. Update calls to
[`Client::new()`](https://docs.rs/openidconnect/latest/openidconnect/struct.Client.html#method.new)
to use the three-argument constructor (which accepts only a `ClientId`, `IssuerUrl`, and
`JsonWebKeySet`). Use the `set_auth_uri()`, `set_token_uri()`, `set_user_info_url()`, and
`set_client_secret()` methods to set the authorization endpoint, token endpoint, user info
endpoint, and client secret, respectively, if applicable to your application's auth flows.
2. If using `Client::from_provider_metadata()`, update call sites that use each auth flow
(e.g., `Client::exchange_code()`) to handle the possibility of a `ConfigurationError` if the
corresponding endpoint was not specified in the provider metadata.
3. If required by your usage of the `Client` or `CoreClient` types (i.e., if you see related
compiler errors), add the following generic parameters:
```rust
HasAuthUrl: EndpointState,
HasDeviceAuthUrl: EndpointState,
HasIntrospectionUrl: EndpointState,
HasRevocationUrl: EndpointState,
HasTokenUrl: EndpointState,
HasUserInfoUrl: EndpointState,
```
For example, if you store a `CoreClient` within another data type, you may need to annotate it as
`CoreClient<EndpointSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointSet, EndpointNotSet>`
if it has both an authorization endpoint and a token endpoint set. Compiler error messages will
likely guide you to the appropriate combination of typestates.
If, instead of using `CoreClient`, you are directly using `Client` with a different set of type
parameters, you will need to append the five generic typestate parameters. For example, replace:
```rust
type SpecialClient = Client<
EmptyAdditionalClaims,
CoreAuthDisplay,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
CoreJsonWebKeyType,
CoreJsonWebKeyUse,
CoreJsonWebKey,
CoreAuthPrompt,
StandardErrorResponse<CoreErrorResponseType>,
SpecialTokenResponse,
CoreTokenType,
CoreTokenIntrospectionResponse,
CoreRevocableToken,
CoreRevocationErrorResponse,
>;
```
with:
```rust
type SpecialClient<
HasAuthUrl = EndpointNotSet,
HasDeviceAuthUrl = EndpointNotSet,
HasIntrospectionUrl = EndpointNotSet,
HasRevocationUrl = EndpointNotSet,
HasTokenUrl = EndpointNotSet,
HasUserInfoUrl = EndpointNotSet,
> = Client<
EmptyAdditionalClaims,
CoreAuthDisplay,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJsonWebKey,
CoreAuthPrompt,
StandardErrorResponse<CoreErrorResponseType>,
SpecialTokenResponse,
CoreTokenIntrospectionResponse,
CoreRevocableToken,
CoreRevocationErrorResponse,
HasAuthUrl,
HasDeviceAuthUrl,
HasIntrospectionUrl,
HasRevocationUrl,
HasTokenUrl,
HasUserInfoUrl,
>;
```
The default values (`= EndpointNotSet`) are optional but often helpful since they will allow you
to instantiate a client using `SpecialClient::new()` instead of having to specify
`SpecialClient::<EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointNotSet>::new()`.
Also note that the `CoreJwsSigningAlgorithm` (`JS`), `CoreJsonWebKeyType` (`JT`),
`CoreJsonWebKeyUse` (`JU`), and `CoreTokenType` (`TT`) type parameters have been removed (see
below) since they are now implied by the `JsonWebKey` (`K`) and `TokenResponse`
(`TR`)/`TokenIntrospectionResponse` (`TIR`) type parameters.
### Replace JWT-related generic traits with associated types
Previously, the `JsonWebKey` trait had the following generic type parameters:
```rust
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
```
In the 4.0 release, these generic type parameters have been removed and replaced with two associated
types:
```rust
/// Allowed key usage.
type KeyUse: JsonWebKeyUse;
/// JSON Web Signature (JWS) algorithm.
type SigningAlgorithm: JwsSigningAlgorithm;
```
The `JT` type parameter was similarly removed from the `JwsSigningAlgorithm` trait and replaced
with an associated type:
```rust
/// Key type (e.g., RSA).
type KeyType: JsonWebKeyType;
```
Similar changes were made to the lesser-used `PrivateSigningKey` and `JweContentEncryptionAlgorithm`
traits.
With the conversion to associated types, many generic type parameters throughout this crate became
redundant and were removed in the 4.0 release. For example, the `Client` no longer needs the
`JS`, `JT`, or `JU` parameters, which are implied by the `JsonWebKey` (`K`) type.
### Rename endpoint getters and setters for consistency
The 2.0 release aimed to align the naming of each endpoint with the terminology used in the relevant
RFC. For example, [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749#section-3.1) uses the
term "endpoint URI" to refer to the authorization and token endpoints, while
[RFC 7009](https://datatracker.ietf.org/doc/html/rfc7009#section-2) refers to the
"token revocation endpoint URL," and
[RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662#section-2) uses neither "URI" nor "URL"
to describe the introspection endpoint. However, the renaming in 2.0 was both internally
inconsistent, and inconsistent with the specs.
In 4.0, the `Client`'s getters and setters for each endpoint are now named as follows:
* Authorization endpoint: `auth_uri()`/`set_auth_uri()` (newly added)
* Token endpoint: `token_uri()`/`set_token_uri()` (newly added)
* Redirect: `redirect_uri()`/`set_redirect_uri()` (no change to setter)
* Revocation endpoint: `revocation_url()`/`set_revocation_url()`
* Introspection endpoint: `introspection_url()`/`set_introspection_url()`
* Device authorization endpoint: `device_authorization_url()`/`set_device_authorization_url()`
* User info: `user_info_url()`/`set_user_info_url()` (newly added)
### Use stateful HTTP clients
Previously, the HTTP clients provided by this crate were stateless. For example, the
`openidconnect::reqwest::async_http_client()` method would instantiate a new `reqwest::Client` for
each request. This meant that TCP connections could not be reused across requests, and customizing
HTTP clients (e.g., adding a custom request header to every request) was inconvenient.
The 4.0 release introduces two new traits: `AsyncHttpClient` and `SyncHttpClient`. Each
`request_async()` and `request()` method now accepts a reference to a type that implements these
traits, respectively, rather than a function type.
> [!WARNING]
> To prevent
[SSRF](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html)
vulnerabilities, be sure to configure the HTTP client **not to follow redirects**. For example, use
> [`redirect::Policy::none`](https://docs.rs/reqwest/latest/reqwest/redirect/struct.Policy.html#method.none)
> when using `reqwest`, or
> [`redirects(0)`](https://docs.rs/ureq/latest/ureq/struct.AgentBuilder.html#method.redirects)
> when using `ureq`.
The `AsyncHttpClient` trait is implemented for the following types:
* `reqwest::Client` (when the default `reqwest` feature is enabled)
* Any function type that implements:
```rust
Fn(HttpRequest) -> F
where
E: std::error::Error + 'static,
F: Future<Output = Result<HttpResponse, E>>,
```
To implement a custom asynchronous HTTP client, either directly implement the `AsyncHttpClient`
trait, or use a function that implements the signature above.
The `SyncHttpClient` trait is implemented for the following types:
* `reqwest::blocking::Client` (when the `reqwest-blocking` feature is enabled; see below)
* `ureq::Agent` (when the `ureq` feature is enabled)
* `openidconnect::CurlHttpClient` (when the `curl` feature is enabled)
* Any function type that implements:
```rust
Fn(HttpRequest) -> Result<HttpResponse, E>
where
E: std::error::Error + 'static,
```
To implement a custom synchronous HTTP client, either directly implement the `SyncHttpClient`
trait, or use a function that implements the signature above.
### Upgrade `http` to 1.0 and `reqwest` to 0.12
The 4.0 release of this crate depends on the new stable [`http`](https://docs.rs/http/latest/http/)
1.0 release, which affects various public interfaces. In particular, `reqwest` has been upgraded
to 0.12, which uses `http` 1.0.
### Enable the `reqwest-blocking` feature to use the synchronous `reqwest` HTTP client
In 4.0, enabling the (default) `reqwest` feature also enabled `reqwest`'s `blocking` feature.
To reduce dependencies and improve compilation speed, the `reqwest` feature now only enables
`reqwest`'s asynchronous (non-blocking) client. To use the synchronous (blocking) client, enable the
`reqwest-blocking` feature in `Cargo.toml`:
```toml
openidconnect = { version = "4", features = ["reqwest-blocking" ] }
```
### Use `http::{Request, Response}` for custom HTTP clients
The `HttpRequest` and `HttpResponse` structs have been replaced with type aliases to
[`http::Request`](https://docs.rs/http/latest/http/request/struct.Request.html) and
[`http::Response`](https://docs.rs/http/latest/http/response/struct.Response.html), respectively.
Custom HTTP clients will need to be updated to use the `http` types. See the
[`reqwest` client implementations](https://github.com/ramosbugs/oauth2-rs/blob/23b952b23e6069525bc7e4c4f2c4924b8d28ce3a/src/reqwest.rs)
in the underlying `oauth2` crate for an example.
### Replace `TT` generic type parameter in `OAuth2TokenResponse` with associated type
Previously, the `TokenResponse`, `OAuth2TokenResponse`, and `TokenIntrospectionResponse` traits had
a generic type parameter `TT: TokenType`. This has been replaced with an associated type called
`TokenType` in `OAuth2TokenResponse` and `TokenIntrospectionResponse`.
Uses of `CoreTokenResponse` and `CoreTokenIntrospectionResponse` should continue to work without
changes, but custom implementations of either trait will need to be updated to replace the type
parameter with an associated type.
#### Remove `TT` generic type parameter from `Client` and each `*Request` type
Removing the `TT` generic type parameter from `TokenResponse` (see above) made the `TT` parameters
to `Client` and each `*Request` (e.g., `CodeTokenRequest`) redundant. Consequently, the `TT`
parameter has been removed from each of these types. `CoreClient` should continue to work
without any changes, but code that provides generic types for `Client` or any of the `*Response`
types will need to be updated to remove the `TT` type parameter.
### Add `Display` to `ErrorResponse` trait
To improve error messages, the
[`RequestTokenError::ServerResponse`](https://docs.rs/oauth2/latest/oauth2/enum.RequestTokenError.html#variant.ServerResponse)
enum variant now prints a message describing the server response using the `Display` trait. For most
users (i.e., those using the default
[`StandardErrorResponse`](https://docs.rs/oauth2/latest/oauth2/struct.StandardErrorResponse.html)),
this does not require any code changes. However, users providing their own implementations
of the `ErrorResponse` trait must now implement the `Display` trait. See
`oauth2::StandardErrorResponse`'s
[`Display` implementation](https://github.com/ramosbugs/oauth2-rs/blob/9d8f11addf819134f15c6d7f03276adb3d32e80b/src/error.rs#L88-L108)
for an example.
### Remove the `jwk-alg` feature flag
The 4.0 release removes the `jwk-alg` feature flag and unconditionally deserializes the optional
`alg` field in `CoreJsonWebKey`. If a key specifies the `alg` field, the key may only be used for
the purposes of verifying signatures using that specific JWS signature algorithm. By comparison,
the 3.0 release ignored the `alg` field unless the `jwk-alg` feature flag was enabled.
### Enable the `timing-resistant-secret-traits` feature flag to securely compare secrets
OpenID Connect flows require comparing secrets (e.g., `CsrfToken` and `Nonce`) received from
providers. To do so securely
while avoiding [timing side-channels](https://en.wikipedia.org/wiki/Timing_attack), the
comparison must be done in constant time, either using a constant-time crate such as
[`constant_time_eq`](https://crates.io/crates/constant_time_eq) (which could break if a future
compiler version decides to be overly smart
about its optimizations), or by first computing a cryptographically-secure hash (e.g., SHA-256)
of both values and then comparing the hashes using `==`.
The `timing-resistant-secret-traits` feature flag adds a safe (but comparatively expensive)
`PartialEq` implementation to the secret types. Timing side-channels are why `PartialEq` is
not auto-derived for this crate's secret types, and the lack of `PartialEq` is intended to
prompt users to think more carefully about these comparisons.
In the 3.0 release, the `Nonce` type implemented `PartialEq` by default, which also allowed the
`IdToken`, `IdTokenClaims`, and `IdTokenFields` types to implement `PartialEq`. In 4.0, these
types implement `PartialEq` only if the `timing-resistant-secret-traits` feature flag is enabled.
### Move `hash_bytes()` method from `JwsSignatureAlgorithm` trait to `JsonWebKey`
Certain JWS signature algorithms (e.g., `EdDSA`) require information from the corresponding public
key (e.g., the `crv` value) to determine which hash function to use for computing the `at_hash` and
`c_hash` ID token claims. To accommodate this requirement, the 4.0 release moves the `hash_bytes()`
method from the `JwsSignatureAlgorithm` trait to the `JsonWebKey` trait.
The `AccessTokenHash::from_token()` and `AuthorizationCodeHash::from_code()` methods now require
a `JsonWebKey` as an argument.
+204
View File
@@ -0,0 +1,204 @@
//!
//! This example showcases the process of integrating with the
//! [GitLab OpenID Connect](https://docs.gitlab.com/ee/integration/openid_connect_provider.html)
//! provider.
//!
//! Before running it, you'll need to generate your own
//! [GitLab Application](https://docs.gitlab.com/ee/integration/oauth_provider.html).
//! The application needs `openid`, `profile` and `email` permission.
//!
//! In order to run the example call:
//!
//! ```sh
//! GITLAB_CLIENT_ID=xxx GITLAB_CLIENT_SECRET=yyy cargo run --example gitlab
//! ```
//!
//! ...and follow the instructions.
//!
use openidconnect::core::{
CoreClient, CoreGenderClaim, CoreIdTokenClaims, CoreIdTokenVerifier, CoreProviderMetadata,
CoreResponseType,
};
use openidconnect::reqwest;
use openidconnect::{AdditionalClaims, UserInfoClaims};
use openidconnect::{
AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce,
OAuth2TokenResponse, RedirectUrl, Scope,
};
use serde::{Deserialize, Serialize};
use url::Url;
use std::env;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::process::exit;
#[derive(Debug, Deserialize, Serialize)]
struct GitLabClaims {
// Deprecated and thus optional as it might be removed in the futre
sub_legacy: Option<String>,
groups: Vec<String>,
}
impl AdditionalClaims for GitLabClaims {}
fn handle_error<T: std::error::Error>(fail: &T, msg: &'static str) {
let mut err_msg = format!("ERROR: {}", msg);
let mut cur_fail: Option<&dyn std::error::Error> = Some(fail);
while let Some(cause) = cur_fail {
err_msg += &format!("\n caused by: {}", cause);
cur_fail = cause.source();
}
println!("{}", err_msg);
exit(1);
}
fn main() {
env_logger::init();
let gitlab_client_id = ClientId::new(
env::var("GITLAB_CLIENT_ID").expect("Missing the GITLAB_CLIENT_ID environment variable."),
);
let gitlab_client_secret = ClientSecret::new(
env::var("GITLAB_CLIENT_SECRET")
.expect("Missing the GITLAB_CLIENT_SECRET environment variable."),
);
let issuer_url = IssuerUrl::new("https://gitlab.com".to_string()).unwrap_or_else(|err| {
handle_error(&err, "Invalid issuer URL");
unreachable!();
});
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap_or_else(|err| {
handle_error(&err, "Failed to build HTTP client");
unreachable!();
});
// Fetch GitLab's OpenID Connect discovery document.
let provider_metadata = CoreProviderMetadata::discover(&issuer_url, &http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to discover OpenID Provider");
unreachable!();
});
// Set up the config for the GitLab OAuth2 process.
let client = CoreClient::from_provider_metadata(
provider_metadata,
gitlab_client_id,
Some(gitlab_client_secret),
)
// This example will be running its own server at localhost:8080.
// See below for the server implementation.
.set_redirect_uri(
RedirectUrl::new("http://localhost:8080".to_string()).unwrap_or_else(|err| {
handle_error(&err, "Invalid redirect URL");
unreachable!();
}),
);
// Generate the authorization URL to which we'll redirect the user.
let (authorize_url, csrf_state, nonce) = client
.authorize_url(
AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
CsrfToken::new_random,
Nonce::new_random,
)
// This example is requesting access to the the user's profile including email.
.add_scope(Scope::new("email".to_string()))
.add_scope(Scope::new("profile".to_string()))
.url();
println!("Open this URL in your browser:\n{authorize_url}\n");
let (code, state) = {
// A very naive implementation of the redirect server.
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
// Accept one connection
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(&stream);
let mut request_line = String::new();
reader.read_line(&mut request_line).unwrap();
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
let code = url
.query_pairs()
.find(|(key, _)| key == "code")
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
.unwrap();
let state = url
.query_pairs()
.find(|(key, _)| key == "state")
.map(|(_, state)| CsrfToken::new(state.into_owned()))
.unwrap();
let message = "Go back to your terminal :)";
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
message.len(),
message
);
stream.write_all(response.as_bytes()).unwrap();
(code, state)
};
println!("GitLab returned the following code:\n{}\n", code.secret());
println!(
"GitLab returned the following state:\n{} (expected `{}`)\n",
state.secret(),
csrf_state.secret()
);
// Exchange the code with a token.
let token_response = client
.exchange_code(code)
.unwrap_or_else(|err| {
handle_error(&err, "No user info endpoint");
unreachable!();
})
.request(&http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to contact token endpoint");
unreachable!();
});
println!(
"GitLab returned access token:\n{}\n",
token_response.access_token().secret()
);
println!("GitLab returned scopes: {:?}", token_response.scopes());
let id_token_verifier: CoreIdTokenVerifier = client.id_token_verifier();
let id_token_claims: &CoreIdTokenClaims = token_response
.extra_fields()
.id_token()
.expect("Server did not return an ID token")
.claims(&id_token_verifier, &nonce)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to verify ID token");
unreachable!();
});
println!("GitLab returned ID token: {:?}\n", id_token_claims);
let userinfo_claims: UserInfoClaims<GitLabClaims, CoreGenderClaim> = client
.user_info(token_response.access_token().to_owned(), None)
.unwrap_or_else(|err| {
handle_error(&err, "No user info endpoint");
unreachable!();
})
.request(&http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed requesting user info");
unreachable!();
});
println!("GitLab returned UserInfo: {:?}", userinfo_claims);
}
+251
View File
@@ -0,0 +1,251 @@
//!
//! This example showcases the process of integrating with the
//! [Google OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect)
//! provider.
//!
//! Before running it, you'll need to generate your own Google OAuth2 credentials.
//!
//! In order to run the example call:
//!
//! ```sh
//! GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=yyy cargo run --example google
//! ```
//!
//! ...and follow the instructions.
//!
use openidconnect::core::{
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, CoreGrantType,
CoreIdTokenClaims, CoreIdTokenVerifier, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType, CoreRevocableToken,
CoreSubjectIdentifierType,
};
use openidconnect::reqwest;
use openidconnect::{
AdditionalProviderMetadata, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret,
CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, ProviderMetadata, RedirectUrl, RevocationUrl,
Scope,
};
use serde::{Deserialize, Serialize};
use url::Url;
use std::env;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::process::exit;
fn handle_error<T: std::error::Error>(fail: &T, msg: &'static str) {
let mut err_msg = format!("ERROR: {}", msg);
let mut cur_fail: Option<&dyn std::error::Error> = Some(fail);
while let Some(cause) = cur_fail {
err_msg += &format!("\n caused by: {}", cause);
cur_fail = cause.source();
}
println!("{}", err_msg);
exit(1);
}
// Teach openidconnect-rs about a Google custom extension to the OpenID Discovery response that we can use as the RFC
// 7009 OAuth 2.0 Token Revocation endpoint. For more information about the Google specific Discovery response see the
// Google OpenID Connect service documentation at: https://developers.google.com/identity/protocols/oauth2/openid-connect#discovery
#[derive(Clone, Debug, Deserialize, Serialize)]
struct RevocationEndpointProviderMetadata {
revocation_endpoint: String,
}
impl AdditionalProviderMetadata for RevocationEndpointProviderMetadata {}
type GoogleProviderMetadata = ProviderMetadata<
RevocationEndpointProviderMetadata,
CoreAuthDisplay,
CoreClientAuthMethod,
CoreClaimName,
CoreClaimType,
CoreGrantType,
CoreJweContentEncryptionAlgorithm,
CoreJweKeyManagementAlgorithm,
CoreJsonWebKey,
CoreResponseMode,
CoreResponseType,
CoreSubjectIdentifierType,
>;
fn main() {
env_logger::init();
let google_client_id = ClientId::new(
env::var("GOOGLE_CLIENT_ID").expect("Missing the GOOGLE_CLIENT_ID environment variable."),
);
let google_client_secret = ClientSecret::new(
env::var("GOOGLE_CLIENT_SECRET")
.expect("Missing the GOOGLE_CLIENT_SECRET environment variable."),
);
let issuer_url =
IssuerUrl::new("https://accounts.google.com".to_string()).unwrap_or_else(|err| {
handle_error(&err, "Invalid issuer URL");
unreachable!();
});
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap_or_else(|err| {
handle_error(&err, "Failed to build HTTP client");
unreachable!();
});
// Fetch Google's OpenID Connect discovery document.
//
// Note: If we don't care about token revocation we can simply use CoreProviderMetadata here
// instead of GoogleProviderMetadata. If instead we wanted to optionally use the token
// revocation endpoint if it seems to be supported we could do something like this:
// #[derive(Clone, Debug, Deserialize, Serialize)]
// struct AllOtherProviderMetadata(HashMap<String, serde_json::Value>);
// impl AdditionalClaims for AllOtherProviderMetadata {}
// And then test for the presence of "revocation_endpoint" in the map returned by a call to
// .additional_metadata().
let provider_metadata = GoogleProviderMetadata::discover(&issuer_url, &http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to discover OpenID Provider");
unreachable!();
});
let revocation_endpoint = provider_metadata
.additional_metadata()
.revocation_endpoint
.clone();
println!(
"Discovered Google revocation endpoint: {}",
revocation_endpoint
);
// Set up the config for the Google OAuth2 process.
let client = CoreClient::from_provider_metadata(
provider_metadata,
google_client_id,
Some(google_client_secret),
)
// This example will be running its own server at localhost:8080.
// See below for the server implementation.
.set_redirect_uri(
RedirectUrl::new("http://localhost:8080".to_string()).unwrap_or_else(|err| {
handle_error(&err, "Invalid redirect URL");
unreachable!();
}),
)
// Google supports OAuth 2.0 Token Revocation (RFC-7009)
.set_revocation_url(
RevocationUrl::new(revocation_endpoint).unwrap_or_else(|err| {
handle_error(&err, "Invalid revocation endpoint URL");
unreachable!();
}),
);
// Generate the authorization URL to which we'll redirect the user.
let (authorize_url, csrf_state, nonce) = client
.authorize_url(
AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
CsrfToken::new_random,
Nonce::new_random,
)
// This example is requesting access to the "calendar" features and the user's profile.
.add_scope(Scope::new("email".to_string()))
.add_scope(Scope::new("profile".to_string()))
.url();
println!("Open this URL in your browser:\n{}\n", authorize_url);
let (code, state) = {
// A very naive implementation of the redirect server.
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
// Accept one connection
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(&stream);
let mut request_line = String::new();
reader.read_line(&mut request_line).unwrap();
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
let code = url
.query_pairs()
.find(|(key, _)| key == "code")
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
.unwrap();
let state = url
.query_pairs()
.find(|(key, _)| key == "state")
.map(|(_, state)| CsrfToken::new(state.into_owned()))
.unwrap();
let message = "Go back to your terminal :)";
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
message.len(),
message
);
stream.write_all(response.as_bytes()).unwrap();
(code, state)
};
println!("Google returned the following code:\n{}\n", code.secret());
println!(
"Google returned the following state:\n{} (expected `{}`)\n",
state.secret(),
csrf_state.secret()
);
// Exchange the code with a token.
let token_response = client
.exchange_code(code)
.unwrap_or_else(|err| {
handle_error(&err, "No user info endpoint");
unreachable!();
})
.request(&http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to contact token endpoint");
unreachable!();
});
println!(
"Google returned access token:\n{}\n",
token_response.access_token().secret()
);
println!("Google returned scopes: {:?}", token_response.scopes());
let id_token_verifier: CoreIdTokenVerifier = client.id_token_verifier();
let id_token_claims: &CoreIdTokenClaims = token_response
.extra_fields()
.id_token()
.expect("Server did not return an ID token")
.claims(&id_token_verifier, &nonce)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to verify ID token");
unreachable!();
});
println!("Google returned ID token: {:?}", id_token_claims);
// Revoke the obtained token
let token_to_revoke: CoreRevocableToken = match token_response.refresh_token() {
Some(token) => token.into(),
None => token_response.access_token().into(),
};
client
.revoke_token(token_to_revoke)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to revoke token");
unreachable!();
})
.request(&http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to revoke token");
unreachable!();
});
}
+145
View File
@@ -0,0 +1,145 @@
//!
//! This example showcases the process of using the device grant flow to obtain an ID token from the
//! [Okta](https://developer.okta.com/docs/guides/device-authorization-grant/main/#request-the-device-verification-code)
//! provider.
//!
//! Before running it, you'll need to generate your own
//! [Okta Server](https://developer.okta.com/signup/).
//!
//! In order to run the example call:
//!
//! ```sh
//! CLIENT_ID=xxx CLIENT_SECRET=yyy ISSUER_URL=zzz cargo run --example okta_device_grant
//! ```
//!
//! ...and follow the instructions.
//!
use openidconnect::core::{
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod,
CoreDeviceAuthorizationResponse, CoreGrantType, CoreJsonWebKey,
CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, CoreResponseMode,
CoreResponseType, CoreSubjectIdentifierType,
};
use openidconnect::reqwest;
use openidconnect::{
AdditionalProviderMetadata, AuthType, ClientId, ClientSecret, DeviceAuthorizationUrl,
IssuerUrl, ProviderMetadata, Scope,
};
use serde::{Deserialize, Serialize};
use std::env;
use std::process::exit;
// Obtain the device_authorization_url from the OIDC metadata provider.
#[derive(Clone, Debug, Deserialize, Serialize)]
struct DeviceEndpointProviderMetadata {
device_authorization_endpoint: DeviceAuthorizationUrl,
}
impl AdditionalProviderMetadata for DeviceEndpointProviderMetadata {}
type DeviceProviderMetadata = ProviderMetadata<
DeviceEndpointProviderMetadata,
CoreAuthDisplay,
CoreClientAuthMethod,
CoreClaimName,
CoreClaimType,
CoreGrantType,
CoreJweContentEncryptionAlgorithm,
CoreJweKeyManagementAlgorithm,
CoreJsonWebKey,
CoreResponseMode,
CoreResponseType,
CoreSubjectIdentifierType,
>;
fn handle_error<T: std::error::Error>(fail: &T, msg: &'static str) {
let mut err_msg = format!("ERROR: {}", msg);
let mut cur_fail: Option<&dyn std::error::Error> = Some(fail);
while let Some(cause) = cur_fail {
err_msg += &format!("\n caused by: {}", cause);
cur_fail = cause.source();
}
println!("{}", err_msg);
exit(1);
}
fn main() -> Result<(), anyhow::Error> {
env_logger::init();
let client_id =
ClientId::new(env::var("CLIENT_ID").expect("Missing the CLIENT_ID environment variable."));
let client_secret = ClientSecret::new(
env::var("CLIENT_SECRET").expect("Missing the CLIENT_SECRET environment variable."),
);
let issuer_url = IssuerUrl::new(
env::var("ISSUER_URL").expect("Missing the ISSUER_URL environment variable."),
)
.unwrap_or_else(|err| {
handle_error(&err, "Invalid issuer URL");
unreachable!();
});
let http_client = reqwest::blocking::ClientBuilder::new()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap_or_else(|err| {
handle_error(&err, "Failed to build HTTP client");
unreachable!();
});
// Fetch Okta's OpenID Connect discovery document.
let provider_metadata = DeviceProviderMetadata::discover(&issuer_url, &http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to discover OpenID Provider");
unreachable!();
});
// Use the custom metadata to get the device_authorization_endpoint
let device_authorization_endpoint = provider_metadata
.additional_metadata()
.device_authorization_endpoint
.clone();
// Set up the config for the Okta device authorization process.
let client =
CoreClient::from_provider_metadata(provider_metadata, client_id, Some(client_secret))
.set_device_authorization_url(device_authorization_endpoint)
.set_auth_type(AuthType::RequestBody);
let details: CoreDeviceAuthorizationResponse = client
.exchange_device_code()
.add_scope(Scope::new("profile".to_string()))
.request(&http_client)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to get device code");
unreachable!();
});
println!("Fetching device code...");
dbg!(&details);
// Display the URL and user-code.
println!(
"Open this URL in your browser:\n{}\nand enter the code: {}",
details.verification_uri_complete().unwrap().secret(),
details.user_code().secret()
);
// Now poll for the token
let token = client
.exchange_device_access_token(&details)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to get access token");
unreachable!();
})
.request(&http_client, std::thread::sleep, None)
.unwrap_or_else(|err| {
handle_error(&err, "Failed to get access token");
unreachable!();
});
// Finally, display the ID Token to verify we are using OIDC
println!("ID Token response: {:?}", token.extra_fields().id_token());
Ok(())
}
+505
View File
@@ -0,0 +1,505 @@
use crate::core::CoreResponseType;
use crate::helpers::join_vec;
use crate::{
AdditionalClaims, AuthDisplay, AuthPrompt, AuthenticationContextClass, CsrfToken, GenderClaim,
IdToken, JweContentEncryptionAlgorithm, JwsSigningAlgorithm, LanguageTag, LoginHint, Nonce,
PkceCodeChallenge, RedirectUrl, ResponseType, Scope,
};
use url::Url;
use std::borrow::Cow;
use std::time::Duration;
/// Authentication flow, which determines how the Authorization Server returns the OpenID Connect
/// ID token and OAuth2 access token to the Relying Party.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthenticationFlow<RT: ResponseType> {
/// Authorization Code Flow.
///
/// The authorization server will return an OAuth2 authorization code. Clients must subsequently
/// call `Client::exchange_code()` with the authorization code in order to retrieve an
/// OpenID Connect ID token and OAuth2 access token.
AuthorizationCode,
/// Implicit Flow.
///
/// Boolean value indicates whether an OAuth2 access token should also be returned. If `true`,
/// the Authorization Server will return both an OAuth2 access token and OpenID Connect ID
/// token. If `false`, it will return only an OpenID Connect ID token.
Implicit(bool),
/// Hybrid Flow.
///
/// A hybrid flow according to [OAuth 2.0 Multiple Response Type Encoding Practices](
/// https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html). The enum value
/// contains the desired `response_type`s. See
/// [Section 3](https://openid.net/specs/openid-connect-core-1_0.html#Authentication) for
/// details.
Hybrid(Vec<RT>),
}
/// A request to the authorization endpoint.
pub struct AuthorizationRequest<'a, AD, P, RT>
where
AD: AuthDisplay,
P: AuthPrompt,
RT: ResponseType,
{
pub(crate) inner: oauth2::AuthorizationRequest<'a>,
pub(crate) acr_values: Vec<AuthenticationContextClass>,
pub(crate) authentication_flow: AuthenticationFlow<RT>,
pub(crate) claims_locales: Vec<LanguageTag>,
pub(crate) display: Option<AD>,
pub(crate) id_token_hint: Option<String>,
pub(crate) login_hint: Option<LoginHint>,
pub(crate) max_age: Option<Duration>,
pub(crate) nonce: Nonce,
pub(crate) prompts: Vec<P>,
pub(crate) ui_locales: Vec<LanguageTag>,
}
impl<'a, AD, P, RT> AuthorizationRequest<'a, AD, P, RT>
where
AD: AuthDisplay,
P: AuthPrompt,
RT: ResponseType,
{
/// Appends a new scope to the authorization URL.
pub fn add_scope(mut self, scope: Scope) -> Self {
self.inner = self.inner.add_scope(scope);
self
}
/// Appends a collection of scopes to the authorization URL.
pub fn add_scopes<I>(mut self, scopes: I) -> Self
where
I: IntoIterator<Item = Scope>,
{
self.inner = self.inner.add_scopes(scopes);
self
}
/// Appends an extra param to the authorization URL.
///
/// This method allows extensions to be used without direct support from
/// this crate. If `name` conflicts with a parameter managed by this crate, the
/// behavior is undefined. In particular, do not set parameters defined by
/// [RFC 6749](https://tools.ietf.org/html/rfc6749) or
/// [RFC 7636](https://tools.ietf.org/html/rfc7636).
///
/// # Security Warning
///
/// Callers should follow the security recommendations for any OAuth2 extensions used with
/// this function, which are beyond the scope of
/// [RFC 6749](https://tools.ietf.org/html/rfc6749).
pub fn add_extra_param<N, V>(mut self, name: N, value: V) -> Self
where
N: Into<Cow<'a, str>>,
V: Into<Cow<'a, str>>,
{
self.inner = self.inner.add_extra_param(name, value);
self
}
/// Enables the use of [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)
/// (PKCE).
///
/// PKCE is *highly recommended* for all public clients (i.e., those for which there
/// is no client secret or for which the client secret is distributed with the client,
/// such as in a native, mobile app, or browser app).
pub fn set_pkce_challenge(mut self, pkce_code_challenge: PkceCodeChallenge) -> Self {
self.inner = self.inner.set_pkce_challenge(pkce_code_challenge);
self
}
/// Requests Authentication Context Class Reference values.
///
/// ACR values should be added in order of preference. The Authentication Context Class
/// satisfied by the authentication performed is accessible from the ID token via the
/// [`IdTokenClaims::auth_context_ref()`](crate::IdTokenClaims::auth_context_ref) method.
pub fn add_auth_context_value(mut self, acr_value: AuthenticationContextClass) -> Self {
self.acr_values.push(acr_value);
self
}
/// Requests the preferred languages for claims returned by the OpenID Connect Provider.
///
/// Languages should be added in order of preference.
pub fn add_claims_locale(mut self, claims_locale: LanguageTag) -> Self {
self.claims_locales.push(claims_locale);
self
}
// TODO: support 'claims' parameter
// https://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
/// Specifies how the OpenID Connect Provider displays the authentication and consent user
/// interfaces to the end user.
pub fn set_display(mut self, display: AD) -> Self {
self.display = Some(display);
self
}
/// Provides an ID token previously issued by this OpenID Connect Provider as a hint about
/// the user's identity.
///
/// This field should be set whenever
/// [`CoreAuthPrompt::None`](crate::core::CoreAuthPrompt::None) is used (see
/// [`AuthorizationRequest::add_prompt`]), it but may be provided for any authorization
/// request.
pub fn set_id_token_hint<AC, GC, JE, JS>(
mut self,
id_token_hint: &'a IdToken<AC, GC, JE, JS>,
) -> Self
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
self.id_token_hint = Some(id_token_hint.to_string());
self
}
/// Provides the OpenID Connect Provider with a hint about the user's identity.
///
/// The nature of this hint is specific to each provider.
pub fn set_login_hint(mut self, login_hint: LoginHint) -> Self {
self.login_hint = Some(login_hint);
self
}
/// Sets a maximum amount of time since the user has last authenticated with the OpenID
/// Connect Provider.
///
/// If more time has elapsed, the provider forces the user to re-authenticate.
pub fn set_max_age(mut self, max_age: Duration) -> Self {
self.max_age = Some(max_age);
self
}
/// Specifies what level of authentication and consent prompts the OpenID Connect Provider
/// should present to the user.
pub fn add_prompt(mut self, prompt: P) -> Self {
self.prompts.push(prompt);
self
}
/// Requests the preferred languages for the user interface presented by the OpenID Connect
/// Provider.
///
/// Languages should be added in order of preference.
pub fn add_ui_locale(mut self, ui_locale: LanguageTag) -> Self {
self.ui_locales.push(ui_locale);
self
}
/// Overrides the `redirect_url` to the one specified.
pub fn set_redirect_uri(mut self, redirect_url: Cow<'a, RedirectUrl>) -> Self {
self.inner = self.inner.set_redirect_uri(redirect_url);
self
}
/// Returns the full authorization URL and CSRF state for this authorization
/// request.
pub fn url(self) -> (Url, CsrfToken, Nonce) {
let response_type = match self.authentication_flow {
AuthenticationFlow::AuthorizationCode => CoreResponseType::Code.to_oauth2(),
AuthenticationFlow::Implicit(include_token) => {
if include_token {
oauth2::ResponseType::new(
[CoreResponseType::IdToken, CoreResponseType::Token]
.iter()
.map(|response_type| response_type.as_ref())
.collect::<Vec<_>>()
.join(" "),
)
} else {
CoreResponseType::IdToken.to_oauth2()
}
}
AuthenticationFlow::Hybrid(ref response_types) => oauth2::ResponseType::new(
response_types
.iter()
.map(|response_type| response_type.as_ref())
.collect::<Vec<_>>()
.join(" "),
),
};
let (mut inner, nonce) = (
self.inner
.set_response_type(&response_type)
.add_extra_param("nonce", self.nonce.secret().clone()),
self.nonce,
);
if !self.acr_values.is_empty() {
inner = inner.add_extra_param("acr_values", join_vec(&self.acr_values));
}
if !self.claims_locales.is_empty() {
inner = inner.add_extra_param("claims_locales", join_vec(&self.claims_locales));
}
if let Some(ref display) = self.display {
inner = inner.add_extra_param("display", display.as_ref());
}
if let Some(ref id_token_hint) = self.id_token_hint {
inner = inner.add_extra_param("id_token_hint", id_token_hint);
}
if let Some(ref login_hint) = self.login_hint {
inner = inner.add_extra_param("login_hint", login_hint.secret());
}
if let Some(max_age) = self.max_age {
inner = inner.add_extra_param("max_age", max_age.as_secs().to_string());
}
if !self.prompts.is_empty() {
inner = inner.add_extra_param("prompt", join_vec(&self.prompts));
}
if !self.ui_locales.is_empty() {
inner = inner.add_extra_param("ui_locales", join_vec(&self.ui_locales));
}
let (url, state) = inner.url();
(url, state, nonce)
}
}
#[cfg(test)]
mod tests {
use crate::core::CoreAuthenticationFlow;
use crate::core::{CoreAuthDisplay, CoreAuthPrompt, CoreClient, CoreIdToken, CoreResponseType};
use crate::IssuerUrl;
use crate::{
AuthUrl, AuthenticationContextClass, AuthenticationFlow, ClientId, ClientSecret, CsrfToken,
EndpointNotSet, EndpointSet, JsonWebKeySet, LanguageTag, LoginHint, Nonce, RedirectUrl,
Scope, TokenUrl,
};
use std::borrow::Cow;
use std::time::Duration;
fn new_client() -> CoreClient<
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointSet,
EndpointNotSet,
> {
color_backtrace::install();
CoreClient::new(
ClientId::new("aaa".to_string()),
IssuerUrl::new("https://example".to_string()).unwrap(),
JsonWebKeySet::default(),
)
.set_client_secret(ClientSecret::new("bbb".to_string()))
.set_auth_uri(AuthUrl::new("https://example/authorize".to_string()).unwrap())
.set_token_uri(TokenUrl::new("https://example/token".to_string()).unwrap())
}
#[test]
fn test_authorize_url_minimal() {
let client = new_client();
let (authorize_url, _, _) = client
.authorize_url(
AuthenticationFlow::AuthorizationCode::<CoreResponseType>,
|| CsrfToken::new("CSRF123".to_string()),
|| Nonce::new("NONCE456".to_string()),
)
.url();
assert_eq!(
"https://example/authorize?response_type=code&client_id=aaa&\
state=CSRF123&scope=openid&nonce=NONCE456",
authorize_url.to_string()
);
}
#[test]
fn test_authorize_url_implicit_with_access_token() {
let client = new_client();
let (authorize_url, _, _) = client
.authorize_url(
AuthenticationFlow::<CoreResponseType>::Implicit(true),
|| CsrfToken::new("CSRF123".to_string()),
|| Nonce::new("NONCE456".to_string()),
)
.url();
assert_eq!(
"https://example/authorize?response_type=id_token+token&client_id=aaa&\
state=CSRF123&scope=openid&nonce=NONCE456",
authorize_url.to_string()
);
}
#[test]
fn test_authorize_url_hybrid() {
let client = new_client();
let (authorize_url, _, _) = client
.authorize_url(
AuthenticationFlow::Hybrid(vec![
CoreResponseType::Code,
CoreResponseType::Extension("other".to_string()),
]),
|| CsrfToken::new("CSRF123".to_string()),
|| Nonce::new("NONCE456".to_string()),
)
.url();
assert_eq!(
"https://example/authorize?response_type=code+other&client_id=aaa&\
state=CSRF123&scope=openid&nonce=NONCE456",
authorize_url.to_string()
);
}
#[test]
fn test_authorize_url_full() {
let client = new_client()
.set_redirect_uri(RedirectUrl::new("http://localhost:8888/".to_string()).unwrap());
let flow = CoreAuthenticationFlow::AuthorizationCode;
fn new_csrf() -> CsrfToken {
CsrfToken::new("CSRF123".to_string())
}
fn new_nonce() -> Nonce {
Nonce::new("NONCE456".to_string())
}
let (authorize_url, _, _) = client
.authorize_url(flow.clone(), new_csrf, new_nonce)
.add_scope(Scope::new("email".to_string()))
.set_display(CoreAuthDisplay::Touch)
.add_prompt(CoreAuthPrompt::Login)
.add_prompt(CoreAuthPrompt::Consent)
.set_max_age(Duration::from_secs(1800))
.add_ui_locale(LanguageTag::new("fr-CA".to_string()))
.add_ui_locale(LanguageTag::new("fr".to_string()))
.add_ui_locale(LanguageTag::new("en".to_string()))
.add_auth_context_value(AuthenticationContextClass::new(
"urn:mace:incommon:iap:silver".to_string(),
))
.url();
assert_eq!(
"https://example/authorize?response_type=code&client_id=aaa&\
state=CSRF123&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2F&scope=openid+email&\
nonce=NONCE456&acr_values=urn%3Amace%3Aincommon%3Aiap%3Asilver&display=touch&\
max_age=1800&prompt=login+consent&ui_locales=fr-CA+fr+en",
authorize_url.to_string()
);
let serialized_jwt =
"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2V4YW1wbGUuY29tIiwiYXVkIjpbIm15X2NsaWVudCJdL\
CJleHAiOjE1NDQ5MzIxNDksImlhdCI6MTU0NDkyODU0OSwiYXV0aF90aW1lIjoxNTQ0OTI4NTQ4LCJub25jZSI\
6InRoZV9ub25jZSIsImFjciI6InRoZV9hY3IiLCJzdWIiOiJzdWJqZWN0In0.gb5HuuyDMu-LvYvG-jJNIJPEZ\
823qNwvgNjdAtW0HJpgwJWhJq0hOHUuZz6lvf8ud5xbg5GOo0Q37v3Ke08TvGu6E1USWjecZzp1aYVm9BiMvw5\
EBRUrwAaOCG2XFjuOKUVfglSMJnRnoNqVVIWpCAr1ETjZzRIbkU3n5GQRguC5CwN5n45I3dtjoKuNGc2Ni-IMl\
J2nRiCJOl2FtStdgs-doc-A9DHtO01x-5HCwytXvcE28Snur1JnqpUgmWrQ8gZMGuijKirgNnze2Dd5BsZRHZ2\
CLGIwBsCnauBrJy_NNlQg4hUcSlGsuTa0dmZY7mCf4BN2WCpyOh0wgtkAgQ";
let id_token = serde_json::from_value::<CoreIdToken>(serde_json::Value::String(
serialized_jwt.to_string(),
))
.unwrap();
let (authorize_url, _, _) = client
.authorize_url(flow.clone(), new_csrf, new_nonce)
.add_scope(Scope::new("email".to_string()))
.set_display(CoreAuthDisplay::Touch)
.set_id_token_hint(&id_token)
.set_login_hint(LoginHint::new("foo@bar.com".to_string()))
.add_prompt(CoreAuthPrompt::Login)
.add_prompt(CoreAuthPrompt::Consent)
.set_max_age(Duration::from_secs(1800))
.add_ui_locale(LanguageTag::new("fr-CA".to_string()))
.add_ui_locale(LanguageTag::new("fr".to_string()))
.add_ui_locale(LanguageTag::new("en".to_string()))
.add_auth_context_value(AuthenticationContextClass::new(
"urn:mace:incommon:iap:silver".to_string(),
))
.add_extra_param("foo", "bar")
.url();
assert_eq!(
format!(
"https://example/authorize?response_type=code&client_id=aaa&state=CSRF123&\
redirect_uri=http%3A%2F%2Flocalhost%3A8888%2F&scope=openid+email&foo=bar&\
nonce=NONCE456&acr_values=urn%3Amace%3Aincommon%3Aiap%3Asilver&display=touch&\
id_token_hint={serialized_jwt}&login_hint=foo%40bar.com&\
max_age=1800&prompt=login+consent&ui_locales=fr-CA+fr+en"
),
authorize_url.to_string()
);
let (authorize_url, _, _) = client
.authorize_url(flow, new_csrf, new_nonce)
.add_scopes(vec![
Scope::new("email".to_string()),
Scope::new("profile".to_string()),
])
.set_display(CoreAuthDisplay::Touch)
.set_id_token_hint(&id_token)
.set_login_hint(LoginHint::new("foo@bar.com".to_string()))
.add_prompt(CoreAuthPrompt::Login)
.add_prompt(CoreAuthPrompt::Consent)
.set_max_age(Duration::from_secs(1800))
.add_ui_locale(LanguageTag::new("fr-CA".to_string()))
.add_ui_locale(LanguageTag::new("fr".to_string()))
.add_ui_locale(LanguageTag::new("en".to_string()))
.add_auth_context_value(AuthenticationContextClass::new(
"urn:mace:incommon:iap:silver".to_string(),
))
.add_extra_param("foo", "bar")
.url();
assert_eq!(
format!(
"https://example/authorize?response_type=code&client_id=aaa&state=CSRF123&\
redirect_uri=http%3A%2F%2Flocalhost%3A8888%2F&scope=openid+email+profile&foo=bar&\
nonce=NONCE456&acr_values=urn%3Amace%3Aincommon%3Aiap%3Asilver&display=touch&\
id_token_hint={serialized_jwt}&login_hint=foo%40bar.com&\
max_age=1800&prompt=login+consent&ui_locales=fr-CA+fr+en"
),
authorize_url.to_string()
);
}
#[test]
fn test_authorize_url_redirect_url_override() {
let client = new_client()
.set_redirect_uri(RedirectUrl::new("http://localhost:8888/".to_string()).unwrap());
let flow = CoreAuthenticationFlow::AuthorizationCode;
fn new_csrf() -> CsrfToken {
CsrfToken::new("CSRF123".to_string())
}
fn new_nonce() -> Nonce {
Nonce::new("NONCE456".to_string())
}
let (authorize_url, _, _) = client
.authorize_url(flow, new_csrf, new_nonce)
.add_scope(Scope::new("email".to_string()))
.set_display(CoreAuthDisplay::Touch)
.add_prompt(CoreAuthPrompt::Login)
.add_prompt(CoreAuthPrompt::Consent)
.set_max_age(Duration::from_secs(1800))
.add_ui_locale(LanguageTag::new("fr-CA".to_string()))
.add_ui_locale(LanguageTag::new("fr".to_string()))
.add_ui_locale(LanguageTag::new("en".to_string()))
.add_auth_context_value(AuthenticationContextClass::new(
"urn:mace:incommon:iap:silver".to_string(),
))
.set_redirect_uri(Cow::Owned(
RedirectUrl::new("http://localhost:8888/alternative".to_string()).unwrap(),
))
.url();
assert_eq!(
"https://example/authorize?response_type=code&client_id=aaa&\
state=CSRF123&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Falternative&scope=openid+email&\
nonce=NONCE456&acr_values=urn%3Amace%3Aincommon%3Aiap%3Asilver&display=touch&\
max_age=1800&prompt=login+consent&ui_locales=fr-CA+fr+en",
authorize_url.to_string()
);
}
}
+480
View File
@@ -0,0 +1,480 @@
use crate::helpers::{Boolean, DeserializeMapField, FlattenFilter, Timestamp};
use crate::types::localized::split_language_tag_key;
use crate::{
AddressCountry, AddressLocality, AddressPostalCode, AddressRegion, EndUserBirthday,
EndUserEmail, EndUserFamilyName, EndUserGivenName, EndUserMiddleName, EndUserName,
EndUserNickname, EndUserPhoneNumber, EndUserPictureUrl, EndUserProfileUrl, EndUserTimezone,
EndUserUsername, EndUserWebsiteUrl, FormattedAddress, LanguageTag, LocalizedClaim,
StreetAddress, SubjectIdentifier,
};
use chrono::{DateTime, Utc};
use serde::de::{DeserializeOwned, Deserializer, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize, Serializer};
use serde_with::skip_serializing_none;
use std::fmt::{Debug, Formatter, Result as FormatterResult};
use std::marker::PhantomData;
use std::str;
/// Additional claims beyond the set of Standard Claims defined by OpenID Connect Core.
pub trait AdditionalClaims: Debug + DeserializeOwned + Serialize + 'static {}
/// No additional claims.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
// In order to support serde flatten, this must be an empty struct rather than an empty
// tuple struct.
pub struct EmptyAdditionalClaims {}
impl AdditionalClaims for EmptyAdditionalClaims {}
/// Address claims.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct AddressClaim {
/// Full mailing address, formatted for display or use on a mailing label.
///
/// This field MAY contain multiple lines, separated by newlines. Newlines can be represented
/// either as a carriage return/line feed pair (`\r\n`) or as a single line feed character
/// (`\n`).
pub formatted: Option<FormattedAddress>,
/// Full street address component, which MAY include house number, street name, Post Office Box,
/// and multi-line extended street address information.
///
/// This field MAY contain multiple lines, separated by newlines. Newlines can be represented
/// either as a carriage return/line feed pair (`\r\n`) or as a single line feed character
/// (`\n`).
pub street_address: Option<StreetAddress>,
/// City or locality component.
pub locality: Option<AddressLocality>,
/// State, province, prefecture, or region component.
pub region: Option<AddressRegion>,
/// Zip code or postal code component.
pub postal_code: Option<AddressPostalCode>,
/// Country name component.
pub country: Option<AddressCountry>,
}
/// Gender claim.
pub trait GenderClaim: Clone + Debug + DeserializeOwned + Serialize + 'static {}
/// Standard Claims defined by OpenID Connect Core.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StandardClaims<GC>
where
GC: GenderClaim,
{
pub(crate) sub: SubjectIdentifier,
pub(crate) name: Option<LocalizedClaim<EndUserName>>,
pub(crate) given_name: Option<LocalizedClaim<EndUserGivenName>>,
pub(crate) family_name: Option<LocalizedClaim<EndUserFamilyName>>,
pub(crate) middle_name: Option<LocalizedClaim<EndUserMiddleName>>,
pub(crate) nickname: Option<LocalizedClaim<EndUserNickname>>,
pub(crate) preferred_username: Option<EndUserUsername>,
pub(crate) profile: Option<LocalizedClaim<EndUserProfileUrl>>,
pub(crate) picture: Option<LocalizedClaim<EndUserPictureUrl>>,
pub(crate) website: Option<LocalizedClaim<EndUserWebsiteUrl>>,
pub(crate) email: Option<EndUserEmail>,
pub(crate) email_verified: Option<bool>,
pub(crate) gender: Option<GC>,
pub(crate) birthday: Option<EndUserBirthday>,
pub(crate) birthdate: Option<EndUserBirthday>,
pub(crate) zoneinfo: Option<EndUserTimezone>,
pub(crate) locale: Option<LanguageTag>,
pub(crate) phone_number: Option<EndUserPhoneNumber>,
pub(crate) phone_number_verified: Option<bool>,
pub(crate) address: Option<AddressClaim>,
pub(crate) updated_at: Option<DateTime<Utc>>,
}
impl<GC> StandardClaims<GC>
where
GC: GenderClaim,
{
/// Initializes a set of Standard Claims.
///
/// The Subject (`sub`) claim is the only required Standard Claim.
pub fn new(subject: SubjectIdentifier) -> Self {
Self {
sub: subject,
name: None,
given_name: None,
family_name: None,
middle_name: None,
nickname: None,
preferred_username: None,
profile: None,
picture: None,
website: None,
email: None,
email_verified: None,
gender: None,
birthday: None,
birthdate: None,
zoneinfo: None,
locale: None,
phone_number: None,
phone_number_verified: None,
address: None,
updated_at: None,
}
}
/// Returns the Subject (`sub`) claim.
pub fn subject(&self) -> &SubjectIdentifier {
&self.sub
}
/// Sets the Subject (`sub`) claim.
pub fn set_subject(mut self, subject: SubjectIdentifier) -> Self {
self.sub = subject;
self
}
field_getters_setters![
pub self [self] ["claim"] {
set_name -> name[Option<LocalizedClaim<EndUserName>>],
set_given_name -> given_name[Option<LocalizedClaim<EndUserGivenName>>],
set_family_name ->
family_name[Option<LocalizedClaim<EndUserFamilyName>>],
set_middle_name ->
middle_name[Option<LocalizedClaim<EndUserMiddleName>>],
set_nickname -> nickname[Option<LocalizedClaim<EndUserNickname>>],
set_preferred_username -> preferred_username[Option<EndUserUsername>],
set_profile -> profile[Option<LocalizedClaim<EndUserProfileUrl>>],
set_picture -> picture[Option<LocalizedClaim<EndUserPictureUrl>>],
set_website -> website[Option<LocalizedClaim<EndUserWebsiteUrl>>],
set_email -> email[Option<EndUserEmail>],
set_email_verified -> email_verified[Option<bool>],
set_gender -> gender[Option<GC>],
set_birthday -> birthday[Option<EndUserBirthday>],
set_birthdate -> birthdate[Option<EndUserBirthday>],
set_zoneinfo -> zoneinfo[Option<EndUserTimezone>],
set_locale -> locale[Option<LanguageTag>],
set_phone_number -> phone_number[Option<EndUserPhoneNumber>],
set_phone_number_verified -> phone_number_verified[Option<bool>],
set_address -> address[Option<AddressClaim>],
set_updated_at -> updated_at[Option<DateTime<Utc>>],
}
];
}
impl<GC> FlattenFilter for StandardClaims<GC>
where
GC: GenderClaim,
{
// When another struct (i.e., additional claims) is co-flattened with this one, only include
// fields in that other struct which are not part of this struct.
fn should_include(field_name: &str) -> bool {
!matches!(
split_language_tag_key(field_name),
("sub", None)
| ("name", _)
| ("given_name", _)
| ("family_name", _)
| ("middle_name", _)
| ("nickname", _)
| ("preferred_username", None)
| ("profile", _)
| ("picture", _)
| ("website", _)
| ("email", None)
| ("email_verified", None)
| ("gender", None)
| ("birthday", None)
| ("birthdate", None)
| ("zoneinfo", None)
| ("locale", None)
| ("phone_number", None)
| ("phone_number_verified", None)
| ("address", None)
| ("updated_at", None)
)
}
}
impl<'de, GC> Deserialize<'de> for StandardClaims<GC>
where
GC: GenderClaim,
{
/// Special deserializer that supports [RFC 5646](https://tools.ietf.org/html/rfc5646) language
/// tags associated with human-readable client metadata fields.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ClaimsVisitor<GC: GenderClaim>(PhantomData<GC>);
impl<'de, GC> Visitor<'de> for ClaimsVisitor<GC>
where
GC: GenderClaim,
{
type Value = StandardClaims<GC>;
fn expecting(&self, formatter: &mut Formatter) -> FormatterResult {
formatter.write_str("struct StandardClaims")
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
// NB: The non-localized fields are actually Option<Option<_>> here so that we can
// distinguish between omitted fields and fields explicitly set to `null`. The
// latter is necessary so that we can detect duplicate fields (e.g., if a key is
// present both with a null value and a non-null value, that's an error).
let mut sub = None;
let mut name = None;
let mut given_name = None;
let mut family_name = None;
let mut middle_name = None;
let mut nickname = None;
let mut preferred_username = None;
let mut profile = None;
let mut picture = None;
let mut website = None;
let mut email = None;
let mut email_verified = None;
let mut gender = None;
let mut birthday = None;
let mut birthdate = None;
let mut zoneinfo = None;
let mut locale = None;
let mut phone_number = None;
let mut phone_number_verified = None;
let mut address = None;
let mut updated_at = None;
macro_rules! field_case {
($field:ident, $typ:ty, $language_tag:ident) => {{
$field = Some(<$typ>::deserialize_map_field(
&mut map,
stringify!($field),
$language_tag,
$field,
)?);
}};
}
while let Some(key) = map.next_key::<String>()? {
let (field_name, language_tag) = split_language_tag_key(&key);
match field_name {
"sub" => field_case!(sub, SubjectIdentifier, language_tag),
"name" => field_case!(name, LocalizedClaim<Option<_>>, language_tag),
"given_name" => {
field_case!(given_name, LocalizedClaim<Option<_>>, language_tag)
}
"family_name" => {
field_case!(family_name, LocalizedClaim<Option<_>>, language_tag)
}
"middle_name" => {
field_case!(middle_name, LocalizedClaim<Option<_>>, language_tag)
}
"nickname" => {
field_case!(nickname, LocalizedClaim<Option<_>>, language_tag)
}
"preferred_username" => {
field_case!(preferred_username, Option<_>, language_tag)
}
"profile" => {
field_case!(profile, LocalizedClaim<Option<_>>, language_tag)
}
"picture" => {
field_case!(picture, LocalizedClaim<Option<_>>, language_tag)
}
"website" => {
field_case!(website, LocalizedClaim<Option<_>>, language_tag)
}
"email" => field_case!(email, Option<_>, language_tag),
"email_verified" => {
field_case!(email_verified, Option<Boolean>, language_tag)
}
"gender" => field_case!(gender, Option<_>, language_tag),
"birthday" => field_case!(birthday, Option<_>, language_tag),
"birthdate" => field_case!(birthdate, Option<_>, language_tag),
"zoneinfo" => field_case!(zoneinfo, Option<_>, language_tag),
"locale" => field_case!(locale, Option<_>, language_tag),
"phone_number" => field_case!(phone_number, Option<_>, language_tag),
"phone_number_verified" => {
field_case!(phone_number_verified, Option<Boolean>, language_tag)
}
"address" => field_case!(address, Option<_>, language_tag),
"updated_at" => field_case!(updated_at, Option<Timestamp>, language_tag),
// Ignore unknown fields.
_ => {
map.next_value::<serde::de::IgnoredAny>()?;
continue;
}
};
}
Ok(StandardClaims {
sub: sub.ok_or_else(|| serde::de::Error::missing_field("sub"))?,
name: name.and_then(LocalizedClaim::flatten_or_none),
given_name: given_name.and_then(LocalizedClaim::flatten_or_none),
family_name: family_name.and_then(LocalizedClaim::flatten_or_none),
middle_name: middle_name.and_then(LocalizedClaim::flatten_or_none),
nickname: nickname.and_then(LocalizedClaim::flatten_or_none),
preferred_username: preferred_username.flatten(),
profile: profile.and_then(LocalizedClaim::flatten_or_none),
picture: picture.and_then(LocalizedClaim::flatten_or_none),
website: website.and_then(LocalizedClaim::flatten_or_none),
email: email.flatten(),
email_verified: email_verified.flatten().map(Boolean::into_inner),
gender: gender.flatten(),
birthday: birthday.flatten(),
birthdate: birthdate.flatten(),
zoneinfo: zoneinfo.flatten(),
locale: locale.flatten(),
phone_number: phone_number.flatten(),
phone_number_verified: phone_number_verified.flatten().map(Boolean::into_inner),
address: address.flatten(),
updated_at: updated_at
.flatten()
.map(|sec| {
sec.to_utc().map_err(|_| {
serde::de::Error::custom(format!(
"failed to parse `{sec}` as UTC datetime (in seconds) for key \
`updated_at`"
))
})
})
.transpose()?,
})
}
}
deserializer.deserialize_map(ClaimsVisitor(PhantomData))
}
}
impl<GC> Serialize for StandardClaims<GC>
where
GC: GenderClaim,
{
#[allow(clippy::cognitive_complexity)]
fn serialize<SE>(&self, serializer: SE) -> Result<SE::Ok, SE::Error>
where
SE: Serializer,
{
serialize_fields! {
self -> serializer {
[sub]
[LanguageTag(name)]
[LanguageTag(given_name)]
[LanguageTag(family_name)]
[LanguageTag(middle_name)]
[LanguageTag(nickname)]
[Option(preferred_username)]
[LanguageTag(profile)]
[LanguageTag(picture)]
[LanguageTag(website)]
[Option(email)]
[Option(email_verified)]
[Option(gender)]
[Option(birthday)]
[Option(birthdate)]
[Option(zoneinfo)]
[Option(locale)]
[Option(phone_number)]
[Option(phone_number_verified)]
[Option(address)]
[Option(DateTime(Seconds(updated_at)))]
}
}
}
}
#[cfg(test)]
mod tests {
use crate::core::CoreGenderClaim;
use crate::StandardClaims;
// The spec states (https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse):
// "If a Claim is not returned, that Claim Name SHOULD be omitted from the JSON object
// representing the Claims; it SHOULD NOT be present with a null or empty string value."
// However, we still aim to support identity providers that disregard this suggestion.
#[test]
fn test_null_optional_claims() {
let claims = serde_json::from_str::<StandardClaims<CoreGenderClaim>>(
r#"{
"sub": "24400320",
"name": null,
"given_name": null,
"family_name": null,
"middle_name": null,
"nickname": null,
"preferred_username": null,
"profile": null,
"picture": null,
"website": null,
"email": null,
"email_verified": null,
"gender": null,
"birthday": null,
"birthdate": null,
"zoneinfo": null,
"locale": null,
"phone_number": null,
"phone_number_verified": null,
"address": null,
"updated_at": null
}"#,
)
.expect("should deserialize successfully");
assert_eq!(claims.subject().as_str(), "24400320");
assert_eq!(claims.name(), None);
}
fn expect_err_prefix(
result: Result<StandardClaims<CoreGenderClaim>, serde_json::Error>,
expected_prefix: &str,
) {
let err_str = result.expect_err("deserialization should fail").to_string();
assert!(
err_str.starts_with(expected_prefix),
"error message should begin with `{expected_prefix}`: {err_str}",
)
}
#[test]
fn test_duplicate_claims() {
expect_err_prefix(
serde_json::from_str(
r#"{
"sub": "24400320",
"sub": "24400321"
}"#,
),
"duplicate field `sub` at line",
);
expect_err_prefix(
serde_json::from_str(
r#"{
"name": null,
"sub": "24400320",
"name": "foo",
}"#,
),
"duplicate field `name` at line",
);
expect_err_prefix(
serde_json::from_str(
r#"{
"name#en": null,
"sub": "24400320",
"name#en": "foo",
}"#,
),
"duplicate field `name#en` at line",
);
}
#[test]
fn test_err_field_name() {
expect_err_prefix(
serde_json::from_str(
r#"{
"sub": 24400320
}"#,
),
"sub: invalid type: integer `24400320`, expected a string at line",
);
}
}
+1470
View File
File diff suppressed because it is too large Load Diff
+234
View File
@@ -0,0 +1,234 @@
use crate::core::jwk::CoreJsonCurveType;
use crate::core::{CoreJsonWebKey, CoreJsonWebKeyType};
use crate::helpers::Base64UrlEncodedBytes;
use crate::{JsonWebKey, SignatureVerificationError};
use std::ops::Deref;
/// Decode a JWK unsigned component into `rsa` 0.10's integer type.
///
/// Leading zero octets are discarded, matching the previous `BigUint` decode.
fn jwk_uint(bytes: &[u8]) -> Result<rsa::BoxedUint, String> {
let start = bytes
.iter()
.position(|byte| *byte != 0)
.ok_or_else(|| "RSA integer component is zero".to_string())?;
let magnitude = &bytes[start..];
let bit_len = u32::try_from(magnitude.len())
.ok()
.and_then(|len| len.checked_mul(8))
.ok_or_else(|| "RSA integer component is too large".to_string())?;
// `BoxedUint` precision is limb-aligned. Round up so the magnitude fits.
let precision = bit_len.div_ceil(64).saturating_mul(64).max(64);
rsa::BoxedUint::from_be_slice(magnitude, precision).map_err(|err| err.to_string())
}
fn rsa_public_key(
key: &CoreJsonWebKey,
) -> Result<(&Base64UrlEncodedBytes, &Base64UrlEncodedBytes), String> {
if *key.key_type() != CoreJsonWebKeyType::RSA {
Err("RSA key required".to_string())
} else {
let n = key
.n
.as_ref()
.ok_or_else(|| "RSA modulus `n` is missing".to_string())?;
let e = key
.e
.as_ref()
.ok_or_else(|| "RSA exponent `e` is missing".to_string())?;
Ok((n, e))
}
}
fn ec_public_key(
key: &CoreJsonWebKey,
) -> Result<
(
&Base64UrlEncodedBytes,
&Base64UrlEncodedBytes,
&CoreJsonCurveType,
),
String,
> {
if *key.key_type() != CoreJsonWebKeyType::EllipticCurve {
Err("EC key required".to_string())
} else {
let x = key
.x
.as_ref()
.ok_or_else(|| "EC `x` part is missing".to_string())?;
let y = key
.y
.as_ref()
.ok_or_else(|| "EC `y` part is missing".to_string())?;
let crv = key
.crv
.as_ref()
.ok_or_else(|| "EC `crv` part is missing".to_string())?;
Ok((x, y, crv))
}
}
fn ed_public_key(
key: &CoreJsonWebKey,
) -> Result<(&Base64UrlEncodedBytes, &CoreJsonCurveType), String> {
if *key.key_type() != CoreJsonWebKeyType::OctetKeyPair {
Err("OKP key required".to_string())
} else {
let x = key
.x
.as_ref()
.ok_or_else(|| "OKP `x` part is missing".to_string())?;
let crv = key
.crv
.as_ref()
.ok_or_else(|| "OKP `crv` part is missing".to_string())?;
Ok((x, crv))
}
}
pub fn verify_rsa_signature(
key: &CoreJsonWebKey,
padding: impl rsa::traits::SignatureScheme,
msg: &[u8],
signature: &[u8],
) -> Result<(), SignatureVerificationError> {
let (n, e) = rsa_public_key(key).map_err(SignatureVerificationError::InvalidKey)?;
// Decode `n` and `e` as unsigned big-endian integers so a leading 0x00
// (RFC 7518 §6.3.1.1) does not change the modulus width.
let n_int = jwk_uint(n.deref()).map_err(SignatureVerificationError::InvalidKey)?;
let e_int = jwk_uint(e.deref()).map_err(SignatureVerificationError::InvalidKey)?;
let public_key = rsa::PublicKey::new(n_int, e_int)
.map_err(|e| SignatureVerificationError::InvalidKey(e.to_string()))?;
public_key
.verify(padding, msg, signature)
.map_err(|_| SignatureVerificationError::CryptoError("bad signature".to_string()))
}
/// According to RFC5480, Section-2.2 implementations of Elliptic Curve Cryptography MUST support the uncompressed form.
/// The first octet of the octet string indicates whether the uncompressed or compressed form is used. For the uncompressed
/// form, the first octet has to be 0x04.
/// According to https://briansmith.org/rustdoc/ring/signature/index.html#ecdsa__fixed-details-fixed-length-pkcs11-style-ecdsa-signatures,
/// to recover the X and Y coordinates from an octet string, the Octet-String-To-Elliptic-Curve-Point Conversion
/// is used (Section 2.3.4 of https://www.secg.org/sec1-v2.pdf).
pub fn verify_ec_signature(
key: &CoreJsonWebKey,
msg: &[u8],
signature: &[u8],
) -> Result<(), SignatureVerificationError> {
use p256::ecdsa::signature::Verifier;
let (x, y, crv) = ec_public_key(key).map_err(SignatureVerificationError::InvalidKey)?;
let mut pk = vec![0x04];
pk.extend(x.deref());
pk.extend(y.deref());
match *crv {
CoreJsonCurveType::P256 => {
let public_key = p256::ecdsa::VerifyingKey::from_sec1_bytes(&pk)
.map_err(|e| SignatureVerificationError::InvalidKey(e.to_string()))?;
public_key
.verify(
msg,
&p256::ecdsa::Signature::from_slice(signature).map_err(|_| {
SignatureVerificationError::CryptoError("Invalid signature".to_string())
})?,
)
.map_err(|_| {
SignatureVerificationError::CryptoError("EC Signature was wrong".to_string())
})
}
CoreJsonCurveType::P384 => {
let public_key = p384::ecdsa::VerifyingKey::from_sec1_bytes(&pk)
.map_err(|e| SignatureVerificationError::InvalidKey(e.to_string()))?;
public_key
.verify(
msg,
&p384::ecdsa::Signature::from_slice(signature).map_err(|_| {
SignatureVerificationError::CryptoError("Invalid signature".to_string())
})?,
)
.map_err(|_| {
SignatureVerificationError::CryptoError("EC Signature was wrong".to_string())
})
}
CoreJsonCurveType::P521 => Err(SignatureVerificationError::UnsupportedAlg(
"P521".to_string(),
)),
_ => Err(SignatureVerificationError::InvalidKey(format!(
"unrecognized curve `{crv:?}`"
))),
}
}
pub fn verify_ed_signature(
key: &CoreJsonWebKey,
msg: &[u8],
signature: &[u8],
) -> Result<(), SignatureVerificationError> {
use ed25519_dalek::Verifier;
let (x, crv) = ed_public_key(key).map_err(SignatureVerificationError::InvalidKey)?;
match *crv {
CoreJsonCurveType::Ed25519 => {
let public_key = ed25519_dalek::VerifyingKey::try_from(x.deref().as_slice())
.map_err(|e| SignatureVerificationError::InvalidKey(e.to_string()))?;
public_key
.verify(
msg,
&ed25519_dalek::Signature::from_slice(signature).map_err(|_| {
SignatureVerificationError::CryptoError("invalid signature".to_string())
})?,
)
.map_err(|_| {
SignatureVerificationError::CryptoError("incorrect EdDSA signature".to_string())
})
}
_ => Err(SignatureVerificationError::InvalidKey(format!(
"unrecognized curve `{crv:?}`"
))),
}
}
#[cfg(test)]
mod tests {
use crate::core::crypto::verify_rsa_signature;
use crate::core::CoreJsonWebKey;
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use base64::Engine;
use sha2::Digest;
#[test]
fn test_leading_zeros_are_parsed_correctly() {
// The message we signed
let msg = "THIS IS A SIGNATURE TEST";
let signature = BASE64_URL_SAFE_NO_PAD.decode("bg0ohqKwYHAiODeG6qkJ-6IhodN7LGPxAh4hbWeIoBdSXrXMt8Ft8U0BV7vANPvF56h20XB9C0021x2kt7iAbMgPNcZ7LCuXMPPq04DrBpMHafH5BXBwnyDKJKrzDm5sfr6OgEkcxSLHaSJ6gTWQ3waPt6_SeH2-Fi74rg13MHyX-0iqz7bZveoBbGIs5yQCwvXgrDS9zW5LUwUHozHfE6FuSi_Z92ioXeu7FHHDg1KFfg3hs8ZLx4wAX15Vw2GCQOzvyNdbItxXRLnrN1NPqxFquVNo5RGlx6ihR1Jfe7y_n0NSR2q2TuU4cIwR0LRwEaANy5SDqtleQPrTEn8nGQ").unwrap();
// RSA pub key with leading 0
let key : CoreJsonWebKey = serde_json::from_value(serde_json::json!(
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "TEST_KEY_ID",
"alg": "RS256",
"n": "AN0M6Y760b9Ok2PxDOps1TgSmiOaR9mLIfUHtZ_o-6JypOckGcl1CxrteyokOb3WyDsfIAN9fFNrycv5YoLKO7sh0IcfzNEXFgzK84HTBcGuqhN8NV98Z6N9EryUrgJYsJeVoPYm0MzkDe4NyWHhnq-9OyNCQzVELH0NhhViQqRyM92OPrJcQlk8s3ZvcgRmkd-rEtRua8SbS3GEvfvgweVy5-qcJCGoziKfx-IteMOm6yKoHvqisKb91N-qw_kSS4YQUx-DZVDo2g24F7VIbcYzJGUOU674HUF1j-wJyXzG3VV8lAXD8hABs5Lh87gr8_hIZD5gbYBJRObJk9XZbfk"
}
)).unwrap();
let mut hasher = sha2::Sha256::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
assert! {
verify_rsa_signature(
&key,
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha256>(),
&hash,
&signature,
).is_ok()
}
}
}
+779
View File
@@ -0,0 +1,779 @@
use crate::core::{crypto, CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm};
use crate::helpers::{deserialize_option_or_none, Base64UrlEncodedBytes};
use crate::types::jwks::check_key_compatibility;
use crate::{
JsonWebKey, JsonWebKeyAlgorithm, JsonWebKeyId, JsonWebKeyType, JsonWebKeyUse,
JsonWebTokenAlgorithm, PrivateSigningKey, SignatureVerificationError, SigningError,
};
use ed25519_dalek::pkcs8::DecodePrivateKey;
use ed25519_dalek::Signer;
use rsa::pkcs1::DecodeRsaPrivateKey;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use sha2::{Digest, Sha256, Sha384, Sha512};
#[cfg(test)]
mod tests;
// Other than the 'kty' (key type) parameter, which must be present in all JWKs, Section 4 of RFC
// 7517 states that "member names used for representing key parameters for different keys types
// need not be distinct." Therefore, it's possible that future or non-standard key types will supply
// some of the following parameters but with different types, causing deserialization to fail. To
// support such key types, we'll need to define a new impl for JsonWebKey. Deserializing the new
// impl would probably need to involve first deserializing the raw values to access the 'kty'
// parameter, and then deserializing the fields and types appropriate for that key type.
/// Public or symmetric key expressed as a JSON Web Key.
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct CoreJsonWebKey {
pub(crate) kty: CoreJsonWebKeyType,
#[serde(rename = "use")]
pub(crate) use_: Option<CoreJsonWebKeyUse>,
pub(crate) kid: Option<JsonWebKeyId>,
/// The algorithm intended to be used with this key (see
/// [RFC 7517](https://www.rfc-editor.org/rfc/rfc7517#section-4.4)).
///
/// It can either be an algorithm intended for use with JWS or JWE, or something different.
pub(crate) alg:
Option<JsonWebTokenAlgorithm<CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm>>,
// From RFC 7517, Section 4: "Additional members can be present in the JWK; if not understood
// by implementations encountering them, they MUST be ignored. Member names used for
// representing key parameters for different keys types need not be distinct."
// Hence, we set fields we fail to deserialize (understand) as None.
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) n: Option<Base64UrlEncodedBytes>,
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) e: Option<Base64UrlEncodedBytes>,
//Elliptic Curve
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) crv: Option<CoreJsonCurveType>,
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) x: Option<Base64UrlEncodedBytes>,
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) y: Option<Base64UrlEncodedBytes>,
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) d: Option<Base64UrlEncodedBytes>,
// Used for symmetric keys, which we only generate internally from the client secret; these
// are never part of the JWK set.
#[serde(default, deserialize_with = "deserialize_option_or_none")]
pub(crate) k: Option<Base64UrlEncodedBytes>,
}
impl CoreJsonWebKey {
/// Instantiate a new RSA public key from the raw modulus (`n`) and public exponent (`e`),
/// along with an optional (but recommended) key ID.
///
/// The key ID is used for matching signed JSON Web Tokens with the keys used for verifying
/// their signatures.
pub fn new_rsa(n: Vec<u8>, e: Vec<u8>, kid: Option<JsonWebKeyId>) -> Self {
Self {
kty: CoreJsonWebKeyType::RSA,
use_: Some(CoreJsonWebKeyUse::Signature),
kid,
n: Some(Base64UrlEncodedBytes::new(n)),
e: Some(Base64UrlEncodedBytes::new(e)),
k: None,
crv: None,
x: None,
y: None,
d: None,
alg: None,
}
}
/// Instantiate a new EC public key from the raw x (`x`) and y(`y`) part of the curve,
/// along with an optional (but recommended) key ID.
///
/// The key ID is used for matching signed JSON Web Tokens with the keys used for verifying
/// their signatures.
pub fn new_ec(
x: Vec<u8>,
y: Vec<u8>,
crv: CoreJsonCurveType,
kid: Option<JsonWebKeyId>,
) -> Self {
Self {
kty: CoreJsonWebKeyType::EllipticCurve,
use_: Some(CoreJsonWebKeyUse::Signature),
kid,
n: None,
e: None,
k: None,
crv: Some(crv),
x: Some(Base64UrlEncodedBytes::new(x)),
y: Some(Base64UrlEncodedBytes::new(y)),
d: None,
alg: None,
}
}
/// Instantiate a new Octet Key-Pair public key from the raw x (`x`) part of the curve,
/// along with an optional (but recommended) key ID.
///
/// The key ID is used for matching signed JSON Web Tokens with the keys used for verifying
/// their signatures.
pub fn new_okp(x: Vec<u8>, crv: CoreJsonCurveType, kid: Option<JsonWebKeyId>) -> Self {
Self {
kty: CoreJsonWebKeyType::OctetKeyPair,
use_: Some(CoreJsonWebKeyUse::Signature),
kid,
n: None,
e: None,
k: None,
crv: Some(crv),
x: Some(Base64UrlEncodedBytes::new(x)),
y: None,
d: None,
alg: None,
}
}
}
impl JsonWebKey for CoreJsonWebKey {
type KeyUse = CoreJsonWebKeyUse;
type SigningAlgorithm = CoreJwsSigningAlgorithm;
fn key_id(&self) -> Option<&JsonWebKeyId> {
self.kid.as_ref()
}
fn key_type(&self) -> &CoreJsonWebKeyType {
&self.kty
}
fn key_use(&self) -> Option<&CoreJsonWebKeyUse> {
self.use_.as_ref()
}
fn signing_alg(&self) -> JsonWebKeyAlgorithm<&CoreJwsSigningAlgorithm> {
match self.alg {
None => JsonWebKeyAlgorithm::Unspecified,
Some(JsonWebTokenAlgorithm::Signature(ref alg)) => JsonWebKeyAlgorithm::Algorithm(alg),
Some(_) => JsonWebKeyAlgorithm::Unsupported,
}
}
fn new_symmetric(key: Vec<u8>) -> Self {
Self {
kty: CoreJsonWebKeyType::Symmetric,
use_: None,
kid: None,
n: None,
e: None,
k: Some(Base64UrlEncodedBytes::new(key)),
crv: None,
x: None,
y: None,
d: None,
alg: None,
}
}
fn verify_signature(
&self,
signature_alg: &CoreJwsSigningAlgorithm,
message: &[u8],
signature: &[u8],
) -> Result<(), SignatureVerificationError> {
use hmac::Mac;
check_key_compatibility(self, signature_alg)
.map_err(|e| SignatureVerificationError::InvalidKey(e.to_owned()))?;
match *signature_alg {
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256 => {
let message = {
let mut hasher = sha2::Sha256::new();
hasher.update(message);
&hasher.finalize()
};
crypto::verify_rsa_signature(
self,
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha256>(),
message,
signature,
)
}
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha384 => {
let message = {
let mut hasher = sha2::Sha384::new();
hasher.update(message);
&hasher.finalize()
};
crypto::verify_rsa_signature(
self,
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha384>(),
message,
signature,
)
}
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha512 => {
let message = {
let mut hasher = sha2::Sha512::new();
hasher.update(message);
&hasher.finalize()
};
crypto::verify_rsa_signature(
self,
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha512>(),
message,
signature,
)
}
CoreJwsSigningAlgorithm::RsaSsaPssSha256 => {
let message = {
let mut hasher = sha2::Sha256::new();
hasher.update(message);
&hasher.finalize()
};
crypto::verify_rsa_signature(
self,
rsa::Pss::<rsa::sha2::Sha256>::new(),
message,
signature,
)
}
CoreJwsSigningAlgorithm::RsaSsaPssSha384 => {
let message = {
let mut hasher = sha2::Sha384::new();
hasher.update(message);
&hasher.finalize()
};
crypto::verify_rsa_signature(
self,
rsa::Pss::<rsa::sha2::Sha384>::new(),
message,
signature,
)
}
CoreJwsSigningAlgorithm::RsaSsaPssSha512 => {
let message = {
let mut hasher = sha2::Sha512::new();
hasher.update(message);
&hasher.finalize()
};
crypto::verify_rsa_signature(
self,
rsa::Pss::<rsa::sha2::Sha512>::new(),
message,
signature,
)
}
CoreJwsSigningAlgorithm::HmacSha256 => {
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(
self.k.as_ref().ok_or_else(|| {
SignatureVerificationError::InvalidKey(
"Symmetric key `k` is missing".to_string(),
)
})?,
)
.map_err(|e| {
SignatureVerificationError::Other(format!("Could not create key: {e}"))
})?;
mac.update(message);
mac.verify(signature.into())
.map_err(|_| SignatureVerificationError::CryptoError("bad HMAC".to_string()))
}
CoreJwsSigningAlgorithm::HmacSha384 => {
let mut mac = hmac::Hmac::<sha2::Sha384>::new_from_slice(
self.k.as_ref().ok_or_else(|| {
SignatureVerificationError::InvalidKey(
"Symmetric key `k` is missing".to_string(),
)
})?,
)
.map_err(|e| {
SignatureVerificationError::Other(format!("Could not create key: {e}"))
})?;
mac.update(message);
mac.verify(signature.into())
.map_err(|_| SignatureVerificationError::CryptoError("bad HMAC".to_string()))
}
CoreJwsSigningAlgorithm::HmacSha512 => {
let mut mac = hmac::Hmac::<sha2::Sha512>::new_from_slice(
self.k.as_ref().ok_or_else(|| {
SignatureVerificationError::InvalidKey(
"Symmetric key `k` is missing".to_string(),
)
})?,
)
.map_err(|e| {
SignatureVerificationError::Other(format!("Could not create key: {e}"))
})?;
mac.update(message);
mac.verify(signature.into())
.map_err(|_| SignatureVerificationError::CryptoError("bad HMAC".to_string()))
}
CoreJwsSigningAlgorithm::EcdsaP256Sha256 => {
if matches!(self.crv, Some(CoreJsonCurveType::P256)) {
crypto::verify_ec_signature(self, message, signature)
} else {
Err(SignatureVerificationError::InvalidKey(
"Key uses different CRV than JWT".to_string(),
))
}
}
CoreJwsSigningAlgorithm::EcdsaP384Sha384 => {
if matches!(self.crv, Some(CoreJsonCurveType::P384)) {
crypto::verify_ec_signature(self, message, signature)
} else {
Err(SignatureVerificationError::InvalidKey(
"Key uses different CRV than JWT".to_string(),
))
}
}
CoreJwsSigningAlgorithm::EdDsa => match self.crv {
None => Err(SignatureVerificationError::InvalidKey(
"EdDSA key must specify `crv`".to_string(),
)),
Some(CoreJsonCurveType::Ed25519) => {
crypto::verify_ed_signature(self, message, signature)
}
Some(ref crv) => Err(SignatureVerificationError::InvalidKey(format!(
"Unsupported EdDSA curve {crv:?}"
))),
},
ref other => Err(SignatureVerificationError::UnsupportedAlg(
serde_plain::to_string(other).unwrap_or_else(|err| {
panic!("signature alg {other:?} failed to serialize to a string: {err}")
}),
)),
}
}
fn hash_bytes(&self, bytes: &[u8], alg: &Self::SigningAlgorithm) -> Result<Vec<u8>, String> {
check_key_compatibility(self, alg).map_err(String::from)?;
match *alg {
CoreJwsSigningAlgorithm::HmacSha256
| CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256
| CoreJwsSigningAlgorithm::RsaSsaPssSha256
| CoreJwsSigningAlgorithm::EcdsaP256Sha256 => {
let mut hasher = Sha256::new();
hasher.update(bytes);
Ok(hasher.finalize().to_vec())
}
CoreJwsSigningAlgorithm::HmacSha384
| CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha384
| CoreJwsSigningAlgorithm::RsaSsaPssSha384
| CoreJwsSigningAlgorithm::EcdsaP384Sha384 => {
let mut hasher = Sha384::new();
hasher.update(bytes);
Ok(hasher.finalize().to_vec())
}
CoreJwsSigningAlgorithm::HmacSha512
| CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha512
| CoreJwsSigningAlgorithm::RsaSsaPssSha512
| CoreJwsSigningAlgorithm::EcdsaP521Sha512 => {
let mut hasher = Sha512::new();
hasher.update(bytes);
Ok(hasher.finalize().to_vec())
}
CoreJwsSigningAlgorithm::EdDsa => match self.crv {
None => Err("EdDSA key must specify `crv`".to_string()),
Some(CoreJsonCurveType::Ed25519) => {
let mut hasher = Sha512::new();
hasher.update(bytes);
Ok(hasher.finalize().to_vec())
}
Some(ref crv) => Err(format!("Unsupported EdDSA curve {crv:?}")),
},
CoreJwsSigningAlgorithm::None => {
Err("Signature algorithm `none` has no corresponding hash algorithm".to_string())
}
}
}
}
/// HMAC secret key.
///
/// This key can be used for signing messages, or converted to a `CoreJsonWebKey` for verifying
/// them.
#[derive(Clone)]
pub struct CoreHmacKey {
secret: Vec<u8>,
}
impl CoreHmacKey {
/// Instantiate a new key from the specified secret bytes.
pub fn new<T>(secret: T) -> Self
where
T: Into<Vec<u8>>,
{
Self {
secret: secret.into(),
}
}
}
impl PrivateSigningKey for CoreHmacKey {
type VerificationKey = CoreJsonWebKey;
fn sign(
&self,
signature_alg: &CoreJwsSigningAlgorithm,
message: &[u8],
) -> Result<Vec<u8>, SigningError> {
use hmac::Mac;
match *signature_alg {
CoreJwsSigningAlgorithm::HmacSha256 => {
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&self.secret)
.map_err(|e| SigningError::Other(format!("Could not create key: {e}")))?;
mac.update(message);
let result = mac.finalize();
Ok(result.into_bytes().as_slice().to_vec())
}
CoreJwsSigningAlgorithm::HmacSha384 => {
let mut mac = hmac::Hmac::<sha2::Sha384>::new_from_slice(&self.secret)
.map_err(|e| SigningError::Other(format!("Could not create key: {e}")))?;
mac.update(message);
let result = mac.finalize();
Ok(result.into_bytes().as_slice().to_vec())
}
CoreJwsSigningAlgorithm::HmacSha512 => {
let mut mac = hmac::Hmac::<sha2::Sha512>::new_from_slice(&self.secret)
.map_err(|e| SigningError::Other(format!("Could not create key: {e}")))?;
mac.update(message);
let result = mac.finalize();
Ok(result.into_bytes().as_slice().to_vec())
}
ref other => Err(SigningError::UnsupportedAlg(
serde_plain::to_string(other).unwrap_or_else(|err| {
panic!("signature alg {other:?} failed to serialize to a string: {err}")
}),
)),
}
}
fn as_verification_key(&self) -> CoreJsonWebKey {
CoreJsonWebKey::new_symmetric(self.secret.clone())
}
}
enum EdDsaSigningKey {
Ed25519(ed25519_dalek::SigningKey),
}
impl EdDsaSigningKey {
fn from_ed25519_pem(pem: &str) -> Result<Self, String> {
Ok(Self::Ed25519(
ed25519_dalek::SigningKey::from_pkcs8_pem(pem).map_err(|err| err.to_string())?,
))
}
fn sign(&self, message: &[u8]) -> Vec<u8> {
match self {
Self::Ed25519(key) => {
let signature = key.sign(message);
signature.to_vec()
}
}
}
}
/// EdDSA Private Key.
///
/// This key can be used for signing messages, or converted to a `CoreJsonWebKey` for verifying
/// them.
pub struct CoreEdDsaPrivateSigningKey {
kid: Option<JsonWebKeyId>,
key_pair: EdDsaSigningKey,
}
impl CoreEdDsaPrivateSigningKey {
/// Converts an EdDSA private key (in PEM format) to a JWK representing its public key.
pub fn from_ed25519_pem(pem: &str, kid: Option<JsonWebKeyId>) -> Result<Self, String> {
Ok(Self {
kid,
key_pair: EdDsaSigningKey::from_ed25519_pem(pem)?,
})
}
}
impl PrivateSigningKey for CoreEdDsaPrivateSigningKey {
type VerificationKey = CoreJsonWebKey;
fn sign(
&self,
signature_alg: &CoreJwsSigningAlgorithm,
message: &[u8],
) -> Result<Vec<u8>, SigningError> {
match *signature_alg {
CoreJwsSigningAlgorithm::EdDsa => Ok(self.key_pair.sign(message)),
ref other => Err(SigningError::UnsupportedAlg(
serde_plain::to_string(other).unwrap_or_else(|err| {
panic!("signature alg {other:?} failed to serialize to a string: {err}")
}),
)),
}
}
fn as_verification_key(&self) -> CoreJsonWebKey {
match &self.key_pair {
EdDsaSigningKey::Ed25519(key) => CoreJsonWebKey {
kty: CoreJsonWebKeyType::OctetKeyPair,
use_: Some(CoreJsonWebKeyUse::Signature),
kid: self.kid.clone(),
n: None,
e: None,
crv: Some(CoreJsonCurveType::Ed25519),
x: Some(Base64UrlEncodedBytes::new(
key.verifying_key().as_bytes().to_vec(),
)),
y: None,
d: None,
k: None,
alg: None,
},
}
}
}
/// Trait used to allow testing with an alternative RNG.
/// Clone is necessary to get a mutable version of the RNG.
pub(crate) trait RngClone: dyn_clone::DynClone + rand::RngCore + rand::CryptoRng {}
dyn_clone::clone_trait_object!(RngClone);
impl<T> RngClone for T where T: rand::RngCore + rand::CryptoRng + Clone {}
/// Adapts a `rand` 0.8 generator to the `rand_core` 0.10 traits used by `rsa` 0.10.
struct Rsa10Rng<R>(R);
impl<R: rand::RngCore> rsa::rand_core::TryRng for Rsa10Rng<R> {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> core::result::Result<u32, Self::Error> {
Ok(self.0.next_u32())
}
fn try_next_u64(&mut self) -> core::result::Result<u64, Self::Error> {
Ok(self.0.next_u64())
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> core::result::Result<(), Self::Error> {
self.0.fill_bytes(dst);
Ok(())
}
}
impl<R: rand::RngCore + rand::CryptoRng> rsa::rand_core::TryCryptoRng for Rsa10Rng<R> {}
/// RSA private key.
///
/// This key can be used for signing messages, or converted to a `CoreJsonWebKey` for verifying
/// them.
pub struct CoreRsaPrivateSigningKey {
key_pair: rsa::PrivateKey,
rng: Box<dyn RngClone + Send + Sync>,
kid: Option<JsonWebKeyId>,
}
impl CoreRsaPrivateSigningKey {
/// Converts an RSA private key (in PEM format) to a JWK representing its public key.
pub fn from_pem(pem: &str, kid: Option<JsonWebKeyId>) -> Result<Self, String> {
Self::from_pem_internal(pem, Box::new(rand::rngs::OsRng), kid)
}
pub(crate) fn from_pem_internal(
pem: &str,
rng: Box<dyn RngClone + Send + Sync>,
kid: Option<JsonWebKeyId>,
) -> Result<Self, String> {
let key_pair = rsa::PrivateKey::from_pkcs1_pem(pem).map_err(|err| err.to_string())?;
Ok(Self { key_pair, rng, kid })
}
}
impl PrivateSigningKey for CoreRsaPrivateSigningKey {
type VerificationKey = CoreJsonWebKey;
fn sign(
&self,
signature_alg: &CoreJwsSigningAlgorithm,
msg: &[u8],
) -> Result<Vec<u8>, SigningError> {
match *signature_alg {
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256 => {
let mut hasher = sha2::Sha256::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
self.key_pair
.sign_with_rng(
&mut Rsa10Rng(dyn_clone::clone_box(&self.rng)),
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha256>(),
&hash,
)
.map_err(|_| SigningError::CryptoError)
}
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha384 => {
let mut hasher = sha2::Sha384::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
self.key_pair
.sign_with_rng(
&mut Rsa10Rng(dyn_clone::clone_box(&self.rng)),
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha384>(),
&hash,
)
.map_err(|_| SigningError::CryptoError)
}
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha512 => {
let mut hasher = sha2::Sha512::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
self.key_pair
.sign_with_rng(
&mut Rsa10Rng(dyn_clone::clone_box(&self.rng)),
rsa::Pkcs1v15Sign::new::<rsa::sha2::Sha512>(),
&hash,
)
.map_err(|_| SigningError::CryptoError)
}
CoreJwsSigningAlgorithm::RsaSsaPssSha256 => {
let mut hasher = sha2::Sha256::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
self.key_pair
.sign_with_rng(
&mut Rsa10Rng(dyn_clone::clone_box(&self.rng)),
rsa::Pss::<rsa::sha2::Sha256>::new_with_salt(hash.len()),
&hash,
)
.map_err(|_| SigningError::CryptoError)
}
CoreJwsSigningAlgorithm::RsaSsaPssSha384 => {
let mut hasher = sha2::Sha384::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
self.key_pair
.sign_with_rng(
&mut Rsa10Rng(dyn_clone::clone_box(&self.rng)),
rsa::Pss::<rsa::sha2::Sha384>::new_with_salt(hash.len()),
&hash,
)
.map_err(|_| SigningError::CryptoError)
}
CoreJwsSigningAlgorithm::RsaSsaPssSha512 => {
let mut hasher = sha2::Sha512::new();
hasher.update(msg);
let hash = hasher.finalize().to_vec();
self.key_pair
.sign_with_rng(
&mut Rsa10Rng(dyn_clone::clone_box(&self.rng)),
rsa::Pss::<rsa::sha2::Sha512>::new_with_salt(hash.len()),
&hash,
)
.map_err(|_| SigningError::CryptoError)
}
ref other => Err(SigningError::UnsupportedAlg(
serde_plain::to_string(other).unwrap_or_else(|err| {
panic!("signature alg {other:?} failed to serialize to a string: {err}")
}),
)),
}
}
fn as_verification_key(&self) -> CoreJsonWebKey {
use rsa::traits::PublicKeyParts;
let public_key = self.key_pair.to_public_key();
CoreJsonWebKey {
kty: CoreJsonWebKeyType::RSA,
use_: Some(CoreJsonWebKeyUse::Signature),
kid: self.kid.clone(),
n: Some(Base64UrlEncodedBytes::new(public_key.n_bytes().into_vec())),
e: Some(Base64UrlEncodedBytes::new(public_key.e_bytes().into_vec())),
k: None,
crv: None,
x: None,
y: None,
d: None,
alg: None,
}
}
}
/// Type of JSON Web Key.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub enum CoreJsonWebKeyType {
/// Elliptic Curve Cryptography (ECC) key.
///
/// ECC algorithms such as ECDSA are currently unsupported.
#[serde(rename = "EC")]
EllipticCurve,
/// RSA key.
#[serde(rename = "RSA")]
RSA,
/// EdDSA key.
#[serde(rename = "OKP")]
OctetKeyPair,
/// Symmetric key.
#[serde(rename = "oct")]
Symmetric,
}
impl JsonWebKeyType for CoreJsonWebKeyType {}
/// Type of EC-Curve
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub enum CoreJsonCurveType {
/// P-256 Curve
#[serde(rename = "P-256")]
P256,
/// P-384 Curve
#[serde(rename = "P-384")]
P384,
/// P-521 Curve (currently not supported)
#[serde(rename = "P-521")]
P521,
/// Ed25519 Curve
#[serde(rename = "Ed25519")]
Ed25519,
}
/// Usage restriction for a JSON Web key.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CoreJsonWebKeyUse {
/// Key may be used for digital signatures.
Signature,
/// Key may be used for encryption.
Encryption,
/// Fallback case for other key uses not understood by this library.
Other(String),
}
impl CoreJsonWebKeyUse {
fn from_str(s: &str) -> Self {
match s {
"sig" => Self::Signature,
"enc" => Self::Encryption,
other => Self::Other(other.to_string()),
}
}
}
impl AsRef<str> for CoreJsonWebKeyUse {
fn as_ref(&self) -> &str {
match self {
CoreJsonWebKeyUse::Signature => "sig",
CoreJsonWebKeyUse::Encryption => "enc",
CoreJsonWebKeyUse::Other(other) => other.as_str(),
}
}
}
impl JsonWebKeyUse for CoreJsonWebKeyUse {
fn allows_signature(&self) -> bool {
matches!(*self, CoreJsonWebKeyUse::Signature)
}
fn allows_encryption(&self) -> bool {
matches!(*self, CoreJsonWebKeyUse::Encryption)
}
}
// FIXME: Once https://github.com/serde-rs/serde/issues/912 is resolved, use #[serde(other)] instead
// of custom serializer/deserializers. Right now this isn't possible because serde(other) only
// supports unit variants.
deserialize_from_str!(CoreJsonWebKeyUse);
serialize_as_str!(CoreJsonWebKeyUse);
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
use crate::core::{CoreGrantType, CoreJwsSigningAlgorithm};
#[test]
fn test_grant_type_serialize() {
let serialized_implicit = serde_json::to_string(&CoreGrantType::Implicit).unwrap();
assert_eq!("\"implicit\"", serialized_implicit);
assert_eq!(
CoreGrantType::Implicit,
serde_json::from_str::<CoreGrantType>(&serialized_implicit).unwrap()
);
}
#[test]
fn test_signature_alg_serde_plain() {
assert_eq!(
serde_plain::to_string(&CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256).unwrap(),
"RS256"
);
assert_eq!(
serde_plain::from_str::<CoreJwsSigningAlgorithm>("RS256").unwrap(),
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256
);
}
+430
View File
@@ -0,0 +1,430 @@
use crate::http_utils::{check_content_type, MIME_TYPE_JSON};
use crate::{
AsyncHttpClient, AuthDisplay, AuthUrl, AuthenticationContextClass, ClaimName, ClaimType,
ClientAuthMethod, GrantType, HttpRequest, HttpResponse, IssuerUrl, JsonWebKey, JsonWebKeySet,
JsonWebKeySetUrl, JweContentEncryptionAlgorithm, JweKeyManagementAlgorithm,
JwsSigningAlgorithm, LanguageTag, OpPolicyUrl, OpTosUrl, RegistrationUrl, ResponseMode,
ResponseType, ResponseTypes, Scope, ServiceDocUrl, SubjectIdentifierType, SyncHttpClient,
TokenUrl, UserInfoUrl,
};
use http::header::{HeaderValue, ACCEPT};
use http::method::Method;
use http::status::StatusCode;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, skip_serializing_none, VecSkipError};
use thiserror::Error;
use std::fmt::Debug;
use std::future::Future;
#[cfg(test)]
mod tests;
const CONFIG_URL_SUFFIX: &str = ".well-known/openid-configuration";
/// Trait for adding extra fields to [`ProviderMetadata`].
pub trait AdditionalProviderMetadata: Clone + Debug + DeserializeOwned + Serialize {}
// In order to support serde flatten, this must be an empty struct rather than an empty
// tuple struct.
/// Empty (default) extra [`ProviderMetadata`] fields.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct EmptyAdditionalProviderMetadata {}
impl AdditionalProviderMetadata for EmptyAdditionalProviderMetadata {}
/// Provider metadata returned by [OpenID Connect Discovery](
/// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata).
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[allow(clippy::type_complexity)]
pub struct ProviderMetadata<A, AD, CA, CN, CT, G, JE, JK, K, RM, RT, S>
where
A: AdditionalProviderMetadata,
AD: AuthDisplay,
CA: ClientAuthMethod,
CN: ClaimName,
CT: ClaimType,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RM: ResponseMode,
RT: ResponseType,
S: SubjectIdentifierType,
{
issuer: IssuerUrl,
authorization_endpoint: AuthUrl,
token_endpoint: Option<TokenUrl>,
userinfo_endpoint: Option<UserInfoUrl>,
jwks_uri: JsonWebKeySetUrl,
#[serde(default = "JsonWebKeySet::default", skip)]
jwks: JsonWebKeySet<K>,
registration_endpoint: Option<RegistrationUrl>,
scopes_supported: Option<Vec<Scope>>,
#[serde(bound(deserialize = "RT: ResponseType"))]
response_types_supported: Vec<ResponseTypes<RT>>,
#[serde(bound(deserialize = "RM: ResponseMode"))]
response_modes_supported: Option<Vec<RM>>,
#[serde(bound(deserialize = "G: GrantType"))]
grant_types_supported: Option<Vec<G>>,
acr_values_supported: Option<Vec<AuthenticationContextClass>>,
#[serde(bound(deserialize = "S: SubjectIdentifierType"))]
subject_types_supported: Vec<S>,
#[serde(bound(deserialize = "K: JsonWebKey"))]
#[serde_as(as = "VecSkipError<_>")]
id_token_signing_alg_values_supported: Vec<K::SigningAlgorithm>,
#[serde(
bound(deserialize = "JK: JweKeyManagementAlgorithm"),
default = "Option::default"
)]
#[serde_as(as = "Option<VecSkipError<_>>")]
id_token_encryption_alg_values_supported: Option<Vec<JK>>,
#[serde(
bound(
deserialize = "JE: JweContentEncryptionAlgorithm<KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType>"
),
default = "Option::default"
)]
#[serde_as(as = "Option<VecSkipError<_>>")]
id_token_encryption_enc_values_supported: Option<Vec<JE>>,
#[serde(bound(deserialize = "K: JsonWebKey"), default = "Option::default")]
#[serde_as(as = "Option<VecSkipError<_>>")]
userinfo_signing_alg_values_supported: Option<Vec<K::SigningAlgorithm>>,
#[serde(
bound(deserialize = "JK: JweKeyManagementAlgorithm"),
default = "Option::default"
)]
#[serde_as(as = "Option<VecSkipError<_>>")]
userinfo_encryption_alg_values_supported: Option<Vec<JK>>,
#[serde(
bound(
deserialize = "JE: JweContentEncryptionAlgorithm<KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType>"
),
default = "Option::default"
)]
#[serde_as(as = "Option<VecSkipError<_>>")]
userinfo_encryption_enc_values_supported: Option<Vec<JE>>,
#[serde(bound(deserialize = "K: JsonWebKey"), default = "Option::default")]
#[serde_as(as = "Option<VecSkipError<_>>")]
request_object_signing_alg_values_supported: Option<Vec<K::SigningAlgorithm>>,
#[serde(
bound(deserialize = "JK: JweKeyManagementAlgorithm"),
default = "Option::default"
)]
#[serde_as(as = "Option<VecSkipError<_>>")]
request_object_encryption_alg_values_supported: Option<Vec<JK>>,
#[serde(
bound(
deserialize = "JE: JweContentEncryptionAlgorithm<KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType>"
),
default = "Option::default"
)]
#[serde_as(as = "Option<VecSkipError<_>>")]
request_object_encryption_enc_values_supported: Option<Vec<JE>>,
#[serde(bound(deserialize = "CA: ClientAuthMethod"))]
token_endpoint_auth_methods_supported: Option<Vec<CA>>,
#[serde(bound(deserialize = "K: JsonWebKey"), default = "Option::default")]
#[serde_as(as = "Option<VecSkipError<_>>")]
token_endpoint_auth_signing_alg_values_supported: Option<Vec<K::SigningAlgorithm>>,
#[serde(bound(deserialize = "AD: AuthDisplay"))]
display_values_supported: Option<Vec<AD>>,
#[serde(bound(deserialize = "CT: ClaimType"))]
claim_types_supported: Option<Vec<CT>>,
#[serde(bound(deserialize = "CN: ClaimName"))]
claims_supported: Option<Vec<CN>>,
service_documentation: Option<ServiceDocUrl>,
claims_locales_supported: Option<Vec<LanguageTag>>,
ui_locales_supported: Option<Vec<LanguageTag>>,
claims_parameter_supported: Option<bool>,
request_parameter_supported: Option<bool>,
request_uri_parameter_supported: Option<bool>,
require_request_uri_registration: Option<bool>,
op_policy_uri: Option<OpPolicyUrl>,
op_tos_uri: Option<OpTosUrl>,
#[serde(bound(deserialize = "A: AdditionalProviderMetadata"), flatten)]
additional_metadata: A,
}
impl<A, AD, CA, CN, CT, G, JE, JK, K, RM, RT, S>
ProviderMetadata<A, AD, CA, CN, CT, G, JE, JK, K, RM, RT, S>
where
A: AdditionalProviderMetadata,
AD: AuthDisplay,
CA: ClientAuthMethod,
CN: ClaimName,
CT: ClaimType,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RM: ResponseMode,
RT: ResponseType,
S: SubjectIdentifierType,
{
/// Instantiates new provider metadata.
pub fn new(
issuer: IssuerUrl,
authorization_endpoint: AuthUrl,
jwks_uri: JsonWebKeySetUrl,
response_types_supported: Vec<ResponseTypes<RT>>,
subject_types_supported: Vec<S>,
id_token_signing_alg_values_supported: Vec<K::SigningAlgorithm>,
additional_metadata: A,
) -> Self {
Self {
issuer,
authorization_endpoint,
token_endpoint: None,
userinfo_endpoint: None,
jwks_uri,
jwks: JsonWebKeySet::new(Vec::new()),
registration_endpoint: None,
scopes_supported: None,
response_types_supported,
response_modes_supported: None,
grant_types_supported: None,
acr_values_supported: None,
subject_types_supported,
id_token_signing_alg_values_supported,
id_token_encryption_alg_values_supported: None,
id_token_encryption_enc_values_supported: None,
userinfo_signing_alg_values_supported: None,
userinfo_encryption_alg_values_supported: None,
userinfo_encryption_enc_values_supported: None,
request_object_signing_alg_values_supported: None,
request_object_encryption_alg_values_supported: None,
request_object_encryption_enc_values_supported: None,
token_endpoint_auth_methods_supported: None,
token_endpoint_auth_signing_alg_values_supported: None,
display_values_supported: None,
claim_types_supported: None,
claims_supported: None,
service_documentation: None,
claims_locales_supported: None,
ui_locales_supported: None,
claims_parameter_supported: None,
request_parameter_supported: None,
request_uri_parameter_supported: None,
require_request_uri_registration: None,
op_policy_uri: None,
op_tos_uri: None,
additional_metadata,
}
}
field_getters_setters![
pub self [self] ["provider metadata value"] {
set_issuer -> issuer[IssuerUrl],
set_authorization_endpoint -> authorization_endpoint[AuthUrl],
set_token_endpoint -> token_endpoint[Option<TokenUrl>],
set_userinfo_endpoint -> userinfo_endpoint[Option<UserInfoUrl>],
set_jwks_uri -> jwks_uri[JsonWebKeySetUrl],
set_jwks -> jwks[JsonWebKeySet<K>],
set_registration_endpoint -> registration_endpoint[Option<RegistrationUrl>],
set_scopes_supported -> scopes_supported[Option<Vec<Scope>>],
set_response_types_supported -> response_types_supported[Vec<ResponseTypes<RT>>],
set_response_modes_supported -> response_modes_supported[Option<Vec<RM>>],
set_grant_types_supported -> grant_types_supported[Option<Vec<G>>],
set_acr_values_supported
-> acr_values_supported[Option<Vec<AuthenticationContextClass>>],
set_subject_types_supported -> subject_types_supported[Vec<S>],
set_id_token_signing_alg_values_supported
-> id_token_signing_alg_values_supported[Vec<K::SigningAlgorithm>],
set_id_token_encryption_alg_values_supported
-> id_token_encryption_alg_values_supported[Option<Vec<JK>>],
set_id_token_encryption_enc_values_supported
-> id_token_encryption_enc_values_supported[Option<Vec<JE>>],
set_userinfo_signing_alg_values_supported
-> userinfo_signing_alg_values_supported[Option<Vec<K::SigningAlgorithm>>],
set_userinfo_encryption_alg_values_supported
-> userinfo_encryption_alg_values_supported[Option<Vec<JK>>],
set_userinfo_encryption_enc_values_supported
-> userinfo_encryption_enc_values_supported[Option<Vec<JE>>],
set_request_object_signing_alg_values_supported
-> request_object_signing_alg_values_supported[Option<Vec<K::SigningAlgorithm>>],
set_request_object_encryption_alg_values_supported
-> request_object_encryption_alg_values_supported[Option<Vec<JK>>],
set_request_object_encryption_enc_values_supported
-> request_object_encryption_enc_values_supported[Option<Vec<JE>>],
set_token_endpoint_auth_methods_supported
-> token_endpoint_auth_methods_supported[Option<Vec<CA>>],
set_token_endpoint_auth_signing_alg_values_supported
-> token_endpoint_auth_signing_alg_values_supported[Option<Vec<K::SigningAlgorithm>>],
set_display_values_supported -> display_values_supported[Option<Vec<AD>>],
set_claim_types_supported -> claim_types_supported[Option<Vec<CT>>],
set_claims_supported -> claims_supported[Option<Vec<CN>>],
set_service_documentation -> service_documentation[Option<ServiceDocUrl>],
set_claims_locales_supported -> claims_locales_supported[Option<Vec<LanguageTag>>],
set_ui_locales_supported -> ui_locales_supported[Option<Vec<LanguageTag>>],
set_claims_parameter_supported -> claims_parameter_supported[Option<bool>],
set_request_parameter_supported -> request_parameter_supported[Option<bool>],
set_request_uri_parameter_supported -> request_uri_parameter_supported[Option<bool>],
set_require_request_uri_registration -> require_request_uri_registration[Option<bool>],
set_op_policy_uri -> op_policy_uri[Option<OpPolicyUrl>],
set_op_tos_uri -> op_tos_uri[Option<OpTosUrl>],
}
];
/// Fetches the OpenID Connect Discovery document and associated JSON Web Key Set from the
/// OpenID Connect Provider.
pub fn discover<C>(
issuer_url: &IssuerUrl,
http_client: &C,
) -> Result<Self, DiscoveryError<<C as SyncHttpClient>::Error>>
where
C: SyncHttpClient,
{
let discovery_url = issuer_url
.join(CONFIG_URL_SUFFIX)
.map_err(DiscoveryError::UrlParse)?;
http_client
.call(
Self::discovery_request(discovery_url.clone()).map_err(|err| {
DiscoveryError::Other(format!("failed to prepare request: {err}"))
})?,
)
.map_err(DiscoveryError::Request)
.and_then(|http_response| {
Self::discovery_response(issuer_url, &discovery_url, http_response)
})
.and_then(|provider_metadata| {
JsonWebKeySet::fetch(provider_metadata.jwks_uri(), http_client).map(|jwks| Self {
jwks,
..provider_metadata
})
})
}
/// Asynchronously fetches the OpenID Connect Discovery document and associated JSON Web Key Set
/// from the OpenID Connect Provider.
pub fn discover_async<'c, C>(
issuer_url: IssuerUrl,
http_client: &'c C,
) -> impl Future<Output = Result<Self, DiscoveryError<<C as AsyncHttpClient<'c>>::Error>>> + 'c
where
Self: 'c,
C: AsyncHttpClient<'c>,
{
Box::pin(async move {
let discovery_url = issuer_url
.join(CONFIG_URL_SUFFIX)
.map_err(DiscoveryError::UrlParse)?;
let provider_metadata = http_client
.call(
Self::discovery_request(discovery_url.clone()).map_err(|err| {
DiscoveryError::Other(format!("failed to prepare request: {err}"))
})?,
)
.await
.map_err(DiscoveryError::Request)
.and_then(|http_response| {
Self::discovery_response(&issuer_url, &discovery_url, http_response)
})?;
JsonWebKeySet::fetch_async(provider_metadata.jwks_uri(), http_client)
.await
.map(|jwks| Self {
jwks,
..provider_metadata
})
})
}
fn discovery_request(discovery_url: url::Url) -> Result<HttpRequest, http::Error> {
http::Request::builder()
.uri(discovery_url.to_string())
.method(Method::GET)
.header(ACCEPT, HeaderValue::from_static(MIME_TYPE_JSON))
.body(Vec::new())
}
fn discovery_response<RE>(
issuer_url: &IssuerUrl,
discovery_url: &url::Url,
discovery_response: HttpResponse,
) -> Result<Self, DiscoveryError<RE>>
where
RE: std::error::Error + 'static,
{
if discovery_response.status() != StatusCode::OK {
return Err(DiscoveryError::Response(
discovery_response.status(),
discovery_response.body().to_owned(),
format!(
"HTTP status code {} at {}",
discovery_response.status(),
discovery_url
),
));
}
check_content_type(discovery_response.headers(), MIME_TYPE_JSON).map_err(|err_msg| {
DiscoveryError::Response(
discovery_response.status(),
discovery_response.body().to_owned(),
err_msg,
)
})?;
let provider_metadata = serde_path_to_error::deserialize::<_, Self>(
&mut serde_json::Deserializer::from_slice(discovery_response.body()),
)
.map_err(DiscoveryError::Parse)?;
if provider_metadata.issuer() != issuer_url {
Err(DiscoveryError::Validation(format!(
"unexpected issuer URI `{}` (expected `{}`)",
provider_metadata.issuer().as_str(),
issuer_url.as_str()
)))
} else {
Ok(provider_metadata)
}
}
/// Returns additional provider metadata fields.
pub fn additional_metadata(&self) -> &A {
&self.additional_metadata
}
/// Returns mutable additional provider metadata fields.
pub fn additional_metadata_mut(&mut self) -> &mut A {
&mut self.additional_metadata
}
}
/// Error retrieving provider metadata.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DiscoveryError<RE>
where
RE: std::error::Error + 'static,
{
/// An unexpected error occurred.
#[error("Other error: {0}")]
Other(String),
/// Failed to parse server response.
#[error("Failed to parse server response")]
Parse(#[source] serde_path_to_error::Error<serde_json::Error>),
/// An error occurred while sending the request or receiving the response (e.g., network
/// connectivity failed).
#[error("Request failed")]
Request(#[source] RE),
/// Server returned an invalid response.
#[error("Server returned invalid response: {2}")]
Response(StatusCode, Vec<u8>, String),
/// Failed to parse discovery URL from issuer URL.
#[error("Failed to parse URL")]
UrlParse(#[source] url::ParseError),
/// Failed to validate provider metadata.
#[error("Validation error: {0}")]
Validation(String),
}
File diff suppressed because it is too large Load Diff
+520
View File
@@ -0,0 +1,520 @@
use crate::types::localized::join_language_tag_key;
use crate::{LanguageTag, LocalizedClaim};
use chrono::{DateTime, TimeZone, Utc};
use serde::de::value::MapDeserializer;
use serde::de::{DeserializeOwned, Deserializer, Error, MapAccess, Visitor};
use serde::{Deserialize, Serialize, Serializer};
use serde_json::from_value;
use serde_value::ValueDeserializer;
use serde_with::{DeserializeAs, SerializeAs};
use std::cmp::PartialEq;
use std::fmt::{Debug, Display, Formatter, Result as FormatterResult};
use std::marker::PhantomData;
pub(crate) fn deserialize_string_or_vec<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
where
T: DeserializeOwned,
D: Deserializer<'de>,
{
let value: serde_json::Value = Deserialize::deserialize(deserializer)?;
match from_value::<Vec<T>>(value.clone()) {
Ok(val) => Ok(val),
Err(_) => {
let single_val: T = from_value(value).map_err(Error::custom)?;
Ok(vec![single_val])
}
}
}
pub(crate) fn deserialize_string_or_vec_opt<'de, T, D>(
deserializer: D,
) -> Result<Option<Vec<T>>, D::Error>
where
T: DeserializeOwned,
D: Deserializer<'de>,
{
let value: serde_json::Value = Deserialize::deserialize(deserializer)?;
match from_value::<Option<Vec<T>>>(value.clone()) {
Ok(val) => Ok(val),
Err(_) => {
let single_val: T = from_value(value).map_err(Error::custom)?;
Ok(Some(vec![single_val]))
}
}
}
// Attempt to deserialize the value; if the value is null or an error occurs, return None.
// This is useful when deserializing fields that may mean different things in different
// contexts, and where we would rather ignore the result than fail to deserialize. For example,
// the fields in JWKs are not well defined; extensions could theoretically define their own
// field names that overload field names used by other JWK types.
pub(crate) fn deserialize_option_or_none<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
where
T: DeserializeOwned,
D: Deserializer<'de>,
{
let value: serde_json::Value = Deserialize::deserialize(deserializer)?;
match from_value::<Option<T>>(value) {
Ok(val) => Ok(val),
Err(_) => Ok(None),
}
}
pub trait DeserializeMapField: Sized {
fn deserialize_map_field<'de, V>(
map: &mut V,
field_name: &'static str,
language_tag: Option<LanguageTag>,
field_value: Option<Self>,
) -> Result<Self, V::Error>
where
V: MapAccess<'de>;
}
impl<T> DeserializeMapField for T
where
T: DeserializeOwned,
{
fn deserialize_map_field<'de, V>(
map: &mut V,
field_name: &'static str,
language_tag: Option<LanguageTag>,
field_value: Option<Self>,
) -> Result<Self, V::Error>
where
V: MapAccess<'de>,
{
if field_value.is_some() {
return Err(serde::de::Error::duplicate_field(field_name));
} else if let Some(language_tag) = language_tag {
return Err(serde::de::Error::custom(format!(
"unexpected language tag `{language_tag}` for key `{field_name}`"
)));
}
map.next_value().map_err(|err| {
V::Error::custom(format!(
"{}: {err}",
join_language_tag_key(field_name, language_tag.as_ref())
))
})
}
}
impl<T> DeserializeMapField for LocalizedClaim<T>
where
T: DeserializeOwned,
{
fn deserialize_map_field<'de, V>(
map: &mut V,
field_name: &'static str,
language_tag: Option<LanguageTag>,
field_value: Option<Self>,
) -> Result<Self, V::Error>
where
V: MapAccess<'de>,
{
let mut localized_claim = field_value.unwrap_or_default();
if localized_claim.contains_key(language_tag.as_ref()) {
return Err(serde::de::Error::custom(format!(
"duplicate field `{}`",
join_language_tag_key(field_name, language_tag.as_ref())
)));
}
let localized_value = map.next_value().map_err(|err| {
V::Error::custom(format!(
"{}: {err}",
join_language_tag_key(field_name, language_tag.as_ref())
))
})?;
localized_claim.insert(language_tag, localized_value);
Ok(localized_claim)
}
}
// Some providers return boolean values as strings. Provide support for
// parsing using stdlib.
#[cfg(feature = "accept-string-booleans")]
pub(crate) mod serde_string_bool {
use serde::{de, Deserializer};
use std::fmt;
pub fn deserialize<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: Deserializer<'de>,
{
struct BooleanLikeVisitor;
impl<'de> de::Visitor<'de> for BooleanLikeVisitor {
type Value = bool;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("A boolean-like value")
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(v)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
v.parse().map_err(E::custom)
}
}
deserializer.deserialize_any(BooleanLikeVisitor)
}
}
/// Serde space-delimited string serializer for an `Option<Vec<String>>`.
///
/// This function serializes a string vector into a single space-delimited string.
/// If `string_vec_opt` is `None`, the function serializes it as `None` (e.g., `null`
/// in the case of JSON serialization).
pub(crate) fn serialize_space_delimited_vec<T, S>(
vec: &[T],
serializer: S,
) -> Result<S::Ok, S::Error>
where
T: AsRef<str>,
S: Serializer,
{
let space_delimited = vec
.iter()
.map(AsRef::<str>::as_ref)
.collect::<Vec<_>>()
.join(" ");
serializer.serialize_str(&space_delimited)
}
pub(crate) trait FlattenFilter {
fn should_include(field_name: &str) -> bool;
}
/// Helper container for filtering map keys out of serde(flatten). This is needed because
/// [`crate::StandardClaims`] doesn't have a fixed set of field names due to its support for
/// localized claims. Consequently, serde by default passes all of the claims to the deserializer
/// for `AC` (additional claims), leading to duplicate claims. [`FilteredFlatten`] is used for
/// eliminating the duplicate claims.
#[derive(Serialize)]
pub(crate) struct FilteredFlatten<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + Serialize,
{
// We include another level of flattening here because the derived flatten
// ([`serde::private::de::FlatMapDeserializer`]) seems to support a wider set of types
// (e.g., various forms of enum tagging) than [`serde_value::ValueDeserializer`].
#[serde(flatten)]
inner: Flatten<T>,
#[serde(skip)]
_phantom: PhantomData<F>,
}
impl<F, T> From<T> for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + Serialize,
{
fn from(value: T) -> Self {
Self {
inner: Flatten { inner: value },
_phantom: PhantomData,
}
}
}
impl<F, T> AsRef<T> for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + Serialize,
{
fn as_ref(&self) -> &T {
self.inner.as_ref()
}
}
impl<F, T> AsMut<T> for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + Serialize,
{
fn as_mut(&mut self) -> &mut T {
self.inner.as_mut()
}
}
impl<F, T> PartialEq for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + PartialEq + Serialize,
{
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<F, T> Clone for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: Clone + DeserializeOwned + Serialize,
{
fn clone(&self) -> Self {
Self {
inner: Flatten {
inner: self.inner.inner.clone(),
},
_phantom: PhantomData,
}
}
}
impl<F, T> Debug for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: Debug + DeserializeOwned + Serialize,
{
// Transparent Debug since we don't care about this struct.
fn fmt(&self, f: &mut Formatter) -> FormatterResult {
Debug::fmt(&self.inner, f)
}
}
impl<'de, F, T> Deserialize<'de> for FilteredFlatten<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + Serialize,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct MapVisitor<F: FlattenFilter, T: DeserializeOwned + Serialize>(PhantomData<(F, T)>);
impl<'de, F, T> Visitor<'de> for MapVisitor<F, T>
where
F: FlattenFilter,
T: DeserializeOwned + Serialize,
{
type Value = Flatten<T>;
fn expecting(&self, formatter: &mut Formatter) -> FormatterResult {
formatter.write_str("map type T")
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
let mut entries = Vec::<(serde_value::Value, serde_value::Value)>::new();
// JSON only supports String keys, and we really only need to support JSON input.
while let Some(key) = map.next_key::<serde_value::Value>()? {
let key_str = String::deserialize(ValueDeserializer::new(key.clone()))?;
if F::should_include(&key_str) {
entries.push((key, map.next_value()?));
}
}
Deserialize::deserialize(MapDeserializer::new(entries.into_iter()))
.map_err(serde_value::DeserializerError::into_error)
}
}
Ok(FilteredFlatten {
inner: deserializer.deserialize_map(MapVisitor(PhantomData::<(F, T)>))?,
_phantom: PhantomData,
})
}
}
#[derive(Deserialize, Serialize)]
struct Flatten<T>
where
T: DeserializeOwned + Serialize,
{
#[serde(flatten, bound = "T: DeserializeOwned + Serialize")]
inner: T,
}
impl<T> AsRef<T> for Flatten<T>
where
T: DeserializeOwned + Serialize,
{
fn as_ref(&self) -> &T {
&self.inner
}
}
impl<T> AsMut<T> for Flatten<T>
where
T: DeserializeOwned + Serialize,
{
fn as_mut(&mut self) -> &mut T {
&mut self.inner
}
}
impl<T> PartialEq for Flatten<T>
where
T: DeserializeOwned + PartialEq + Serialize,
{
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T> Debug for Flatten<T>
where
T: Debug + DeserializeOwned + Serialize,
{
// Transparent Debug since we don't care about this struct.
fn fmt(&self, f: &mut Formatter) -> FormatterResult {
Debug::fmt(&self.inner, f)
}
}
pub(crate) fn join_vec<T>(entries: &[T]) -> String
where
T: AsRef<str>,
{
entries
.iter()
.map(AsRef::as_ref)
.collect::<Vec<_>>()
.join(" ")
}
/// Newtype around a bool, optionally supporting string values.
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub(crate) struct Boolean(
#[cfg_attr(
feature = "accept-string-booleans",
serde(deserialize_with = "crate::helpers::serde_string_bool::deserialize")
)]
pub bool,
);
impl Boolean {
pub(crate) fn into_inner(self) -> bool {
self.0
}
}
impl Display for Boolean {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
Display::fmt(&self.0, f)
}
}
/// Timestamp as seconds since the unix epoch, or optionally an ISO 8601 string.
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub(crate) enum Timestamp {
Seconds(serde_json::Number),
#[cfg(feature = "accept-rfc3339-timestamps")]
Rfc3339(String),
}
impl Timestamp {
// The spec is ambiguous about whether seconds should be expressed as integers, or
// whether floating-point values are allowed. For compatibility with a wide range of
// clients, we round down to the nearest second.
pub(crate) fn from_utc(utc: &DateTime<Utc>) -> Self {
Timestamp::Seconds(utc.timestamp().into())
}
pub(crate) fn to_utc(&self) -> Result<DateTime<Utc>, ()> {
match self {
Timestamp::Seconds(seconds) => {
let (secs, nsecs) = if seconds.is_i64() {
(seconds.as_i64().ok_or(())?, 0u32)
} else {
let secs_f64 = seconds.as_f64().ok_or(())?;
let secs = secs_f64.floor();
(
secs as i64,
((secs_f64 - secs) * 1_000_000_000.).floor() as u32,
)
};
Utc.timestamp_opt(secs, nsecs).single().ok_or(())
}
#[cfg(feature = "accept-rfc3339-timestamps")]
Timestamp::Rfc3339(iso) => {
let datetime = DateTime::parse_from_rfc3339(iso).map_err(|_| ())?;
Ok(datetime.into())
}
}
}
}
impl Display for Timestamp {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
match self {
Timestamp::Seconds(seconds) => Display::fmt(seconds, f),
#[cfg(feature = "accept-rfc3339-timestamps")]
Timestamp::Rfc3339(iso) => Display::fmt(iso, f),
}
}
}
impl<'de> DeserializeAs<'de, DateTime<Utc>> for Timestamp {
fn deserialize_as<D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
D: Deserializer<'de>,
{
let seconds: Timestamp = Deserialize::deserialize(deserializer)?;
seconds.to_utc().map_err(|_| {
serde::de::Error::custom(format!(
"failed to parse `{seconds}` as UTC datetime (in seconds)"
))
})
}
}
impl SerializeAs<DateTime<Utc>> for Timestamp {
fn serialize_as<S>(source: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Timestamp::from_utc(source).serialize(serializer)
}
}
new_type![
#[derive(Deserialize, Hash, Serialize)]
pub(crate) Base64UrlEncodedBytes(
#[serde(with = "serde_base64url_byte_array")]
Vec<u8>
)
];
mod serde_base64url_byte_array {
use crate::core::base64_url_safe_no_pad;
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use base64::Engine;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
use serde_json::{from_value, Value};
pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let value: Value = Deserialize::deserialize(deserializer)?;
let base64_encoded: String = from_value(value).map_err(D::Error::custom)?;
base64_url_safe_no_pad()
.decode(&base64_encoded)
.map_err(|err| {
D::Error::custom(format!(
"invalid base64url encoding `{base64_encoded}`: {err:?}"
))
})
}
pub fn serialize<S>(v: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let base64_encoded = BASE64_URL_SAFE_NO_PAD.encode(v);
serializer.serialize_str(&base64_encoded)
}
}
+49
View File
@@ -0,0 +1,49 @@
use crate::AccessToken;
use http::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
pub const MIME_TYPE_JSON: &str = "application/json";
pub const MIME_TYPE_JWKS: &str = "application/jwk-set+json";
pub const MIME_TYPE_JWT: &str = "application/jwt";
pub const BEARER: &str = "Bearer";
// The [essence](https://mimesniff.spec.whatwg.org/#mime-type-essence) is the <type>/<subtype>
// representation.
pub fn content_type_has_essence(content_type: &HeaderValue, expected_essence: &str) -> bool {
#[allow(clippy::or_fun_call)]
content_type
.to_str()
.ok()
.filter(|ct| {
ct[..ct.find(';').unwrap_or(ct.len())].to_lowercase() == expected_essence.to_lowercase()
})
.is_some()
}
pub fn check_content_type(headers: &HeaderMap, expected_content_type: &str) -> Result<(), String> {
headers
.get(CONTENT_TYPE)
.map_or(Ok(()), |content_type|
// Section 3.1.1.1 of RFC 7231 indicates that media types are case insensitive and
// may be followed by optional whitespace and/or a parameter (e.g., charset).
// See https://tools.ietf.org/html/rfc7231#section-3.1.1.1.
if !content_type_has_essence(content_type, expected_content_type) {
Err(
format!(
"Unexpected response Content-Type: {content_type:?}, should be `{expected_content_type}`"
)
)
} else {
Ok(())
}
)
}
pub fn auth_bearer(access_token: &AccessToken) -> (HeaderName, HeaderValue) {
(
AUTHORIZATION,
HeaderValue::from_str(&format!("{} {}", BEARER, access_token.secret()))
.expect("invalid access token"),
)
}
+426
View File
@@ -0,0 +1,426 @@
use crate::helpers::{deserialize_string_or_vec, FilteredFlatten, Timestamp};
use crate::jwt::JsonWebTokenAccess;
use crate::jwt::{JsonWebTokenError, JsonWebTokenJsonPayloadSerde};
use crate::types::jwk::JwsSigningAlgorithm;
use crate::{
AccessToken, AccessTokenHash, AdditionalClaims, AddressClaim, Audience, AudiencesClaim,
AuthenticationContextClass, AuthenticationMethodReference, AuthorizationCode,
AuthorizationCodeHash, ClaimsVerificationError, ClientId, EndUserBirthday, EndUserEmail,
EndUserFamilyName, EndUserGivenName, EndUserMiddleName, EndUserName, EndUserNickname,
EndUserPhoneNumber, EndUserPictureUrl, EndUserProfileUrl, EndUserTimezone, EndUserUsername,
EndUserWebsiteUrl, ExtraTokenFields, GenderClaim, IdTokenVerifier, IssuerClaim, IssuerUrl,
JsonWebKey, JsonWebToken, JsonWebTokenAlgorithm, JweContentEncryptionAlgorithm, LanguageTag,
LocalizedClaim, Nonce, NonceVerifier, PrivateSigningKey, SignatureVerificationError,
StandardClaims, SubjectIdentifier,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::{serde_as, skip_serializing_none};
use std::fmt::{Debug, Display};
use std::str::FromStr;
#[cfg(test)]
mod tests;
// This wrapper layer exists instead of directly verifying the JWT and returning the claims so that
// we can pass it around and easily access a serialized JWT representation of it (e.g., for passing
// to the authorization endpoint as an id_token_hint).
/// OpenID Connect ID token.
#[cfg_attr(
any(test, feature = "timing-resistant-secret-traits"),
derive(PartialEq)
)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IdToken<
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
>(
#[serde(bound = "AC: AdditionalClaims")]
JsonWebToken<JE, JS, IdTokenClaims<AC, GC>, JsonWebTokenJsonPayloadSerde>,
);
impl<AC, GC, JE, JS> FromStr for IdToken<AC, GC, JE, JS>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
type Err = serde_json::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_value(Value::String(s.to_string()))
}
}
impl<AC, GC, JE, JS> IdToken<AC, GC, JE, JS>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
/// Initializes an ID token with the specified claims, signed using the given signing key and
/// algorithm.
///
/// If an `access_token` and/or `code` are provided, this method sets the `at_hash` and/or
/// `c_hash` claims using the given signing algorithm, respectively. Otherwise, those claims are
/// unchanged from the values specified in `claims`.
pub fn new<S>(
claims: IdTokenClaims<AC, GC>,
signing_key: &S,
alg: JS,
access_token: Option<&AccessToken>,
code: Option<&AuthorizationCode>,
) -> Result<Self, JsonWebTokenError>
where
S: PrivateSigningKey,
<S as PrivateSigningKey>::VerificationKey: JsonWebKey<SigningAlgorithm = JS>,
{
let verification_key = signing_key.as_verification_key();
let at_hash = access_token
.map(|at| {
AccessTokenHash::from_token(at, &alg, &verification_key)
.map_err(JsonWebTokenError::SigningError)
})
.transpose()?
.or_else(|| claims.access_token_hash.clone());
let c_hash = code
.map(|c| {
AuthorizationCodeHash::from_code(c, &alg, &verification_key)
.map_err(JsonWebTokenError::SigningError)
})
.transpose()?
.or_else(|| claims.code_hash.clone());
JsonWebToken::new(
IdTokenClaims {
access_token_hash: at_hash,
code_hash: c_hash,
..claims
},
signing_key,
&alg,
)
.map(Self)
}
/// Verifies and returns a reference to the ID token claims.
pub fn claims<'a, K, N>(
&'a self,
verifier: &IdTokenVerifier<K>,
nonce_verifier: N,
) -> Result<&'a IdTokenClaims<AC, GC>, ClaimsVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>,
N: NonceVerifier,
{
verifier.verified_claims(&self.0, nonce_verifier)
}
/// Verifies and returns the ID token claims.
pub fn into_claims<K, N>(
self,
verifier: &IdTokenVerifier<K>,
nonce_verifier: N,
) -> Result<IdTokenClaims<AC, GC>, ClaimsVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>,
N: NonceVerifier,
{
verifier.verified_claims_owned(self.0, nonce_verifier)
}
/// Returns the [`JwsSigningAlgorithm`] used to sign this ID token.
///
/// This function returns an error if the token is unsigned or utilizes JSON Web Encryption
/// (JWE).
pub fn signing_alg(&self) -> Result<&JS, SignatureVerificationError> {
match self.0.unverified_header().alg {
JsonWebTokenAlgorithm::Signature(ref signing_alg) => Ok(signing_alg),
JsonWebTokenAlgorithm::Encryption(ref other) => {
Err(SignatureVerificationError::UnsupportedAlg(
serde_plain::to_string(other).unwrap_or_else(|err| {
panic!("encryption alg {other:?} failed to serialize to a string: {err}")
}),
))
}
JsonWebTokenAlgorithm::None => Err(SignatureVerificationError::NoSignature),
}
}
/// Returns the [`JsonWebKey`] usable for verifying this ID token's JSON Web Signature.
///
/// This function returns an error if the token has no signature or a corresponding key cannot
/// be found.
pub fn signing_key<'s, K>(
&self,
verifier: &'s IdTokenVerifier<'s, K>,
) -> Result<&'s K, SignatureVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>,
{
verifier
.jwt_verifier
.signing_key(self.0.unverified_header().kid.as_ref(), self.signing_alg()?)
}
}
impl<AC, GC, JE, JS> Display for IdToken<AC, GC, JE, JS>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let value = serde_json::to_value(self)
// This should never arise, since we're just asking serde_json to serialize the
// signing input concatenated with the signature, both of which are precomputed.
.expect("ID token serialization failed");
let str = value
.as_str()
// This should also never arise, since our IdToken serializer always calls serialize_str
.expect("ID token serializer did not produce a str");
write!(f, "{str}")
}
}
/// OpenID Connect ID token claims.
#[cfg_attr(
any(test, feature = "timing-resistant-secret-traits"),
derive(PartialEq)
)]
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IdTokenClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
#[serde(rename = "iss")]
issuer: IssuerUrl,
// We always serialize as an array, which is valid according to the spec. This sets the
// 'default' attribute to be compatible with non-spec compliant OIDC providers that omit this
// field.
#[serde(
default,
rename = "aud",
deserialize_with = "deserialize_string_or_vec"
)]
audiences: Vec<Audience>,
#[serde_as(as = "Timestamp")]
#[serde(rename = "exp")]
expiration: DateTime<Utc>,
#[serde_as(as = "Timestamp")]
#[serde(rename = "iat")]
issue_time: DateTime<Utc>,
#[serde_as(as = "Option<Timestamp>")]
auth_time: Option<DateTime<Utc>>,
nonce: Option<Nonce>,
#[serde(rename = "acr")]
auth_context_ref: Option<AuthenticationContextClass>,
#[serde(rename = "amr")]
auth_method_refs: Option<Vec<AuthenticationMethodReference>>,
#[serde(rename = "azp")]
authorized_party: Option<ClientId>,
#[serde(rename = "at_hash")]
access_token_hash: Option<AccessTokenHash>,
#[serde(rename = "c_hash")]
code_hash: Option<AuthorizationCodeHash>,
#[serde(bound = "GC: GenderClaim")]
#[serde(flatten)]
standard_claims: StandardClaims<GC>,
#[serde(bound = "AC: AdditionalClaims")]
#[serde(flatten)]
additional_claims: FilteredFlatten<StandardClaims<GC>, AC>,
}
impl<AC, GC> IdTokenClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
/// Initializes new ID token claims.
pub fn new(
issuer: IssuerUrl,
audiences: Vec<Audience>,
expiration: DateTime<Utc>,
issue_time: DateTime<Utc>,
standard_claims: StandardClaims<GC>,
additional_claims: AC,
) -> Self {
Self {
issuer,
audiences,
expiration,
issue_time,
auth_time: None,
nonce: None,
auth_context_ref: None,
auth_method_refs: None,
authorized_party: None,
access_token_hash: None,
code_hash: None,
standard_claims,
additional_claims: additional_claims.into(),
}
}
field_getters_setters![
pub self [self] ["claim"] {
set_issuer -> issuer[IssuerUrl] ["iss"],
set_audiences -> audiences[Vec<Audience>] ["aud"],
set_expiration -> expiration[DateTime<Utc>] ["exp"],
set_issue_time -> issue_time[DateTime<Utc>] ["iat"],
set_auth_time -> auth_time[Option<DateTime<Utc>>],
set_nonce -> nonce[Option<Nonce>],
set_auth_context_ref -> auth_context_ref[Option<AuthenticationContextClass>] ["acr"],
set_auth_method_refs -> auth_method_refs[Option<Vec<AuthenticationMethodReference>>] ["amr"],
set_authorized_party -> authorized_party[Option<ClientId>] ["azp"],
set_access_token_hash -> access_token_hash[Option<AccessTokenHash>] ["at_hash"],
set_code_hash -> code_hash[Option<AuthorizationCodeHash>] ["c_hash"],
}
];
/// Returns the `sub` claim.
pub fn subject(&self) -> &SubjectIdentifier {
&self.standard_claims.sub
}
/// Sets the `sub` claim.
pub fn set_subject(mut self, subject: SubjectIdentifier) -> Self {
self.standard_claims.sub = subject;
self
}
field_getters_setters![
pub self [self.standard_claims] ["claim"] {
set_name -> name[Option<LocalizedClaim<EndUserName>>],
set_given_name -> given_name[Option<LocalizedClaim<EndUserGivenName>>],
set_family_name ->
family_name[Option<LocalizedClaim<EndUserFamilyName>>],
set_middle_name ->
middle_name[Option<LocalizedClaim<EndUserMiddleName>>],
set_nickname -> nickname[Option<LocalizedClaim<EndUserNickname>>],
set_preferred_username -> preferred_username[Option<EndUserUsername>],
set_profile -> profile[Option<LocalizedClaim<EndUserProfileUrl>>],
set_picture -> picture[Option<LocalizedClaim<EndUserPictureUrl>>],
set_website -> website[Option<LocalizedClaim<EndUserWebsiteUrl>>],
set_email -> email[Option<EndUserEmail>],
set_email_verified -> email_verified[Option<bool>],
set_gender -> gender[Option<GC>],
set_birthday -> birthday[Option<EndUserBirthday>],
set_birthdate -> birthdate[Option<EndUserBirthday>],
set_zoneinfo -> zoneinfo[Option<EndUserTimezone>],
set_locale -> locale[Option<LanguageTag>],
set_phone_number -> phone_number[Option<EndUserPhoneNumber>],
set_phone_number_verified -> phone_number_verified[Option<bool>],
set_address -> address[Option<AddressClaim>],
set_updated_at -> updated_at[Option<DateTime<Utc>>],
}
];
/// Returns additional ID token claims.
pub fn additional_claims(&self) -> &AC {
self.additional_claims.as_ref()
}
/// Returns mutable additional ID token claims.
pub fn additional_claims_mut(&mut self) -> &mut AC {
self.additional_claims.as_mut()
}
}
impl<AC, GC> AudiencesClaim for IdTokenClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn audiences(&self) -> Option<&Vec<Audience>> {
Some(IdTokenClaims::audiences(self))
}
}
impl<AC, GC> AudiencesClaim for &IdTokenClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn audiences(&self) -> Option<&Vec<Audience>> {
Some(IdTokenClaims::audiences(self))
}
}
impl<AC, GC> IssuerClaim for IdTokenClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn issuer(&self) -> Option<&IssuerUrl> {
Some(IdTokenClaims::issuer(self))
}
}
impl<AC, GC> IssuerClaim for &IdTokenClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn issuer(&self) -> Option<&IssuerUrl> {
Some(IdTokenClaims::issuer(self))
}
}
/// Extends the base OAuth2 token response with an ID token.
#[cfg_attr(
any(test, feature = "timing-resistant-secret-traits"),
derive(PartialEq)
)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IdTokenFields<AC, EF, GC, JE, JS>
where
AC: AdditionalClaims,
EF: ExtraTokenFields,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
#[serde(bound = "AC: AdditionalClaims")]
id_token: Option<IdToken<AC, GC, JE, JS>>,
#[serde(bound = "EF: ExtraTokenFields", flatten)]
extra_fields: EF,
}
impl<AC, EF, GC, JE, JS> IdTokenFields<AC, EF, GC, JE, JS>
where
AC: AdditionalClaims,
EF: ExtraTokenFields,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
/// Initializes new ID token fields containing the specified [`IdToken`] and extra fields.
pub fn new(id_token: Option<IdToken<AC, GC, JE, JS>>, extra_fields: EF) -> Self {
Self {
id_token,
extra_fields,
}
}
/// Returns the [`IdToken`] contained in the OAuth2 token response.
pub fn id_token(&self) -> Option<&IdToken<AC, GC, JE, JS>> {
self.id_token.as_ref()
}
/// Returns the extra fields contained in the OAuth2 token response.
pub fn extra_fields(&self) -> &EF {
&self.extra_fields
}
}
impl<AC, EF, GC, JE, JS> ExtraTokenFields for IdTokenFields<AC, EF, GC, JE, JS>
where
AC: AdditionalClaims,
EF: ExtraTokenFields,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
}
+717
View File
@@ -0,0 +1,717 @@
use crate::claims::{AdditionalClaims, EmptyAdditionalClaims, StandardClaims};
use crate::core::{
CoreGenderClaim, CoreIdToken, CoreIdTokenClaims, CoreTokenResponse, CoreTokenType,
};
use crate::jwt::JsonWebTokenAccess;
use crate::{
AccessTokenHash, AddressClaim, AddressCountry, AddressLocality, AddressPostalCode,
AddressRegion, Audience, AudiencesClaim, AuthenticationContextClass,
AuthenticationMethodReference, AuthorizationCodeHash, ClientId, EndUserBirthday, EndUserEmail,
EndUserFamilyName, EndUserGivenName, EndUserMiddleName, EndUserName, EndUserNickname,
EndUserPhoneNumber, EndUserPictureUrl, EndUserProfileUrl, EndUserTimezone, EndUserUsername,
EndUserWebsiteUrl, FormattedAddress, IdTokenClaims, IssuerClaim, IssuerUrl, LanguageTag, Nonce,
StreetAddress, SubjectIdentifier,
};
use chrono::{TimeZone, Utc};
use oauth2::TokenResponse;
use pretty_assertions::assert_eq;
use serde::{Deserialize, Serialize};
use url::Url;
use std::collections::HashMap;
use std::str::FromStr;
#[test]
fn test_id_token() {
static ID_TOKEN: &str = concat!(
"eyJhbGciOiJSUzI1NiJ9.",
"eyJpc3MiOiJodHRwczovL3NlcnZlci5leGFtcGxlLmNvbSIsImF1ZCI6WyJzNkJoZ",
"FJrcXQzIl0sImV4cCI6MTMxMTI4MTk3MCwiaWF0IjoxMzExMjgwOTcwLCJzdWIiOi",
"IyNDQwMDMyMCIsInRmYV9tZXRob2QiOiJ1MmYifQ.",
"aW52YWxpZF9zaWduYXR1cmU"
);
// `serde::Deserialize` implementation is tested within the `FromStr` implementation
let id_token = CoreIdToken::from_str(ID_TOKEN).expect("failed to parse id_token");
let claims = id_token.0.unverified_payload_ref();
assert_eq!(
*claims.issuer().url(),
Url::parse("https://server.example.com").unwrap()
);
assert_eq!(
*claims.audiences(),
vec![Audience::new("s6BhdRkqt3".to_string())]
);
assert_eq!(
claims.expiration(),
Utc.timestamp_opt(1311281970, 0)
.single()
.expect("valid timestamp")
);
assert_eq!(
claims.issue_time(),
Utc.timestamp_opt(1311280970, 0)
.single()
.expect("valid timestamp")
);
assert_eq!(
*claims.subject(),
SubjectIdentifier::new("24400320".to_string())
);
// test `ToString` implementation
assert_eq!(&id_token.to_string(), ID_TOKEN);
// test `serde::Serialize` implementation too
let de = serde_json::to_string(&id_token).expect("failed to deserializee id token");
assert_eq!(de, format!("\"{}\"", ID_TOKEN));
}
#[test]
fn test_oauth2_response() {
let response_str = "{\
\"access_token\":\"foobar\",\
\"token_type\":\"bearer\",\
\"id_token\":\"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NlcnZlci5leGFtcGxlLmNvbSIsImF\
1ZCI6WyJzNkJoZFJrcXQzIl0sImV4cCI6MTMxMTI4MTk3MCwiaWF0IjoxMzExMjgwOTcwLCJzdWIiOiIyNDQwMD\
MyMCIsInRmYV9tZXRob2QiOiJ1MmYifQ.aW52YWxpZF9zaWduYXR1cmU\"\
}";
let response =
serde_json::from_str::<CoreTokenResponse>(response_str).expect("failed to deserialize");
assert_eq!(*response.access_token().secret(), "foobar");
assert_eq!(*response.token_type(), CoreTokenType::Bearer);
let id_token = response.extra_fields().id_token();
let claims = id_token.unwrap().0.unverified_payload_ref();
assert_eq!(
*claims.issuer().url(),
Url::parse("https://server.example.com").unwrap()
);
assert_eq!(
*claims.audiences(),
vec![Audience::new("s6BhdRkqt3".to_string())]
);
assert_eq!(
claims.expiration(),
Utc.timestamp_opt(1311281970, 0)
.single()
.expect("valid timestamp")
);
assert_eq!(
claims.issue_time(),
Utc.timestamp_opt(1311280970, 0)
.single()
.expect("valid timestamp")
);
assert_eq!(
*claims.subject(),
SubjectIdentifier::new("24400320".to_string())
);
assert_eq!(
serde_json::to_string(&response).expect("failed to serialize"),
response_str
);
}
#[test]
fn test_minimal_claims_serde() {
let new_claims = CoreIdTokenClaims::new(
IssuerUrl::new("https://server.example.com".to_string()).unwrap(),
vec![Audience::new("s6BhdRkqt3".to_string())],
Utc.timestamp_opt(1311281970, 0)
.single()
.expect("valid timestamp"),
Utc.timestamp_opt(1311280970, 0)
.single()
.expect("valid timestamp"),
StandardClaims::new(SubjectIdentifier::new("24400320".to_string())),
EmptyAdditionalClaims {},
);
let expected_serialized_claims = "\
{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"sub\":\"24400320\"\
}";
let new_serialized_claims = serde_json::to_string(&new_claims).expect("failed to serialize");
assert_eq!(new_serialized_claims, expected_serialized_claims);
let claims: CoreIdTokenClaims = serde_json::from_str(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": \"s6BhdRkqt3\",
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect("failed to deserialize");
assert_eq!(claims, new_claims);
assert_eq!(claims.issuer().url(), new_claims.issuer().url());
assert_eq!(claims.audiences(), new_claims.audiences());
assert_eq!(claims.expiration(), new_claims.expiration());
assert_eq!(claims.issue_time(), new_claims.issue_time());
assert_eq!(claims.auth_time(), None);
assert!(claims.nonce().is_none());
assert_eq!(claims.auth_context_ref(), None);
assert_eq!(claims.auth_method_refs(), None);
assert_eq!(claims.authorized_party(), None);
assert_eq!(claims.access_token_hash(), None);
assert_eq!(claims.code_hash(), None);
assert_eq!(*claims.additional_claims(), EmptyAdditionalClaims {});
assert_eq!(claims.subject(), new_claims.subject());
assert_eq!(claims.name(), None);
assert_eq!(claims.given_name(), None);
assert_eq!(claims.family_name(), None);
assert_eq!(claims.middle_name(), None);
assert_eq!(claims.nickname(), None);
assert_eq!(claims.preferred_username(), None);
assert_eq!(claims.profile(), None);
assert_eq!(claims.picture(), None);
assert_eq!(claims.website(), None);
assert_eq!(claims.email(), None);
assert_eq!(claims.email_verified(), None);
assert_eq!(claims.gender(), None);
assert_eq!(claims.birthday(), None);
assert_eq!(claims.birthdate(), None);
assert_eq!(claims.zoneinfo(), None);
assert_eq!(claims.locale(), None);
assert_eq!(claims.phone_number(), None);
assert_eq!(claims.phone_number_verified(), None);
assert_eq!(claims.address(), None);
assert_eq!(claims.updated_at(), None);
let serialized_claims = serde_json::to_string(&claims).expect("failed to serialize");
assert_eq!(serialized_claims, expected_serialized_claims);
let claims_round_trip: CoreIdTokenClaims =
serde_json::from_str(&serialized_claims).expect("failed to deserialize");
assert_eq!(claims, claims_round_trip);
}
#[test]
fn test_complete_claims_serde() {
let claims_json = "{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"auth_time\":1311282970,\
\"nonce\":\"Zm9vYmFy\",\
\"acr\":\"urn:mace:incommon:iap:silver\",\
\"amr\":[\"password\",\"totp\"],\
\"azp\":\"dGhpc19jbGllbnQ\",\
\"at_hash\":\"_JPLB-GtkomFJxAOWKHPHQ\",\
\"c_hash\":\"VpTQii5T_8rgwxA-Wtb2Bw\",\
\"sub\":\"24400320\",\
\"name\":\"Homer Simpson\",\
\"name#es\":\"Jomer Simpson\",\
\"given_name\":\"Homer\",\
\"given_name#es\":\"Jomer\",\
\"family_name\":\"Simpson\",\
\"family_name#es\":\"Simpson\",\
\"middle_name\":\"Jay\",\
\"middle_name#es\":\"Jay\",\
\"nickname\":\"Homer\",\
\"nickname#es\":\"Jomer\",\
\"preferred_username\":\"homersimpson\",\
\"profile\":\"https://example.com/profile?id=12345\",\
\"profile#es\":\"https://example.com/profile?id=12345&lang=es\",\
\"picture\":\"https://example.com/avatar?id=12345\",\
\"picture#es\":\"https://example.com/avatar?id=12345&lang=es\",\
\"website\":\"https://homersimpson.me\",\
\"website#es\":\"https://homersimpson.me/?lang=es\",\
\"email\":\"homer@homersimpson.me\",\
\"email_verified\":true,\
\"gender\":\"male\",\
\"birthday\":\"1956-05-12\",\
\"birthdate\":\"1956-07-12\",\
\"zoneinfo\":\"America/Los_Angeles\",\
\"locale\":\"en-US\",\
\"phone_number\":\"+1 (555) 555-5555\",\
\"phone_number_verified\":false,\
\"address\":{\
\"formatted\":\"1234 Hollywood Blvd., Los Angeles, CA 90210\",\
\"street_address\":\"1234 Hollywood Blvd.\",\
\"locality\":\"Los Angeles\",\
\"region\":\"CA\",\
\"postal_code\":\"90210\",\
\"country\":\"US\"\
},\
\"updated_at\":1311283970\
}";
let new_claims = CoreIdTokenClaims::new(
IssuerUrl::new("https://server.example.com".to_string()).unwrap(),
vec![Audience::new("s6BhdRkqt3".to_string())],
Utc.timestamp_opt(1311281970, 0)
.single()
.expect("valid timestamp"),
Utc.timestamp_opt(1311280970, 0)
.single()
.expect("valid timestamp"),
StandardClaims {
sub: SubjectIdentifier::new("24400320".to_string()),
name: Some(
vec![
(None, EndUserName::new("Homer Simpson".to_string())),
(
Some(LanguageTag::new("es".to_string())),
EndUserName::new("Jomer Simpson".to_string()),
),
]
.into_iter()
.collect(),
),
given_name: Some(
vec![
(None, EndUserGivenName::new("Homer".to_string())),
(
Some(LanguageTag::new("es".to_string())),
EndUserGivenName::new("Jomer".to_string()),
),
]
.into_iter()
.collect(),
),
family_name: Some(
vec![
(None, EndUserFamilyName::new("Simpson".to_string())),
(
Some(LanguageTag::new("es".to_string())),
EndUserFamilyName::new("Simpson".to_string()),
),
]
.into_iter()
.collect(),
),
middle_name: Some(
vec![
(None, EndUserMiddleName::new("Jay".to_string())),
(
Some(LanguageTag::new("es".to_string())),
EndUserMiddleName::new("Jay".to_string()),
),
]
.into_iter()
.collect(),
),
nickname: Some(
vec![
(None, EndUserNickname::new("Homer".to_string())),
(
Some(LanguageTag::new("es".to_string())),
EndUserNickname::new("Jomer".to_string()),
),
]
.into_iter()
.collect(),
),
preferred_username: Some(EndUserUsername::new("homersimpson".to_string())),
profile: Some(
vec![
(
None,
EndUserProfileUrl::new("https://example.com/profile?id=12345".to_string()),
),
(
Some(LanguageTag::new("es".to_string())),
EndUserProfileUrl::new(
"https://example.com/profile?id=12345&lang=es".to_string(),
),
),
]
.into_iter()
.collect(),
),
picture: Some(
vec![
(
None,
EndUserPictureUrl::new("https://example.com/avatar?id=12345".to_string()),
),
(
Some(LanguageTag::new("es".to_string())),
EndUserPictureUrl::new(
"https://example.com/avatar?id=12345&lang=es".to_string(),
),
),
]
.into_iter()
.collect(),
),
website: Some(
vec![
(
None,
EndUserWebsiteUrl::new("https://homersimpson.me".to_string()),
),
(
Some(LanguageTag::new("es".to_string())),
EndUserWebsiteUrl::new("https://homersimpson.me/?lang=es".to_string()),
),
]
.into_iter()
.collect(),
),
email: Some(EndUserEmail::new("homer@homersimpson.me".to_string())),
email_verified: Some(true),
gender: Some(CoreGenderClaim::new("male".to_string())),
birthday: Some(EndUserBirthday::new("1956-05-12".to_string())),
birthdate: Some(EndUserBirthday::new("1956-07-12".to_string())),
zoneinfo: Some(EndUserTimezone::new("America/Los_Angeles".to_string())),
locale: Some(LanguageTag::new("en-US".to_string())),
phone_number: Some(EndUserPhoneNumber::new("+1 (555) 555-5555".to_string())),
phone_number_verified: Some(false),
address: Some(AddressClaim {
formatted: Some(FormattedAddress::new(
"1234 Hollywood Blvd., Los Angeles, CA 90210".to_string(),
)),
street_address: Some(StreetAddress::new("1234 Hollywood Blvd.".to_string())),
locality: Some(AddressLocality::new("Los Angeles".to_string())),
region: Some(AddressRegion::new("CA".to_string())),
postal_code: Some(AddressPostalCode::new("90210".to_string())),
country: Some(AddressCountry::new("US".to_string())),
}),
updated_at: Some(
Utc.timestamp_opt(1311283970, 0)
.single()
.expect("valid timestamp"),
),
},
EmptyAdditionalClaims {},
)
.set_auth_time(Some(
Utc.timestamp_opt(1311282970, 0)
.single()
.expect("valid timestamp"),
))
.set_nonce(Some(Nonce::new("Zm9vYmFy".to_string())))
.set_auth_context_ref(Some(AuthenticationContextClass::new(
"urn:mace:incommon:iap:silver".to_string(),
)))
.set_auth_method_refs(Some(vec![
AuthenticationMethodReference::new("password".to_string()),
AuthenticationMethodReference::new("totp".to_string()),
]))
.set_authorized_party(Some(ClientId::new("dGhpc19jbGllbnQ".to_string())))
.set_access_token_hash(Some(AccessTokenHash::new(
"_JPLB-GtkomFJxAOWKHPHQ".to_string(),
)))
.set_code_hash(Some(AuthorizationCodeHash::new(
"VpTQii5T_8rgwxA-Wtb2Bw".to_string(),
)));
let claims: CoreIdTokenClaims =
serde_json::from_str(claims_json).expect("failed to deserialize");
assert_eq!(claims, new_claims);
assert_eq!(claims.issuer(), new_claims.issuer());
assert_eq!(claims.issuer().url(), new_claims.issuer().url());
assert_eq!(claims.audiences(), new_claims.audiences());
assert_eq!(claims.expiration(), new_claims.expiration());
assert_eq!(claims.issue_time(), new_claims.issue_time());
assert_eq!(claims.auth_time(), new_claims.auth_time());
assert_eq!(
claims.nonce().unwrap().secret(),
new_claims.nonce().unwrap().secret()
);
assert_eq!(claims.auth_context_ref(), new_claims.auth_context_ref());
assert_eq!(claims.auth_method_refs(), new_claims.auth_method_refs());
assert_eq!(claims.authorized_party(), new_claims.authorized_party());
assert_eq!(claims.access_token_hash(), new_claims.access_token_hash());
assert_eq!(claims.code_hash(), new_claims.code_hash());
assert_eq!(*claims.additional_claims(), EmptyAdditionalClaims {});
assert_eq!(claims.subject(), new_claims.subject());
assert_eq!(claims.name(), new_claims.name());
assert_eq!(claims.given_name(), new_claims.given_name());
assert_eq!(claims.family_name(), new_claims.family_name());
assert_eq!(claims.middle_name(), new_claims.middle_name());
assert_eq!(claims.nickname(), new_claims.nickname());
assert_eq!(claims.preferred_username(), new_claims.preferred_username());
assert_eq!(claims.preferred_username(), new_claims.preferred_username());
assert_eq!(claims.profile(), new_claims.profile());
assert_eq!(claims.picture(), new_claims.picture());
assert_eq!(claims.website(), new_claims.website());
assert_eq!(claims.email(), new_claims.email());
assert_eq!(claims.email_verified(), new_claims.email_verified());
assert_eq!(claims.gender(), new_claims.gender());
assert_eq!(claims.birthday(), new_claims.birthday());
assert_eq!(claims.birthdate(), new_claims.birthdate());
assert_eq!(claims.zoneinfo(), new_claims.zoneinfo());
assert_eq!(claims.locale(), new_claims.locale());
assert_eq!(claims.phone_number(), new_claims.phone_number(),);
assert_eq!(
claims.phone_number_verified(),
new_claims.phone_number_verified()
);
assert_eq!(claims.address(), new_claims.address());
assert_eq!(claims.updated_at(), new_claims.updated_at());
let serialized_claims = serde_json::to_string(&claims).expect("failed to serialize");
let claims_round_trip: CoreIdTokenClaims =
serde_json::from_str(&serialized_claims).expect("failed to deserialize");
assert_eq!(claims, claims_round_trip);
let serialized_new_claims = serde_json::to_string(&new_claims).expect("failed to serialize");
assert_eq!(serialized_new_claims, claims_json);
}
// See https://github.com/ramosbugs/openidconnect-rs/issues/23
#[test]
#[cfg(feature = "accept-rfc3339-timestamps")]
fn test_accept_rfc3339_timestamp() {
let claims: CoreIdTokenClaims = serde_json::from_str(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": \"s6BhdRkqt3\",
\"exp\": 1311281970,
\"iat\": 1311280970,
\"updated_at\": \"2021-12-22T02:10:37.000Z\"
}",
)
.expect("failed to deserialize");
assert_eq!(
claims.updated_at(),
Some(
Utc.timestamp_opt(1640139037, 0)
.single()
.expect("valid timestamp")
)
);
}
#[test]
fn test_unknown_claims_serde() {
let expected_serialized_claims = "{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"sub\":\"24400320\"\
}";
let claims: CoreIdTokenClaims = serde_json::from_str(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": \"s6BhdRkqt3\",
\"exp\": 1311281970,
\"iat\": 1311280970,
\"some_other_field\":\"some_other_value\"\
}",
)
.expect("failed to deserialize");
let serialized_claims = serde_json::to_string(&claims).expect("failed to serialize");
assert_eq!(serialized_claims, expected_serialized_claims);
let claims_round_trip: CoreIdTokenClaims =
serde_json::from_str(&serialized_claims).expect("failed to deserialize");
assert_eq!(claims, claims_round_trip);
}
#[test]
fn test_audience() {
let single_aud_str_claims = serde_json::from_str::<CoreIdTokenClaims>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": \"s6BhdRkqt3\",
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect("failed to deserialize");
assert_eq!(
*single_aud_str_claims.audiences(),
vec![Audience::new("s6BhdRkqt3".to_string())],
);
// We always serialize aud as an array, which is valid according to the spec.
assert_eq!(
serde_json::to_string(&single_aud_str_claims).expect("failed to serialize"),
"{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"sub\":\"24400320\"\
}",
);
let single_aud_vec_claims = serde_json::from_str::<CoreIdTokenClaims>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"],
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect("failed to deserialize");
assert_eq!(
*single_aud_vec_claims.audiences(),
vec![Audience::new("s6BhdRkqt3".to_string())],
);
assert_eq!(
serde_json::to_string(&single_aud_vec_claims).expect("failed to serialize"),
"{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"sub\":\"24400320\"\
}",
);
let multi_aud_claims = serde_json::from_str::<CoreIdTokenClaims>(
"{\
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\", \"aud2\"],
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect("failed to deserialize");
assert_eq!(
*multi_aud_claims.audiences(),
vec![
Audience::new("s6BhdRkqt3".to_string()),
Audience::new("aud2".to_string())
],
);
assert_eq!(
serde_json::to_string(&multi_aud_claims).expect("failed to serialize"),
"{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\",\"aud2\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"sub\":\"24400320\"\
}",
);
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
struct TestClaims {
pub tfa_method: String,
}
impl AdditionalClaims for TestClaims {}
#[test]
fn test_additional_claims() {
let claims = serde_json::from_str::<IdTokenClaims<TestClaims, CoreGenderClaim>>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"],
\"exp\": 1311281970,
\"iat\": 1311280970,
\"tfa_method\": \"u2f\"
}",
)
.expect("failed to deserialize");
assert_eq!(claims.additional_claims().tfa_method, "u2f");
assert_eq!(
serde_json::to_string(&claims).expect("failed to serialize"),
"{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"exp\":1311281970,\
\"iat\":1311280970,\
\"sub\":\"24400320\",\
\"tfa_method\":\"u2f\"\
}",
);
serde_json::from_str::<IdTokenClaims<TestClaims, CoreGenderClaim>>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"],
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect_err("missing claim should fail to deserialize");
}
#[derive(Debug, Deserialize, Serialize)]
struct AllOtherClaims(HashMap<String, serde_json::Value>);
impl AdditionalClaims for AllOtherClaims {}
#[test]
fn test_catch_all_additional_claims() {
let claims = serde_json::from_str::<IdTokenClaims<AllOtherClaims, CoreGenderClaim>>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"],
\"exp\": 1311281970,
\"iat\": 1311280970,
\"tfa_method\": \"u2f\",
\"updated_at\": 1000
}",
)
.expect("failed to deserialize");
assert_eq!(claims.additional_claims().0.len(), 1);
assert_eq!(claims.additional_claims().0["tfa_method"], "u2f");
}
#[test]
fn test_audiences_claim() {
let claims = serde_json::from_str::<CoreIdTokenClaims>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": \"s6BhdRkqt3\",
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect("failed to deserialize");
fn verify_audiences<A: AudiencesClaim>(audiences_claim: &A) {
assert_eq!(
(*audiences_claim).audiences(),
Some(&vec![Audience::new("s6BhdRkqt3".to_string())]),
)
}
verify_audiences(&claims);
verify_audiences(&&claims);
}
#[test]
fn test_issuer_claim() {
let claims = serde_json::from_str::<CoreIdTokenClaims>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": \"s6BhdRkqt3\",
\"exp\": 1311281970,
\"iat\": 1311280970
}",
)
.expect("failed to deserialize");
fn verify_issuer<I: IssuerClaim>(issuer_claim: &I) {
assert_eq!(
(*issuer_claim).issuer(),
Some(&IssuerUrl::new("https://server.example.com".to_string()).unwrap()),
)
}
verify_issuer(&claims);
verify_issuer(&&claims);
}
+525
View File
@@ -0,0 +1,525 @@
use crate::{
JsonWebKey, JsonWebKeyId, JweContentEncryptionAlgorithm, JwsSigningAlgorithm,
PrivateSigningKey, SignatureVerificationError, SigningError,
};
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use base64::Engine;
use serde::de::{DeserializeOwned, Error as _, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_with::skip_serializing_none;
use thiserror::Error;
use std::fmt::Debug;
use std::marker::PhantomData;
#[cfg(test)]
pub(crate) mod tests;
new_type![
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
JsonWebTokenContentType(String)
];
/// Error type used when normalizing [`JsonWebTokenType`] objects
#[derive(Error, Debug)]
#[error("Invalid JWT type: {typ}")]
pub struct InvalidJsonWebTokenTypeError {
typ: String,
}
new_type![
/// JSON Web Token type field (typ)
///
/// This type stores the raw (deserialized) value.
///
/// To compare two different JSON Web Token types, please use the normalized version via [`JsonWebTokenType::normalize`].
#[derive(Deserialize, Hash, Serialize)]
JsonWebTokenType(String)
impl {
/// Expands a [`JsonWebTokenType`] and produces a [`NormalizedJsonWebTokenType`] according to RFC2045 and RFC7515.
///
/// See [RFC 2045 section 5.1](https://tools.ietf.org/html/rfc2045#section-5.1) for the full Content-Type Header Field spec.
/// See [RFC 7515 section 4.19](https://tools.ietf.org/html/rfc7515#section-4.1.9) for specific requirements of JSON Web Token Types.
pub fn normalize(&self) -> Result<NormalizedJsonWebTokenType, InvalidJsonWebTokenTypeError> {
self.try_into()
}
}
];
/// Normalized JSON Web Token type field (typ)
///
/// This type stores the normalized value of a [`JsonWebTokenType`].
/// To retrieve a normalized value according to RFC2045 and RFC7515 see [`JsonWebTokenType::normalize`]
///
/// See [RFC 2045 section 5.1](https://tools.ietf.org/html/rfc2045#section-5.1) for the full Content-Type Header Field spec.
/// See [RFC 7515 section 4.1.9](https://tools.ietf.org/html/rfc7515#section-4.1.9) for specific requirements of JSON Web Token Types.
///
/// It is recommended to instantiate `NormalizedJsonWebTokenType` objects via [`JsonWebTokenType`] and then call [`JsonWebTokenType::normalize`].
///
/// ```rust
/// # use openidconnect::{NormalizedJsonWebTokenType, JsonWebTokenType};
/// let token_type = JsonWebTokenType::new("jwt+at".to_string()).normalize();
/// // normalized value looks like "application/jwt+at"
/// # assert_eq!(*token_type.unwrap(), "application/jwt+at")
/// ```
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize)]
pub struct NormalizedJsonWebTokenType(String);
impl std::ops::Deref for NormalizedJsonWebTokenType {
type Target = String;
fn deref(&self) -> &String {
&self.0
}
}
impl From<NormalizedJsonWebTokenType> for String {
fn from(t: NormalizedJsonWebTokenType) -> String {
t.0
}
}
impl From<NormalizedJsonWebTokenType> for JsonWebTokenType {
fn from(t: NormalizedJsonWebTokenType) -> JsonWebTokenType {
JsonWebTokenType::new(t.0)
}
}
impl TryFrom<&JsonWebTokenType> for NormalizedJsonWebTokenType {
type Error = InvalidJsonWebTokenTypeError;
/// Normalizes a [`JsonWebTokenType`] and produces a [`NormalizedJsonWebTokenType`] according to RFC2045.
///
/// See [RFC 2045 section 5.1](https://tools.ietf.org/html/rfc2045#section-5.1) for the full Content-Type Header Field spec.
/// See [RFC 7515 section 4.19](https://tools.ietf.org/html/rfc7515#section-4.1.9) for specific requirements of JSON Web Token Types.
fn try_from(t: &JsonWebTokenType) -> Result<NormalizedJsonWebTokenType, Self::Error> {
let lowercase_jwt_type = t.0.to_lowercase();
if let Some(slash_location) = lowercase_jwt_type.find('/') {
if let Some(semicolon_location) = lowercase_jwt_type.find(';') {
// If '/' is not before ';' as then the MIME type is invalid
// e.g. some;arg="1/2" is invalid, but application/some;arg=1 is valid
// OR
// If MIME type has not at least one character
// OR
// If MIME subtype has not at least one character
if slash_location > semicolon_location
|| slash_location == 0
|| slash_location.saturating_add(1) >= semicolon_location
{
Err(InvalidJsonWebTokenTypeError {
typ: lowercase_jwt_type,
})
} else {
Ok(NormalizedJsonWebTokenType(lowercase_jwt_type))
}
} else {
Ok(NormalizedJsonWebTokenType(lowercase_jwt_type))
}
} else {
Ok(NormalizedJsonWebTokenType(format!(
"application/{lowercase_jwt_type}"
)))
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum JsonWebTokenAlgorithm<JE, JS>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
Encryption(JE),
Signature(JS),
/// No digital signature or MAC performed.
///
/// # Security Warning
///
/// This algorithm provides no security over the integrity of the JSON Web Token. Clients
/// should be careful not to rely on unsigned JWT's for security purposes. See
/// [Critical vulnerabilities in JSON Web Token libraries](
/// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/) for
/// further discussion.
None,
}
impl<'de, JE, JS> Deserialize<'de> for JsonWebTokenAlgorithm<JE, JS>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value: serde_json::Value = Deserialize::deserialize(deserializer)?;
// TODO: get rid of this clone() (see below)
let s: String = serde_json::from_value(value.clone()).map_err(D::Error::custom)?;
// NB: These comparisons are case-sensitive. Section 4.1.1 of RFC 7515 states: "The "alg"
// value is a case-sensitive ASCII string containing a StringOrURI value."
if s == "none" {
Ok(JsonWebTokenAlgorithm::None)
// TODO: Figure out a way to deserialize the enums without giving up ownership
} else if let Ok(val) = serde_json::from_value::<JE>(value.clone()) {
Ok(JsonWebTokenAlgorithm::Encryption(val))
} else if let Ok(val) = serde_json::from_value::<JS>(value) {
Ok(JsonWebTokenAlgorithm::Signature(val))
} else {
Err(D::Error::custom(format!(
"unrecognized JSON Web Algorithm `{s}`"
)))
}
}
}
impl<JE, JS> Serialize for JsonWebTokenAlgorithm<JE, JS>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
fn serialize<SE>(&self, serializer: SE) -> Result<SE::Ok, SE::Error>
where
SE: Serializer,
{
match self {
JsonWebTokenAlgorithm::Encryption(ref enc) => enc.serialize(serializer),
JsonWebTokenAlgorithm::Signature(ref sig) => sig.serialize(serializer),
JsonWebTokenAlgorithm::None => serializer.serialize_str("none"),
}
}
}
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct JsonWebTokenHeader<JE, JS>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
#[serde(
bound = "JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>, JS: JwsSigningAlgorithm"
)]
pub alg: JsonWebTokenAlgorithm<JE, JS>,
// Additional critical header parameters that must be understood by this implementation. Since
// we don't understand any such extensions, we reject any JWT with this value present (the
// spec specifically prohibits including public (standard) headers in this field).
// See https://tools.ietf.org/html/rfc7515#section-4.1.11.
pub crit: Option<Vec<String>>,
pub cty: Option<JsonWebTokenContentType>,
pub kid: Option<JsonWebKeyId>,
pub typ: Option<JsonWebTokenType>,
// Other JOSE header fields are omitted since the OpenID Connect spec specifically says that
// the "x5u", "x5c", "jku", "jwk" header parameter fields SHOULD NOT be used.
// See http://openid.net/specs/openid-connect-core-1_0-final.html#IDToken.
}
pub trait JsonWebTokenPayloadSerde<P>: Debug
where
P: Debug + DeserializeOwned + Serialize,
{
fn deserialize<DE: serde::de::Error>(payload: &[u8]) -> Result<P, DE>;
fn serialize(payload: &P) -> Result<String, serde_json::Error>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsonWebTokenJsonPayloadSerde;
impl<P> JsonWebTokenPayloadSerde<P> for JsonWebTokenJsonPayloadSerde
where
P: Debug + DeserializeOwned + Serialize,
{
fn deserialize<DE: serde::de::Error>(payload: &[u8]) -> Result<P, DE> {
serde_json::from_slice(payload)
.map_err(|err| DE::custom(format!("Failed to parse payload JSON: {err:?}")))
}
fn serialize(payload: &P) -> Result<String, serde_json::Error> {
serde_json::to_string(payload)
}
}
// Helper trait so that we can get borrowed payload when we have a reference to the JWT and owned
// payload when we own the JWT.
pub trait JsonWebTokenAccess<JE, JS, P>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
{
type ReturnType;
fn unverified_header(&self) -> &JsonWebTokenHeader<JE, JS>;
fn unverified_payload(self) -> Self::ReturnType;
fn unverified_payload_ref(&self) -> &P;
fn payload<K>(
self,
signature_alg: &JS,
key: &K,
) -> Result<Self::ReturnType, SignatureVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>;
fn signing_alg(&self) -> Result<&JS, SignatureVerificationError> {
match self.unverified_header().alg {
JsonWebTokenAlgorithm::Signature(ref signing_alg) => Ok(signing_alg),
JsonWebTokenAlgorithm::Encryption(ref other) => {
Err(SignatureVerificationError::UnsupportedAlg(
serde_plain::to_string(other).unwrap_or_else(|err| {
panic!("encryption alg {other:?} failed to serialize to a string: {err}")
}),
))
}
// Section 2 of OpenID Connect Core 1.0 specifies that "ID Tokens MUST NOT use
// none as the alg value unless the Response Type used returns no ID Token from
// the Authorization Endpoint (such as when using the Authorization Code Flow)
// and the Client explicitly requested the use of none at Registration time."
//
// While there's technically a use case where this is ok, we choose not to
// support it for now to protect against accidental misuse. If demand arises,
// we can figure out a API that mitigates the risk.
JsonWebTokenAlgorithm::None => Err(SignatureVerificationError::NoSignature),
}
}
}
/// Error creating a JSON Web Token.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum JsonWebTokenError {
/// Failed to serialize JWT.
#[error("Failed to serialize JWT")]
SerializationError(#[source] serde_json::Error),
/// Failed to sign JWT.
#[error("Failed to sign JWT")]
SigningError(#[source] SigningError),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsonWebToken<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
header: JsonWebTokenHeader<JE, JS>,
payload: P,
signature: Vec<u8>,
signing_input: String,
_phantom: PhantomData<S>,
}
impl<JE, JS, P, S> JsonWebToken<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
pub fn new<SK>(payload: P, signing_key: &SK, alg: &JS) -> Result<Self, JsonWebTokenError>
where
SK: PrivateSigningKey,
<SK as PrivateSigningKey>::VerificationKey: JsonWebKey<SigningAlgorithm = JS>,
{
let header = JsonWebTokenHeader::<JE, _> {
alg: JsonWebTokenAlgorithm::Signature(alg.clone()),
crit: None,
cty: None,
kid: signing_key.as_verification_key().key_id().cloned(),
typ: None,
};
let header_json =
serde_json::to_string(&header).map_err(JsonWebTokenError::SerializationError)?;
let header_base64 = BASE64_URL_SAFE_NO_PAD.encode(header_json);
let serialized_payload =
S::serialize(&payload).map_err(JsonWebTokenError::SerializationError)?;
let payload_base64 = BASE64_URL_SAFE_NO_PAD.encode(serialized_payload);
let signing_input = format!("{header_base64}.{payload_base64}");
let signature = signing_key
.sign(alg, signing_input.as_bytes())
.map_err(JsonWebTokenError::SigningError)?;
Ok(JsonWebToken {
header,
payload,
signature,
signing_input,
_phantom: PhantomData,
})
}
}
// Owned JWT.
impl<JE, JS, P, S> JsonWebTokenAccess<JE, JS, P> for JsonWebToken<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
type ReturnType = P;
fn unverified_header(&self) -> &JsonWebTokenHeader<JE, JS> {
&self.header
}
fn unverified_payload(self) -> Self::ReturnType {
self.payload
}
fn unverified_payload_ref(&self) -> &P {
&self.payload
}
fn payload<K>(
self,
signature_alg: &JS,
key: &K,
) -> Result<Self::ReturnType, SignatureVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>,
{
key.verify_signature(
signature_alg,
self.signing_input.as_bytes(),
&self.signature,
)?;
Ok(self.payload)
}
}
// Borrowed JWT.
impl<'a, JE, JS, P, S> JsonWebTokenAccess<JE, JS, P> for &'a JsonWebToken<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
type ReturnType = &'a P;
fn unverified_header(&self) -> &JsonWebTokenHeader<JE, JS> {
&self.header
}
fn unverified_payload(self) -> Self::ReturnType {
&self.payload
}
fn unverified_payload_ref(&self) -> &P {
&self.payload
}
fn payload<K>(
self,
signature_alg: &JS,
key: &K,
) -> Result<Self::ReturnType, SignatureVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>,
{
key.verify_signature(
signature_alg,
self.signing_input.as_bytes(),
&self.signature,
)?;
Ok(&self.payload)
}
}
impl<'de, JE, JS, P, S> Deserialize<'de> for JsonWebToken<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct JsonWebTokenVisitor<
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
>(PhantomData<(JE, JS, P, S)>);
impl<'de, JE, JS, P, S> Visitor<'de> for JsonWebTokenVisitor<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
type Value = JsonWebToken<JE, JS, P, S>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("JsonWebToken")
}
fn visit_str<DE>(self, v: &str) -> Result<Self::Value, DE>
where
DE: serde::de::Error,
{
let raw_token = v.to_string();
let header: JsonWebTokenHeader<JE, JS>;
let payload: P;
let signature;
let signing_input;
{
let parts = raw_token.split('.').collect::<Vec<_>>();
// NB: We avoid including the full payload encoding in the error output to avoid
// clients potentially logging sensitive values.
if parts.len() != 3 {
return Err(DE::custom(format!(
"Invalid JSON web token: found {} parts (expected 3)",
parts.len()
)));
}
let header_json = crate::core::base64_url_safe_no_pad()
.decode(parts[0])
.map_err(|err| {
DE::custom(format!("Invalid base64url header encoding: {err:?}"))
})?;
header = serde_json::from_slice(&header_json).map_err(|err| {
DE::custom(format!("Failed to parse header JSON: {err:?}"))
})?;
let raw_payload = crate::core::base64_url_safe_no_pad()
.decode(parts[1])
.map_err(|err| {
DE::custom(format!("Invalid base64url payload encoding: {err:?}"))
})?;
payload = S::deserialize::<DE>(&raw_payload)?;
signature = crate::core::base64_url_safe_no_pad()
.decode(parts[2])
.map_err(|err| {
DE::custom(format!("Invalid base64url signature encoding: {err:?}"))
})?;
signing_input = format!("{}.{}", parts[0], parts[1]);
}
Ok(JsonWebToken {
header,
payload,
signature,
signing_input,
_phantom: PhantomData,
})
}
}
deserializer.deserialize_str(JsonWebTokenVisitor(PhantomData))
}
}
impl<JE, JS, P, S> Serialize for JsonWebToken<JE, JS, P, S>
where
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
P: Debug + DeserializeOwned + Serialize,
S: JsonWebTokenPayloadSerde<P>,
{
fn serialize<SE>(&self, serializer: SE) -> Result<SE::Ok, SE::Error>
where
SE: Serializer,
{
let signature_base64 = BASE64_URL_SAFE_NO_PAD.encode(&self.signature);
serializer.serialize_str(&format!("{}.{}", self.signing_input, signature_base64))
}
}
+392
View File
@@ -0,0 +1,392 @@
use crate::core::{
CoreJsonWebKey, CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm,
CoreRsaPrivateSigningKey,
};
use crate::jwt::{
InvalidJsonWebTokenTypeError, JsonWebToken, JsonWebTokenAccess, JsonWebTokenAlgorithm,
JsonWebTokenJsonPayloadSerde, JsonWebTokenPayloadSerde,
};
use crate::{JsonWebKeyId, JsonWebTokenType};
use serde::{Deserialize, Serialize};
use std::string::ToString;
type CoreAlgorithm =
JsonWebTokenAlgorithm<CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm>;
pub const TEST_JWT: &str =
"eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9.SXTigJlzIGEgZ\
GFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGU\
gcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlc\
mUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e\
5CZ5NlKtainoFmKZopdHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4JIwmDLJK3l\
fWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8wW1Kt9eRo4QPocSadnHXFxnt8Is9UzpERV\
0ePPQdLuW3IS_de3xyIrDaLGdjluPxUAhb6L2aXic1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41\
Axf_fcIe8u9ipH84ogoree7vjbU5y18kDquDg";
const TEST_JWT_PAYLOAD: &str = "It\u{2019}s a dangerous business, Frodo, going out your \
door. You step onto the road, and if you don't keep your feet, \
there\u{2019}s no knowing where you might be swept off \
to.";
pub const TEST_RSA_PUB_KEY: &str = "{
\"kty\": \"RSA\",
\"kid\": \"bilbo.baggins@hobbiton.example\",
\"use\": \"sig\",
\"n\": \"n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT\
-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqV\
wGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-\
oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde\
3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuC\
LqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5g\
HdrNP5zw\",
\"e\": \"AQAB\"
}";
pub const TEST_ED_PUB_KEY_ED25519: &str = r#"{
"kty": "OKP",
"use": "sig",
"alg": "EdDSA",
"crv": "Ed25519",
"x": "sfliRRhciU_d5qsuC5Vcydi-t8bRfxTg_4qulVatW4A"
}"#;
pub const TEST_EC_PUB_KEY_P256: &str = r#"{
"kty": "EC",
"kid": "bilbo.baggins@hobbiton.example",
"use": "sig",
"crv": "P-256",
"x": "t6PHivOTggpaX9lkMkis2p8kMhy-CktJAFTz6atReZw",
"y": "ODobXupKlD0DeM1yRd7bX4XFNBO1HOgCT1UCu0KY3lc"
}"#;
pub const TEST_EC_PUB_KEY_P384: &str = r#"{
"kty": "EC",
"kid": "bilbo.baggins@hobbiton.example",
"use": "sig",
"crv" : "P-384",
"x": "9ywsUbxX59kJXFRiWHcx97wRKNiF8Hc9F5wI08n8h2ek_qAl0veEc36k1Qz6KLiL",
"y": "6PWlqjRbaV7V8ohDscM243IneuLZmxDGLiGNA1w69fQhEDsvZtKLUQ5KiHLgR3op"
}"#;
// This is the PEM form of the test private key from:
// https://tools.ietf.org/html/rfc7520#section-3.4
pub const TEST_RSA_PRIV_KEY: &str = "-----BEGIN RSA PRIVATE KEY-----\n\
MIIEowIBAAKCAQEAn4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8/KuKPEHLd4\n\
rHVTeT+O+XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz/AJmSCpMaJMRBSFKrKb2wqVwG\n\
U/NsYOYL+QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj+oBHqFEHYpP\n\
e7Tpe+OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzw\n\
OHrtIQbS0FVbb9k3+tVTU4fg/3L/vniUFAKwuCLqKnS2BYwdq/mzSnbLY7h/qixo\n\
R7jig3//kRhuaxwUkRz5iaiQkqgc5gHdrNP5zwIDAQABAoIBAG1lAvQfhBUSKPJK\n\
Rn4dGbshj7zDSr2FjbQf4pIh/ZNtHk/jtavyO/HomZKV8V0NFExLNi7DUUvvLiW7\n\
0PgNYq5MDEjJCtSd10xoHa4QpLvYEZXWO7DQPwCmRofkOutf+NqyDS0QnvFvp2d+\n\
Lov6jn5C5yvUFgw6qWiLAPmzMFlkgxbtjFAWMJB0zBMy2BqjntOJ6KnqtYRMQUxw\n\
TgXZDF4rhYVKtQVOpfg6hIlsaoPNrF7dofizJ099OOgDmCaEYqM++bUlEHxgrIVk\n\
wZz+bg43dfJCocr9O5YX0iXaz3TOT5cpdtYbBX+C/5hwrqBWru4HbD3xz8cY1TnD\n\
qQa0M8ECgYEA3Slxg/DwTXJcb6095RoXygQCAZ5RnAvZlno1yhHtnUex/fp7AZ/9\n\
nRaO7HX/+SFfGQeutao2TDjDAWU4Vupk8rw9JR0AzZ0N2fvuIAmr/WCsmGpeNqQn\n\
ev1T7IyEsnh8UMt+n5CafhkikzhEsrmndH6LxOrvRJlsPp6Zv8bUq0kCgYEAuKE2\n\
dh+cTf6ERF4k4e/jy78GfPYUIaUyoSSJuBzp3Cubk3OCqs6grT8bR/cu0Dm1MZwW\n\
mtdqDyI95HrUeq3MP15vMMON8lHTeZu2lmKvwqW7anV5UzhM1iZ7z4yMkuUwFWoB\n\
vyY898EXvRD+hdqRxHlSqAZ192zB3pVFJ0s7pFcCgYAHw9W9eS8muPYv4ZhDu/fL\n\
2vorDmD1JqFcHCxZTOnX1NWWAj5hXzmrU0hvWvFC0P4ixddHf5Nqd6+5E9G3k4E5\n\
2IwZCnylu3bqCWNh8pT8T3Gf5FQsfPT5530T2BcsoPhUaeCnP499D+rb2mTnFYeg\n\
mnTT1B/Ue8KGLFFfn16GKQKBgAiw5gxnbocpXPaO6/OKxFFZ+6c0OjxfN2PogWce\n\
TU/k6ZzmShdaRKwDFXisxRJeNQ5Rx6qgS0jNFtbDhW8E8WFmQ5urCOqIOYk28EBi\n\
At4JySm4v+5P7yYBh8B8YD2l9j57z/s8hJAxEbn/q8uHP2ddQqvQKgtsni+pHSk9\n\
XGBfAoGBANz4qr10DdM8DHhPrAb2YItvPVz/VwkBd1Vqj8zCpyIEKe/07oKOvjWQ\n\
SgkLDH9x2hBgY01SbP43CvPk0V72invu2TGkI/FXwXWJLLG7tDSgw4YyfhrYrHmg\n\
1Vre3XB9HH8MYBVB6UIexaAq4xSeoemRKTBesZro7OKjKT8/GmiO\n\
-----END RSA PRIVATE KEY-----";
#[test]
fn test_jwt_algorithm_deserialization() {
assert_eq!(
serde_json::from_str::<CoreAlgorithm>("\"A128CBC-HS256\"").expect("failed to deserialize"),
JsonWebTokenAlgorithm::Encryption(CoreJweContentEncryptionAlgorithm::Aes128CbcHmacSha256),
);
assert_eq!(
serde_json::from_str::<CoreAlgorithm>("\"A128GCM\"").expect("failed to deserialize"),
JsonWebTokenAlgorithm::Encryption(CoreJweContentEncryptionAlgorithm::Aes128Gcm),
);
assert_eq!(
serde_json::from_str::<CoreAlgorithm>("\"HS256\"").expect("failed to deserialize"),
JsonWebTokenAlgorithm::Signature(CoreJwsSigningAlgorithm::HmacSha256),
);
assert_eq!(
serde_json::from_str::<CoreAlgorithm>("\"RS256\"").expect("failed to deserialize"),
JsonWebTokenAlgorithm::Signature(CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256),
);
assert_eq!(
serde_json::from_str::<CoreAlgorithm>("\"none\"").expect("failed to deserialize"),
JsonWebTokenAlgorithm::None,
);
serde_json::from_str::<CoreAlgorithm>("\"invalid\"")
.expect_err("deserialization should have failed");
}
#[test]
fn test_jwt_algorithm_serialization() {
assert_eq!(
serde_json::to_string::<CoreAlgorithm>(&JsonWebTokenAlgorithm::Encryption(
CoreJweContentEncryptionAlgorithm::Aes128CbcHmacSha256
))
.expect("failed to serialize"),
"\"A128CBC-HS256\"",
);
assert_eq!(
serde_json::to_string::<CoreAlgorithm>(&JsonWebTokenAlgorithm::Encryption(
CoreJweContentEncryptionAlgorithm::Aes128Gcm
))
.expect("failed to serialize"),
"\"A128GCM\"",
);
assert_eq!(
serde_json::to_string::<CoreAlgorithm>(&JsonWebTokenAlgorithm::Signature(
CoreJwsSigningAlgorithm::HmacSha256
))
.expect("failed to serialize"),
"\"HS256\"",
);
assert_eq!(
serde_json::to_string::<CoreAlgorithm>(&JsonWebTokenAlgorithm::Signature(
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256
))
.expect("failed to serialize"),
"\"RS256\"",
);
assert_eq!(
serde_json::to_string::<CoreAlgorithm>(&JsonWebTokenAlgorithm::None)
.expect("failed to serialize"),
"\"none\"",
);
}
#[derive(Clone, Debug)]
pub struct JsonWebTokenStringPayloadSerde;
impl JsonWebTokenPayloadSerde<String> for JsonWebTokenStringPayloadSerde {
fn deserialize<DE: serde::de::Error>(payload: &[u8]) -> Result<String, DE> {
Ok(String::from_utf8(payload.to_owned()).unwrap())
}
fn serialize(payload: &String) -> Result<String, serde_json::Error> {
Ok(payload.to_string())
}
}
#[test]
fn test_jwt_basic() {
fn verify_jwt<A>(jwt_access: A, key: &CoreJsonWebKey, expected_payload: &str)
where
A: JsonWebTokenAccess<CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm, String>,
A::ReturnType: ToString,
{
{
let header = jwt_access.unverified_header();
assert_eq!(
header.alg,
JsonWebTokenAlgorithm::Signature(CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256)
);
assert_eq!(header.crit, None);
assert_eq!(header.cty, None);
assert_eq!(
header.kid,
Some(JsonWebKeyId::new(
"bilbo.baggins@hobbiton.example".to_string()
))
);
assert_eq!(header.typ, None);
}
assert_eq!(jwt_access.unverified_payload_ref(), expected_payload);
assert_eq!(
jwt_access
.payload(&CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256, key)
.expect("failed to validate payload")
.to_string(),
expected_payload
);
}
let key: CoreJsonWebKey =
serde_json::from_str(TEST_RSA_PUB_KEY).expect("deserialization failed");
let jwt: JsonWebToken<
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
String,
JsonWebTokenStringPayloadSerde,
> = serde_json::from_value(serde_json::Value::String(TEST_JWT.to_string()))
.expect("failed to deserialize");
assert_eq!(
serde_json::to_value(&jwt).expect("failed to serialize"),
serde_json::Value::String(TEST_JWT.to_string())
);
verify_jwt(&jwt, &key, TEST_JWT_PAYLOAD);
assert_eq!((&jwt).unverified_payload(), TEST_JWT_PAYLOAD);
verify_jwt(jwt, &key, TEST_JWT_PAYLOAD);
}
#[test]
fn test_new_jwt() {
let signing_key = CoreRsaPrivateSigningKey::from_pem(
TEST_RSA_PRIV_KEY,
Some(JsonWebKeyId::new(
"bilbo.baggins@hobbiton.example".to_string(),
)),
)
.unwrap();
let new_jwt = JsonWebToken::<
CoreJweContentEncryptionAlgorithm,
_,
_,
JsonWebTokenStringPayloadSerde,
>::new(
TEST_JWT_PAYLOAD.to_owned(),
&signing_key,
&CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256,
)
.unwrap();
assert_eq!(
serde_json::to_value(new_jwt).expect("failed to serialize"),
serde_json::Value::String(TEST_JWT.to_string())
);
}
#[test]
fn test_invalid_signature() {
let corrupted_jwt_str = TEST_JWT
.to_string()
.chars()
.take(TEST_JWT.len() - 1)
.collect::<String>()
+ "f";
let jwt: JsonWebToken<
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
String,
JsonWebTokenStringPayloadSerde,
> = serde_json::from_value(serde_json::Value::String(corrupted_jwt_str))
.expect("failed to deserialize");
let key: CoreJsonWebKey =
serde_json::from_str(TEST_RSA_PUB_KEY).expect("deserialization failed");
// JsonWebTokenAccess for reference.
(&jwt)
.payload(&CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256, &key)
.expect_err("signature verification should have failed");
// JsonWebTokenAccess for owned value.
jwt.payload(&CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256, &key)
.expect_err("signature verification should have failed");
}
#[test]
fn test_invalid_deserialization() {
#[derive(Debug, Deserialize, Serialize)]
struct TestPayload {
foo: String,
}
fn expect_deserialization_err<I: Into<String>>(jwt_str: I, pattern: &str) {
let err = serde_json::from_value::<
JsonWebToken<
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
TestPayload,
JsonWebTokenJsonPayloadSerde,
>,
>(serde_json::Value::String(jwt_str.into()))
.expect_err("deserialization should have failed");
assert!(
err.to_string().contains(pattern),
"Error `{err}` must contain string `{pattern}`",
);
}
// Too many dots
expect_deserialization_err("a.b.c.d", "found 4 parts (expected 3)");
// Invalid header base64
expect_deserialization_err("a!.b.c", "Invalid base64url header encoding");
// Invalid header utf-8 (after base64 decoding)
expect_deserialization_err("gA.b.c", "Error(\"expected value\", line: 1, column: 1)");
// Invalid header JSON
expect_deserialization_err("bm90X2pzb24.b.c", "Failed to parse header JSON");
let valid_header = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9";
// Invalid payload base64
expect_deserialization_err(
format!("{valid_header}.b!.c"),
"Invalid base64url payload encoding",
);
// Invalid payload utf-8 (after base64 decoding)
expect_deserialization_err(
format!("{valid_header}.gA.c"),
"Error(\"expected value\", line: 1, column: 1)",
);
// Invalid payload JSON
expect_deserialization_err(
format!("{valid_header}.bm90X2pzb24.c"),
"Failed to parse payload JSON",
);
let valid_body = "eyJmb28iOiAiYmFyIn0";
// Invalid signature base64
expect_deserialization_err(
format!("{valid_header}.{valid_body}.c!"),
"Invalid base64url signature encoding",
);
let deserialized = serde_json::from_value::<
JsonWebToken<
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
TestPayload,
JsonWebTokenJsonPayloadSerde,
>,
>(serde_json::Value::String(format!(
"{valid_header}.{valid_body}.e2FiY30"
)))
.expect("failed to deserialize");
assert_eq!(deserialized.unverified_payload().foo, "bar");
}
#[test]
fn test_json_web_token_type_normalization() {
fn assert_token_type_normalization(
jwt_type_string: &str,
expected_normalized_jwt_type_string: &str,
) -> Result<(), InvalidJsonWebTokenTypeError> {
let jwt_type = JsonWebTokenType::new(jwt_type_string.to_string());
let normalized_jwt_type = jwt_type.normalize()?;
assert_eq!(*normalized_jwt_type, expected_normalized_jwt_type_string);
Ok(())
}
assert_token_type_normalization("jwt", "application/jwt").unwrap();
assert_token_type_normalization("jwt;arg=some", "application/jwt;arg=some").unwrap();
assert!(assert_token_type_normalization("jwt;arg=some/other", "").is_err());
assert!(assert_token_type_normalization("/jwt;arg=some/other", "").is_err());
assert!(assert_token_type_normalization("application/;arg=some/other", "").is_err());
assert_token_type_normalization("application/jwt", "application/jwt").unwrap();
assert_token_type_normalization(
"application/jwt;arg=some/other",
"application/jwt;arg=some/other",
)
.unwrap();
assert_token_type_normalization("special/type", "special/type").unwrap();
assert_token_type_normalization("special/type;arg=some", "special/type;arg=some").unwrap();
assert_token_type_normalization("s/t;arg=some/o", "s/t;arg=some/o").unwrap();
}
+740
View File
@@ -0,0 +1,740 @@
#![warn(missing_docs)]
#![allow(clippy::unreadable_literal, clippy::type_complexity)]
#![cfg_attr(test, allow(clippy::cognitive_complexity))]
//!
//! [OpenID Connect](https://openid.net/specs/openid-connect-core-1_0.html) library.
//!
//! This library provides extensible, strongly-typed interfaces for the OpenID Connect protocol.
//! For convenience, the [`core`] module provides type aliases for common usage that adheres to the
//! [OpenID Connect Core](https://openid.net/specs/openid-connect-core-1_0.html) spec. Users of
//! this crate may define their own extensions and custom type parameters in lieu of using the
//! [`core`] module.
//!
//! # Contents
//! * [Importing `openidconnect`: selecting an HTTP client interface](#importing-openidconnect-selecting-an-http-client-interface)
//! * [OpenID Connect Relying Party (Client) Interface](#openid-connect-relying-party-client-interface)
//! * [Examples](#examples)
//! * [Getting started: Authorization Code Grant w/ PKCE](#getting-started-authorization-code-grant-w-pkce)
//! * [OpenID Connect Provider (Server) Interface](#openid-connect-provider-server-interface)
//! * [OpenID Connect Discovery document](#openid-connect-discovery-document)
//! * [OpenID Connect Discovery JSON Web Key Set](#openid-connect-discovery-json-web-key-set)
//! * [OpenID Connect ID Token](#openid-connect-id-token)
//! * [Asynchronous API](#asynchronous-api)
//!
//! # Importing `openidconnect`: selecting an HTTP client interface
//!
//!
//! This library offers a flexible HTTP client interface with two modes:
//! * **Synchronous (blocking)**
//!
//! NOTE: Be careful not to use a blocking HTTP client within `async` Rust code, which may panic
//! or cause other issues. The
//! [`tokio::task::spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html)
//! function may be useful in this situation.
//! * **Asynchronous**
//!
//! ## Security Warning
//!
//! To prevent
//! [SSRF](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html)
//! vulnerabilities, be sure to configure the HTTP client **not to follow redirects**. For example,
//! use [`redirect::Policy::none`](reqwest::redirect::Policy::none) when using
//! [`reqwest`], or [`redirects(0)`](ureq::AgentBuilder::redirects) when using [`ureq`].
//!
//! ## HTTP Clients
//!
//! For the HTTP client modes described above, the following HTTP client implementations can be
//! used:
//! * **[`reqwest`]**
//!
//! The `reqwest` HTTP client supports both the synchronous and asynchronous modes and is enabled
//! by default.
//!
//! Synchronous client: [`reqwest::blocking::Client`]
//! (requires the `reqwest-blocking` feature flag)
//!
//! Asynchronous client: [`reqwest::Client`] (requires either
//! the `reqwest` or `reqwest-blocking` feature flags)
//!
//! * **[`curl`]**
//!
//! The `curl` HTTP client only supports the synchronous HTTP client mode and can be enabled in
//! `Cargo.toml` via the `curl` feature flag.
//!
//! Synchronous client: [`CurlHttpClient`]
//!
//! * **[`ureq`]**
//!
//! The `ureq` HTTP client is a simple HTTP client with minimal dependencies. It only supports
//! the synchronous HTTP client mode and can be enabled in `Cargo.toml` via the `ureq` feature
//! flag.
//!
//! Synchronous client: [`ureq::Agent`]
//!
//! * **Custom**
//!
//! In addition to the clients above, users may define their own HTTP clients, which must accept
//! an [`HttpRequest`] and return an [`HttpResponse`] or error. Users writing their own clients
//! may wish to disable the default `reqwest` dependency by specifying
//! `default-features = false` in `Cargo.toml` (replacing `...` with the desired version of this
//! crate):
//! ```toml
//! openidconnect = { version = "...", default-features = false }
//! ```
//!
//! Synchronous HTTP clients should implement the [`SyncHttpClient`] trait, which is
//! automatically implemented for any function/closure that implements:
//! ```rust,ignore
//! Fn(HttpRequest) -> Result<HttpResponse, E>
//! where
//! E: std::error::Error + 'static
//! ```
//!
//! Asynchronous HTTP clients should implement the [`AsyncHttpClient`] trait, which is
//! automatically implemented for any function/closure that implements:
//! ```rust,ignore
//! Fn(HttpRequest) -> F
//! where
//! E: std::error::Error + 'static,
//! F: Future<Output = Result<HttpResponse, E>>,
//! ```
//!
//! # Comparing secrets securely
//!
//! OpenID Connect flows require comparing secrets received from providers. To do so securely
//! while avoiding [timing side-channels](https://en.wikipedia.org/wiki/Timing_attack), the
//! comparison must be done in constant time, either using a constant-time crate such as
//! [`constant_time_eq`](https://crates.io/crates/constant_time_eq) (which could break if a future
//! compiler version decides to be overly smart
//! about its optimizations), or by first computing a cryptographically-secure hash (e.g., SHA-256)
//! of both values and then comparing the hashes using `==`.
//!
//! The `timing-resistant-secret-traits` feature flag adds a safe (but comparatively expensive)
//! [`PartialEq`] implementation to the secret types. Timing side-channels are why [`PartialEq`] is
//! not auto-derived for this crate's secret types, and the lack of [`PartialEq`] is intended to
//! prompt users to think more carefully about these comparisons.
//!
//! # OpenID Connect Relying Party (Client) Interface
//!
//! The [`Client`] struct provides the OpenID Connect Relying Party interface. The most common
//! usage is provided by the [`core::CoreClient`] type alias.
//!
//! ## Examples
//!
//! * [Google](https://github.com/ramosbugs/openidconnect-rs/tree/main/examples/google.rs)
//!
//! ## Getting started: Authorization Code Grant w/ PKCE
//!
//! This is the most common OIDC/OAuth2 flow. PKCE is recommended whenever the client has no
//! client secret or has a client secret that cannot remain confidential (e.g., native, mobile, or
//! client-side web applications).
//!
//! ### Example
//!
//! ```rust,no_run
//! use anyhow::anyhow;
//! use openidconnect::{
//! AccessTokenHash,
//! AuthenticationFlow,
//! AuthorizationCode,
//! ClientId,
//! ClientSecret,
//! CsrfToken,
//! IssuerUrl,
//! Nonce,
//! OAuth2TokenResponse,
//! PkceCodeChallenge,
//! RedirectUrl,
//! Scope,
//! TokenResponse,
//! };
//! use openidconnect::core::{
//! CoreAuthenticationFlow,
//! CoreClient,
//! CoreProviderMetadata,
//! CoreResponseType,
//! CoreUserInfoClaims,
//! };
//! # #[cfg(feature = "reqwest-blocking")]
//! use openidconnect::reqwest;
//! use url::Url;
//!
//! # #[cfg(feature = "reqwest-blocking")]
//! # fn err_wrapper() -> Result<(), anyhow::Error> {
//! let http_client = reqwest::blocking::ClientBuilder::new()
//! // Following redirects opens the client up to SSRF vulnerabilities.
//! .redirect(reqwest::redirect::Policy::none())
//! .build()
//! .expect("Client should build");
//!
//! // Use OpenID Connect Discovery to fetch the provider metadata.
//! let provider_metadata = CoreProviderMetadata::discover(
//! &IssuerUrl::new("https://accounts.example.com".to_string())?,
//! &http_client,
//! )?;
//!
//! // Create an OpenID Connect client by specifying the client ID, client secret, authorization URL
//! // and token URL.
//! let client =
//! CoreClient::from_provider_metadata(
//! provider_metadata,
//! ClientId::new("client_id".to_string()),
//! Some(ClientSecret::new("client_secret".to_string())),
//! )
//! // Set the URL the user will be redirected to after the authorization process.
//! .set_redirect_uri(RedirectUrl::new("http://redirect".to_string())?);
//!
//! // Generate a PKCE challenge.
//! let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
//!
//! // Generate the full authorization URL.
//! let (auth_url, csrf_token, nonce) = client
//! .authorize_url(
//! CoreAuthenticationFlow::AuthorizationCode,
//! CsrfToken::new_random,
//! Nonce::new_random,
//! )
//! // Set the desired scopes.
//! .add_scope(Scope::new("read".to_string()))
//! .add_scope(Scope::new("write".to_string()))
//! // Set the PKCE code challenge.
//! .set_pkce_challenge(pkce_challenge)
//! .url();
//!
//! // This is the URL you should redirect the user to, in order to trigger the authorization
//! // process.
//! println!("Browse to: {}", auth_url);
//!
//! // Once the user has been redirected to the redirect URL, you'll have access to the
//! // authorization code. For security reasons, your code should verify that the `state`
//! // parameter returned by the server matches `csrf_state`.
//!
//! // Now you can exchange it for an access token and ID token.
//! let token_response =
//! client
//! .exchange_code(AuthorizationCode::new("some authorization code".to_string()))?
//! // Set the PKCE code verifier.
//! .set_pkce_verifier(pkce_verifier)
//! .request(&http_client)?;
//!
//! // Extract the ID token claims after verifying its authenticity and nonce.
//! let id_token = token_response
//! .id_token()
//! .ok_or_else(|| anyhow!("Server did not return an ID token"))?;
//! let id_token_verifier = client.id_token_verifier();
//! let claims = id_token.claims(&id_token_verifier, &nonce)?;
//!
//! // Verify the access token hash to ensure that the access token hasn't been substituted for
//! // another user's.
//! if let Some(expected_access_token_hash) = claims.access_token_hash() {
//! let actual_access_token_hash = AccessTokenHash::from_token(
//! token_response.access_token(),
//! id_token.signing_alg()?,
//! id_token.signing_key(&id_token_verifier)?,
//! )?;
//! if actual_access_token_hash != *expected_access_token_hash {
//! return Err(anyhow!("Invalid access token"));
//! }
//! }
//!
//! // The authenticated user's identity is now available. See the IdTokenClaims struct for a
//! // complete listing of the available claims.
//! println!(
//! "User {} with e-mail address {} has authenticated successfully",
//! claims.subject().as_str(),
//! claims.email().map(|email| email.as_str()).unwrap_or("<not provided>"),
//! );
//!
//! // If available, we can use the user info endpoint to request additional information.
//!
//! // The user_info request uses the AccessToken returned in the token response. To parse custom
//! // claims, use UserInfoClaims directly (with the desired type parameters) rather than using the
//! // CoreUserInfoClaims type alias.
//! let userinfo: CoreUserInfoClaims = client
//! .user_info(token_response.access_token().to_owned(), None)?
//! .request(&http_client)
//! .map_err(|err| anyhow!("Failed requesting user info: {}", err))?;
//!
//! // See the OAuth2TokenResponse trait for a listing of other available fields such as
//! // access_token() and refresh_token().
//!
//! # Ok(())
//! # }
//! ```
//!
//! # OpenID Connect Provider (Server) Interface
//!
//! This library does not implement a complete OpenID Connect Provider, which requires
//! functionality such as credential and session management. However, it does provide
//! strongly-typed interfaces for parsing and building OpenID Connect protocol messages.
//!
//! ## OpenID Connect Discovery document
//!
//! The [`ProviderMetadata`] struct implements the
//! [OpenID Connect Discovery document](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig).
//! This data structure should be serialized to JSON and served via the
//! `GET .well-known/openid-configuration` path relative to your provider's issuer URL.
//!
//! ### Example
//!
//! ```rust,no_run
//! use openidconnect::{
//! AuthUrl,
//! EmptyAdditionalProviderMetadata,
//! IssuerUrl,
//! JsonWebKeySetUrl,
//! ResponseTypes,
//! Scope,
//! TokenUrl,
//! UserInfoUrl,
//! };
//! use openidconnect::core::{
//! CoreClaimName,
//! CoreJwsSigningAlgorithm,
//! CoreProviderMetadata,
//! CoreResponseType,
//! CoreSubjectIdentifierType
//! };
//! use url::Url;
//!
//! # fn err_wrapper() -> Result<String, anyhow::Error> {
//! let provider_metadata = CoreProviderMetadata::new(
//! // Parameters required by the OpenID Connect Discovery spec.
//! IssuerUrl::new("https://accounts.example.com".to_string())?,
//! AuthUrl::new("https://accounts.example.com/authorize".to_string())?,
//! // Use the JsonWebKeySet struct to serve the JWK Set at this URL.
//! JsonWebKeySetUrl::new("https://accounts.example.com/jwk".to_string())?,
//! // Supported response types (flows).
//! vec![
//! // Recommended: support the code flow.
//! ResponseTypes::new(vec![CoreResponseType::Code]),
//! // Optional: support the implicit flow.
//! ResponseTypes::new(vec![CoreResponseType::Token, CoreResponseType::IdToken])
//! // Other flows including hybrid flows may also be specified here.
//! ],
//! // For user privacy, the Pairwise subject identifier type is preferred. This prevents
//! // distinct relying parties (clients) from knowing whether their users represent the same
//! // real identities. This identifier type is only useful for relying parties that don't
//! // receive the 'email', 'profile' or other personally-identifying scopes.
//! // The Public subject identifier type is also supported.
//! vec![CoreSubjectIdentifierType::Pairwise],
//! // Support the RS256 signature algorithm.
//! vec![CoreJwsSigningAlgorithm::RsaSsaPssSha256],
//! // OpenID Connect Providers may supply custom metadata by providing a struct that
//! // implements the AdditionalProviderMetadata trait. This requires manually using the
//! // generic ProviderMetadata struct rather than the CoreProviderMetadata type alias,
//! // however.
//! EmptyAdditionalProviderMetadata {},
//! )
//! // Specify the token endpoint (required for the code flow).
//! .set_token_endpoint(Some(TokenUrl::new("https://accounts.example.com/token".to_string())?))
//! // Recommended: support the user info endpoint.
//! .set_userinfo_endpoint(
//! Some(UserInfoUrl::new("https://accounts.example.com/userinfo".to_string())?)
//! )
//! // Recommended: specify the supported scopes.
//! .set_scopes_supported(Some(vec![
//! Scope::new("openid".to_string()),
//! Scope::new("email".to_string()),
//! Scope::new("profile".to_string()),
//! ]))
//! // Recommended: specify the supported ID token claims.
//! .set_claims_supported(Some(vec![
//! // Providers may also define an enum instead of using CoreClaimName.
//! CoreClaimName::new("sub".to_string()),
//! CoreClaimName::new("aud".to_string()),
//! CoreClaimName::new("email".to_string()),
//! CoreClaimName::new("email_verified".to_string()),
//! CoreClaimName::new("exp".to_string()),
//! CoreClaimName::new("iat".to_string()),
//! CoreClaimName::new("iss".to_string()),
//! CoreClaimName::new("name".to_string()),
//! CoreClaimName::new("given_name".to_string()),
//! CoreClaimName::new("family_name".to_string()),
//! CoreClaimName::new("picture".to_string()),
//! CoreClaimName::new("locale".to_string()),
//! ]));
//!
//! serde_json::to_string(&provider_metadata).map_err(From::from)
//! # }
//! ```
//!
//! ## OpenID Connect Discovery JSON Web Key Set
//!
//! The JSON Web Key Set (JWKS) provides the public keys that relying parties (clients) use to
//! verify the authenticity of ID tokens returned by this OpenID Connect Provider. The
//! [`JsonWebKeySet`] data structure should be serialized as JSON and served at the URL specified
//! in the `jwks_uri` field of the [`ProviderMetadata`] returned in the OpenID Connect Discovery
//! document.
//!
//! ### Example
//!
//! ```rust,no_run
//! use openidconnect::{JsonWebKeyId, PrivateSigningKey};
//! use openidconnect::core::{CoreJsonWebKey, CoreJsonWebKeySet, CoreRsaPrivateSigningKey};
//!
//! # fn err_wrapper() -> Result<String, anyhow::Error> {
//! # let rsa_pem = "";
//! let jwks = CoreJsonWebKeySet::new(
//! vec![
//! // RSA keys may also be constructed directly using CoreJsonWebKey::new_rsa(). Providers
//! // aiming to support other key types may provide their own implementation of the
//! // JsonWebKey trait or submit a PR to add the desired support to this crate.
//! CoreRsaPrivateSigningKey::from_pem(
//! &rsa_pem,
//! Some(JsonWebKeyId::new("key1".to_string()))
//! )
//! .expect("Invalid RSA private key")
//! .as_verification_key()
//! ]
//! );
//!
//! serde_json::to_string(&jwks).map_err(From::from)
//! # }
//! ```
//!
//! ## OpenID Connect ID Token
//!
//! The [`IdToken::new`] method is used for signing ID token claims, which can then be returned
//! from the token endpoint as part of the [`StandardTokenResponse`] struct
//! (or [`core::CoreTokenResponse`] type alias). The ID token can also be serialized to a string
//! using the `IdToken::to_string` method and returned directly from the authorization endpoint
//! when the implicit flow or certain hybrid flows are used. Note that in these flows, ID tokens
//! must only be returned in the URL fragment, and never as a query parameter.
//!
//! The ID token contains a combination of the
//! [OpenID Connect Standard Claims](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)
//! (see [`StandardClaims`]) and claims specific to the
//! [OpenID Connect ID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken)
//! (see [`IdTokenClaims`]).
//!
//! ### Example
//!
//! ```rust,no_run
//! use chrono::{Duration, Utc};
//! use openidconnect::{
//! AccessToken,
//! Audience,
//! EmptyAdditionalClaims,
//! EmptyExtraTokenFields,
//! EndUserEmail,
//! IssuerUrl,
//! JsonWebKeyId,
//! StandardClaims,
//! SubjectIdentifier,
//! };
//! use openidconnect::core::{
//! CoreIdToken,
//! CoreIdTokenClaims,
//! CoreIdTokenFields,
//! CoreJwsSigningAlgorithm,
//! CoreRsaPrivateSigningKey,
//! CoreTokenResponse,
//! CoreTokenType,
//! };
//!
//! # fn err_wrapper() -> Result<CoreTokenResponse, anyhow::Error> {
//! # let rsa_pem = "";
//! # let access_token = AccessToken::new("".to_string());
//! let id_token = CoreIdToken::new(
//! CoreIdTokenClaims::new(
//! // Specify the issuer URL for the OpenID Connect Provider.
//! IssuerUrl::new("https://accounts.example.com".to_string())?,
//! // The audience is usually a single entry with the client ID of the client for whom
//! // the ID token is intended. This is a required claim.
//! vec![Audience::new("client-id-123".to_string())],
//! // The ID token expiration is usually much shorter than that of the access or refresh
//! // tokens issued to clients.
//! Utc::now() + Duration::seconds(300),
//! // The issue time is usually the current time.
//! Utc::now(),
//! // Set the standard claims defined by the OpenID Connect Core spec.
//! StandardClaims::new(
//! // Stable subject identifiers are recommended in place of e-mail addresses or other
//! // potentially unstable identifiers. This is the only required claim.
//! SubjectIdentifier::new("5f83e0ca-2b8e-4e8c-ba0a-f80fe9bc3632".to_string())
//! )
//! // Optional: specify the user's e-mail address. This should only be provided if the
//! // client has been granted the 'profile' or 'email' scopes.
//! .set_email(Some(EndUserEmail::new("bob@example.com".to_string())))
//! // Optional: specify whether the provider has verified the user's e-mail address.
//! .set_email_verified(Some(true)),
//! // OpenID Connect Providers may supply custom claims by providing a struct that
//! // implements the AdditionalClaims trait. This requires manually using the
//! // generic IdTokenClaims struct rather than the CoreIdTokenClaims type alias,
//! // however.
//! EmptyAdditionalClaims {},
//! ),
//! // The private key used for signing the ID token. For confidential clients (those able
//! // to maintain a client secret), a CoreHmacKey can also be used, in conjunction
//! // with one of the CoreJwsSigningAlgorithm::HmacSha* signing algorithms. When using an
//! // HMAC-based signing algorithm, the UTF-8 representation of the client secret should
//! // be used as the HMAC key.
//! &CoreRsaPrivateSigningKey::from_pem(
//! &rsa_pem,
//! Some(JsonWebKeyId::new("key1".to_string()))
//! )
//! .expect("Invalid RSA private key"),
//! // Uses the RS256 signature algorithm. This crate supports any RS*, PS*, or HS*
//! // signature algorithm.
//! CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256,
//! // When returning the ID token alongside an access token (e.g., in the Authorization Code
//! // flow), it is recommended to pass the access token here to set the `at_hash` claim
//! // automatically.
//! Some(&access_token),
//! // When returning the ID token alongside an authorization code (e.g., in the implicit
//! // flow), it is recommended to pass the authorization code here to set the `c_hash` claim
//! // automatically.
//! None,
//! )?;
//!
//! Ok(CoreTokenResponse::new(
//! AccessToken::new("some_secret".to_string()),
//! CoreTokenType::Bearer,
//! CoreIdTokenFields::new(Some(id_token), EmptyExtraTokenFields {}),
//! ))
//! # }
//! ```
//!
//! # Asynchronous API
//!
//! An asynchronous API for async/await is also provided.
//!
//! ## Example
//!
//! ```rust,no_run
//! use anyhow::anyhow;
//! use openidconnect::{
//! AccessTokenHash,
//! AuthenticationFlow,
//! AuthorizationCode,
//! ClientId,
//! ClientSecret,
//! CsrfToken,
//! IssuerUrl,
//! Nonce,
//! OAuth2TokenResponse,
//! PkceCodeChallenge,
//! RedirectUrl,
//! Scope,
//! TokenResponse,
//! };
//! use openidconnect::core::{
//! CoreAuthenticationFlow,
//! CoreClient,
//! CoreProviderMetadata,
//! CoreResponseType,
//! };
//! # #[cfg(feature = "reqwest")]
//! use openidconnect::reqwest;
//! use url::Url;
//!
//!
//! # #[cfg(feature = "reqwest")]
//! # async fn err_wrapper() -> Result<(), anyhow::Error> {
//! let http_client = reqwest::ClientBuilder::new()
//! // Following redirects opens the client up to SSRF vulnerabilities.
//! .redirect(reqwest::redirect::Policy::none())
//! .build()
//! .expect("Client should build");
//!
//! // Use OpenID Connect Discovery to fetch the provider metadata.
//! let provider_metadata = CoreProviderMetadata::discover_async(
//! IssuerUrl::new("https://accounts.example.com".to_string())?,
//! &http_client,
//! )
//! .await?;
//!
//! // Create an OpenID Connect client by specifying the client ID, client secret, authorization URL
//! // and token URL.
//! let client =
//! CoreClient::from_provider_metadata(
//! provider_metadata,
//! ClientId::new("client_id".to_string()),
//! Some(ClientSecret::new("client_secret".to_string())),
//! )
//! // Set the URL the user will be redirected to after the authorization process.
//! .set_redirect_uri(RedirectUrl::new("http://redirect".to_string())?);
//!
//! // Generate a PKCE challenge.
//! let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
//!
//! // Generate the full authorization URL.
//! let (auth_url, csrf_token, nonce) = client
//! .authorize_url(
//! CoreAuthenticationFlow::AuthorizationCode,
//! CsrfToken::new_random,
//! Nonce::new_random,
//! )
//! // Set the desired scopes.
//! .add_scope(Scope::new("read".to_string()))
//! .add_scope(Scope::new("write".to_string()))
//! // Set the PKCE code challenge.
//! .set_pkce_challenge(pkce_challenge)
//! .url();
//!
//! // This is the URL you should redirect the user to, in order to trigger the authorization
//! // process.
//! println!("Browse to: {}", auth_url);
//!
//! // Once the user has been redirected to the redirect URL, you'll have access to the
//! // authorization code. For security reasons, your code should verify that the `state`
//! // parameter returned by the server matches `csrf_state`.
//!
//! // Now you can exchange it for an access token and ID token.
//! let token_response =
//! client
//! .exchange_code(AuthorizationCode::new("some authorization code".to_string()))?
//! // Set the PKCE code verifier.
//! .set_pkce_verifier(pkce_verifier)
//! .request_async(&http_client)
//! .await?;
//!
//! // Extract the ID token claims after verifying its authenticity and nonce.
//! let id_token = token_response
//! .id_token()
//! .ok_or_else(|| anyhow!("Server did not return an ID token"))?;
//! let id_token_verifier = client.id_token_verifier();
//! let claims = id_token.claims(&id_token_verifier, &nonce)?;
//!
//! // Verify the access token hash to ensure that the access token hasn't been substituted for
//! // another user's.
//! if let Some(expected_access_token_hash) = claims.access_token_hash() {
//! let actual_access_token_hash = AccessTokenHash::from_token(
//! token_response.access_token(),
//! id_token.signing_alg()?,
//! id_token.signing_key(&id_token_verifier)?,
//! )?;
//! if actual_access_token_hash != *expected_access_token_hash {
//! return Err(anyhow!("Invalid access token"));
//! }
//! }
//!
//! // The authenticated user's identity is now available. See the IdTokenClaims struct for a
//! // complete listing of the available claims.
//! println!(
//! "User {} with e-mail address {} has authenticated successfully",
//! claims.subject().as_str(),
//! claims.email().map(|email| email.as_str()).unwrap_or("<not provided>"),
//! );
//!
//! // See the OAuth2TokenResponse trait for a listing of other available fields such as
//! // access_token() and refresh_token().
//!
//! # Ok(())
//! # }
//! ```
use crate::jwt::{JsonWebToken, JsonWebTokenAccess, JsonWebTokenAlgorithm, JsonWebTokenHeader};
use crate::verification::{AudiencesClaim, IssuerClaim};
// Defined first since other modules need the macros, and definition order is significant for
// macros. This module is private.
#[macro_use]
mod macros;
/// Baseline OpenID Connect implementation and types.
pub mod core;
/// OpenID Connect Dynamic Client Registration.
pub mod registration;
// Private modules since we may move types between different modules; these are exported publicly
// via the pub use above.
mod authorization;
mod claims;
mod client;
mod discovery;
mod helpers;
mod id_token;
mod logout;
mod token;
mod types;
mod user_info;
mod verification;
// Private module for HTTP(S) utilities.
mod http_utils;
// Private module for JWT utilities.
mod jwt;
pub use oauth2::{
AccessToken, AsyncHttpClient, AuthType, AuthUrl, AuthorizationCode,
ClientCredentialsTokenRequest, ClientId, ClientSecret, CodeTokenRequest, ConfigurationError,
CsrfToken, DeviceAccessTokenRequest, DeviceAuthorizationRequest, DeviceAuthorizationResponse,
DeviceAuthorizationUrl, DeviceCode, DeviceCodeErrorResponse, DeviceCodeErrorResponseType,
EmptyExtraDeviceAuthorizationFields, EmptyExtraTokenFields, EndUserVerificationUrl,
EndpointMaybeSet, EndpointNotSet, EndpointSet, EndpointState, ErrorResponse, ErrorResponseType,
ExtraDeviceAuthorizationFields, ExtraTokenFields, HttpClientError, HttpRequest, HttpResponse,
IntrospectionRequest, IntrospectionUrl, PasswordTokenRequest, PkceCodeChallenge,
PkceCodeChallengeMethod, PkceCodeVerifier, RedirectUrl, RefreshToken, RefreshTokenRequest,
RequestTokenError, ResourceOwnerPassword, ResourceOwnerUsername, RevocableToken,
RevocationErrorResponseType, RevocationRequest, RevocationUrl, Scope, StandardErrorResponse,
StandardTokenIntrospectionResponse, StandardTokenResponse, SyncHttpClient,
TokenIntrospectionResponse, TokenResponse as OAuth2TokenResponse, TokenType, TokenUrl,
UserCode, VerificationUriComplete,
};
/// Public re-exports of types used for HTTP client interfaces.
pub use oauth2::http;
pub use oauth2::url;
#[cfg(all(feature = "curl", not(target_arch = "wasm32")))]
pub use oauth2::curl;
#[cfg(all(feature = "curl", not(target_arch = "wasm32")))]
pub use oauth2::CurlHttpClient;
#[cfg(all(feature = "curl", target_arch = "wasm32"))]
compile_error!("wasm32 is not supported with the `curl` feature. Use the `reqwest` backend or a custom backend for wasm32 support");
#[cfg(any(feature = "reqwest", feature = "reqwest-blocking"))]
pub use oauth2::reqwest;
#[cfg(feature = "ureq")]
pub use oauth2::ureq;
pub use crate::authorization::{AuthenticationFlow, AuthorizationRequest};
pub use crate::claims::{
AdditionalClaims, AddressClaim, EmptyAdditionalClaims, GenderClaim, StandardClaims,
};
pub use crate::client::Client;
pub use crate::discovery::{
AdditionalProviderMetadata, DiscoveryError, EmptyAdditionalProviderMetadata, ProviderMetadata,
};
pub use crate::id_token::IdTokenFields;
pub use crate::id_token::{IdToken, IdTokenClaims};
pub use crate::jwt::{JsonWebTokenError, JsonWebTokenType, NormalizedJsonWebTokenType};
pub use crate::logout::{LogoutProviderMetadata, LogoutRequest, ProviderMetadataWithLogout};
pub use crate::token::TokenResponse;
// Flatten the module hierarchy involving types. They're only separated to improve code
// organization.
pub use crate::types::jwk::{
JsonWebKey, JsonWebKeyAlgorithm, JsonWebKeyId, JsonWebKeyType, JsonWebKeyUse,
JweContentEncryptionAlgorithm, JweKeyManagementAlgorithm, JwsSigningAlgorithm,
PrivateSigningKey,
};
pub use crate::types::jwks::{JsonWebKeySet, JsonWebKeySetUrl};
pub use crate::types::localized::{LanguageTag, LocalizedClaim};
pub use crate::types::{
AccessTokenHash, AddressCountry, AddressLocality, AddressPostalCode, AddressRegion,
ApplicationType, Audience, AuthDisplay, AuthPrompt, AuthenticationContextClass,
AuthenticationMethodReference, AuthorizationCodeHash, ClaimName, ClaimType, ClientAuthMethod,
ClientConfigUrl, ClientContactEmail, ClientName, ClientUrl, EndSessionUrl, EndUserBirthday,
EndUserEmail, EndUserFamilyName, EndUserGivenName, EndUserMiddleName, EndUserName,
EndUserNickname, EndUserPhoneNumber, EndUserPictureUrl, EndUserProfileUrl, EndUserTimezone,
EndUserUsername, EndUserWebsiteUrl, FormattedAddress, GrantType, InitiateLoginUrl, IssuerUrl,
LoginHint, LogoUrl, LogoutHint, Nonce, OpPolicyUrl, OpTosUrl, PolicyUrl, PostLogoutRedirectUrl,
RegistrationAccessToken, RegistrationUrl, RequestUrl, ResponseMode, ResponseType,
ResponseTypes, SectorIdentifierUrl, ServiceDocUrl, SigningError, StreetAddress,
SubjectIdentifier, SubjectIdentifierType, ToSUrl,
};
pub use crate::user_info::{
UserInfoClaims, UserInfoError, UserInfoJsonWebToken, UserInfoRequest, UserInfoResponseType,
UserInfoUrl,
};
pub use crate::verification::{
ClaimsVerificationError, IdTokenVerifier, NonceVerifier, SignatureVerificationError,
UserInfoVerifier,
};
+308
View File
@@ -0,0 +1,308 @@
use crate::core::{
CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClientAuthMethod, CoreGrantType,
CoreJsonWebKey, CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm,
CoreResponseMode, CoreResponseType, CoreSubjectIdentifierType,
};
use crate::helpers::join_vec;
use crate::types::{LogoutHint, PostLogoutRedirectUrl};
use crate::{
AdditionalClaims, AdditionalProviderMetadata, ClientId, CsrfToken,
EmptyAdditionalProviderMetadata, EndSessionUrl, GenderClaim, IdToken,
JweContentEncryptionAlgorithm, JwsSigningAlgorithm, LanguageTag, ProviderMetadata,
};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use url::Url;
/// Additional metadata for providers implementing [OpenID Connect RP-Initiated
/// Logout 1.0](https://openid.net/specs/openid-connect-rpinitiated-1_0.html).
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct LogoutProviderMetadata<A>
where
A: AdditionalProviderMetadata,
{
/// The end session endpoint as described in [OpenID Connect RP-Initiated
/// Logout 1.0](https://openid.net/specs/openid-connect-rpinitiated-1_0.html).
pub end_session_endpoint: Option<EndSessionUrl>,
#[serde(bound = "A: AdditionalProviderMetadata", flatten)]
/// A field for an additional struct implementing AdditionalProviderMetadata.
pub additional_metadata: A,
}
impl<A> AdditionalProviderMetadata for LogoutProviderMetadata<A> where A: AdditionalProviderMetadata {}
/// Provider metadata returned by [OpenID Connect Discovery](
/// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata)
/// that returns [`ProviderMetadata::additional_metadata`] for providers
/// implementing [OpenID Connect RP-Initiated Logout 1.0](
/// https://openid.net/specs/openid-connect-rpinitiated-1_0.html).
pub type ProviderMetadataWithLogout = ProviderMetadata<
LogoutProviderMetadata<EmptyAdditionalProviderMetadata>,
CoreAuthDisplay,
CoreClientAuthMethod,
CoreClaimName,
CoreClaimType,
CoreGrantType,
CoreJweContentEncryptionAlgorithm,
CoreJweKeyManagementAlgorithm,
CoreJsonWebKey,
CoreResponseMode,
CoreResponseType,
CoreSubjectIdentifierType,
>;
/// A request to the end session endpoint.
pub struct LogoutRequest {
end_session_endpoint: EndSessionUrl,
parameters: LogoutRequestParameters,
}
#[derive(Default)]
struct LogoutRequestParameters {
id_token_hint: Option<String>,
logout_hint: Option<LogoutHint>,
client_id: Option<ClientId>,
post_logout_redirect_uri: Option<PostLogoutRedirectUrl>,
state: Option<CsrfToken>,
ui_locales: Vec<LanguageTag>,
}
impl From<EndSessionUrl> for LogoutRequest {
fn from(value: EndSessionUrl) -> Self {
LogoutRequest {
end_session_endpoint: value,
parameters: Default::default(),
}
}
}
impl LogoutRequest {
/// Provides an ID token previously issued by this OpenID Connect Provider as a hint about
/// the user's identity.
pub fn set_id_token_hint<AC, GC, JE, JS>(
mut self,
id_token_hint: &IdToken<AC, GC, JE, JS>,
) -> Self
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
self.parameters.id_token_hint = Some(id_token_hint.to_string());
self
}
/// Provides the OpenID Connect Provider with a hint about the user's identity.
///
/// The nature of this hint is specific to each provider.
pub fn set_logout_hint(mut self, logout_hint: LogoutHint) -> Self {
self.parameters.logout_hint = Some(logout_hint);
self
}
/// Provides the OpenID Connect Provider with the client identifier.
///
/// When both this and `id_token_hint` are set, the provider must verify that
/// this client id matches the one used when the ID token was issued.
pub fn set_client_id(mut self, client_id: ClientId) -> Self {
self.parameters.client_id = Some(client_id);
self
}
/// Provides the OpenID Connect Provider with a URI to redirect to after
/// the logout has been performed.
pub fn set_post_logout_redirect_uri(mut self, redirect_uri: PostLogoutRedirectUrl) -> Self {
self.parameters.post_logout_redirect_uri = Some(redirect_uri);
self
}
/// Specify an opaque value that the OpenID Connect Provider should pass back
/// to your application using the state parameter when redirecting to post_logout_redirect_uri.
pub fn set_state(mut self, state: CsrfToken) -> Self {
self.parameters.state = Some(state);
self
}
/// Requests the preferred languages for the user interface presented by the OpenID Connect
/// Provider.
///
/// Languages should be added in order of preference.
pub fn add_ui_locale(mut self, ui_locale: LanguageTag) -> Self {
self.parameters.ui_locales.push(ui_locale);
self
}
/// Returns the full logout URL. In order to logout, a GET request should be made to this URL
/// by the client's browser.
pub fn http_get_url(self) -> Url {
let mut url = self.end_session_endpoint.url().to_owned();
{
let mut query = url.query_pairs_mut();
macro_rules! add_pair {
($name:ident, $acc:expr) => {
if let Some($name) = self.parameters.$name {
query.append_pair(stringify!($name), $acc);
}
};
}
add_pair!(id_token_hint, id_token_hint.as_str());
add_pair!(logout_hint, logout_hint.secret());
add_pair!(client_id, client_id.as_str());
add_pair!(post_logout_redirect_uri, post_logout_redirect_uri.as_str());
add_pair!(state, state.secret());
if !self.parameters.ui_locales.is_empty() {
query.append_pair("ui_locales", &join_vec(&self.parameters.ui_locales));
}
}
if url.query() == Some("") {
url.set_query(None);
}
url
}
}
#[cfg(test)]
mod tests {
use crate::core::{
CoreGenderClaim, CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm,
};
use crate::types::{LogoutHint, PostLogoutRedirectUrl};
use crate::{
AuthUrl, ClientId, CsrfToken, EmptyAdditionalClaims, EndSessionUrl, IdToken, IssuerUrl,
JsonWebKeySetUrl, LanguageTag, LogoutProviderMetadata, LogoutRequest,
ProviderMetadataWithLogout,
};
use url::Url;
use std::str::FromStr;
#[test]
fn test_end_session_endpoint_deserialization() {
// Fetched from: https://rp.certification.openid.net:8080/openidconnect-rs/
// rp-response_type-code/.well-known/openid-configuration
// But pared down
let json_response = "{\
\"issuer\":\"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\",\
\"authorization_endpoint\":\"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/authorization\",\
\"jwks_uri\":\"https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json\",\
\"response_types_supported\":[],\
\"subject_types_supported\":[],\
\"id_token_signing_alg_values_supported\": [],\
\"end_session_endpoint\":\"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session\",\
\"version\":\"3.0\"}";
let new_provider_metadata = ProviderMetadataWithLogout::new(
IssuerUrl::new(
"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code"
.to_string(),
)
.unwrap(),
AuthUrl::new(
"https://rp.certification.openid.net:8080/openidconnect-rs/\
rp-response_type-code/authorization"
.to_string(),
)
.unwrap(),
JsonWebKeySetUrl::new(
"https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json"
.to_string(),
)
.unwrap(),
vec![],
vec![],
vec![],
LogoutProviderMetadata {
end_session_endpoint: Some(EndSessionUrl::new(
"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session"
.to_string()
).unwrap()),
additional_metadata: Default::default(),
},
);
let provider_metadata: ProviderMetadataWithLogout =
serde_json::from_str(json_response).unwrap();
assert_eq!(provider_metadata, new_provider_metadata);
assert_eq!(
Some(EndSessionUrl::new(
"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session"
.to_string()
).unwrap()),
provider_metadata.additional_metadata().end_session_endpoint
);
}
#[test]
fn test_logout_request_with_no_parameters() {
let endpoint = EndSessionUrl::new(
"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session"
.to_string()
).unwrap();
let logout_url = LogoutRequest::from(endpoint).http_get_url();
assert_eq!(
Url::parse(
"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session"
).unwrap(),
logout_url
);
}
#[test]
fn test_logout_request_with_all_parameters() {
let endpoint = EndSessionUrl::new(
"https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session"
.to_string()
).unwrap();
let logout_url = LogoutRequest::from(endpoint)
.set_id_token_hint(
&IdToken::<
EmptyAdditionalClaims,
CoreGenderClaim,
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
>::from_str(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwcz\
ovL3JwLmNlcnRpZmljYXRpb24ub3BlbmlkLm5ldDo4MDgwLyIsImV4c\
CI6MTUxNjIzOTAyMiwiaWF0IjoxNTE2MjM5MDIyLCJzdWIiOiJhc2Rm\
In0.cPwX6csO2uBEOZLVAGR7x5rHLRfD36MHpPy3JTk6orM",
)
.unwrap(),
)
.set_logout_hint(LogoutHint::new("johndoe".to_string()))
.set_client_id(ClientId::new("asdf".to_string()))
.set_post_logout_redirect_uri(
PostLogoutRedirectUrl::new("https://localhost:8000/".to_string()).unwrap(),
)
.set_state(CsrfToken::new("asdf".to_string()))
.add_ui_locale(LanguageTag::new("en-US".to_string()))
.add_ui_locale(LanguageTag::new("fr-FR".to_string()))
.http_get_url();
assert_eq!(
Url::parse(
"https://rp.certification.openid.net:8080/openidconnect-rs\
/rp-response_type-code/end_session?id_token_hint=eyJhbGciO\
iJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3JwLmNlcn\
RpZmljYXRpb24ub3BlbmlkLm5ldDo4MDgwLyIsImV4cCI6MTUxNjIzOTAy\
MiwiaWF0IjoxNTE2MjM5MDIyLCJzdWIiOiJhc2RmIn0.cPwX6csO2uBEOZ\
LVAGR7x5rHLRfD36MHpPy3JTk6orM&logout_hint=johndoe&client_i\
d=asdf&post_logout_redirect_uri=https%3A%2F%2Flocalhost%3A\
8000%2F&state=asdf&ui_locales=en-US+fr-FR"
)
.unwrap(),
logout_url
);
}
}
+750
View File
@@ -0,0 +1,750 @@
/// Copied from oauth2-rs crate (not part of that crate's stable public interface).
macro_rules! new_type {
// Convenience pattern without an impl.
(
$(#[$attr:meta])*
$name:ident(
$(#[$type_attr:meta])*
$type:ty
)
) => {
new_type![
@new_type_pub $(#[$attr])*,
$name(
$(#[$type_attr])*
$type
),
concat!(
"Create a new `",
stringify!($name),
"` to wrap the given `",
stringify!($type),
"`."
),
impl {}
];
};
// Convenience pattern without an impl.
(
$(#[$attr:meta])*
pub(crate) $name:ident(
$(#[$type_attr:meta])*
$type:ty
)
) => {
new_type![
@new_type_pub_crate $(#[$attr])*,
$name(
$(#[$type_attr])*
$type
),
concat!(
"Create a new `",
stringify!($name),
"` to wrap the given `",
stringify!($type),
"`."
),
impl {}
];
};
// Main entry point with an impl.
(
$(#[$attr:meta])*
$name:ident(
$(#[$type_attr:meta])*
$type:ty
)
impl {
$($item:tt)*
}
) => {
new_type![
@new_type_pub $(#[$attr])*,
$name(
$(#[$type_attr])*
$type
),
concat!(
"Create a new `",
stringify!($name),
"` to wrap the given `",
stringify!($type),
"`."
),
impl {
$($item)*
}
];
};
// Main entry point with an impl.
(
$(#[$attr:meta])*
pub(crate) $name:ident(
$(#[$type_attr:meta])*
$type:ty
)
impl {
$($item:tt)*
}
) => {
new_type![
@new_type_pub_crate $(#[$attr])*,
$name(
$(#[$type_attr])*
$type
),
concat!(
"Create a new `",
stringify!($name),
"` to wrap the given `",
stringify!($type),
"`."
),
impl {
$($item)*
}
];
};
// Actual implementation, after stringifying the #[doc] attr.
(
@new_type_pub $(#[$attr:meta])*,
$name:ident(
$(#[$type_attr:meta])*
$type:ty
),
$new_doc:expr,
impl {
$($item:tt)*
}
) => {
$(#[$attr])*
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct $name(
$(#[$type_attr])*
$type
);
impl $name {
$($item)*
#[allow(dead_code)]
#[doc = $new_doc]
pub fn new(s: $type) -> Self {
$name(s)
}
}
impl std::ops::Deref for $name {
type Target = $type;
fn deref(&self) -> &$type {
&self.0
}
}
impl From<$name> for $type {
fn from(t: $name) -> $type {
t.0
}
}
};
// Actual implementation, after stringifying the #[doc] attr.
(
@new_type_pub_crate $(#[$attr:meta])*,
$name:ident(
$(#[$type_attr:meta])*
$type:ty
),
$new_doc:expr,
impl {
$($item:tt)*
}
) => {
$(#[$attr])*
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct $name(
$(#[$type_attr])*
$type
);
impl $name {
$($item)*
#[doc = $new_doc]
pub const fn new(s: $type) -> Self {
$name(s)
}
}
impl std::ops::Deref for $name {
type Target = $type;
fn deref(&self) -> &$type {
&self.0
}
}
impl From<$name> for $type {
fn from(t: $name) -> $type {
t.0
}
}
};
}
/// Copied from oauth2-rs crate (not part of that crate's stable public interface).
macro_rules! new_secret_type {
(
$(#[$attr:meta])*
$name:ident($type:ty)
) => {
new_secret_type![
$(#[$attr])*
$name($type)
impl {}
];
};
(
$(#[$attr:meta])*
$name:ident($type:ty)
impl {
$($item:tt)*
}
) => {
new_secret_type![
$(#[$attr])*,
$name($type),
concat!(
"Create a new `",
stringify!($name),
"` to wrap the given `",
stringify!($type),
"`."
),
concat!("Get the secret contained within this `", stringify!($name), "`."),
impl {
$($item)*
}
];
};
(
$(#[$attr:meta])*,
$name:ident($type:ty),
$new_doc:expr,
$secret_doc:expr,
impl {
$($item:tt)*
}
) => {
$(
#[$attr]
)*
#[cfg_attr(feature = "timing-resistant-secret-traits", derive(Eq))]
pub struct $name($type);
impl $name {
$($item)*
#[doc = $new_doc]
pub fn new(s: $type) -> Self {
$name(s)
}
#[doc = $secret_doc]
///
/// # Security Warning
///
/// Leaking this value may compromise the security of the OAuth2 flow.
pub fn secret(&self) -> &$type { &self.0 }
#[doc = $secret_doc]
///
/// # Security Warning
///
/// Leaking this value may compromise the security of the OAuth2 flow.
pub fn into_secret(self) -> $type { self.0 }
}
impl Debug for $name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, concat!(stringify!($name), "([redacted])"))
}
}
#[cfg(any(test, feature = "timing-resistant-secret-traits"))]
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
<sha2::Sha256 as sha2::Digest>::digest(&self.0)
== <sha2::Sha256 as sha2::Digest>::digest(&other.0)
}
}
#[cfg(feature = "timing-resistant-secret-traits")]
impl std::hash::Hash for $name {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
<sha2::Sha256 as sha2::Digest>::digest(&self.0).hash(state)
}
}
};
}
/// Creates a URL-specific new type
///
/// Types created by this macro enforce during construction that the contained value represents a
/// syntactically valid URL. However, comparisons and hashes of these types are based on the string
/// representation given during construction, disregarding any canonicalization performed by the
/// underlying `Url` struct. OpenID Connect requires certain URLs (e.g., ID token issuers) to be
/// compared exactly, without canonicalization.
///
/// In addition to the raw string representation, these types include a `url` method to retrieve a
/// parsed `Url` struct.
macro_rules! new_url_type {
// Convenience pattern without an impl.
(
$(#[$attr:meta])*
$name:ident
) => {
new_url_type![
@new_type_pub $(#[$attr])*,
$name,
concat!("Create a new `", stringify!($name), "` from a `String` to wrap a URL."),
concat!("Create a new `", stringify!($name), "` from a `Url` to wrap a URL."),
concat!("Return this `", stringify!($name), "` as a parsed `Url`."),
impl {}
];
};
// Main entry point with an impl.
(
$(#[$attr:meta])*
$name:ident
impl {
$($item:tt)*
}
) => {
new_url_type![
@new_type_pub $(#[$attr])*,
$name,
concat!("Create a new `", stringify!($name), "` from a `String` to wrap a URL."),
concat!("Create a new `", stringify!($name), "` from a `Url` to wrap a URL."),
concat!("Return this `", stringify!($name), "` as a parsed `Url`."),
impl {
$($item)*
}
];
};
// Actual implementation, after stringifying the #[doc] attr.
(
@new_type_pub $(#[$attr:meta])*,
$name:ident,
$new_doc:expr,
$from_url_doc:expr,
$url_doc:expr,
impl {
$($item:tt)*
}
) => {
$(#[$attr])*
#[derive(Clone)]
pub struct $name(url::Url, String);
impl $name {
#[doc = $new_doc]
pub fn new(url: String) -> Result<Self, ::url::ParseError> {
Ok($name(url::Url::parse(&url)?, url))
}
#[doc = $from_url_doc]
pub fn from_url(url: url::Url) -> Self {
let s = url.to_string();
Self(url, s)
}
#[doc = $url_doc]
pub fn url(&self) -> &url::Url {
return &self.0;
}
$($item)*
}
impl std::ops::Deref for $name {
type Target = String;
fn deref(&self) -> &String {
&self.1
}
}
impl ::std::fmt::Display for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
write!(f, "{}", self.1)
}
}
impl From<$name> for url::Url {
fn from(t: $name) -> url::Url {
t.0
}
}
impl ::std::fmt::Debug for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
let mut debug_trait_builder = f.debug_tuple(stringify!($name));
debug_trait_builder.field(&self.1);
debug_trait_builder.finish()
}
}
impl<'de> ::serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::de::Deserializer<'de>,
{
struct UrlVisitor;
impl<'de> ::serde::de::Visitor<'de> for UrlVisitor {
type Value = $name;
fn expecting(
&self,
formatter: &mut ::std::fmt::Formatter
) -> ::std::fmt::Result {
formatter.write_str(stringify!($name))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
$name::new(v.to_string()).map_err(E::custom)
}
}
deserializer.deserialize_str(UrlVisitor {})
}
}
impl ::serde::Serialize for $name {
fn serialize<SE>(&self, serializer: SE) -> Result<SE::Ok, SE::Error>
where
SE: ::serde::Serializer,
{
serializer.serialize_str(&self.1)
}
}
impl ::std::hash::Hash for $name {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) -> () {
::std::hash::Hash::hash(&(self.1), state);
}
}
impl Ord for $name {
fn cmp(&self, other: &$name) -> ::std::cmp::Ordering {
self.1.cmp(&other.1)
}
}
impl PartialOrd for $name {
fn partial_cmp(&self, other: &$name) -> Option<::std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for $name {
fn eq(&self, other: &$name) -> bool {
self.1 == other.1
}
}
impl Eq for $name {}
};
}
macro_rules! serialize_fields {
(@case $self:ident $map:ident Option(Seconds($field:ident))) => {
if let Some(ref $field) = $self.$field {
$map.serialize_entry(stringify!($field), &$field.as_secs())?;
}
};
(@case $self:ident $map:ident Option(DateTime(Seconds($field:ident)))) => {
if let Some(ref $field) = $self.$field {
$map.serialize_entry(stringify!($field), &crate::helpers::Timestamp::from_utc(&$field))?;
}
};
(@case $self:ident $map:ident Option($field:ident)) => {
if let Some(ref $field) = $self.$field {
$map.serialize_entry(stringify!($field), $field)?;
}
};
(@case $self:ident $map:ident LanguageTag($field:ident)) => {
if let Some(ref field_map) = $self.$field {
use itertools::sorted;
let sorted_field_map = sorted(field_map.iter());
for (language_tag_opt, $field) in sorted_field_map {
if let Some(ref language_tag) = language_tag_opt {
$map.serialize_entry(
&format!(concat!(stringify!($field), "#{}"), language_tag.as_ref()),
&$field
)?;
} else {
$map.serialize_entry(stringify!($field), &$field)?;
}
}
}
};
(@case $self:ident $map:ident $field:ident) => {
$map.serialize_entry(stringify!($field), &$self.$field)?;
};
// Main entry point
(
$self:ident -> $serializer:ident {
$([$($entry:tt)+])+
}
) => {
let mut map = $serializer.serialize_map(None)?;
$(
serialize_fields![@case $self map $($entry)+];
)+
map.end()
};
}
macro_rules! field_getters {
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident Option < bool >) => {
#[doc = $doc]
$vis fn $field(&$self) -> Option<bool> {
$zero.$field
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident Option < bool > { $($body:tt)+ }) => {
#[doc = $doc]
$vis fn $field(&$self) -> Option<bool> {
$($body)+
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident Option < DateTime < Utc >>) => {
#[doc = $doc]
$vis fn $field(&$self) -> Option<DateTime<Utc>> {
$zero.$field
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident Option < DateTime < Utc >> { $($body:tt)+ }) => {
#[doc = $doc]
$vis fn $field(&$self) -> Option<DateTime<Utc>> {
$($body)+
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident Option < $type:ty >) => {
#[doc = $doc]
$vis fn $field(&$self) -> Option<&$type> {
$zero.$field.as_ref()
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident Option < $type:ty > { $($body:tt)+ }) => {
#[doc = $doc]
$vis fn $field(&$self) -> Option<$type> {
$($body)+
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident DateTime < Utc >) => {
#[doc = $doc]
$vis fn $field(&$self) -> DateTime<Utc> {
$zero.$field
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident $type:ty) => {
#[doc = $doc]
$vis fn $field(&$self) -> &$type {
&$zero.$field
}
};
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $field:ident $type:ty { $($body:tt)+ }) => {
#[doc = $doc]
$vis fn $field(&$self) -> $type {
$($body)+
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() Option < bool >) => {
#[doc = $doc]
fn $field(&$self) -> Option<bool> {
$zero.$field()
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() Option < bool > { $($body:tt)+ }) => {
#[doc = $doc]
fn $field(&$self) -> Option<bool> {
$($body)+
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() Option < DateTime < Utc >>) => {
#[doc = $doc]
fn $field(&$self) -> Option<DateTime<Utc>> {
$zero.$field()
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() Option < DateTime < Utc >> { $($body:tt)+ }) => {
#[doc = $doc]
fn $field(&$self) -> Option<DateTime<Utc>> {
$($body)+
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() Option < $type:ty >) => {
#[doc = $doc]
fn $field(&$self) -> Option<&$type> {
$zero.$field()
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() Option < $type:ty > { $($body:tt)+ }) => {
#[doc = $doc]
fn $field(&$self) -> Option<$type> {
$($body)+
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() DateTime < Utc >) => {
#[doc = $doc]
fn $field(&$self) -> DateTime<Utc> {
$zero.$field()
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() $type:ty) => {
#[doc = $doc]
fn $field(&$self) -> &$type {
&$zero.$field()
}
};
(@case [$doc:expr] $self:ident [$zero:expr] $field:ident() $type:ty { $($body:tt)+ }) => {
#[doc = $doc]
fn $field(&$self) -> $type {
$($body)+
}
};
// Main entry points
(
$vis:vis $self:ident [$zero:expr] [$doc:expr] {
$(
$field:ident[$($entry:tt)+] [$doc_field:expr],
)+
}
) => {
$(
field_getters![
@case
[concat!("Returns the `", $doc_field, "` ", $doc, ".")]
$vis $self [$zero] $field $($entry)+
];
)+
};
(
$vis:vis $self:ident [$zero:expr]() [$doc:expr] {
$(
$field:ident[$($entry:tt)+] [$doc_field:expr],
)+
}
) => {
$(
field_getters![
@case
[concat!("Returns the `", $doc_field, "` ", $doc, ".")]
$vis $self [$zero] $field() $($entry)+
];
)+
};
}
macro_rules! field_setters {
(@case [$doc:expr] $vis:vis $self:ident [$zero:expr] $setter:ident $field:ident $type:ty [$doc_field:expr]) => {
field_setters![
@case2
[concat!("Sets the `", $doc_field, "` ", $doc, ".")]
$vis $self [$zero] $setter $field $type
];
};
(@case2 [$doc:expr] $vis:vis $self:ident [$zero:expr] $setter:ident $field:ident $type:ty) => {
#[doc = $doc]
$vis fn $setter(
mut $self,
$field: $type
) -> Self {
$zero.$field = $field;
$self
}
};
// Main entry point
(
$vis:vis $self:ident [$zero:expr] [$doc:expr] {
$setter:ident -> $field:ident[$($entry:tt)+] [$doc_field:expr]
}
) => {
field_setters![
@case [$doc] $vis $self [$zero] $setter $field $($entry)+ [$doc_field]
];
};
}
macro_rules! field_getters_setters {
(
@single $vis:vis $self:ident [$zero:expr] [$doc:expr]
[$setter:ident -> $field:ident[$($entry:tt)+] [$field_doc:expr], $($rest:tt)*]
) => {
field_getters![$vis $self [$zero] [$doc] { $field[$($entry)+] [$field_doc], }];
field_setters![
$vis $self [$zero] [$doc] { $setter -> $field[$($entry)+] [$field_doc] }
];
field_getters_setters![@single $vis $self [$zero] [$doc] [$($rest)*]];
};
(
@single $vis:vis $self:ident [$zero:expr]() [$doc:expr]
[$setter:ident -> $field:ident[$($entry:tt)+] [$field_doc:expr], $($rest:tt)*]
) => {
field_getters![$vis $self [$zero]() [$doc] { $field[$($entry)+] [$field_doc], }];
field_setters![
$vis $self [$zero] [$doc] { $setter -> $field[$($entry)+] [$field_doc] }
];
field_getters_setters![@single $vis $self [$zero]() [$doc] [$($rest)*]];
};
(
@single $vis:vis $self:ident [$zero:expr] [$doc:expr]
[$setter:ident -> $field:ident[$($entry:tt)+], $($rest:tt)*]
) => {
field_getters![$vis $self [$zero] [$doc] { $field[$($entry)+] [stringify!($field)], }];
field_setters![
$vis $self [$zero] [$doc] { $setter -> $field[$($entry)+] [stringify!($field)] }
];
field_getters_setters![@single $vis $self [$zero] [$doc] [$($rest)*]];
};
(
@single $vis:vis $self:ident [$zero:expr]() [$doc:expr]
[$setter:ident -> $field:ident[$($entry:tt)+], $($rest:tt)*]
) => {
field_getters![$vis $self [$zero]() [$doc] { $field[$($entry)+] [stringify!($field)], }];
field_setters![
$vis $self [$zero] [$doc] { $setter -> $field[$($entry)+] [stringify!($field)] }
];
field_getters_setters![@single $vis $self [$zero]() [$doc] [$($rest)*]];
};
// Base case.
(@single $vis:vis $self:ident [$zero:expr] [$doc:expr] []) => {};
// Main entry points.
(
$vis:vis $self:ident [$zero:expr] [$doc:expr] {
$setter:ident -> $field:ident[$($entry:tt)+] $($rest:tt)*
}
) => {
field_getters_setters![
@single
$vis $self [$zero] [$doc] [$setter -> $field[$($entry)+] $($rest)*]
];
};
(
$vis:vis $self:ident [$zero:expr]() [$doc:expr] {
$setter:ident -> $field:ident[$($entry:tt)+] $($rest:tt)*
}
) => {
field_getters_setters![
@single
$vis $self [$zero]() [$doc] [$setter -> $field[$($entry)+] $($rest)*]
];
};
}
macro_rules! deserialize_from_str {
($type:path) => {
impl<'de> serde::Deserialize<'de> for $type {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let variant_str = String::deserialize(deserializer)?;
Ok(Self::from_str(&variant_str))
}
}
};
}
macro_rules! serialize_as_str {
($type:path) => {
impl serde::ser::Serialize for $type {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
};
}
+918
View File
@@ -0,0 +1,918 @@
use crate::helpers::{DeserializeMapField, Timestamp};
use crate::http_utils::{auth_bearer, check_content_type, MIME_TYPE_JSON};
use crate::types::localized::split_language_tag_key;
use crate::types::{
ApplicationType, AuthenticationContextClass, ClientAuthMethod, ClientConfigUrl,
ClientContactEmail, ClientName, ClientUrl, GrantType, InitiateLoginUrl, LogoUrl, PolicyUrl,
RegistrationAccessToken, RegistrationUrl, RequestUrl, ResponseType, ResponseTypes,
SectorIdentifierUrl, SubjectIdentifierType, ToSUrl,
};
use crate::{
AccessToken, AsyncHttpClient, ClientId, ClientSecret, ErrorResponseType, HttpRequest,
HttpResponse, JsonWebKey, JsonWebKeySet, JsonWebKeySetUrl, JweContentEncryptionAlgorithm,
JweKeyManagementAlgorithm, JwsSigningAlgorithm, LocalizedClaim, RedirectUrl,
StandardErrorResponse, SyncHttpClient,
};
use chrono::{DateTime, Utc};
use http::header::{HeaderValue, ACCEPT, CONTENT_TYPE};
use http::method::Method;
use http::status::StatusCode;
use serde::de::{DeserializeOwned, Deserializer, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize, Serializer};
use serde_with::{serde_as, skip_serializing_none};
use thiserror::Error;
use std::fmt::{Debug, Formatter, Result as FormatterResult};
use std::future::Future;
use std::marker::PhantomData;
use std::time::Duration;
#[cfg(test)]
mod tests;
/// Trait for adding extra fields to [`ClientMetadata`].
pub trait AdditionalClientMetadata: Debug + DeserializeOwned + Serialize {}
// In order to support serde flatten, this must be an empty struct rather than an empty
// tuple struct.
/// Empty (default) extra [`ClientMetadata`] fields.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct EmptyAdditionalClientMetadata {}
impl AdditionalClientMetadata for EmptyAdditionalClientMetadata {}
/// Client metadata used in dynamic client registration.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ClientMetadata<A, AT, CA, G, JE, JK, K, RT, S>
where
A: AdditionalClientMetadata,
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
// To avoid implementing a custom deserializer that handles both language tags and flatten,
// we wrap the language tag handling in its own flattened struct.
#[serde(bound = "AT: ApplicationType", flatten)]
standard_metadata: StandardClientMetadata<AT, CA, G, JE, JK, K, RT, S>,
#[serde(bound = "A: AdditionalClientMetadata", flatten)]
additional_metadata: A,
}
impl<A, AT, CA, G, JE, JK, K, RT, S> ClientMetadata<A, AT, CA, G, JE, JK, K, RT, S>
where
A: AdditionalClientMetadata,
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
/// Instantiates new client metadata.
pub fn new(redirect_uris: Vec<RedirectUrl>, additional_metadata: A) -> Self {
Self {
standard_metadata: StandardClientMetadata {
redirect_uris,
response_types: None,
grant_types: None,
application_type: None,
contacts: None,
client_name: None,
logo_uri: None,
client_uri: None,
policy_uri: None,
tos_uri: None,
jwks_uri: None,
jwks: None,
sector_identifier_uri: None,
subject_type: None,
id_token_signed_response_alg: None,
id_token_encrypted_response_alg: None,
id_token_encrypted_response_enc: None,
userinfo_signed_response_alg: None,
userinfo_encrypted_response_alg: None,
userinfo_encrypted_response_enc: None,
request_object_signing_alg: None,
request_object_encryption_alg: None,
request_object_encryption_enc: None,
token_endpoint_auth_method: None,
token_endpoint_auth_signing_alg: None,
default_max_age: None,
require_auth_time: None,
default_acr_values: None,
initiate_login_uri: None,
request_uris: None,
},
additional_metadata,
}
}
field_getters_setters![
pub self [self.standard_metadata] ["client metadata value"] {
set_redirect_uris -> redirect_uris[Vec<RedirectUrl>],
set_response_types -> response_types[Option<Vec<ResponseTypes<RT>>>],
set_grant_types -> grant_types[Option<Vec<G>>],
set_application_type -> application_type[Option<AT>],
set_contacts -> contacts[Option<Vec<ClientContactEmail>>],
set_client_name -> client_name[Option<LocalizedClaim<ClientName>>],
set_logo_uri -> logo_uri[Option<LocalizedClaim<LogoUrl>>],
set_client_uri -> client_uri[Option<LocalizedClaim<ClientUrl>>],
set_policy_uri -> policy_uri[Option<LocalizedClaim<PolicyUrl>>],
set_tos_uri -> tos_uri[Option<LocalizedClaim<ToSUrl>>],
set_jwks_uri -> jwks_uri[Option<JsonWebKeySetUrl>],
set_jwks -> jwks[Option<JsonWebKeySet<K>>],
set_sector_identifier_uri -> sector_identifier_uri[Option<SectorIdentifierUrl>],
set_subject_type -> subject_type[Option<S>],
set_id_token_signed_response_alg -> id_token_signed_response_alg[Option<K::SigningAlgorithm>],
set_id_token_encrypted_response_alg -> id_token_encrypted_response_alg[Option<JK>],
set_id_token_encrypted_response_enc -> id_token_encrypted_response_enc[Option<JE>],
set_userinfo_signed_response_alg -> userinfo_signed_response_alg[Option<K::SigningAlgorithm>],
set_userinfo_encrypted_response_alg -> userinfo_encrypted_response_alg[Option<JK>],
set_userinfo_encrypted_response_enc -> userinfo_encrypted_response_enc[Option<JE>],
set_request_object_signing_alg -> request_object_signing_alg[Option<K::SigningAlgorithm>],
set_request_object_encryption_alg -> request_object_encryption_alg[Option<JK>],
set_request_object_encryption_enc -> request_object_encryption_enc[Option<JE>],
set_token_endpoint_auth_method -> token_endpoint_auth_method[Option<CA>],
set_token_endpoint_auth_signing_alg -> token_endpoint_auth_signing_alg[Option<K::SigningAlgorithm>],
set_default_max_age -> default_max_age[Option<Duration>],
set_require_auth_time -> require_auth_time[Option<bool>],
set_default_acr_values -> default_acr_values[Option<Vec<AuthenticationContextClass>>],
set_initiate_login_uri -> initiate_login_uri[Option<InitiateLoginUrl>],
set_request_uris -> request_uris[Option<Vec<RequestUrl>>],
}
];
/// Returns additional client metadata fields.
pub fn additional_metadata(&self) -> &A {
&self.additional_metadata
}
/// Returns mutable additional client metadata fields.
pub fn additional_metadata_mut(&mut self) -> &mut A {
&mut self.additional_metadata
}
}
#[derive(Clone, Debug, PartialEq)]
struct StandardClientMetadata<AT, CA, G, JE, JK, K, RT, S>
where
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
redirect_uris: Vec<RedirectUrl>,
response_types: Option<Vec<ResponseTypes<RT>>>,
grant_types: Option<Vec<G>>,
application_type: Option<AT>,
contacts: Option<Vec<ClientContactEmail>>,
client_name: Option<LocalizedClaim<ClientName>>,
logo_uri: Option<LocalizedClaim<LogoUrl>>,
client_uri: Option<LocalizedClaim<ClientUrl>>,
policy_uri: Option<LocalizedClaim<PolicyUrl>>,
tos_uri: Option<LocalizedClaim<ToSUrl>>,
jwks_uri: Option<JsonWebKeySetUrl>,
jwks: Option<JsonWebKeySet<K>>,
sector_identifier_uri: Option<SectorIdentifierUrl>,
subject_type: Option<S>,
id_token_signed_response_alg: Option<K::SigningAlgorithm>,
id_token_encrypted_response_alg: Option<JK>,
id_token_encrypted_response_enc: Option<JE>,
userinfo_signed_response_alg: Option<K::SigningAlgorithm>,
userinfo_encrypted_response_alg: Option<JK>,
userinfo_encrypted_response_enc: Option<JE>,
request_object_signing_alg: Option<K::SigningAlgorithm>,
request_object_encryption_alg: Option<JK>,
request_object_encryption_enc: Option<JE>,
token_endpoint_auth_method: Option<CA>,
token_endpoint_auth_signing_alg: Option<K::SigningAlgorithm>,
default_max_age: Option<Duration>,
require_auth_time: Option<bool>,
default_acr_values: Option<Vec<AuthenticationContextClass>>,
initiate_login_uri: Option<InitiateLoginUrl>,
request_uris: Option<Vec<RequestUrl>>,
}
impl<'de, AT, CA, G, JE, JK, K, RT, S> Deserialize<'de>
for StandardClientMetadata<AT, CA, G, JE, JK, K, RT, S>
where
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
/// Special deserializer that supports [RFC 5646](https://tools.ietf.org/html/rfc5646) language
/// tags associated with human-readable client metadata fields.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct MetadataVisitor<
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
>(PhantomData<(AT, CA, G, JE, JK, K, RT, S)>);
impl<'de, AT, CA, G, JE, JK, K, RT, S> Visitor<'de> for MetadataVisitor<AT, CA, G, JE, JK, K, RT, S>
where
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
type Value = StandardClientMetadata<AT, CA, G, JE, JK, K, RT, S>;
fn expecting(&self, formatter: &mut Formatter) -> FormatterResult {
formatter.write_str("struct StandardClientMetadata")
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
// NB: The non-localized fields are actually Option<Option<_>> here so that we can
// distinguish between omitted fields and fields explicitly set to `null`. The
// latter is necessary so that we can detect duplicate fields (e.g., if a key is
// present both with a null value and a non-null value, that's an error).
let mut redirect_uris = None;
let mut response_types = None;
let mut grant_types = None;
let mut application_type = None;
let mut contacts = None;
let mut client_name = None;
let mut logo_uri = None;
let mut client_uri = None;
let mut policy_uri = None;
let mut tos_uri = None;
let mut jwks_uri = None;
let mut jwks = None;
let mut sector_identifier_uri = None;
let mut subject_type = None;
let mut id_token_signed_response_alg = None;
let mut id_token_encrypted_response_alg = None;
let mut id_token_encrypted_response_enc = None;
let mut userinfo_signed_response_alg = None;
let mut userinfo_encrypted_response_alg = None;
let mut userinfo_encrypted_response_enc = None;
let mut request_object_signing_alg = None;
let mut request_object_encryption_alg = None;
let mut request_object_encryption_enc = None;
let mut token_endpoint_auth_method = None;
let mut token_endpoint_auth_signing_alg = None;
let mut default_max_age = None;
let mut require_auth_time = None;
let mut default_acr_values = None;
let mut initiate_login_uri = None;
let mut request_uris = None;
macro_rules! field_case {
($field:ident, $typ:ty, $language_tag:ident) => {{
$field = Some(<$typ>::deserialize_map_field(
&mut map,
stringify!($field),
$language_tag,
$field,
)?);
}};
}
while let Some(key) = map.next_key::<String>()? {
let (field_name, language_tag) = split_language_tag_key(&key);
match field_name {
"redirect_uris" => field_case!(redirect_uris, Vec<_>, language_tag),
"response_types" => field_case!(response_types, Option<_>, language_tag),
"grant_types" => field_case!(grant_types, Option<_>, language_tag),
"application_type" => {
field_case!(application_type, Option<_>, language_tag)
}
"contacts" => field_case!(contacts, Option<_>, language_tag),
"client_name" => {
field_case!(client_name, LocalizedClaim<Option<_>>, language_tag)
}
"logo_uri" => {
field_case!(logo_uri, LocalizedClaim<Option<_>>, language_tag)
}
"client_uri" => {
field_case!(client_uri, LocalizedClaim<Option<_>>, language_tag)
}
"policy_uri" => {
field_case!(policy_uri, LocalizedClaim<Option<_>>, language_tag)
}
"tos_uri" => field_case!(tos_uri, LocalizedClaim<Option<_>>, language_tag),
"jwks_uri" => field_case!(jwks_uri, Option<_>, language_tag),
"jwks" => field_case!(jwks, Option<_>, language_tag),
"sector_identifier_uri" => {
field_case!(sector_identifier_uri, Option<_>, language_tag)
}
"subject_type" => field_case!(subject_type, Option<_>, language_tag),
"id_token_signed_response_alg" => {
field_case!(id_token_signed_response_alg, Option<_>, language_tag)
}
"id_token_encrypted_response_alg" => {
field_case!(id_token_encrypted_response_alg, Option<_>, language_tag)
}
"id_token_encrypted_response_enc" => {
field_case!(id_token_encrypted_response_enc, Option<_>, language_tag)
}
"userinfo_signed_response_alg" => {
field_case!(userinfo_signed_response_alg, Option<_>, language_tag)
}
"userinfo_encrypted_response_alg" => {
field_case!(userinfo_encrypted_response_alg, Option<_>, language_tag)
}
"userinfo_encrypted_response_enc" => {
field_case!(userinfo_encrypted_response_enc, Option<_>, language_tag)
}
"request_object_signing_alg" => {
field_case!(request_object_signing_alg, Option<_>, language_tag)
}
"request_object_encryption_alg" => {
field_case!(request_object_encryption_alg, Option<_>, language_tag)
}
"request_object_encryption_enc" => {
field_case!(request_object_encryption_enc, Option<_>, language_tag)
}
"token_endpoint_auth_method" => {
field_case!(token_endpoint_auth_method, Option<_>, language_tag)
}
"token_endpoint_auth_signing_alg" => {
field_case!(token_endpoint_auth_signing_alg, Option<_>, language_tag)
}
"default_max_age" => {
field_case!(default_max_age, Option<u64>, language_tag)
}
"require_auth_time" => {
field_case!(require_auth_time, Option<_>, language_tag)
}
"default_acr_values" => {
field_case!(default_acr_values, Option<_>, language_tag)
}
"initiate_login_uri" => {
field_case!(initiate_login_uri, Option<_>, language_tag)
}
"request_uris" => field_case!(request_uris, Option<_>, language_tag),
// Ignore unknown fields.
_ => {
map.next_value::<serde::de::IgnoredAny>()?;
continue;
}
};
}
Ok(StandardClientMetadata {
redirect_uris: redirect_uris
.ok_or_else(|| serde::de::Error::missing_field("redirect_uris"))?,
response_types: response_types.flatten(),
grant_types: grant_types.flatten(),
application_type: application_type.flatten(),
contacts: contacts.flatten(),
client_name: client_name.and_then(LocalizedClaim::flatten_or_none),
logo_uri: logo_uri.and_then(LocalizedClaim::flatten_or_none),
client_uri: client_uri.and_then(LocalizedClaim::flatten_or_none),
policy_uri: policy_uri.and_then(LocalizedClaim::flatten_or_none),
tos_uri: tos_uri.and_then(LocalizedClaim::flatten_or_none),
jwks_uri: jwks_uri.flatten(),
jwks: jwks.flatten(),
sector_identifier_uri: sector_identifier_uri.flatten(),
subject_type: subject_type.flatten(),
id_token_signed_response_alg: id_token_signed_response_alg.flatten(),
id_token_encrypted_response_alg: id_token_encrypted_response_alg.flatten(),
id_token_encrypted_response_enc: id_token_encrypted_response_enc.flatten(),
userinfo_signed_response_alg: userinfo_signed_response_alg.flatten(),
userinfo_encrypted_response_alg: userinfo_encrypted_response_alg.flatten(),
userinfo_encrypted_response_enc: userinfo_encrypted_response_enc.flatten(),
request_object_signing_alg: request_object_signing_alg.flatten(),
request_object_encryption_alg: request_object_encryption_alg.flatten(),
request_object_encryption_enc: request_object_encryption_enc.flatten(),
token_endpoint_auth_method: token_endpoint_auth_method.flatten(),
token_endpoint_auth_signing_alg: token_endpoint_auth_signing_alg.flatten(),
default_max_age: default_max_age.flatten().map(Duration::from_secs),
require_auth_time: require_auth_time.flatten(),
default_acr_values: default_acr_values.flatten(),
initiate_login_uri: initiate_login_uri.flatten(),
request_uris: request_uris.flatten(),
})
}
}
deserializer.deserialize_map(MetadataVisitor(PhantomData))
}
}
impl<AT, CA, G, JE, JK, K, RT, S> Serialize for StandardClientMetadata<AT, CA, G, JE, JK, K, RT, S>
where
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
#[allow(clippy::cognitive_complexity)]
fn serialize<SE>(&self, serializer: SE) -> Result<SE::Ok, SE::Error>
where
SE: Serializer,
{
serialize_fields! {
self -> serializer {
[redirect_uris]
[Option(response_types)]
[Option(grant_types)]
[Option(application_type)]
[Option(contacts)]
[LanguageTag(client_name)]
[LanguageTag(logo_uri)]
[LanguageTag(client_uri)]
[LanguageTag(policy_uri)]
[LanguageTag(tos_uri)]
[Option(jwks_uri)]
[Option(jwks)]
[Option(sector_identifier_uri)]
[Option(subject_type)]
[Option(id_token_signed_response_alg)]
[Option(id_token_encrypted_response_alg)]
[Option(id_token_encrypted_response_enc)]
[Option(userinfo_signed_response_alg)]
[Option(userinfo_encrypted_response_alg)]
[Option(userinfo_encrypted_response_enc)]
[Option(request_object_signing_alg)]
[Option(request_object_encryption_alg)]
[Option(request_object_encryption_enc)]
[Option(token_endpoint_auth_method)]
[Option(token_endpoint_auth_signing_alg)]
[Option(Seconds(default_max_age))]
[Option(require_auth_time)]
[Option(default_acr_values)]
[Option(initiate_login_uri)]
[Option(request_uris)]
}
}
}
}
/// Dynamic client registration request.
#[derive(Clone, Debug)]
pub struct ClientRegistrationRequest<AC, AR, AT, CA, ET, G, JE, JK, K, RT, S>
where
AC: AdditionalClientMetadata,
AR: AdditionalClientRegistrationResponse,
AT: ApplicationType,
CA: ClientAuthMethod,
ET: RegisterErrorResponseType,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
client_metadata: ClientMetadata<AC, AT, CA, G, JE, JK, K, RT, S>,
initial_access_token: Option<AccessToken>,
_phantom: PhantomData<(AR, ET)>,
}
impl<AC, AR, AT, CA, ET, G, JE, JK, K, RT, S>
ClientRegistrationRequest<AC, AR, AT, CA, ET, G, JE, JK, K, RT, S>
where
AC: AdditionalClientMetadata,
AR: AdditionalClientRegistrationResponse,
AT: ApplicationType,
CA: ClientAuthMethod,
ET: RegisterErrorResponseType + Send + Sync,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType + Send + Sync,
{
/// Instantiates a new dynamic client registration request.
pub fn new(redirect_uris: Vec<RedirectUrl>, additional_metadata: AC) -> Self {
Self {
client_metadata: ClientMetadata::new(redirect_uris, additional_metadata),
initial_access_token: None,
_phantom: PhantomData,
}
}
/// Submits this request to the specified registration endpoint using the specified synchronous
/// HTTP client.
pub fn register<C>(
&self,
registration_endpoint: &RegistrationUrl,
http_client: &C,
) -> Result<
ClientRegistrationResponse<AC, AR, AT, CA, G, JE, JK, K, RT, S>,
ClientRegistrationError<ET, <C as SyncHttpClient>::Error>,
>
where
C: SyncHttpClient,
{
self.prepare_registration(registration_endpoint)
.and_then(|http_request| {
http_client
.call(http_request)
.map_err(ClientRegistrationError::Request)
})
.and_then(Self::register_response)
}
/// Submits this request to the specified registration endpoint using the specified asynchronous
/// HTTP client.
pub fn register_async<'c, C>(
&'c self,
registration_endpoint: &'c RegistrationUrl,
http_client: &'c C,
) -> impl Future<
Output = Result<
ClientRegistrationResponse<AC, AR, AT, CA, G, JE, JK, K, RT, S>,
ClientRegistrationError<ET, <C as AsyncHttpClient<'c>>::Error>,
>,
> + 'c
where
Self: 'c,
C: AsyncHttpClient<'c>,
{
Box::pin(async move {
let http_request = self.prepare_registration(registration_endpoint)?;
let http_response = http_client
.call(http_request)
.await
.map_err(ClientRegistrationError::Request)?;
Self::register_response(http_response)
})
}
fn prepare_registration<RE>(
&self,
registration_endpoint: &RegistrationUrl,
) -> Result<HttpRequest, ClientRegistrationError<ET, RE>>
where
RE: std::error::Error + 'static,
{
let request_json = serde_json::to_string(self.client_metadata())
.map_err(ClientRegistrationError::Serialize)?
.into_bytes();
let auth_header_opt = self.initial_access_token().map(auth_bearer);
let mut request = http::Request::builder()
.uri(registration_endpoint.to_string())
.method(Method::POST)
.header(ACCEPT, HeaderValue::from_static(MIME_TYPE_JSON))
.header(CONTENT_TYPE, HeaderValue::from_static(MIME_TYPE_JSON));
if let Some((header, value)) = auth_header_opt {
request = request.header(header, value);
}
request.body(request_json).map_err(|err| {
ClientRegistrationError::Other(format!("failed to prepare request: {err}"))
})
}
fn register_response<RE>(
http_response: HttpResponse,
) -> Result<
ClientRegistrationResponse<AC, AR, AT, CA, G, JE, JK, K, RT, S>,
ClientRegistrationError<ET, RE>,
>
where
RE: std::error::Error + 'static,
{
// TODO: check for WWW-Authenticate response header if bearer auth was used (see
// https://tools.ietf.org/html/rfc6750#section-3)
// TODO: other necessary response validation? check spec
// Spec says that a successful response SHOULD use 201 Created, and a registration error
// condition returns (no "SHOULD") 400 Bad Request. For now, only accept these two status
// codes. We may need to relax the success status to improve interoperability.
if http_response.status() != StatusCode::CREATED
&& http_response.status() != StatusCode::BAD_REQUEST
{
return Err(ClientRegistrationError::Response(
http_response.status(),
http_response.body().to_owned(),
"unexpected HTTP status code".to_string(),
));
}
check_content_type(http_response.headers(), MIME_TYPE_JSON).map_err(|err_msg| {
ClientRegistrationError::Response(
http_response.status(),
http_response.body().to_owned(),
err_msg,
)
})?;
let response_body =
String::from_utf8(http_response.body().to_owned()).map_err(|parse_error| {
ClientRegistrationError::Other(format!(
"couldn't parse response as UTF-8: {parse_error}"
))
})?;
if http_response.status() == StatusCode::BAD_REQUEST {
let response_error: StandardErrorResponse<ET> = serde_path_to_error::deserialize(
&mut serde_json::Deserializer::from_str(&response_body),
)
.map_err(ClientRegistrationError::Parse)?;
return Err(ClientRegistrationError::ServerResponse(response_error));
}
serde_path_to_error::deserialize(&mut serde_json::Deserializer::from_str(&response_body))
.map_err(ClientRegistrationError::Parse)
}
/// Returns the client metadata associated with this registration request.
pub fn client_metadata(&self) -> &ClientMetadata<AC, AT, CA, G, JE, JK, K, RT, S> {
&self.client_metadata
}
/// Returns the initial access token associated with this registration request.
pub fn initial_access_token(&self) -> Option<&AccessToken> {
self.initial_access_token.as_ref()
}
/// Sets the initial access token for this request.
pub fn set_initial_access_token(mut self, access_token: Option<AccessToken>) -> Self {
self.initial_access_token = access_token;
self
}
field_getters_setters![
pub self [self.client_metadata.standard_metadata] ["client metadata value"] {
set_redirect_uris -> redirect_uris[Vec<RedirectUrl>],
set_response_types -> response_types[Option<Vec<ResponseTypes<RT>>>],
set_grant_types -> grant_types[Option<Vec<G>>],
set_application_type -> application_type[Option<AT>],
set_contacts -> contacts[Option<Vec<ClientContactEmail>>],
set_client_name -> client_name[Option<LocalizedClaim<ClientName>>],
set_logo_uri -> logo_uri[Option<LocalizedClaim<LogoUrl>>],
set_client_uri -> client_uri[Option<LocalizedClaim<ClientUrl>>],
set_policy_uri -> policy_uri[Option<LocalizedClaim<PolicyUrl>>],
set_tos_uri -> tos_uri[Option<LocalizedClaim<ToSUrl>>],
set_jwks_uri -> jwks_uri[Option<JsonWebKeySetUrl>],
set_jwks -> jwks[Option<JsonWebKeySet<K>>],
set_sector_identifier_uri -> sector_identifier_uri[Option<SectorIdentifierUrl>],
set_subject_type -> subject_type[Option<S>],
set_id_token_signed_response_alg -> id_token_signed_response_alg[Option<K::SigningAlgorithm>],
set_id_token_encrypted_response_alg -> id_token_encrypted_response_alg[Option<JK>],
set_id_token_encrypted_response_enc -> id_token_encrypted_response_enc[Option<JE>],
set_userinfo_signed_response_alg -> userinfo_signed_response_alg[Option<K::SigningAlgorithm>],
set_userinfo_encrypted_response_alg -> userinfo_encrypted_response_alg[Option<JK>],
set_userinfo_encrypted_response_enc -> userinfo_encrypted_response_enc[Option<JE>],
set_request_object_signing_alg -> request_object_signing_alg[Option<K::SigningAlgorithm>],
set_request_object_encryption_alg -> request_object_encryption_alg[Option<JK>],
set_request_object_encryption_enc -> request_object_encryption_enc[Option<JE>],
set_token_endpoint_auth_method -> token_endpoint_auth_method[Option<CA>],
set_token_endpoint_auth_signing_alg -> token_endpoint_auth_signing_alg[Option<K::SigningAlgorithm>],
set_default_max_age -> default_max_age[Option<Duration>],
set_require_auth_time -> require_auth_time[Option<bool>],
set_default_acr_values -> default_acr_values[Option<Vec<AuthenticationContextClass>>],
set_initiate_login_uri -> initiate_login_uri[Option<InitiateLoginUrl>],
set_request_uris -> request_uris[Option<Vec<RequestUrl>>],
}
];
/// Returns additional client metadata fields.
pub fn additional_metadata(&self) -> &AC {
&self.client_metadata.additional_metadata
}
/// Returns mutable additional client metadata fields.
pub fn additional_metadata_mut(&mut self) -> &mut AC {
&mut self.client_metadata.additional_metadata
}
}
/// Trait for adding extra fields to the [`ClientRegistrationResponse`].
pub trait AdditionalClientRegistrationResponse: Debug + DeserializeOwned + Serialize {}
// In order to support serde flatten, this must be an empty struct rather than an empty
// tuple struct.
/// Empty (default) extra [`ClientRegistrationResponse`] fields.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct EmptyAdditionalClientRegistrationResponse {}
impl AdditionalClientRegistrationResponse for EmptyAdditionalClientRegistrationResponse {}
/// Response to a dynamic client registration request.
#[serde_as]
#[skip_serializing_none]
#[derive(Debug, Deserialize, Serialize)]
pub struct ClientRegistrationResponse<AC, AR, AT, CA, G, JE, JK, K, RT, S>
where
AC: AdditionalClientMetadata,
AR: AdditionalClientRegistrationResponse,
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
client_id: ClientId,
client_secret: Option<ClientSecret>,
registration_access_token: Option<RegistrationAccessToken>,
registration_client_uri: Option<ClientConfigUrl>,
#[serde_as(as = "Option<Timestamp>")]
client_id_issued_at: Option<DateTime<Utc>>,
#[serde_as(as = "Option<Timestamp>")]
client_secret_expires_at: Option<DateTime<Utc>>,
#[serde(bound = "AC: AdditionalClientMetadata", flatten)]
client_metadata: ClientMetadata<AC, AT, CA, G, JE, JK, K, RT, S>,
#[serde(bound = "AR: AdditionalClientRegistrationResponse", flatten)]
additional_response: AR,
}
impl<AC, AR, AT, CA, G, JE, JK, K, RT, S>
ClientRegistrationResponse<AC, AR, AT, CA, G, JE, JK, K, RT, S>
where
AC: AdditionalClientMetadata,
AR: AdditionalClientRegistrationResponse,
AT: ApplicationType,
CA: ClientAuthMethod,
G: GrantType,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
JK: JweKeyManagementAlgorithm,
K: JsonWebKey,
RT: ResponseType,
S: SubjectIdentifierType,
{
/// Instantiates a new dynamic client registration response.
pub fn new(
client_id: ClientId,
redirect_uris: Vec<RedirectUrl>,
additional_metadata: AC,
additional_response: AR,
) -> Self {
Self {
client_id,
client_secret: None,
registration_access_token: None,
registration_client_uri: None,
client_id_issued_at: None,
client_secret_expires_at: None,
client_metadata: ClientMetadata::new(redirect_uris, additional_metadata),
additional_response,
}
}
/// Instantiates a new dynamic client registration response using the specified client metadata.
pub fn from_client_metadata(
client_id: ClientId,
client_metadata: ClientMetadata<AC, AT, CA, G, JE, JK, K, RT, S>,
additional_response: AR,
) -> Self {
Self {
client_id,
client_secret: None,
registration_access_token: None,
registration_client_uri: None,
client_id_issued_at: None,
client_secret_expires_at: None,
client_metadata,
additional_response,
}
}
field_getters_setters![
pub self [self] ["response field"] {
set_client_id -> client_id[ClientId],
set_client_secret -> client_secret[Option<ClientSecret>],
set_registration_access_token
-> registration_access_token[Option<RegistrationAccessToken>],
set_registration_client_uri -> registration_client_uri[Option<ClientConfigUrl>],
set_client_id_issued_at -> client_id_issued_at[Option<DateTime<Utc>>],
set_client_secret_expires_at -> client_secret_expires_at[Option<DateTime<Utc>>],
}
];
field_getters_setters![
pub self [self.client_metadata.standard_metadata] ["client metadata value"] {
set_redirect_uris -> redirect_uris[Vec<RedirectUrl>],
set_response_types -> response_types[Option<Vec<ResponseTypes<RT>>>],
set_grant_types -> grant_types[Option<Vec<G>>],
set_application_type -> application_type[Option<AT>],
set_contacts -> contacts[Option<Vec<ClientContactEmail>>],
set_client_name -> client_name[Option<LocalizedClaim<ClientName>>],
set_logo_uri -> logo_uri[Option<LocalizedClaim<LogoUrl>>],
set_client_uri -> client_uri[Option<LocalizedClaim<ClientUrl>>],
set_policy_uri -> policy_uri[Option<LocalizedClaim<PolicyUrl>>],
set_tos_uri -> tos_uri[Option<LocalizedClaim<ToSUrl>>],
set_jwks_uri -> jwks_uri[Option<JsonWebKeySetUrl>],
set_jwks -> jwks[Option<JsonWebKeySet<K>>],
set_sector_identifier_uri -> sector_identifier_uri[Option<SectorIdentifierUrl>],
set_subject_type -> subject_type[Option<S>],
set_id_token_signed_response_alg -> id_token_signed_response_alg[Option<K::SigningAlgorithm>],
set_id_token_encrypted_response_alg -> id_token_encrypted_response_alg[Option<JK>],
set_id_token_encrypted_response_enc -> id_token_encrypted_response_enc[Option<JE>],
set_userinfo_signed_response_alg -> userinfo_signed_response_alg[Option<K::SigningAlgorithm>],
set_userinfo_encrypted_response_alg -> userinfo_encrypted_response_alg[Option<JK>],
set_userinfo_encrypted_response_enc -> userinfo_encrypted_response_enc[Option<JE>],
set_request_object_signing_alg -> request_object_signing_alg[Option<K::SigningAlgorithm>],
set_request_object_encryption_alg -> request_object_encryption_alg[Option<JK>],
set_request_object_encryption_enc -> request_object_encryption_enc[Option<JE>],
set_token_endpoint_auth_method -> token_endpoint_auth_method[Option<CA>],
set_token_endpoint_auth_signing_alg -> token_endpoint_auth_signing_alg[Option<K::SigningAlgorithm>],
set_default_max_age -> default_max_age[Option<Duration>],
set_require_auth_time -> require_auth_time[Option<bool>],
set_default_acr_values -> default_acr_values[Option<Vec<AuthenticationContextClass>>],
set_initiate_login_uri -> initiate_login_uri[Option<InitiateLoginUrl>],
set_request_uris -> request_uris[Option<Vec<RequestUrl>>],
}
];
/// Returns additional client metadata fields.
pub fn additional_metadata(&self) -> &AC {
&self.client_metadata.additional_metadata
}
/// Returns mutable additional client metadata fields.
pub fn additional_metadata_mut(&mut self) -> &mut AC {
&mut self.client_metadata.additional_metadata
}
/// Returns additional response fields.
pub fn additional_response(&self) -> &AR {
&self.additional_response
}
/// Returns mutable additional response fields.
pub fn additional_response_mut(&mut self) -> &mut AR {
&mut self.additional_response
}
}
// TODO: implement client configuration endpoint request (Section 4)
/// Trait representing an error returned by the dynamic client registration endpoint.
pub trait RegisterErrorResponseType: ErrorResponseType + 'static {}
/// Error registering a client.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ClientRegistrationError<T, RE>
where
RE: std::error::Error + 'static,
T: RegisterErrorResponseType,
{
/// An unexpected error occurred.
#[error("Other error: {0}")]
Other(String),
/// Failed to parse server response.
#[error("Failed to parse server response")]
Parse(#[source] serde_path_to_error::Error<serde_json::Error>),
/// An error occurred while sending the request or receiving the response (e.g., network
/// connectivity failed).
#[error("Request failed")]
Request(#[source] RE),
/// Server returned an invalid response.
#[error("Server returned invalid response with status {0}: {2}")]
Response(StatusCode, Vec<u8>, String),
/// Failed to serialize client metadata.
#[error("Failed to serialize client metadata")]
Serialize(#[source] serde_json::Error),
/// Server returned an error.
#[error("Server returned error: {0}")]
ServerResponse(StandardErrorResponse<T>),
}
+643
View File
@@ -0,0 +1,643 @@
use crate::core::{
CoreApplicationType, CoreClientAuthMethod, CoreClientMetadata, CoreClientRegistrationResponse,
CoreGrantType, CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm,
CoreJwsSigningAlgorithm, CoreResponseType, CoreSubjectIdentifierType,
};
use crate::jwt::tests::TEST_RSA_PUB_KEY;
use crate::{
AuthenticationContextClass, ClientConfigUrl, ClientContactEmail, ClientName, ClientUrl,
JsonWebKeySet, JsonWebKeySetUrl, LanguageTag, LogoUrl, PolicyUrl, RequestUrl, ResponseTypes,
SectorIdentifierUrl, ToSUrl,
};
use crate::{ClientId, RedirectUrl};
use chrono::{TimeZone, Utc};
use itertools::sorted;
use std::time::Duration;
#[test]
fn test_metadata_serialization() {
// `jwks_uri` and `jwks` aren't supposed to be used together, but this test is just for
// serialization/deserialization.
let json_response = format!("{{
\"redirect_uris\": [\"https://example.com/redirect-1\", \"https://example.com/redirect-2\"],
\"response_types\": [\"code\", \"code token id_token\"],
\"grant_types\": [\"authorization_code\", \"client_credentials\", \"implicit\", \
\"password\", \"refresh_token\"],
\"application_type\": \"web\",
\"contacts\": [\"user@example.com\", \"admin@openidconnect.local\"],
\"client_name\": \"Example\",
\"client_name#es\": \"Ejemplo\",
\"logo_uri\": \"https://example.com/logo.png\",
\"logo_uri#fr\": \"https://example.com/logo-fr.png\",
\"client_uri\": \"https://example.com/client-app\",
\"client_uri#de\": \"https://example.com/client-app-de\",
\"policy_uri\": \"https://example.com/policy\",
\"policy_uri#sr-Latn\": \"https://example.com/policy-sr-latin\",
\"tos_uri\": \"https://example.com/tos\",
\"tos_uri#sr-Cyrl\": \"https://example.com/tos-sr-cyrl\",
\"jwks_uri\": \"https://example.com/jwks\",
\"jwks\": {{\"keys\": [{TEST_RSA_PUB_KEY}]}},
\"sector_identifier_uri\": \"https://example.com/sector\",
\"subject_type\": \"pairwise\",
\"id_token_signed_response_alg\": \"HS256\",
\"id_token_encrypted_response_alg\": \"RSA1_5\",
\"id_token_encrypted_response_enc\": \"A128CBC-HS256\",
\"userinfo_signed_response_alg\": \"RS384\",
\"userinfo_encrypted_response_alg\": \"RSA-OAEP\",
\"userinfo_encrypted_response_enc\": \"A256CBC-HS512\",
\"request_object_signing_alg\": \"ES512\",
\"request_object_encryption_alg\": \"ECDH-ES+A128KW\",
\"request_object_encryption_enc\": \"A256GCM\",
\"token_endpoint_auth_method\": \"client_secret_basic\",
\"token_endpoint_auth_signing_alg\": \"PS512\",
\"default_max_age\": 3600,
\"require_auth_time\": true,
\"default_acr_values\": [\"0\", \"urn:mace:incommon:iap:silver\", \
\"urn:mace:incommon:iap:bronze\"],
\"initiate_login_uri\": \"https://example.com/login\",
\"request_uris\": [\"https://example.com/request-1\", \"https://example.com/request-2\"]
}}");
let client_metadata: CoreClientMetadata = serde_json::from_str(&json_response).unwrap();
assert_eq!(
*client_metadata.redirect_uris(),
vec![
RedirectUrl::new("https://example.com/redirect-1".to_string()).unwrap(),
RedirectUrl::new("https://example.com/redirect-2".to_string()).unwrap(),
]
);
assert_eq!(
*client_metadata.response_types().unwrap(),
vec![
ResponseTypes::new(vec![CoreResponseType::Code]),
ResponseTypes::new(vec![
CoreResponseType::Code,
CoreResponseType::Token,
CoreResponseType::IdToken,
]),
]
);
assert_eq!(
client_metadata.grant_types().unwrap(),
&vec![
CoreGrantType::AuthorizationCode,
CoreGrantType::ClientCredentials,
CoreGrantType::Implicit,
CoreGrantType::Password,
CoreGrantType::RefreshToken,
]
);
assert_eq!(
*client_metadata.application_type().unwrap(),
CoreApplicationType::Web
);
assert_eq!(
*client_metadata.contacts().unwrap(),
vec![
ClientContactEmail::new("user@example.com".to_string()),
ClientContactEmail::new("admin@openidconnect.local".to_string()),
]
);
assert_eq!(
sorted(client_metadata.client_name().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, ClientName)>>(),
vec![
(None, ClientName::new("Example".to_string())),
(
Some(LanguageTag::new("es".to_string())),
ClientName::new("Ejemplo".to_string()),
),
]
);
assert_eq!(
sorted(client_metadata.logo_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, LogoUrl)>>(),
vec![
(
None,
LogoUrl::new("https://example.com/logo.png".to_string()).unwrap(),
),
(
Some(LanguageTag::new("fr".to_string())),
LogoUrl::new("https://example.com/logo-fr.png".to_string()).unwrap(),
),
]
);
assert_eq!(
sorted(client_metadata.client_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, ClientUrl)>>(),
vec![
(
None,
ClientUrl::new("https://example.com/client-app".to_string()).unwrap(),
),
(
Some(LanguageTag::new("de".to_string())),
ClientUrl::new("https://example.com/client-app-de".to_string()).unwrap(),
),
]
);
assert_eq!(
sorted(client_metadata.policy_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, PolicyUrl)>>(),
vec![
(
None,
PolicyUrl::new("https://example.com/policy".to_string()).unwrap(),
),
(
Some(LanguageTag::new("sr-Latn".to_string())),
PolicyUrl::new("https://example.com/policy-sr-latin".to_string()).unwrap(),
),
]
);
assert_eq!(
sorted(client_metadata.tos_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, ToSUrl)>>(),
vec![
(
None,
ToSUrl::new("https://example.com/tos".to_string()).unwrap(),
),
(
Some(LanguageTag::new("sr-Cyrl".to_string())),
ToSUrl::new("https://example.com/tos-sr-cyrl".to_string()).unwrap(),
),
]
);
assert_eq!(
*client_metadata.jwks_uri().unwrap(),
JsonWebKeySetUrl::new("https://example.com/jwks".to_string()).unwrap()
);
assert_eq!(
client_metadata.jwks(),
Some(&JsonWebKeySet::new(vec![serde_json::from_str(
TEST_RSA_PUB_KEY
)
.unwrap()],))
);
assert_eq!(
*client_metadata.sector_identifier_uri().unwrap(),
SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap()
);
assert_eq!(
*client_metadata.subject_type().unwrap(),
CoreSubjectIdentifierType::Pairwise
);
assert_eq!(
*client_metadata.id_token_signed_response_alg().unwrap(),
CoreJwsSigningAlgorithm::HmacSha256
);
assert_eq!(
*client_metadata.id_token_encrypted_response_alg().unwrap(),
CoreJweKeyManagementAlgorithm::RsaPkcs1V15
);
assert_eq!(
*client_metadata.id_token_encrypted_response_enc().unwrap(),
CoreJweContentEncryptionAlgorithm::Aes128CbcHmacSha256
);
assert_eq!(
*client_metadata.userinfo_signed_response_alg().unwrap(),
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha384
);
assert_eq!(
*client_metadata.userinfo_encrypted_response_alg().unwrap(),
CoreJweKeyManagementAlgorithm::RsaOaep
);
assert_eq!(
*client_metadata.userinfo_encrypted_response_enc().unwrap(),
CoreJweContentEncryptionAlgorithm::Aes256CbcHmacSha512
);
assert_eq!(
*client_metadata.request_object_signing_alg().unwrap(),
CoreJwsSigningAlgorithm::EcdsaP521Sha512
);
assert_eq!(
*client_metadata.request_object_encryption_alg().unwrap(),
CoreJweKeyManagementAlgorithm::EcdhEsAesKeyWrap128
);
assert_eq!(
*client_metadata.request_object_encryption_enc().unwrap(),
CoreJweContentEncryptionAlgorithm::Aes256Gcm
);
assert_eq!(
*client_metadata.token_endpoint_auth_method().unwrap(),
CoreClientAuthMethod::ClientSecretBasic
);
assert_eq!(
*client_metadata.token_endpoint_auth_signing_alg().unwrap(),
CoreJwsSigningAlgorithm::RsaSsaPssSha512
);
assert_eq!(
*client_metadata.default_max_age().unwrap(),
Duration::from_secs(3600)
);
assert!(client_metadata.require_auth_time().unwrap());
assert_eq!(
*client_metadata.default_acr_values().unwrap(),
vec![
AuthenticationContextClass::new("0".to_string()),
AuthenticationContextClass::new("urn:mace:incommon:iap:silver".to_string()),
AuthenticationContextClass::new("urn:mace:incommon:iap:bronze".to_string()),
]
);
assert_eq!(
*client_metadata.sector_identifier_uri().unwrap(),
SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap()
);
assert_eq!(
*client_metadata.request_uris().unwrap(),
vec![
RequestUrl::new("https://example.com/request-1".to_string()).unwrap(),
RequestUrl::new("https://example.com/request-2".to_string()).unwrap(),
]
);
let serialized_json = serde_json::to_string(&client_metadata).unwrap();
assert_eq!(
client_metadata,
serde_json::from_str(&serialized_json).unwrap()
);
}
#[test]
fn test_metadata_serialization_minimal() {
let json_response = "{\"redirect_uris\": [\"https://example.com/redirect-1\"]}";
let client_metadata: CoreClientMetadata = serde_json::from_str(json_response).unwrap();
assert_eq!(
*client_metadata.redirect_uris(),
vec![RedirectUrl::new("https://example.com/redirect-1".to_string()).unwrap(),]
);
assert_eq!(client_metadata.response_types(), None);
assert_eq!(client_metadata.grant_types(), None);
assert_eq!(client_metadata.application_type(), None);
assert_eq!(client_metadata.contacts(), None);
assert_eq!(client_metadata.client_name(), None);
assert_eq!(client_metadata.logo_uri(), None);
assert_eq!(client_metadata.client_uri(), None);
assert_eq!(client_metadata.policy_uri(), None);
assert_eq!(client_metadata.tos_uri(), None);
assert_eq!(client_metadata.jwks_uri(), None);
assert_eq!(client_metadata.jwks(), None);
assert_eq!(client_metadata.sector_identifier_uri(), None);
assert_eq!(client_metadata.subject_type(), None);
assert_eq!(client_metadata.id_token_signed_response_alg(), None);
assert_eq!(client_metadata.id_token_encrypted_response_alg(), None);
assert_eq!(client_metadata.id_token_encrypted_response_enc(), None);
assert_eq!(client_metadata.userinfo_signed_response_alg(), None);
assert_eq!(client_metadata.userinfo_encrypted_response_alg(), None);
assert_eq!(client_metadata.userinfo_encrypted_response_enc(), None);
assert_eq!(client_metadata.request_object_signing_alg(), None);
assert_eq!(client_metadata.request_object_encryption_alg(), None);
assert_eq!(client_metadata.request_object_encryption_enc(), None);
assert_eq!(client_metadata.token_endpoint_auth_method(), None);
assert_eq!(client_metadata.token_endpoint_auth_signing_alg(), None);
assert_eq!(client_metadata.default_max_age(), None);
assert_eq!(client_metadata.require_auth_time(), None);
assert_eq!(client_metadata.default_acr_values(), None);
assert_eq!(client_metadata.sector_identifier_uri(), None);
assert_eq!(client_metadata.request_uris(), None);
let serialized_json = serde_json::to_string(&client_metadata).unwrap();
assert_eq!(
client_metadata,
serde_json::from_str(&serialized_json).unwrap()
);
}
#[test]
fn test_response_serialization() {
let json_response = format!("{{
\"client_id\": \"abcdefgh\",
\"client_secret\": \"shhhh\",
\"registration_access_token\": \"use_me_to_update_registration\",
\"registration_client_uri\": \"https://example-provider.com/registration\",
\"client_id_issued_at\": 1523953306,
\"client_secret_expires_at\": 1526545306,
\"redirect_uris\": [\"https://example.com/redirect-1\", \"https://example.com/redirect-2\"],
\"response_types\": [\"code\", \"code token id_token\"],
\"grant_types\": [\"authorization_code\", \"client_credentials\", \"implicit\", \
\"password\", \"refresh_token\"],
\"application_type\": \"web\",
\"contacts\": [\"user@example.com\", \"admin@openidconnect.local\"],
\"client_name\": \"Example\",
\"client_name#es\": \"Ejemplo\",
\"logo_uri\": \"https://example.com/logo.png\",
\"logo_uri#fr\": \"https://example.com/logo-fr.png\",
\"client_uri\": \"https://example.com/client-app\",
\"client_uri#de\": \"https://example.com/client-app-de\",
\"policy_uri\": \"https://example.com/policy\",
\"policy_uri#sr-Latn\": \"https://example.com/policy-sr-latin\",
\"tos_uri\": \"https://example.com/tos\",
\"tos_uri#sr-Cyrl\": \"https://example.com/tos-sr-cyrl\",
\"jwks_uri\": \"https://example.com/jwks\",
\"jwks\": {{\"keys\": [{TEST_RSA_PUB_KEY}]}},
\"sector_identifier_uri\": \"https://example.com/sector\",
\"subject_type\": \"pairwise\",
\"id_token_signed_response_alg\": \"HS256\",
\"id_token_encrypted_response_alg\": \"RSA1_5\",
\"id_token_encrypted_response_enc\": \"A128CBC-HS256\",
\"userinfo_signed_response_alg\": \"RS384\",
\"userinfo_encrypted_response_alg\": \"RSA-OAEP\",
\"userinfo_encrypted_response_enc\": \"A256CBC-HS512\",
\"request_object_signing_alg\": \"ES512\",
\"request_object_encryption_alg\": \"ECDH-ES+A128KW\",
\"request_object_encryption_enc\": \"A256GCM\",
\"token_endpoint_auth_method\": \"client_secret_basic\",
\"token_endpoint_auth_signing_alg\": \"PS512\",
\"default_max_age\": 3600,
\"require_auth_time\": true,
\"default_acr_values\": [\"0\", \"urn:mace:incommon:iap:silver\", \
\"urn:mace:incommon:iap:bronze\"],
\"initiate_login_uri\": \"https://example.com/login\",
\"request_uris\": [\"https://example.com/request-1\", \"https://example.com/request-2\"]
}}");
let registration_response: CoreClientRegistrationResponse =
serde_json::from_str(&json_response).unwrap();
assert_eq!(
*registration_response.client_id(),
ClientId::new("abcdefgh".to_string())
);
assert_eq!(
*registration_response.client_secret().unwrap().secret(),
"shhhh"
);
assert_eq!(
*registration_response
.registration_access_token()
.unwrap()
.secret(),
"use_me_to_update_registration",
);
assert_eq!(
*registration_response.registration_client_uri().unwrap(),
ClientConfigUrl::new("https://example-provider.com/registration".to_string()).unwrap()
);
assert_eq!(
registration_response.client_id_issued_at().unwrap(),
Utc.timestamp_opt(1523953306, 0)
.single()
.expect("valid timestamp")
);
assert_eq!(
registration_response.client_secret_expires_at().unwrap(),
Utc.timestamp_opt(1526545306, 0)
.single()
.expect("valid timestamp")
);
assert_eq!(
*registration_response.redirect_uris(),
vec![
RedirectUrl::new("https://example.com/redirect-1".to_string()).unwrap(),
RedirectUrl::new("https://example.com/redirect-2".to_string()).unwrap(),
]
);
assert_eq!(
*registration_response.response_types().unwrap(),
vec![
ResponseTypes::new(vec![CoreResponseType::Code]),
ResponseTypes::new(vec![
CoreResponseType::Code,
CoreResponseType::Token,
CoreResponseType::IdToken,
]),
]
);
assert_eq!(
registration_response.grant_types().unwrap(),
&vec![
CoreGrantType::AuthorizationCode,
CoreGrantType::ClientCredentials,
CoreGrantType::Implicit,
CoreGrantType::Password,
CoreGrantType::RefreshToken,
]
);
assert_eq!(
*registration_response.application_type().unwrap(),
CoreApplicationType::Web
);
assert_eq!(
*registration_response.contacts().unwrap(),
vec![
ClientContactEmail::new("user@example.com".to_string()),
ClientContactEmail::new("admin@openidconnect.local".to_string()),
]
);
assert_eq!(
sorted(registration_response.client_name().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, ClientName)>>(),
vec![
(None, ClientName::new("Example".to_string())),
(
Some(LanguageTag::new("es".to_string())),
ClientName::new("Ejemplo".to_string()),
),
]
);
assert_eq!(
sorted(registration_response.logo_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, LogoUrl)>>(),
vec![
(
None,
LogoUrl::new("https://example.com/logo.png".to_string()).unwrap(),
),
(
Some(LanguageTag::new("fr".to_string())),
LogoUrl::new("https://example.com/logo-fr.png".to_string()).unwrap(),
),
]
);
assert_eq!(
sorted(registration_response.client_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, ClientUrl)>>(),
vec![
(
None,
ClientUrl::new("https://example.com/client-app".to_string()).unwrap(),
),
(
Some(LanguageTag::new("de".to_string())),
ClientUrl::new("https://example.com/client-app-de".to_string()).unwrap(),
),
]
);
assert_eq!(
sorted(registration_response.policy_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, PolicyUrl)>>(),
vec![
(
None,
PolicyUrl::new("https://example.com/policy".to_string()).unwrap(),
),
(
Some(LanguageTag::new("sr-Latn".to_string())),
PolicyUrl::new("https://example.com/policy-sr-latin".to_string()).unwrap(),
),
]
);
assert_eq!(
sorted(registration_response.tos_uri().unwrap().clone())
.collect::<Vec<(Option<LanguageTag>, ToSUrl)>>(),
vec![
(
None,
ToSUrl::new("https://example.com/tos".to_string()).unwrap(),
),
(
Some(LanguageTag::new("sr-Cyrl".to_string())),
ToSUrl::new("https://example.com/tos-sr-cyrl".to_string()).unwrap(),
),
]
);
assert_eq!(
*registration_response.jwks_uri().unwrap(),
JsonWebKeySetUrl::new("https://example.com/jwks".to_string()).unwrap()
);
assert_eq!(
registration_response.jwks(),
Some(&JsonWebKeySet::new(vec![serde_json::from_str(
TEST_RSA_PUB_KEY
)
.unwrap()],)),
);
assert_eq!(
*registration_response.sector_identifier_uri().unwrap(),
SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap()
);
assert_eq!(
*registration_response.subject_type().unwrap(),
CoreSubjectIdentifierType::Pairwise
);
assert_eq!(
*registration_response
.id_token_signed_response_alg()
.unwrap(),
CoreJwsSigningAlgorithm::HmacSha256
);
assert_eq!(
*registration_response
.id_token_encrypted_response_alg()
.unwrap(),
CoreJweKeyManagementAlgorithm::RsaPkcs1V15
);
assert_eq!(
*registration_response
.id_token_encrypted_response_enc()
.unwrap(),
CoreJweContentEncryptionAlgorithm::Aes128CbcHmacSha256
);
assert_eq!(
*registration_response
.userinfo_signed_response_alg()
.unwrap(),
CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha384
);
assert_eq!(
*registration_response
.userinfo_encrypted_response_alg()
.unwrap(),
CoreJweKeyManagementAlgorithm::RsaOaep
);
assert_eq!(
*registration_response
.userinfo_encrypted_response_enc()
.unwrap(),
CoreJweContentEncryptionAlgorithm::Aes256CbcHmacSha512
);
assert_eq!(
*registration_response.request_object_signing_alg().unwrap(),
CoreJwsSigningAlgorithm::EcdsaP521Sha512
);
assert_eq!(
*registration_response
.request_object_encryption_alg()
.unwrap(),
CoreJweKeyManagementAlgorithm::EcdhEsAesKeyWrap128
);
assert_eq!(
*registration_response
.request_object_encryption_enc()
.unwrap(),
CoreJweContentEncryptionAlgorithm::Aes256Gcm
);
assert_eq!(
*registration_response.token_endpoint_auth_method().unwrap(),
CoreClientAuthMethod::ClientSecretBasic
);
assert_eq!(
*registration_response
.token_endpoint_auth_signing_alg()
.unwrap(),
CoreJwsSigningAlgorithm::RsaSsaPssSha512
);
assert_eq!(
*registration_response.default_max_age().unwrap(),
Duration::from_secs(3600)
);
assert!(registration_response.require_auth_time().unwrap());
assert_eq!(
*registration_response.default_acr_values().unwrap(),
vec![
AuthenticationContextClass::new("0".to_string()),
AuthenticationContextClass::new("urn:mace:incommon:iap:silver".to_string()),
AuthenticationContextClass::new("urn:mace:incommon:iap:bronze".to_string()),
]
);
assert_eq!(
*registration_response.sector_identifier_uri().unwrap(),
SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap()
);
assert_eq!(
*registration_response.request_uris().unwrap(),
vec![
RequestUrl::new("https://example.com/request-1".to_string()).unwrap(),
RequestUrl::new("https://example.com/request-2".to_string()).unwrap(),
]
);
let serialized_json = serde_json::to_string(&registration_response).unwrap();
let deserialized: CoreClientRegistrationResponse =
serde_json::from_str(&serialized_json).unwrap();
assert_eq!(registration_response.client_id, deserialized.client_id);
assert_eq!(
registration_response.client_secret.unwrap().secret(),
deserialized.client_secret.unwrap().secret(),
);
assert_eq!(
registration_response
.registration_access_token
.unwrap()
.secret(),
deserialized.registration_access_token.unwrap().secret(),
);
assert_eq!(
registration_response.registration_client_uri,
deserialized.registration_client_uri,
);
assert_eq!(
registration_response.client_id_issued_at,
deserialized.client_id_issued_at,
);
assert_eq!(
registration_response.client_secret_expires_at,
deserialized.client_secret_expires_at,
);
assert_eq!(
registration_response.client_metadata,
deserialized.client_metadata,
);
assert_eq!(
registration_response.additional_response,
deserialized.additional_response,
);
}
+35
View File
@@ -0,0 +1,35 @@
use crate::{
AdditionalClaims, ExtraTokenFields, GenderClaim, IdToken, IdTokenFields,
JweContentEncryptionAlgorithm, JwsSigningAlgorithm, OAuth2TokenResponse, StandardTokenResponse,
TokenType,
};
/// Extends the base OAuth2 token response with an ID token.
pub trait TokenResponse<AC, GC, JE, JS>: OAuth2TokenResponse
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
/// Returns the ID token provided by the token response.
///
/// OpenID Connect authorization servers should always return this field, but it is optional
/// to allow for interoperability with authorization servers that only support OAuth2.
fn id_token(&self) -> Option<&IdToken<AC, GC, JE, JS>>;
}
impl<AC, EF, GC, JE, JS, TT> TokenResponse<AC, GC, JE, JS>
for StandardTokenResponse<IdTokenFields<AC, EF, GC, JE, JS>, TT>
where
AC: AdditionalClaims,
EF: ExtraTokenFields,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
TT: TokenType,
{
fn id_token(&self) -> Option<&IdToken<AC, GC, JE, JS>> {
self.extra_fields().id_token()
}
}
+144
View File
@@ -0,0 +1,144 @@
use crate::{SignatureVerificationError, SigningError};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::hash::Hash;
new_type![
/// ID of a JSON Web Key.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
JsonWebKeyId(String)
];
/// JSON Web Key.
pub trait JsonWebKey: Clone + Debug + DeserializeOwned + Serialize + 'static {
/// Allowed key usage.
type KeyUse: JsonWebKeyUse;
/// JSON Web Signature (JWS) algorithm.
type SigningAlgorithm: JwsSigningAlgorithm;
/// Returns the key ID, or `None` if no key ID is specified.
fn key_id(&self) -> Option<&JsonWebKeyId>;
/// Returns the key type (e.g., RSA).
fn key_type(&self) -> &<Self::SigningAlgorithm as JwsSigningAlgorithm>::KeyType;
/// Returns the allowed key usage (e.g., signing or encryption), or `None` if no usage is
/// specified.
fn key_use(&self) -> Option<&Self::KeyUse>;
/// Returns the algorithm (e.g. ES512) this key must be used with, or `Unspecified` if
/// no algorithm constraint was given, or unsupported if the algorithm is not for signing.
///
/// It's not sufficient to tell whether a key can be used for signing, as key use also has to be validated.
fn signing_alg(&self) -> JsonWebKeyAlgorithm<&Self::SigningAlgorithm>;
/// Initializes a new symmetric key or shared signing secret from the specified raw bytes.
fn new_symmetric(key: Vec<u8>) -> Self;
/// Verifies the given `signature` using the given signature algorithm (`signature_alg`) over
/// the given `message`.
///
/// Returns `Ok` if the signature is valid, or an `Err` otherwise.
fn verify_signature(
&self,
signature_alg: &Self::SigningAlgorithm,
message: &[u8],
signature: &[u8],
) -> Result<(), SignatureVerificationError>;
/// Hashes the given `bytes` using the hash function associated with the specified signing
/// algorithm and returns the hashed bytes.
///
/// Certain signing algorithms (e.g., `EdDSA`) use different hash functions depending on the
/// type of key (e.g., whether the `Ed25519` or `Ed448` curve is used), so this method is
/// implemented on the corresponding public key instead of the [`JwsSigningAlgorithm`] trait
/// to allow the implementation to determine the proper hash function to use.
/// If hashing fails or this key/signing algorithm does not have an associated hash function, an
/// `Err` is returned with a string describing the cause of the error. An error is also returned
/// if the specified signature algorithm is incompatible with this key (e.g., passing `EdDSA`
/// with an RSA key).
fn hash_bytes(&self, bytes: &[u8], alg: &Self::SigningAlgorithm) -> Result<Vec<u8>, String>;
}
/// Encodes a JWK key's alg field compatibility with either signing or encryption operations.
#[derive(Debug)]
pub enum JsonWebKeyAlgorithm<A: Debug> {
/// the alg field allows this kind of operation to be performed with this algorithm only
Algorithm(A),
/// there is no alg field
Unspecified,
/// the alg field's algorithm is incompatible with this kind of operation
Unsupported,
}
/// Private or symmetric key for signing.
pub trait PrivateSigningKey {
/// Corresponding type of JSON Web Key used for verifying signatures produced by this key.
type VerificationKey: JsonWebKey;
/// Signs the given `message` using the given signature algorithm.
fn sign(
&self,
signature_alg: &<Self::VerificationKey as JsonWebKey>::SigningAlgorithm,
message: &[u8],
) -> Result<Vec<u8>, SigningError>;
/// Converts this key to a JSON Web Key that can be used for verifying signatures.
fn as_verification_key(&self) -> Self::VerificationKey;
}
/// Key type (e.g., RSA).
pub trait JsonWebKeyType:
Clone + Debug + DeserializeOwned + PartialEq + Serialize + 'static
{
}
/// Allowed key usage.
pub trait JsonWebKeyUse: Debug + DeserializeOwned + Serialize + 'static {
/// Returns true if the associated key may be used for digital signatures, or false otherwise.
fn allows_signature(&self) -> bool;
/// Returns true if the associated key may be used for encryption, or false otherwise.
fn allows_encryption(&self) -> bool;
}
/// JSON Web Encryption (JWE) content encryption algorithm.
pub trait JweContentEncryptionAlgorithm:
Clone + Debug + DeserializeOwned + Serialize + 'static
{
/// Key type (e.g., RSA).
type KeyType: JsonWebKeyType;
/// Returns the type of key required to use this encryption algorithm.
fn key_type(&self) -> Result<Self::KeyType, String>;
}
/// JSON Web Encryption (JWE) key management algorithm.
pub trait JweKeyManagementAlgorithm: Debug + DeserializeOwned + Serialize + 'static {
// TODO: add a key_type() method
}
/// JSON Web Signature (JWS) algorithm.
pub trait JwsSigningAlgorithm:
Clone + Debug + DeserializeOwned + Eq + Hash + PartialEq + Serialize + 'static
{
/// Key type (e.g., RSA).
type KeyType: JsonWebKeyType;
/// Returns the type of key required to use this signature algorithm, or `None` if this
/// algorithm does not require a key.
fn key_type(&self) -> Option<Self::KeyType>;
/// Returns true if the signature algorithm uses a shared secret (symmetric key).
fn uses_shared_secret(&self) -> bool;
/// Returns the RS256 algorithm.
///
/// This is the default algorithm for OpenID Connect ID tokens and must be supported by all
/// implementations.
fn rsa_sha_256() -> Self;
}
+190
View File
@@ -0,0 +1,190 @@
use crate::http_utils::{check_content_type, MIME_TYPE_JSON, MIME_TYPE_JWKS};
use crate::types::jwk::{JsonWebKey, JsonWebKeyId, JwsSigningAlgorithm};
use crate::{
AsyncHttpClient, DiscoveryError, HttpRequest, HttpResponse, JsonWebKeyUse, SyncHttpClient,
};
use http::header::ACCEPT;
use http::{HeaderValue, Method, StatusCode};
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, VecSkipError};
use std::future::Future;
new_url_type![
/// JSON Web Key Set URL.
JsonWebKeySetUrl
];
/// JSON Web Key Set.
#[serde_as]
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct JsonWebKeySet<K>
where
K: JsonWebKey,
{
// FIXME: write a test that ensures duplicate object member names cause an error
// (see https://tools.ietf.org/html/rfc7517#section-5)
#[serde(bound = "K: JsonWebKey")]
// Ignores invalid keys rather than failing. That way, clients can function using the keys that
// they do understand, which is fine if they only ever get JWTs signed with those keys.
#[serde_as(as = "VecSkipError<_>")]
keys: Vec<K>,
}
/// Checks whether a JWK key can be used with a given signing algorithm.
pub(crate) fn check_key_compatibility<K>(
key: &K,
signing_algorithm: &K::SigningAlgorithm,
) -> Result<(), &'static str>
where
K: JsonWebKey,
{
// if this key isn't suitable for signing
if let Some(use_) = key.key_use() {
if !use_.allows_signature() {
return Err("key usage not permitted for digital signatures");
}
}
// if this key doesn't have the right key type
if signing_algorithm.key_type().as_ref() != Some(key.key_type()) {
return Err("key type does not match signature algorithm");
}
match key.signing_alg() {
// if no specific algorithm is mandated, any will do
crate::JsonWebKeyAlgorithm::Unspecified => Ok(()),
crate::JsonWebKeyAlgorithm::Unsupported => Err("key algorithm is not a signing algorithm"),
crate::JsonWebKeyAlgorithm::Algorithm(key_alg) if key_alg == signing_algorithm => Ok(()),
crate::JsonWebKeyAlgorithm::Algorithm(_) => Err("incompatible key algorithm"),
}
}
impl<K> JsonWebKeySet<K>
where
K: JsonWebKey,
{
/// Create a new JSON Web Key Set.
pub fn new(keys: Vec<K>) -> Self {
Self { keys }
}
/// Return a list of suitable keys, given a key ID and signature algorithm
pub(crate) fn filter_keys(
&self,
key_id: Option<&JsonWebKeyId>,
signature_alg: &K::SigningAlgorithm,
) -> Vec<&K> {
self.keys()
.iter()
.filter(|key|
// Either the JWT doesn't include a 'kid' (in which case any 'kid'
// is acceptable), or the 'kid' matches the key's ID.
if key_id.is_some() && key_id != key.key_id() {
false
} else {
check_key_compatibility(*key, signature_alg).is_ok()
}
)
.collect()
}
/// Fetch a remote JSON Web Key Set from the specified `url` using the given `http_client`
/// (e.g., [`reqwest::blocking::Client`](crate::reqwest::blocking::Client) or
/// [`CurlHttpClient`](crate::CurlHttpClient)).
pub fn fetch<C>(
url: &JsonWebKeySetUrl,
http_client: &C,
) -> Result<Self, DiscoveryError<<C as SyncHttpClient>::Error>>
where
C: SyncHttpClient,
{
http_client
.call(Self::fetch_request(url).map_err(|err| {
DiscoveryError::Other(format!("failed to prepare request: {err}"))
})?)
.map_err(DiscoveryError::Request)
.and_then(Self::fetch_response)
}
/// Fetch a remote JSON Web Key Set from the specified `url` using the given async `http_client`
/// (e.g., [`reqwest::Client`](crate::reqwest::Client)).
pub fn fetch_async<'c, C>(
url: &JsonWebKeySetUrl,
http_client: &'c C,
) -> impl Future<Output = Result<Self, DiscoveryError<<C as AsyncHttpClient<'c>>::Error>>> + 'c
where
Self: 'c,
C: AsyncHttpClient<'c>,
{
let fetch_request = Self::fetch_request(url)
.map_err(|err| DiscoveryError::Other(format!("failed to prepare request: {err}")));
Box::pin(async move {
http_client
.call(fetch_request?)
.await
.map_err(DiscoveryError::Request)
.and_then(Self::fetch_response)
})
}
fn fetch_request(url: &JsonWebKeySetUrl) -> Result<HttpRequest, http::Error> {
http::Request::builder()
.uri(url.to_string())
.method(Method::GET)
.header(ACCEPT, HeaderValue::from_static(MIME_TYPE_JSON))
.body(Vec::new())
}
fn fetch_response<RE>(http_response: HttpResponse) -> Result<Self, DiscoveryError<RE>>
where
RE: std::error::Error + 'static,
{
if http_response.status() != StatusCode::OK {
return Err(DiscoveryError::Response(
http_response.status(),
http_response.body().to_owned(),
format!("HTTP status code {}", http_response.status()),
));
}
check_content_type(http_response.headers(), MIME_TYPE_JSON)
.or_else(|err| {
check_content_type(http_response.headers(), MIME_TYPE_JWKS).map_err(|_| err)
})
.map_err(|err_msg| {
DiscoveryError::Response(
http_response.status(),
http_response.body().to_owned(),
err_msg,
)
})?;
serde_path_to_error::deserialize(&mut serde_json::Deserializer::from_slice(
http_response.body(),
))
.map_err(DiscoveryError::Parse)
}
/// Return the keys in this JSON Web Key Set.
pub fn keys(&self) -> &Vec<K> {
&self.keys
}
}
impl<K> Clone for JsonWebKeySet<K>
where
K: JsonWebKey,
{
fn clone(&self) -> Self {
Self::new(self.keys.clone())
}
}
impl<K> Default for JsonWebKeySet<K>
where
K: JsonWebKey,
{
fn default() -> Self {
Self::new(Vec::new())
}
}
+179
View File
@@ -0,0 +1,179 @@
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Display;
new_type![
/// Language tag adhering to RFC 5646 (e.g., `fr` or `fr-CA`).
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
LanguageTag(String)
];
impl AsRef<str> for LanguageTag {
fn as_ref(&self) -> &str {
self
}
}
impl Display for LanguageTag {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "{}", self.as_ref())
}
}
pub(crate) fn split_language_tag_key(key: &str) -> (&str, Option<LanguageTag>) {
let mut lang_tag_sep = key.splitn(2, '#');
// String::splitn(2) always returns at least one element.
let field_name = lang_tag_sep.next().unwrap();
let language_tag = lang_tag_sep
.next()
.filter(|language_tag| !language_tag.is_empty())
.map(|language_tag| LanguageTag::new(language_tag.to_string()));
(field_name, language_tag)
}
pub(crate) fn join_language_tag_key<'a>(
field_name: &'a str,
language_tag: Option<&LanguageTag>,
) -> Cow<'a, str> {
if let Some(language_tag) = language_tag {
Cow::Owned(format!("{field_name}#{language_tag}"))
} else {
Cow::Borrowed(field_name)
}
}
/// A [locale-aware](https://openid.net/specs/openid-connect-core-1_0.html#IndividualClaimsLanguages)
/// claim.
///
/// This structure associates one more `Option<LanguageTag>` locales with the corresponding
/// claims values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LocalizedClaim<T>(HashMap<LanguageTag, T>, Option<T>);
impl<T> LocalizedClaim<T> {
/// Initialize an empty claim.
pub fn new() -> Self {
Self::default()
}
/// Returns true if the claim contains a value for the specified locale.
pub fn contains_key(&self, locale: Option<&LanguageTag>) -> bool {
if let Some(l) = locale {
self.0.contains_key(l)
} else {
self.1.is_some()
}
}
/// Returns the entry for the specified locale or `None` if there is no such entry.
pub fn get(&self, locale: Option<&LanguageTag>) -> Option<&T> {
if let Some(l) = locale {
self.0.get(l)
} else {
self.1.as_ref()
}
}
/// Returns an iterator over the locales and claim value entries.
pub fn iter(&self) -> impl Iterator<Item = (Option<&LanguageTag>, &T)> {
self.1
.iter()
.map(|value| (None, value))
.chain(self.0.iter().map(|(locale, value)| (Some(locale), value)))
}
/// Inserts or updates an entry for the specified locale.
///
/// Returns the current value associated with the given locale, or `None` if there is no
/// such entry.
pub fn insert(&mut self, locale: Option<LanguageTag>, value: T) -> Option<T> {
if let Some(l) = locale {
self.0.insert(l, value)
} else {
self.1.replace(value)
}
}
/// Removes an entry for the specified locale.
///
/// Returns the current value associated with the given locale, or `None` if there is no
/// such entry.
pub fn remove(&mut self, locale: Option<&LanguageTag>) -> Option<T> {
if let Some(l) = locale {
self.0.remove(l)
} else {
self.1.take()
}
}
}
impl<T> LocalizedClaim<Option<T>> {
pub(crate) fn flatten_or_none(self) -> Option<LocalizedClaim<T>> {
let flattened_tagged = self
.0
.into_iter()
.filter_map(|(k, v)| v.map(|v| (k, v)))
.collect::<HashMap<_, _>>();
let flattened_default = self.1.flatten();
if flattened_tagged.is_empty() && flattened_default.is_none() {
None
} else {
Some(LocalizedClaim(flattened_tagged, flattened_default))
}
}
}
impl<T> Default for LocalizedClaim<T> {
fn default() -> Self {
Self(HashMap::new(), None)
}
}
impl<T> From<T> for LocalizedClaim<T> {
fn from(default: T) -> Self {
Self(HashMap::new(), Some(default))
}
}
impl<T> FromIterator<(Option<LanguageTag>, T)> for LocalizedClaim<T> {
fn from_iter<I: IntoIterator<Item = (Option<LanguageTag>, T)>>(iter: I) -> Self {
let mut temp: HashMap<Option<LanguageTag>, T> = iter.into_iter().collect();
let default = temp.remove(&None);
Self(
temp.into_iter()
.filter_map(|(locale, value)| locale.map(|l| (l, value)))
.collect(),
default,
)
}
}
impl<T> IntoIterator for LocalizedClaim<T>
where
T: 'static,
{
type Item = <LocalizedClaimIterator<T> as Iterator>::Item;
type IntoIter = LocalizedClaimIterator<T>;
fn into_iter(self) -> Self::IntoIter {
LocalizedClaimIterator {
inner: Box::new(
self.1.into_iter().map(|value| (None, value)).chain(
self.0
.into_iter()
.map(|(locale, value)| (Some(locale), value)),
),
),
}
}
}
/// Owned iterator over a LocalizedClaim.
pub struct LocalizedClaimIterator<T> {
inner: Box<dyn Iterator<Item = (Option<LanguageTag>, T)>>,
}
impl<T> Iterator for LocalizedClaimIterator<T> {
type Item = (Option<LanguageTag>, T);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
+455
View File
@@ -0,0 +1,455 @@
use crate::types::jwk::JsonWebKey;
use crate::{AccessToken, AuthorizationCode};
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use base64::Engine;
use oauth2::helpers::deserialize_space_delimited_vec;
use rand::{thread_rng, Rng};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use url::Url;
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Deref;
pub(crate) mod jwk;
pub(crate) mod jwks;
pub(crate) mod localized;
#[cfg(test)]
mod tests;
/// Client application type.
pub trait ApplicationType: Debug + DeserializeOwned + Serialize + 'static {}
/// How the Authorization Server displays the authentication and consent user interface pages to
/// the End-User.
pub trait AuthDisplay: AsRef<str> + Debug + DeserializeOwned + Serialize + 'static {}
/// Whether the Authorization Server should prompt the End-User for reauthentication and consent.
pub trait AuthPrompt: AsRef<str> + 'static {}
/// Claim name.
pub trait ClaimName: Debug + DeserializeOwned + Serialize + 'static {}
/// Claim type (e.g., normal, aggregated, or distributed).
pub trait ClaimType: Debug + DeserializeOwned + Serialize + 'static {}
/// Client authentication method.
pub trait ClientAuthMethod: Debug + DeserializeOwned + Serialize + 'static {}
/// Grant type.
pub trait GrantType: Debug + DeserializeOwned + Serialize + 'static {}
/// Error signing a message.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum SigningError {
/// Failed to sign the message using the given key and parameters.
#[error("Crypto error")]
CryptoError,
/// Unsupported signature algorithm.
#[error("Unsupported signature algorithm: {0}")]
UnsupportedAlg(String),
/// An unexpected error occurred.
#[error("Other error: {0}")]
Other(String),
}
/// Response mode indicating how the OpenID Connect Provider should return the Authorization
/// Response to the Relying Party (client).
pub trait ResponseMode: Debug + DeserializeOwned + Serialize + 'static {}
/// Response type indicating the desired authorization processing flow, including what
/// parameters are returned from the endpoints used.
pub trait ResponseType: AsRef<str> + Debug + DeserializeOwned + Serialize + 'static {
/// Converts this OpenID Connect response type to an [`oauth2::ResponseType`] used by the
/// underlying [`oauth2`] crate.
fn to_oauth2(&self) -> oauth2::ResponseType;
}
/// Subject identifier type returned by an OpenID Connect Provider to uniquely identify its users.
pub trait SubjectIdentifierType: Debug + DeserializeOwned + Serialize + 'static {}
new_type![
/// Set of authentication methods or procedures that are considered to be equivalent to each
/// other in a particular context.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AuthenticationContextClass(String)
];
impl AsRef<str> for AuthenticationContextClass {
fn as_ref(&self) -> &str {
self
}
}
new_type![
/// Identifier for an authentication method (e.g., `password` or `totp`).
///
/// Defining specific AMR identifiers is beyond the scope of the OpenID Connect Core spec.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AuthenticationMethodReference(String)
];
new_type![
/// Access token hash.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AccessTokenHash(String)
impl {
/// Initialize a new access token hash from an [`AccessToken`] and signature algorithm.
pub fn from_token<K>(
access_token: &AccessToken,
alg: &K::SigningAlgorithm,
key: &K,
) -> Result<Self, SigningError>
where
K: JsonWebKey,
{
key.hash_bytes(access_token.secret().as_bytes(), alg)
.map(|hash| Self::new(BASE64_URL_SAFE_NO_PAD.encode(&hash[0..hash.len() / 2])))
.map_err(SigningError::UnsupportedAlg)
}
}
];
new_type![
/// Country portion of address.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AddressCountry(String)
];
new_type![
/// Locality portion of address.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AddressLocality(String)
];
new_type![
/// Postal code portion of address.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AddressPostalCode(String)
];
new_type![
/// Region portion of address.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AddressRegion(String)
];
new_type![
/// Audience claim value.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
Audience(String)
];
new_type![
/// Authorization code hash.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
AuthorizationCodeHash(String)
impl {
/// Initialize a new authorization code hash from an [`AuthorizationCode`] and signature
/// algorithm.
pub fn from_code<K>(
code: &AuthorizationCode,
alg: &K::SigningAlgorithm,
key: &K,
) -> Result<Self, SigningError>
where
K: JsonWebKey,
{
key.hash_bytes(code.secret().as_bytes(), alg)
.map(|hash| Self::new(BASE64_URL_SAFE_NO_PAD.encode(&hash[0..hash.len() / 2])))
.map_err(SigningError::UnsupportedAlg)
}
}
];
new_type![
/// OpenID Connect client name.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
ClientName(String)
];
new_url_type![
/// Client configuration endpoint URL.
ClientConfigUrl
];
new_url_type![
/// Client homepage URL.
ClientUrl
];
new_type![
/// Client contact e-mail address.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
ClientContactEmail(String)
];
new_url_type![
/// URL for the [OpenID Connect RP-Initiated Logout 1.0](
/// https://openid.net/specs/openid-connect-rpinitiated-1_0.html) end session endpoint.
EndSessionUrl
];
new_type![
/// End user's birthday, represented as an
/// [ISO 8601:2004](https://www.iso.org/standard/40874.html) `YYYY-MM-DD` format.
///
/// The year MAY be `0000`, indicating that it is omitted. To represent only the year, `YYYY`
/// format is allowed. Note that depending on the underlying platform's date related function,
/// providing just year can result in varying month and day, so the implementers need to take
/// this factor into account to correctly process the dates.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserBirthday(String)
];
new_type![
/// End user's e-mail address.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserEmail(String)
];
new_type![
/// End user's family name.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserFamilyName(String)
];
new_type![
/// End user's given name.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserGivenName(String)
];
new_type![
/// End user's middle name.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserMiddleName(String)
];
new_type![
/// End user's name.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserName(String)
];
new_type![
/// End user's nickname.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserNickname(String)
];
new_type![
/// End user's phone number.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserPhoneNumber(String)
];
new_type![
/// URL of end user's profile picture.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserPictureUrl(String)
];
new_type![
/// URL of end user's profile page.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserProfileUrl(String)
];
new_type![
/// End user's time zone as a string from the
/// [time zone database](https://www.iana.org/time-zones).
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserTimezone(String)
];
new_type![
/// URL of end user's website.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserWebsiteUrl(String)
];
new_type![
/// End user's username.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
EndUserUsername(String)
];
new_type![
/// Full mailing address, formatted for display or use on a mailing label.
///
/// This field MAY contain multiple lines, separated by newlines. Newlines can be represented
/// either as a carriage return/line feed pair (`"\r\n"`) or as a single line feed character
/// (`"\n"`).
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
FormattedAddress(String)
];
new_url_type![
/// URI using the `https` scheme that a third party can use to initiate a login by the Relying
/// Party.
InitiateLoginUrl
];
new_url_type![
/// URL using the `https` scheme with no query or fragment component that the OP asserts as its
/// Issuer Identifier.
IssuerUrl
impl {
/// Parse a string as a URL, with this URL as the base URL.
///
/// See [`Url::parse`].
pub fn join(&self, suffix: &str) -> Result<Url, url::ParseError> {
if let Some('/') = self.1.chars().next_back() {
Url::parse(&(self.1.clone() + suffix))
} else {
Url::parse(&(self.1.clone() + "/" + suffix))
}
}
}
];
new_secret_type![
/// Hint about the login identifier the End-User might use to log in.
///
/// The use of this parameter is left to the OpenID Connect Provider's discretion.
#[derive(Clone, Deserialize, Serialize)]
LoginHint(String)
];
new_secret_type![
/// Hint about the logout identifier the End-User might use to log out.
///
/// The use of this parameter is left to the OpenID Connect Provider's discretion.
#[derive(Clone, Deserialize, Serialize)]
LogoutHint(String)
];
new_url_type![
/// URL that references a logo for the Client application.
LogoUrl
];
new_secret_type![
/// String value used to associate a client session with an ID Token, and to mitigate replay
/// attacks.
#[derive(Clone, Deserialize, Serialize)]
Nonce(String)
impl {
/// Generate a new random, base64-encoded 128-bit nonce.
pub fn new_random() -> Self {
Nonce::new_random_len(16)
}
/// Generate a new random, base64-encoded nonce of the specified length.
///
/// # Arguments
///
/// * `num_bytes` - Number of random bytes to generate, prior to base64-encoding.
pub fn new_random_len(num_bytes: u32) -> Self {
let random_bytes: Vec<u8> = (0..num_bytes).map(|_| thread_rng().gen::<u8>()).collect();
Nonce::new(BASE64_URL_SAFE_NO_PAD.encode(random_bytes))
}
}
];
new_url_type![
/// URL providing the OpenID Connect Provider's data usage policies for client applications.
OpPolicyUrl
];
new_url_type![
/// URL providing the OpenID Connect Provider's Terms of Service.
OpTosUrl
];
new_url_type![
/// URL providing a client application's data usage policy.
PolicyUrl
];
new_url_type![
/// The post logout redirect URL, which should be passed to the end session endpoint
/// of providers implementing [OpenID Connect RP-Initiated Logout 1.0](
/// https://openid.net/specs/openid-connect-rpinitiated-1_0.html).
PostLogoutRedirectUrl
];
new_secret_type![
/// Access token used by a client application to access the Client Registration endpoint.
#[derive(Clone, Deserialize, Serialize)]
RegistrationAccessToken(String)
];
new_url_type![
/// URL of the Client Registration endpoint.
RegistrationUrl
];
new_url_type![
/// URL used to pass request parameters as JWTs by reference.
RequestUrl
];
/// Informs the Authorization Server of the desired authorization processing flow, including what
/// parameters are returned from the endpoints used.
///
/// See [OAuth 2.0 Multiple Response Type Encoding Practices](
/// http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseTypesAndModes)
/// for further details.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct ResponseTypes<RT: ResponseType>(
#[serde(
deserialize_with = "deserialize_space_delimited_vec",
serialize_with = "crate::helpers::serialize_space_delimited_vec"
)]
Vec<RT>,
);
impl<RT: ResponseType> ResponseTypes<RT> {
/// Create a new [`ResponseTypes<RT>`] to wrap the given [`Vec<RT>`].
pub fn new(s: Vec<RT>) -> Self {
ResponseTypes::<RT>(s)
}
}
impl<RT: ResponseType> Deref for ResponseTypes<RT> {
type Target = Vec<RT>;
fn deref(&self) -> &Vec<RT> {
&self.0
}
}
new_url_type![
/// URL for retrieving redirect URIs that should receive identical pairwise subject identifiers.
SectorIdentifierUrl
];
new_url_type![
/// URL for developer documentation for an OpenID Connect Provider.
ServiceDocUrl
];
new_type![
/// A user's street address.
///
/// Full street address component, which MAY include house number, street name, Post Office Box,
/// and multi-line extended street address information. This field MAY contain multiple lines,
/// separated by newlines. Newlines can be represented either as a carriage return/line feed
/// pair (`\r\n`) or as a single line feed character (`\n`).
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
StreetAddress(String)
];
new_type![
/// Locally unique and never reassigned identifier within the Issuer for the End-User, which is
/// intended to be consumed by the client application.
#[derive(Deserialize, Hash, Ord, PartialOrd, Serialize)]
SubjectIdentifier(String)
];
new_url_type![
/// URL for the relying party's Terms of Service.
ToSUrl
];
+73
View File
@@ -0,0 +1,73 @@
use crate::IssuerUrl;
#[test]
fn test_issuer_url_append() {
assert_eq!(
"http://example.com/.well-known/openid-configuration",
IssuerUrl::new("http://example.com".to_string())
.unwrap()
.join(".well-known/openid-configuration")
.unwrap()
.to_string()
);
assert_eq!(
"http://example.com/.well-known/openid-configuration",
IssuerUrl::new("http://example.com/".to_string())
.unwrap()
.join(".well-known/openid-configuration")
.unwrap()
.to_string()
);
assert_eq!(
"http://example.com/x/.well-known/openid-configuration",
IssuerUrl::new("http://example.com/x".to_string())
.unwrap()
.join(".well-known/openid-configuration")
.unwrap()
.to_string()
);
assert_eq!(
"http://example.com/x/.well-known/openid-configuration",
IssuerUrl::new("http://example.com/x/".to_string())
.unwrap()
.join(".well-known/openid-configuration")
.unwrap()
.to_string()
);
}
#[test]
fn test_url_serialize() {
let issuer_url =
IssuerUrl::new("http://example.com/.well-known/openid-configuration".to_string()).unwrap();
let serialized_url = serde_json::to_string(&issuer_url).unwrap();
assert_eq!(
"\"http://example.com/.well-known/openid-configuration\"",
serialized_url
);
let deserialized_url = serde_json::from_str(&serialized_url).unwrap();
assert_eq!(issuer_url, deserialized_url);
assert_eq!(
serde_json::to_string(&IssuerUrl::new("http://example.com".to_string()).unwrap()).unwrap(),
"\"http://example.com\"",
);
}
#[cfg(feature = "accept-string-booleans")]
#[test]
fn test_string_bool_parse() {
use crate::helpers::Boolean;
fn test_case(input: &str, expect: bool) {
let value: Boolean = serde_json::from_str(input).unwrap();
assert_eq!(value.0, expect);
}
test_case("true", true);
test_case("false", false);
test_case("\"true\"", true);
test_case("\"false\"", false);
assert!(serde_json::from_str::<Boolean>("\"maybe\"").is_err());
}
+615
View File
@@ -0,0 +1,615 @@
use crate::helpers::{deserialize_string_or_vec_opt, FilteredFlatten};
use crate::http_utils::{auth_bearer, content_type_has_essence, MIME_TYPE_JSON, MIME_TYPE_JWT};
use crate::jwt::{JsonWebTokenError, JsonWebTokenJsonPayloadSerde};
use crate::verification::UserInfoVerifier;
use crate::{
AccessToken, AdditionalClaims, AddressClaim, AsyncHttpClient, Audience, AudiencesClaim,
AuthDisplay, AuthPrompt, ClaimsVerificationError, Client, EndUserBirthday, EndUserEmail,
EndUserFamilyName, EndUserGivenName, EndUserMiddleName, EndUserName, EndUserNickname,
EndUserPhoneNumber, EndUserPictureUrl, EndUserProfileUrl, EndUserTimezone, EndUserUsername,
EndUserWebsiteUrl, EndpointState, ErrorResponse, GenderClaim, HttpRequest, HttpResponse,
IssuerClaim, IssuerUrl, JsonWebKey, JsonWebToken, JweContentEncryptionAlgorithm,
JwsSigningAlgorithm, LanguageTag, LocalizedClaim, PrivateSigningKey, RevocableToken,
SignatureVerificationError, StandardClaims, SubjectIdentifier, SyncHttpClient,
TokenIntrospectionResponse, TokenResponse,
};
use chrono::{DateTime, Utc};
use http::header::{HeaderValue, ACCEPT, CONTENT_TYPE};
use http::method::Method;
use http::status::StatusCode;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use thiserror::Error;
use std::future::Future;
use std::str;
impl<
AC,
AD,
GC,
JE,
K,
P,
TE,
TR,
TIR,
RT,
TRE,
HasAuthUrl,
HasDeviceAuthUrl,
HasIntrospectionUrl,
HasRevocationUrl,
HasTokenUrl,
HasUserInfoUrl,
>
Client<
AC,
AD,
GC,
JE,
K,
P,
TE,
TR,
TIR,
RT,
TRE,
HasAuthUrl,
HasDeviceAuthUrl,
HasIntrospectionUrl,
HasRevocationUrl,
HasTokenUrl,
HasUserInfoUrl,
>
where
AC: AdditionalClaims,
AD: AuthDisplay,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
K: JsonWebKey,
P: AuthPrompt,
TE: ErrorResponse + 'static,
TR: TokenResponse<AC, GC, JE, K::SigningAlgorithm>,
TIR: TokenIntrospectionResponse,
RT: RevocableToken,
TRE: ErrorResponse + 'static,
HasAuthUrl: EndpointState,
HasDeviceAuthUrl: EndpointState,
HasIntrospectionUrl: EndpointState,
HasRevocationUrl: EndpointState,
HasTokenUrl: EndpointState,
HasUserInfoUrl: EndpointState,
{
pub(crate) fn user_info_impl<'a>(
&'a self,
userinfo_endpoint: &'a UserInfoUrl,
access_token: AccessToken,
expected_subject: Option<SubjectIdentifier>,
) -> UserInfoRequest<'a, JE, K> {
UserInfoRequest {
url: userinfo_endpoint,
access_token,
require_signed_response: false,
response_type: UserInfoResponseType::Json,
signed_response_verifier: UserInfoVerifier::new(
self.client_id.clone(),
self.issuer.clone(),
self.jwks.clone(),
expected_subject,
),
}
}
}
/// User info request.
pub struct UserInfoRequest<'a, JE, K>
where
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
K: JsonWebKey,
{
pub(crate) url: &'a UserInfoUrl,
pub(crate) access_token: AccessToken,
pub(crate) require_signed_response: bool,
pub(crate) signed_response_verifier: UserInfoVerifier<'static, JE, K>,
pub(crate) response_type: UserInfoResponseType,
}
impl<'a, JE, K> UserInfoRequest<'a, JE, K>
where
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
K: JsonWebKey,
{
/// Submits this request to the associated user info endpoint using the specified synchronous
/// HTTP client.
pub fn request<AC, GC, C>(
self,
http_client: &C,
) -> Result<UserInfoClaims<AC, GC>, UserInfoError<<C as SyncHttpClient>::Error>>
where
AC: AdditionalClaims,
GC: GenderClaim,
C: SyncHttpClient,
{
http_client
.call(
self.prepare_request().map_err(|err| {
UserInfoError::Other(format!("failed to prepare request: {err}"))
})?,
)
.map_err(UserInfoError::Request)
.and_then(|http_response| self.user_info_response(http_response))
}
/// Submits this request to the associated user info endpoint using the specified asynchronous
/// HTTP client.
pub fn request_async<'c, AC, C, GC>(
self,
http_client: &'c C,
) -> impl Future<
Output = Result<UserInfoClaims<AC, GC>, UserInfoError<<C as AsyncHttpClient<'c>>::Error>>,
> + 'c
where
Self: 'c,
AC: AdditionalClaims,
C: AsyncHttpClient<'c>,
GC: GenderClaim,
{
Box::pin(async move {
let http_response = http_client
.call(self.prepare_request().map_err(|err| {
UserInfoError::Other(format!("failed to prepare request: {err}"))
})?)
.await
.map_err(UserInfoError::Request)?;
self.user_info_response(http_response)
})
}
fn prepare_request(&self) -> Result<HttpRequest, http::Error> {
let (auth_header, auth_value) = auth_bearer(&self.access_token);
let accept_value = match self.response_type {
UserInfoResponseType::Jwt => MIME_TYPE_JWT,
_ => MIME_TYPE_JSON,
};
http::Request::builder()
.uri(self.url.to_string())
.method(Method::GET)
.header(ACCEPT, HeaderValue::from_static(accept_value))
.header(auth_header, auth_value)
.body(Vec::new())
}
fn user_info_response<AC, GC, RE>(
self,
http_response: HttpResponse,
) -> Result<UserInfoClaims<AC, GC>, UserInfoError<RE>>
where
AC: AdditionalClaims,
GC: GenderClaim,
RE: std::error::Error + 'static,
{
if http_response.status() != StatusCode::OK {
return Err(UserInfoError::Response(
http_response.status(),
http_response.body().to_owned(),
"unexpected HTTP status code".to_string(),
));
}
match http_response
.headers()
.get(CONTENT_TYPE)
.map(ToOwned::to_owned)
.unwrap_or_else(|| HeaderValue::from_static(MIME_TYPE_JSON))
{
ref content_type if content_type_has_essence(content_type, MIME_TYPE_JSON) => {
if self.require_signed_response {
return Err(UserInfoError::ClaimsVerification(
ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::NoSignature,
),
));
}
UserInfoClaims::from_json(
http_response.body(),
self.signed_response_verifier.expected_subject(),
)
}
ref content_type if content_type_has_essence(content_type, MIME_TYPE_JWT) => {
let jwt_str = String::from_utf8(http_response.body().to_owned()).map_err(|_| {
UserInfoError::Other("response body has invalid UTF-8 encoding".to_string())
})?;
serde_path_to_error::deserialize::<
_,
UserInfoJsonWebToken<AC, GC, JE, K::SigningAlgorithm>,
>(serde_json::Value::String(jwt_str))
.map_err(UserInfoError::Parse)?
.claims(&self.signed_response_verifier)
.map_err(UserInfoError::ClaimsVerification)
}
ref content_type => Err(UserInfoError::Response(
http_response.status(),
http_response.body().to_owned(),
format!("unexpected response Content-Type: `{content_type:?}`"),
)),
}
}
/// Specifies whether to require the user info response to be a signed JSON Web Token (JWT).
pub fn require_signed_response(mut self, require_signed_response: bool) -> Self {
self.require_signed_response = require_signed_response;
self
}
/// Specifies whether to require the issuer of the signed JWT response to match the expected
/// issuer URL for this provider.
///
/// This option has no effect on unsigned JSON responses.
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.signed_response_verifier = self
.signed_response_verifier
.require_issuer_match(iss_required);
self
}
/// Specifies whether to require the audience of the signed JWT response to match the expected
/// audience (client ID).
///
/// This option has no effect on unsigned JSON responses.
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.signed_response_verifier = self
.signed_response_verifier
.require_audience_match(aud_required);
self
}
/// Specifies the expected response type by setting the `Accept` header. Note that the server can ignore this header.
pub fn set_response_type(mut self, response_type: UserInfoResponseType) -> Self {
self.response_type = response_type;
self
}
}
/// User info claims.
#[derive(Clone, Debug, Serialize)]
pub struct UserInfoClaims<AC: AdditionalClaims, GC: GenderClaim>(UserInfoClaimsImpl<AC, GC>);
impl<AC, GC> UserInfoClaims<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
/// Initializes user info claims.
pub fn new(standard_claims: StandardClaims<GC>, additional_claims: AC) -> Self {
Self(UserInfoClaimsImpl {
issuer: None,
audiences: None,
standard_claims,
additional_claims: additional_claims.into(),
})
}
/// Initializes user info claims from the provided raw JSON response.
///
/// If an `expected_subject` is provided, this function verifies that the user info claims
/// contain the expected subject and returns an error otherwise.
pub fn from_json<RE>(
user_info_json: &[u8],
expected_subject: Option<&SubjectIdentifier>,
) -> Result<Self, UserInfoError<RE>>
where
RE: std::error::Error + 'static,
{
let user_info = serde_path_to_error::deserialize::<_, UserInfoClaimsImpl<AC, GC>>(
&mut serde_json::Deserializer::from_slice(user_info_json),
)
.map_err(UserInfoError::Parse)?;
// This is the only verification we need to do for JSON-based user info claims, so don't
// bother with the complexity of a separate verifier object.
if expected_subject
.iter()
.all(|expected_subject| user_info.standard_claims.sub == **expected_subject)
{
Ok(Self(user_info))
} else {
Err(UserInfoError::ClaimsVerification(
ClaimsVerificationError::InvalidSubject(format!(
"expected `{}` (found `{}`)",
// This can only happen when expected_subject is not None.
expected_subject.unwrap().as_str(),
user_info.standard_claims.sub.as_str(),
)),
))
}
}
field_getters_setters![
pub self [self.0] ["claim"] {
set_issuer -> issuer[Option<IssuerUrl>],
set_audiences -> audiences[Option<Vec<Audience>>] ["aud"],
}
];
/// Returns the `sub` claim.
pub fn subject(&self) -> &SubjectIdentifier {
&self.0.standard_claims.sub
}
/// Sets the `sub` claim.
pub fn set_subject(&mut self, subject: SubjectIdentifier) {
self.0.standard_claims.sub = subject
}
field_getters_setters![
pub self [self.0.standard_claims] ["claim"] {
set_name -> name[Option<LocalizedClaim<EndUserName>>],
set_given_name -> given_name[Option<LocalizedClaim<EndUserGivenName>>],
set_family_name ->
family_name[Option<LocalizedClaim<EndUserFamilyName>>],
set_middle_name ->
middle_name[Option<LocalizedClaim<EndUserMiddleName>>],
set_nickname -> nickname[Option<LocalizedClaim<EndUserNickname>>],
set_preferred_username -> preferred_username[Option<EndUserUsername>],
set_profile -> profile[Option<LocalizedClaim<EndUserProfileUrl>>],
set_picture -> picture[Option<LocalizedClaim<EndUserPictureUrl>>],
set_website -> website[Option<LocalizedClaim<EndUserWebsiteUrl>>],
set_email -> email[Option<EndUserEmail>],
set_email_verified -> email_verified[Option<bool>],
set_gender -> gender[Option<GC>],
set_birthday -> birthday[Option<EndUserBirthday>],
set_birthdate -> birthdate[Option<EndUserBirthday>],
set_zoneinfo -> zoneinfo[Option<EndUserTimezone>],
set_locale -> locale[Option<LanguageTag>],
set_phone_number -> phone_number[Option<EndUserPhoneNumber>],
set_phone_number_verified -> phone_number_verified[Option<bool>],
set_address -> address[Option<AddressClaim>],
set_updated_at -> updated_at[Option<DateTime<Utc>>],
}
];
/// Returns the standard claims as a `StandardClaims` object.
pub fn standard_claims(&self) -> &StandardClaims<GC> {
&self.0.standard_claims
}
/// Returns additional user info claims.
pub fn additional_claims(&self) -> &AC {
self.0.additional_claims.as_ref()
}
/// Returns mutable additional user info claims.
pub fn additional_claims_mut(&mut self) -> &mut AC {
self.0.additional_claims.as_mut()
}
}
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct UserInfoClaimsImpl<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
#[serde(rename = "iss")]
pub issuer: Option<IssuerUrl>,
// We always serialize as an array, which is valid according to the spec.
#[serde(
default,
rename = "aud",
deserialize_with = "deserialize_string_or_vec_opt"
)]
pub audiences: Option<Vec<Audience>>,
#[serde(bound = "GC: GenderClaim", flatten)]
pub standard_claims: StandardClaims<GC>,
#[serde(bound = "AC: AdditionalClaims", flatten)]
pub additional_claims: FilteredFlatten<StandardClaims<GC>, AC>,
}
impl<AC, GC> AudiencesClaim for UserInfoClaimsImpl<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn audiences(&self) -> Option<&Vec<Audience>> {
self.audiences.as_ref()
}
}
impl<AC, GC> AudiencesClaim for &UserInfoClaimsImpl<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn audiences(&self) -> Option<&Vec<Audience>> {
self.audiences.as_ref()
}
}
impl<AC, GC> IssuerClaim for UserInfoClaimsImpl<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn issuer(&self) -> Option<&IssuerUrl> {
self.issuer.as_ref()
}
}
impl<AC, GC> IssuerClaim for &UserInfoClaimsImpl<AC, GC>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
fn issuer(&self) -> Option<&IssuerUrl> {
self.issuer.as_ref()
}
}
/// JSON Web Token (JWT) containing user info claims.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UserInfoJsonWebToken<
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
>(
#[serde(bound = "AC: AdditionalClaims")]
JsonWebToken<JE, JS, UserInfoClaimsImpl<AC, GC>, JsonWebTokenJsonPayloadSerde>,
);
impl<AC, GC, JE, JS> UserInfoJsonWebToken<AC, GC, JE, JS>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<KeyType = JS::KeyType>,
JS: JwsSigningAlgorithm,
{
/// Initializes a new signed JWT containing the specified claims, signed with the specified key
/// and signing algorithm.
pub fn new<S>(
claims: UserInfoClaims<AC, GC>,
signing_key: &S,
alg: JS,
) -> Result<Self, JsonWebTokenError>
where
S: PrivateSigningKey,
<S as PrivateSigningKey>::VerificationKey: JsonWebKey<SigningAlgorithm = JS>,
{
Ok(Self(JsonWebToken::new(claims.0, signing_key, &alg)?))
}
/// Verifies and returns the user info claims.
pub fn claims<K>(
self,
verifier: &UserInfoVerifier<JE, K>,
) -> Result<UserInfoClaims<AC, GC>, ClaimsVerificationError>
where
K: JsonWebKey<SigningAlgorithm = JS>,
{
Ok(UserInfoClaims(verifier.verified_claims(self.0)?))
}
}
new_url_type![
/// URL for a provider's user info endpoint.
UserInfoUrl
];
/// Indicates via the `Accept` header the body response type the server should use to return the user info. Note that the server can ignore this header.
///
/// Defaults to Json.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum UserInfoResponseType {
/// Sets the `Accept` header to `application/json`.
Json,
/// Sets the `Accept` header to `application/jwt`.
Jwt,
}
/// Error retrieving user info.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum UserInfoError<RE>
where
RE: std::error::Error + 'static,
{
/// Failed to verify user info claims.
#[error("Failed to verify claims")]
ClaimsVerification(#[source] ClaimsVerificationError),
/// Failed to parse server response.
#[error("Failed to parse server response")]
Parse(#[source] serde_path_to_error::Error<serde_json::Error>),
/// An error occurred while sending the request or receiving the response (e.g., network
/// connectivity failed).
#[error("Request failed")]
Request(#[source] RE),
/// Server returned an invalid response.
#[error("Server returned invalid response: {2}")]
Response(StatusCode, Vec<u8>, String),
/// An unexpected error occurred.
#[error("Other error: {0}")]
Other(String),
}
#[cfg(test)]
mod tests {
use crate::core::CoreGenderClaim;
use crate::{AdditionalClaims, UserInfoClaims};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
struct TestClaims {
pub tfa_method: String,
}
impl AdditionalClaims for TestClaims {}
#[test]
fn test_additional_claims() {
let claims =
UserInfoClaims::<TestClaims, CoreGenderClaim>::from_json::<crate::reqwest::Error>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"],
\"tfa_method\": \"u2f\"
}"
.as_bytes(),
None,
)
.expect("failed to deserialize");
assert_eq!(claims.additional_claims().tfa_method, "u2f");
assert_eq!(
serde_json::to_string(&claims).expect("failed to serialize"),
"{\
\"iss\":\"https://server.example.com\",\
\"aud\":[\"s6BhdRkqt3\"],\
\"sub\":\"24400320\",\
\"tfa_method\":\"u2f\"\
}",
);
UserInfoClaims::<TestClaims, CoreGenderClaim>::from_json::<crate::reqwest::Error>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"]
}"
.as_bytes(),
None,
)
.expect_err("missing claim should fail to deserialize");
}
#[derive(Debug, Deserialize, Serialize)]
struct AllOtherClaims(HashMap<String, serde_json::Value>);
impl AdditionalClaims for AllOtherClaims {}
#[test]
fn test_catch_all_additional_claims() {
let claims =
UserInfoClaims::<AllOtherClaims, CoreGenderClaim>::from_json::<crate::reqwest::Error>(
"{
\"iss\": \"https://server.example.com\",
\"sub\": \"24400320\",
\"aud\": [\"s6BhdRkqt3\"],
\"tfa_method\": \"u2f\",
\"updated_at\": 1000
}"
.as_bytes(),
None,
)
.expect("failed to deserialize");
assert_eq!(claims.additional_claims().0.len(), 1);
assert_eq!(claims.additional_claims().0["tfa_method"], "u2f");
}
}
+943
View File
@@ -0,0 +1,943 @@
use crate::jwt::{JsonWebToken, JsonWebTokenJsonPayloadSerde, NormalizedJsonWebTokenType};
use crate::user_info::UserInfoClaimsImpl;
use crate::{
AdditionalClaims, Audience, AuthenticationContextClass, ClientId, ClientSecret, GenderClaim,
IdTokenClaims, IssuerUrl, JsonWebKey, JsonWebKeyId, JsonWebKeySet, JsonWebTokenAccess,
JsonWebTokenAlgorithm, JsonWebTokenHeader, JsonWebTokenType, JweContentEncryptionAlgorithm,
JwsSigningAlgorithm, Nonce, SubjectIdentifier,
};
use chrono::{DateTime, Utc};
use serde::de::DeserializeOwned;
use serde::Serialize;
use sha2::{Digest, Sha256};
use thiserror::Error;
use std::collections::HashSet;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::Arc;
#[cfg(test)]
mod tests;
pub(crate) trait AudiencesClaim {
fn audiences(&self) -> Option<&Vec<Audience>>;
}
pub(crate) trait IssuerClaim {
fn issuer(&self) -> Option<&IssuerUrl>;
}
/// Error verifying claims.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClaimsVerificationError {
/// Claims have expired.
#[error("Expired: {0}")]
Expired(String),
/// Audience claim is invalid.
#[error("Invalid audiences: {0}")]
InvalidAudience(String),
/// Authorization context class reference (`acr`) claim is invalid.
#[error("Invalid authorization context class reference: {0}")]
InvalidAuthContext(String),
/// User authenticated too long ago.
#[error("Invalid authentication time: {0}")]
InvalidAuthTime(String),
/// Issuer claim is invalid.
#[error("Invalid issuer: {0}")]
InvalidIssuer(String),
/// Nonce is invalid.
#[error("Invalid nonce: {0}")]
InvalidNonce(String),
/// Subject claim is invalid.
#[error("Invalid subject: {0}")]
InvalidSubject(String),
/// An unexpected error occurred.
#[error("{0}")]
Other(String),
/// Failed to verify the claims signature.
#[error("Signature verification failed")]
SignatureVerification(#[source] SignatureVerificationError),
/// Unsupported argument or value.
#[error("Unsupported: {0}")]
Unsupported(String),
}
/// Error verifying claims signature.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignatureVerificationError {
/// More than one key matches the supplied key constraints (e.g., key ID).
#[error("Ambiguous key identification: {0}")]
AmbiguousKeyId(String),
/// Invalid signature for the supplied claims and signing key.
#[error("Crypto error: {0}")]
CryptoError(String),
/// The supplied signature algorithm is disallowed by the verifier.
#[error("Disallowed signature algorithm: {0}")]
DisallowedAlg(String),
/// The supplied key cannot be used in this context. This may occur if the key type does not
/// match the signature type (e.g., an RSA key used to validate an HMAC) or the JWK usage
/// disallows signatures.
#[error("Invalid cryptographic key: {0}")]
InvalidKey(String),
/// The signing key needed for verifying the
/// [JSON Web Token](https://tools.ietf.org/html/rfc7519)'s signature/MAC could not be found.
/// This error can occur if the key ID (`kid`) specified in the JWT's
/// [JOSE header](https://tools.ietf.org/html/rfc7519#section-5) does not match the ID of any
/// key in the OpenID Connect provider's JSON Web Key Set (JWKS), typically retrieved from
/// the provider's [JWKS document](
/// http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata). To support
/// [rotation of asymmetric signing keys](
/// http://openid.net/specs/openid-connect-core-1_0.html#RotateSigKeys), client applications
/// should consider refreshing the JWKS document (via
/// [`JsonWebKeySet::fetch`][crate::JsonWebKeySet::fetch]).
///
/// This error can also occur if the identified
/// [JSON Web Key](https://tools.ietf.org/html/rfc7517) is of the wrong type (e.g., an RSA key
/// when the JOSE header specifies an ECDSA algorithm) or does not support signing.
#[error("No matching key found")]
NoMatchingKey,
/// No signature present but claims must be signed.
#[error("No signature found")]
NoSignature,
/// Unsupported signature algorithm.
#[error("Unsupported signature algorithm: {0}")]
UnsupportedAlg(String),
/// An unexpected error occurred.
#[error("Other error: {0}")]
Other(String),
}
// This struct is intentionally private.
#[derive(Clone)]
pub(crate) struct JwtClaimsVerifier<'a, K>
where
K: JsonWebKey,
{
allowed_jose_types: Option<HashSet<NormalizedJsonWebTokenType>>,
allowed_algs: Option<HashSet<K::SigningAlgorithm>>,
aud_match_required: bool,
client_id: ClientId,
client_secret: Option<ClientSecret>,
iss_required: bool,
issuer: IssuerUrl,
is_signature_check_enabled: bool,
other_aud_verifier_fn: Arc<dyn Fn(&Audience) -> bool + 'a + Send + Sync>,
signature_keys: JsonWebKeySet<K>,
}
impl<'a, K> JwtClaimsVerifier<'a, K>
where
K: JsonWebKey,
{
pub fn new(client_id: ClientId, issuer: IssuerUrl, signature_keys: JsonWebKeySet<K>) -> Self {
JwtClaimsVerifier {
allowed_algs: Some(
[K::SigningAlgorithm::rsa_sha_256()]
.iter()
.cloned()
.collect(),
),
allowed_jose_types: Some(HashSet::from([
JsonWebTokenType::new("application/jwt".to_string())
.normalize()
.expect("application/jwt should be a valid JWT type"), // used by many IdP, but not standardized
JsonWebTokenType::new("application/jose".to_string())
.normalize()
.expect("application/jose should be a valid JWT type"), // standard as defined in https://tools.ietf.org/html/rfc7515#section-4.1.9
// we do not support JOSE+JSON, so we omit this here in the default configuration
])),
aud_match_required: true,
client_id,
client_secret: None,
iss_required: true,
issuer,
is_signature_check_enabled: true,
// Secure default: reject all other audiences as untrusted, since any other audience
// can potentially impersonate the user when by sending its copy of these claims
// to this relying party.
other_aud_verifier_fn: Arc::new(|_| false),
signature_keys,
}
}
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.aud_match_required = aud_required;
self
}
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.iss_required = iss_required;
self
}
pub fn require_signature_check(mut self, sig_required: bool) -> Self {
self.is_signature_check_enabled = sig_required;
self
}
pub fn set_allowed_algs<I>(mut self, algs: I) -> Self
where
I: IntoIterator<Item = K::SigningAlgorithm>,
{
self.allowed_algs = Some(algs.into_iter().collect());
self
}
pub fn allow_any_alg(mut self) -> Self {
self.allowed_algs = None;
self
}
/// Allows setting specific JOSE types. The verifier will check against them during verification.
///
/// See [RFC 7515 section 4.1.9](https://tools.ietf.org/html/rfc7515#section-4.1.9) for more details.
pub fn set_allowed_jose_types<I>(mut self, types: I) -> Self
where
I: IntoIterator<Item = NormalizedJsonWebTokenType>,
{
self.allowed_jose_types = Some(types.into_iter().collect());
self
}
pub fn allow_all_jose_types(mut self) -> Self {
self.allowed_jose_types = None;
self
}
pub fn set_client_secret(mut self, client_secret: ClientSecret) -> Self {
self.client_secret = Some(client_secret);
self
}
pub fn set_other_audience_verifier_fn<T>(mut self, other_aud_verifier_fn: T) -> Self
where
T: Fn(&Audience) -> bool + 'a + Send + Sync,
{
self.other_aud_verifier_fn = Arc::new(other_aud_verifier_fn);
self
}
fn validate_jose_header<JE>(
&self,
jose_header: &JsonWebTokenHeader<JE, K::SigningAlgorithm>,
) -> Result<(), ClaimsVerificationError>
where
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
{
// The 'typ' header field must either be omitted or have the canonicalized value JWT.
// see https://tools.ietf.org/html/rfc7519#section-5.1
if let Some(ref jwt_type) = jose_header.typ {
if let Some(allowed_jose_types) = &self.allowed_jose_types {
// Check according to https://tools.ietf.org/html/rfc7515#section-4.1.9
// See https://tools.ietf.org/html/rfc2045#section-5.1 for the full Content-Type Header Field spec.
//
// For sake of simplicity, we do not support matching on application types with parameters like
// application/example;part="1/2". If you know your parameters exactly, just set the whole Content Type manually.
let valid_jwt_type = if let Ok(normalized_jwt_type) = jwt_type.normalize() {
allowed_jose_types.contains(&normalized_jwt_type)
} else {
false
};
if !valid_jwt_type {
return Err(ClaimsVerificationError::Unsupported(format!(
"unexpected or unsupported JWT type `{}`",
**jwt_type
)));
}
}
}
// The 'cty' header field must be omitted, since it's only used for JWTs that contain
// content types other than JSON-encoded claims. This may include nested JWTs, such as if
// JWE encryption is used. This is currently unsupported.
if let Some(ref content_type) = jose_header.cty {
if content_type.to_uppercase() == "JWT" {
return Err(ClaimsVerificationError::Unsupported(
"nested JWT's are not currently supported".to_string(),
));
} else {
return Err(ClaimsVerificationError::Unsupported(format!(
"unexpected or unsupported JWT content type `{}`",
**content_type
)));
}
}
// If 'crit' fields are specified, we must reject any we do not understand. Since this
// implementation doesn't understand any of them, unconditionally reject the JWT. Note that
// the spec prohibits this field from containing any of the standard headers or being empty.
if jose_header.crit.is_some() {
// https://tools.ietf.org/html/rfc7515#appendix-E
return Err(ClaimsVerificationError::Unsupported(
"critical JWT header fields are unsupported".to_string(),
));
}
Ok(())
}
pub fn verified_claims<A, C, JE, T>(&self, jwt: A) -> Result<T, ClaimsVerificationError>
where
A: JsonWebTokenAccess<JE, K::SigningAlgorithm, C, ReturnType = T>,
C: AudiencesClaim + Debug + DeserializeOwned + IssuerClaim + Serialize,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
T: AudiencesClaim + IssuerClaim,
{
{
let jose_header = jwt.unverified_header();
self.validate_jose_header(jose_header)?;
// The code below roughly follows the validation steps described in
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// 1. If the ID Token is encrypted, decrypt it using the keys and algorithms that the Client
// specified during Registration that the OP was to use to encrypt the ID Token. If
// encryption was negotiated with the OP at Registration time and the ID Token is not
// encrypted, the RP SHOULD reject it.
if let JsonWebTokenAlgorithm::Encryption(ref encryption_alg) = jose_header.alg {
return Err(ClaimsVerificationError::Unsupported(format!(
"JWE encryption is not currently supported (found algorithm `{}`)",
serde_plain::to_string(encryption_alg).unwrap_or_else(|err| panic!(
"encryption alg {encryption_alg:?} failed to serialize to a string: {err}"
)),
)));
}
}
// TODO: Add encryption (JWE) support
{
// 2. The Issuer Identifier for the OpenID Provider (which is typically obtained during
// Discovery) MUST exactly match the value of the iss (issuer) Claim.
let unverified_claims = jwt.unverified_payload_ref();
if self.iss_required {
if let Some(issuer) = unverified_claims.issuer() {
if *issuer != self.issuer {
return Err(ClaimsVerificationError::InvalidIssuer(format!(
"expected `{}` (found `{}`)",
*self.issuer, **issuer
)));
}
} else {
return Err(ClaimsVerificationError::InvalidIssuer(
"missing issuer claim".to_string(),
));
}
}
// 3. The Client MUST validate that the aud (audience) Claim contains its client_id value
// registered at the Issuer identified by the iss (issuer) Claim as an audience. The aud
// (audience) Claim MAY contain an array with more than one element. The ID Token MUST be
// rejected if the ID Token does not list the Client as a valid audience, or if it
// contains additional audiences not trusted by the Client.
if self.aud_match_required {
if let Some(audiences) = unverified_claims.audiences() {
if !audiences
.iter()
.any(|aud| (**aud).deref() == self.client_id.deref())
{
return Err(ClaimsVerificationError::InvalidAudience(format!(
"must contain `{}` (found audiences: {})",
*self.client_id,
audiences
.iter()
.map(|aud| format!("`{}`", Deref::deref(aud)))
.collect::<Vec<_>>()
.join(", ")
)));
} else if audiences.len() > 1 {
audiences
.iter()
.filter(|aud| (**aud).deref() != self.client_id.deref())
.find(|aud| !(self.other_aud_verifier_fn)(aud))
.map(|aud| {
Err(ClaimsVerificationError::InvalidAudience(format!(
"`{}` is not a trusted audience",
**aud,
)))
})
.unwrap_or(Ok(()))?;
}
} else {
return Err(ClaimsVerificationError::InvalidAudience(
"missing audiences claim".to_string(),
));
}
}
}
// Steps 4--5 (azp claim validation) are specific to the ID token.
// 6. If the ID Token is received via direct communication between the Client and the Token
// Endpoint (which it is in this flow), the TLS server validation MAY be used to validate
// the issuer in place of checking the token signature. The Client MUST validate the
// signature of all other ID Tokens according to JWS [JWS] using the algorithm specified
// in the JWT alg Header Parameter. The Client MUST use the keys provided by the Issuer.
if !self.is_signature_check_enabled {
return Ok(jwt.unverified_payload());
}
// Borrow the header again. We had to drop the reference above to allow for the
// early exit calling jwt.unverified_claims(), which takes ownership of the JWT.
let signature_alg = jwt
.signing_alg()
.map_err(ClaimsVerificationError::SignatureVerification)?
.to_owned();
// 7. The alg value SHOULD be the default of RS256 or the algorithm sent by the Client
// in the id_token_signed_response_alg parameter during Registration.
if let Some(ref allowed_algs) = self.allowed_algs {
if !allowed_algs.contains(&signature_alg) {
return Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::DisallowedAlg(format!(
"algorithm `{}` is not one of: {}",
serde_plain::to_string(&signature_alg).unwrap_or_else(|err| panic!(
"signature alg {signature_alg:?} failed to serialize to a string: {err}",
)),
allowed_algs
.iter()
.map(
|alg| serde_plain::to_string(alg).unwrap_or_else(|err| panic!(
"signature alg {alg:?} failed to serialize to a string: {err}",
))
)
.collect::<Vec<_>>()
.join(", "),
)),
));
}
}
// NB: We must *not* trust the 'kid' (key ID) or 'alg' (algorithm) fields present in the
// JOSE header, as an attacker could manipulate these while forging the JWT. The code
// below must be secure regardless of how these fields are manipulated.
if signature_alg.uses_shared_secret() {
// 8. If the JWT alg Header Parameter uses a MAC based algorithm such as HS256,
// HS384, or HS512, the octets of the UTF-8 representation of the client_secret
// corresponding to the client_id contained in the aud (audience) Claim are used
// as the key to validate the signature. For MAC based algorithms, the behavior
// is unspecified if the aud is multi-valued or if an azp value is present that
// is different than the aud value.
if let Some(ref client_secret) = self.client_secret {
let key = K::new_symmetric(client_secret.secret().clone().into_bytes());
return jwt
.payload(&signature_alg, &key)
.map_err(ClaimsVerificationError::SignatureVerification);
} else {
// The client secret isn't confidential for public clients, so anyone can forge a
// JWT with a valid signature.
return Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::DisallowedAlg(
"symmetric signatures are disallowed for public clients".to_string(),
),
));
}
}
// Section 10.1 of OpenID Connect Core 1.0 states that the JWT must include a key ID
// if the JWK set contains more than one public key.
let public_key = self
.signing_key(jwt.unverified_header().kid.as_ref(), &signature_alg)
.map_err(ClaimsVerificationError::SignatureVerification)?;
jwt.payload(&signature_alg.clone(), public_key)
.map_err(ClaimsVerificationError::SignatureVerification)
// Steps 9--13 are specific to the ID token.
}
pub(crate) fn signing_key<'b>(
&'b self,
key_id: Option<&JsonWebKeyId>,
signature_alg: &K::SigningAlgorithm,
) -> Result<&'b K, SignatureVerificationError> {
// See if any key has a matching key ID (if supplied) and compatible type.
let public_keys = self.signature_keys.filter_keys(key_id, signature_alg);
if public_keys.is_empty() {
Err(SignatureVerificationError::NoMatchingKey)
} else if public_keys.len() == 1 {
Ok(public_keys.first().expect("unreachable"))
} else {
Err(SignatureVerificationError::AmbiguousKeyId(format!(
"JWK set must only contain one eligible public key, but found {} eligible keys: {}",
public_keys.len(),
public_keys
.iter()
.map(|key| format!(
"{} ({})",
key.key_id()
.map(|kid| format!("`{}`", **kid))
.unwrap_or_else(|| "null ID".to_string()),
serde_plain::to_string(key.key_type()).unwrap_or_else(|err| panic!(
"key type {:?} failed to serialize to a string: {}",
key.key_type(),
err,
))
))
.collect::<Vec<_>>()
.join(", ")
)))
}
}
}
/// Trait for verifying ID token nonces.
pub trait NonceVerifier {
/// Verifies the nonce.
///
/// Returns `Ok(())` if the nonce is valid, or a string describing the error otherwise.
fn verify(self, nonce: Option<&Nonce>) -> Result<(), String>;
}
impl NonceVerifier for &Nonce {
fn verify(self, nonce: Option<&Nonce>) -> Result<(), String> {
if let Some(claims_nonce) = nonce {
// Avoid timing side-channel.
if Sha256::digest(claims_nonce.secret()) != Sha256::digest(self.secret()) {
return Err("nonce mismatch".to_string());
}
} else {
return Err("missing nonce claim".to_string());
}
Ok(())
}
}
impl<F> NonceVerifier for F
where
F: FnOnce(Option<&Nonce>) -> Result<(), String>,
{
fn verify(self, nonce: Option<&Nonce>) -> Result<(), String> {
self(nonce)
}
}
/// ID token verifier.
#[derive(Clone)]
pub struct IdTokenVerifier<'a, K>
where
K: JsonWebKey,
{
acr_verifier_fn:
Arc<dyn Fn(Option<&AuthenticationContextClass>) -> Result<(), String> + 'a + Send + Sync>,
#[allow(clippy::type_complexity)]
auth_time_verifier_fn:
Arc<dyn Fn(Option<DateTime<Utc>>) -> Result<(), String> + 'a + Send + Sync>,
iat_verifier_fn: Arc<dyn Fn(DateTime<Utc>) -> Result<(), String> + 'a + Send + Sync>,
pub(crate) jwt_verifier: JwtClaimsVerifier<'a, K>,
time_fn: Arc<dyn Fn() -> DateTime<Utc> + 'a + Send + Sync>,
}
impl<'a, K> IdTokenVerifier<'a, K>
where
K: JsonWebKey,
{
fn new(jwt_verifier: JwtClaimsVerifier<'a, K>) -> Self {
IdTokenVerifier {
// By default, accept authorization context reference (acr claim).
acr_verifier_fn: Arc::new(|_| Ok(())),
auth_time_verifier_fn: Arc::new(|_| Ok(())),
// By default, accept any issued time (iat claim).
iat_verifier_fn: Arc::new(|_| Ok(())),
jwt_verifier,
// By default, use the current system time.
time_fn: Arc::new(Utc::now),
}
}
/// Initializes a new verifier for a public client (i.e., one without a client secret).
pub fn new_public_client(
client_id: ClientId,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<K>,
) -> Self {
Self::new(JwtClaimsVerifier::new(client_id, issuer, signature_keys))
}
/// Initializes a no-op verifier that performs no signature, audience, or issuer verification.
/// The token's expiration time is still checked, and the token is otherwise required to conform to the expected format.
pub fn new_insecure_without_verification() -> Self {
let empty_issuer = IssuerUrl::new("https://0.0.0.0".to_owned())
.expect("Creating empty issuer url mustn't fail");
Self::new_public_client(
ClientId::new(String::new()),
empty_issuer,
JsonWebKeySet::new(vec![]),
)
.insecure_disable_signature_check()
.require_audience_match(false)
.require_issuer_match(false)
}
/// Initializes a new verifier for a confidential client (i.e., one with a client secret).
///
/// A confidential client verifier is required in order to verify ID tokens signed using a
/// shared secret algorithm such as `HS256`, `HS384`, or `HS512`. For these algorithms, the
/// client secret is the shared secret.
pub fn new_confidential_client(
client_id: ClientId,
client_secret: ClientSecret,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<K>,
) -> Self {
Self::new(
JwtClaimsVerifier::new(client_id, issuer, signature_keys)
.set_client_secret(client_secret),
)
}
/// Specifies which JSON Web Signature algorithms are supported.
pub fn set_allowed_algs<I>(mut self, algs: I) -> Self
where
I: IntoIterator<Item = K::SigningAlgorithm>,
{
self.jwt_verifier = self.jwt_verifier.set_allowed_algs(algs);
self
}
/// Specifies that any signature algorithm is supported.
pub fn allow_any_alg(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.allow_any_alg();
self
}
/// Allows setting specific JOSE types. The verifier will check against them during verification.
///
/// See [RFC 7515 section 4.1.9](https://tools.ietf.org/html/rfc7515#section-4.1.9) for more details.
pub fn set_allowed_jose_types<I>(mut self, types: I) -> Self
where
I: IntoIterator<Item = NormalizedJsonWebTokenType>,
{
self.jwt_verifier = self.jwt_verifier.set_allowed_jose_types(types);
self
}
/// Allow all JSON Web Token Header types.
pub fn allow_all_jose_types(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.allow_all_jose_types();
self
}
/// Specifies a function for verifying the `acr` claim.
///
/// The function should return `Ok(())` if the claim is valid, or a string describing the error
/// otherwise.
pub fn set_auth_context_verifier_fn<T>(mut self, acr_verifier_fn: T) -> Self
where
T: Fn(Option<&AuthenticationContextClass>) -> Result<(), String> + 'a + Send + Sync,
{
self.acr_verifier_fn = Arc::new(acr_verifier_fn);
self
}
/// Specifies a function for verifying the `auth_time` claim.
///
/// The function should return `Ok(())` if the claim is valid, or a string describing the error
/// otherwise.
pub fn set_auth_time_verifier_fn<T>(mut self, auth_time_verifier_fn: T) -> Self
where
T: Fn(Option<DateTime<Utc>>) -> Result<(), String> + 'a + Send + Sync,
{
self.auth_time_verifier_fn = Arc::new(auth_time_verifier_fn);
self
}
/// Enables signature verification.
///
/// Signature verification is enabled by default, so this function is only useful if
/// [`IdTokenVerifier::insecure_disable_signature_check`] was previously invoked.
pub fn enable_signature_check(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.require_signature_check(true);
self
}
/// Disables signature verification.
///
/// # Security Warning
///
/// Unverified ID tokens may be subject to forgery. See [Section 16.3](
/// https://openid.net/specs/openid-connect-core-1_0.html#TokenManufacture) for more
/// information.
pub fn insecure_disable_signature_check(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.require_signature_check(false);
self
}
/// Specifies whether the issuer claim must match the expected issuer URL for the provider.
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_issuer_match(iss_required);
self
}
/// Specifies whether the audience claim must match this client's client ID.
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_audience_match(aud_required);
self
}
/// Specifies a function for returning the current time.
///
/// This function is used for verifying the ID token expiration time.
pub fn set_time_fn<T>(mut self, time_fn: T) -> Self
where
T: Fn() -> DateTime<Utc> + 'a + Send + Sync,
{
self.time_fn = Arc::new(time_fn);
self
}
/// Specifies a function for verifying the ID token issue time.
///
/// The function should return `Ok(())` if the claim is valid, or a string describing the error
/// otherwise.
pub fn set_issue_time_verifier_fn<T>(mut self, iat_verifier_fn: T) -> Self
where
T: Fn(DateTime<Utc>) -> Result<(), String> + 'a + Send + Sync,
{
self.iat_verifier_fn = Arc::new(iat_verifier_fn);
self
}
/// Specifies a function for verifying audiences included in the `aud` claim that differ from
/// this client's client ID.
///
/// The function should return `true` if the audience is trusted, or `false` otherwise.
///
/// [Section 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation)
/// states that *"The ID Token MUST be rejected if the ID Token does not list the Client as a
/// valid audience, or if it contains additional audiences not trusted by the Client."*
pub fn set_other_audience_verifier_fn<T>(mut self, other_aud_verifier_fn: T) -> Self
where
T: Fn(&Audience) -> bool + 'a + Send + Sync,
{
self.jwt_verifier = self
.jwt_verifier
.set_other_audience_verifier_fn(other_aud_verifier_fn);
self
}
pub(crate) fn verified_claims<'b, AC, GC, JE, N>(
&self,
jwt: &'b JsonWebToken<
JE,
K::SigningAlgorithm,
IdTokenClaims<AC, GC>,
JsonWebTokenJsonPayloadSerde,
>,
nonce_verifier: N,
) -> Result<&'b IdTokenClaims<AC, GC>, ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
N: NonceVerifier,
{
// The code below roughly follows the validation steps described in
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// Steps 1--3 are handled by the generic JwtClaimsVerifier.
let partially_verified_claims = self.jwt_verifier.verified_claims(jwt)?;
self.verify_claims(partially_verified_claims, nonce_verifier)?;
Ok(partially_verified_claims)
}
pub(crate) fn verified_claims_owned<AC, GC, JE, N>(
&self,
jwt: JsonWebToken<
JE,
K::SigningAlgorithm,
IdTokenClaims<AC, GC>,
JsonWebTokenJsonPayloadSerde,
>,
nonce_verifier: N,
) -> Result<IdTokenClaims<AC, GC>, ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
N: NonceVerifier,
{
// The code below roughly follows the validation steps described in
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// Steps 1--3 are handled by the generic JwtClaimsVerifier.
let partially_verified_claims = self.jwt_verifier.verified_claims(jwt)?;
self.verify_claims(&partially_verified_claims, nonce_verifier)?;
Ok(partially_verified_claims)
}
fn verify_claims<AC, GC, N>(
&self,
partially_verified_claims: &'_ IdTokenClaims<AC, GC>,
nonce_verifier: N,
) -> Result<(), ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
N: NonceVerifier,
{
// 4. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp
// Claim is present.
// There is significant confusion and contradiction in the OpenID Connect Core spec around
// the azp claim. See https://bitbucket.org/openid/connect/issues/973/ for a detailed
// discussion. Given the lack of clarity around how this claim should be used, we defer
// any verification of it here until a use case becomes apparent. If such a use case does
// arise, we most likely want to allow clients to pass in a function for validating the
// azp claim rather than introducing logic that affects all clients of this library.
// This naive implementation of the spec would almost certainly not be useful in practice:
/*
let azp_required = partially_verified_claims.audiences().len() > 1;
// 5. If an azp (authorized party) Claim is present, the Client SHOULD verify that its
// client_id is the Claim Value.
if let Some(authorized_party) = partially_verified_claims.authorized_party() {
if *authorized_party != self.client_id {
return Err(ClaimsVerificationError::InvalidAudience(format!(
"authorized party must match client ID `{}` (found `{}`",
*self.client_id, **authorized_party
)));
}
} else if azp_required {
return Err(ClaimsVerificationError::InvalidAudience(format!(
"missing authorized party claim but multiple audiences found"
)));
}
*/
// Steps 6--8 are handled by the generic JwtClaimsVerifier.
// 9. The current time MUST be before the time represented by the exp Claim.
let cur_time = (*self.time_fn)();
if cur_time >= partially_verified_claims.expiration() {
return Err(ClaimsVerificationError::Expired(format!(
"ID token expired at {} (current time is {})",
partially_verified_claims.expiration(),
cur_time
)));
}
// 10. The iat Claim can be used to reject tokens that were issued too far away from the
// current time, limiting the amount of time that nonces need to be stored to prevent
// attacks. The acceptable range is Client specific.
(*self.iat_verifier_fn)(partially_verified_claims.issue_time())
.map_err(ClaimsVerificationError::Expired)?;
// 11. If a nonce value was sent in the Authentication Request, a nonce Claim MUST be
// present and its value checked to verify that it is the same value as the one that was
// sent in the Authentication Request. The Client SHOULD check the nonce value for
// replay attacks. The precise method for detecting replay attacks is Client specific.
nonce_verifier
.verify(partially_verified_claims.nonce())
.map_err(ClaimsVerificationError::InvalidNonce)?;
// 12. If the acr Claim was requested, the Client SHOULD check that the asserted Claim Value
// is appropriate. The meaning and processing of acr Claim Values is out of scope for
// this specification.
(*self.acr_verifier_fn)(partially_verified_claims.auth_context_ref())
.map_err(ClaimsVerificationError::InvalidAuthContext)?;
// 13. If the auth_time Claim was requested, either through a specific request for this
// Claim or by using the max_age parameter, the Client SHOULD check the auth_time Claim
// value and request re-authentication if it determines too much time has elapsed since
// the last End-User authentication.
(*self.auth_time_verifier_fn)(partially_verified_claims.auth_time())
.map_err(ClaimsVerificationError::InvalidAuthTime)?;
Ok(())
}
}
/// User info verifier.
#[derive(Clone)]
pub struct UserInfoVerifier<'a, JE, K>
where
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
K: JsonWebKey,
{
jwt_verifier: JwtClaimsVerifier<'a, K>,
expected_subject: Option<SubjectIdentifier>,
_phantom: PhantomData<JE>,
}
impl<'a, JE, K> UserInfoVerifier<'a, JE, K>
where
JE: JweContentEncryptionAlgorithm<
KeyType = <K::SigningAlgorithm as JwsSigningAlgorithm>::KeyType,
>,
K: JsonWebKey,
{
/// Instantiates a user info verifier.
pub fn new(
client_id: ClientId,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<K>,
expected_subject: Option<SubjectIdentifier>,
) -> Self {
UserInfoVerifier {
jwt_verifier: JwtClaimsVerifier::new(client_id, issuer, signature_keys),
expected_subject,
_phantom: PhantomData,
}
}
pub(crate) fn expected_subject(&self) -> Option<&SubjectIdentifier> {
self.expected_subject.as_ref()
}
/// Specifies whether the issuer claim must match the expected issuer URL for the provider.
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_issuer_match(iss_required);
self
}
/// Specifies whether the audience claim must match this client's client ID.
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_audience_match(aud_required);
self
}
pub(crate) fn verified_claims<AC, GC>(
&self,
user_info_jwt: JsonWebToken<
JE,
K::SigningAlgorithm,
UserInfoClaimsImpl<AC, GC>,
JsonWebTokenJsonPayloadSerde,
>,
) -> Result<UserInfoClaimsImpl<AC, GC>, ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
let user_info = self.jwt_verifier.verified_claims(user_info_jwt)?;
if self
.expected_subject
.iter()
.all(|expected_subject| user_info.standard_claims.sub == *expected_subject)
{
Ok(user_info)
} else {
Err(ClaimsVerificationError::InvalidSubject(format!(
"expected `{}` (found `{}`)",
// This can only happen when self.expected_subject is not None.
self.expected_subject.as_ref().unwrap().as_str(),
user_info.standard_claims.sub.as_str()
)))
}
}
}
File diff suppressed because it is too large Load Diff
+613
View File
@@ -0,0 +1,613 @@
#![allow(clippy::expect_fun_call)]
use crate::rp_common::{
get_provider_metadata, http_client, init_log, issuer_url, register_client, PanicIfFail,
};
use http::header::LOCATION;
use http::method::Method;
use log::{debug, error, info};
use openidconnect::core::{
CoreClient, CoreClientAuthMethod, CoreClientRegistrationRequest,
CoreClientRegistrationResponse, CoreIdToken, CoreIdTokenClaims, CoreIdTokenVerifier,
CoreJsonWebKeySet, CoreJwsSigningAlgorithm, CoreProviderMetadata, CoreResponseType,
CoreUserInfoClaims,
};
use openidconnect::Nonce;
use openidconnect::{
AccessToken, AuthType, AuthenticationFlow, AuthorizationCode, ClaimsVerificationError,
CsrfToken, EndpointMaybeSet, EndpointNotSet, EndpointSet, HttpClientError, OAuth2TokenResponse,
RequestTokenError, Scope, SignatureVerificationError, UserInfoError,
};
use reqwest::{blocking::Client, redirect::Policy};
use url::Url;
use std::collections::HashMap;
mod rp_common;
struct TestState {
access_token: Option<AccessToken>,
authorization_code: Option<AuthorizationCode>,
client: CoreClient<
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointMaybeSet,
EndpointMaybeSet,
>,
id_token: Option<CoreIdToken>,
nonce: Option<Nonce>,
provider_metadata: CoreProviderMetadata,
registration_response: CoreClientRegistrationResponse,
}
impl TestState {
pub fn init<F>(test_id: &'static str, reg_request_fn: F) -> Self
where
F: FnOnce(CoreClientRegistrationRequest) -> CoreClientRegistrationRequest,
{
init_log(test_id);
let _issuer_url = issuer_url(test_id);
let provider_metadata = get_provider_metadata(test_id);
let registration_response = register_client(&provider_metadata, reg_request_fn);
let redirect_uri = registration_response.redirect_uris()[0].clone();
let client: CoreClient<_, _, _, _, _, _> = CoreClient::from_provider_metadata(
provider_metadata.clone(),
registration_response.client_id().to_owned(),
registration_response.client_secret().cloned(),
)
.set_redirect_uri(redirect_uri);
TestState {
access_token: None,
authorization_code: None,
client,
id_token: None,
nonce: None,
provider_metadata,
registration_response,
}
}
pub fn access_token(&self) -> &AccessToken {
self.access_token.as_ref().expect("no access_token")
}
pub fn authorize(mut self, scopes: &[Scope]) -> Self {
let (authorization_code, nonce) = {
let mut authorization_request = self.client.authorize_url(
AuthenticationFlow::AuthorizationCode::<CoreResponseType>,
CsrfToken::new_random,
Nonce::new_random,
);
authorization_request =
scopes
.iter()
.fold(authorization_request, |mut authorization_request, scope| {
authorization_request = authorization_request.add_scope(scope.clone());
authorization_request
});
let (url, state, nonce) = authorization_request.url();
log_debug!("Authorize URL: {:?}", url);
let http_client = Client::builder().redirect(Policy::none()).build().unwrap();
let redirect_response = http_client
.execute(
http_client
.request(Method::GET, url.as_str())
.build()
.unwrap(),
)
.unwrap();
assert!(redirect_response.status().is_redirection());
let redirected_url = Url::parse(
redirect_response
.headers()
.get(LOCATION)
.unwrap()
.to_str()
.unwrap(),
)
.unwrap();
log_debug!("Authorization Server redirected to: {:?}", redirected_url);
let mut query_params = HashMap::new();
redirected_url.query_pairs().for_each(|(key, value)| {
query_params.insert(key, value);
});
log_debug!(
"Authorization Server returned query params: {:?}",
query_params
);
assert_eq!(
self.provider_metadata.issuer().as_str(),
query_params.get("iss").unwrap()
);
assert_eq!(state.secret(), query_params.get("state").unwrap());
log_info!("Successfully received authentication response from Authorization Server");
let authorization_code =
AuthorizationCode::new(query_params.get("code").unwrap().to_string());
log_debug!(
"Authorization Server returned authorization code: {}",
authorization_code.secret()
);
(authorization_code, nonce)
};
self.authorization_code = Some(authorization_code);
self.nonce = Some(nonce);
self
}
pub fn exchange_code(mut self) -> Self {
let token_response = self
.client
.exchange_code(
self.authorization_code
.take()
.expect("no authorization_code"),
)
.panic_if_fail("should have a token endpoint")
.request(&http_client)
.panic_if_fail("failed to exchange authorization code for token");
log_debug!(
"Authorization Server returned token response: {:?}",
token_response
);
self.access_token = Some(token_response.access_token().clone());
let id_token = (*token_response
.extra_fields()
.id_token()
.expect("no id_token"))
.clone();
self.id_token = Some(id_token);
self
}
pub fn id_token(&self) -> &CoreIdToken {
self.id_token.as_ref().expect("no id_token")
}
pub fn id_token_verifier(&self, jwks: CoreJsonWebKeySet) -> CoreIdTokenVerifier<'_> {
CoreIdTokenVerifier::new_confidential_client(
self.registration_response.client_id().clone(),
self.registration_response
.client_secret()
.expect("no client_secret")
.clone(),
self.provider_metadata.issuer().clone(),
jwks,
)
}
pub fn id_token_claims(&self) -> &CoreIdTokenClaims {
let verifier = self.id_token_verifier(self.jwks());
self.id_token()
.claims(&verifier, self.nonce.as_ref().expect("no nonce"))
.panic_if_fail("failed to validate claims")
}
pub fn id_token_claims_failure(&self) -> ClaimsVerificationError {
let verifier = self.id_token_verifier(self.jwks());
self.id_token()
.claims(&verifier, self.nonce.as_ref().expect("no nonce"))
.expect_err("claims verification succeeded but was expected to fail")
}
pub fn jwks(&self) -> CoreJsonWebKeySet {
CoreJsonWebKeySet::fetch(self.provider_metadata.jwks_uri(), &http_client)
.panic_if_fail("failed to fetch JWK set")
}
pub fn set_auth_type(mut self, auth_type: AuthType) -> Self {
self.client = self.client.set_auth_type(auth_type);
self
}
pub fn user_info_claims(&self) -> CoreUserInfoClaims {
self.client
.user_info(
self.access_token().to_owned(),
Some(self.id_token_claims().subject().clone()),
)
.unwrap()
.require_signed_response(false)
.request(&http_client)
.panic_if_fail("failed to get UserInfo")
}
pub fn user_info_claims_failure(&self) -> UserInfoError<HttpClientError<reqwest::Error>> {
let user_info_result: Result<CoreUserInfoClaims, _> = self
.client
.user_info(
self.access_token().to_owned(),
Some(self.id_token_claims().subject().clone()),
)
.unwrap()
.require_signed_response(false)
.request(&http_client);
match user_info_result {
Err(err) => err,
_ => panic!("claims verification succeeded but was expected to fail"),
}
}
}
#[test]
#[ignore]
fn rp_response_type_code() {
let test_state = TestState::init("rp-response_type-code", |reg| reg).authorize(&[]);
assert!(
test_state
.authorization_code
.expect("no authorization_code")
.secret()
!= ""
);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_scope_userinfo_claims() {
let user_info_scopes = ["profile", "email", "address", "phone"]
.iter()
.map(|scope| Scope::new((*scope).to_string()))
.collect::<Vec<_>>();
let test_state = TestState::init("rp-scope-userinfo-claims", |reg| reg)
.authorize(&user_info_scopes)
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
let user_info_claims = test_state.user_info_claims();
log_debug!("UserInfo response: {:?}", user_info_claims);
assert_eq!(id_token_claims.subject(), user_info_claims.subject());
assert!(!user_info_claims
.email()
.expect("no email returned by UserInfo endpoint")
.is_empty());
assert!(!user_info_claims
.address()
.expect("no address returned by UserInfo endpoint")
.street_address
.as_ref()
.expect("no street address returned by UserInfo endpoint")
.is_empty());
assert!(!user_info_claims
.phone_number()
.expect("no phone_number returned by UserInfo endpoint")
.is_empty());
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_nonce_invalid() {
let test_state = TestState::init("rp-nonce-invalid", |reg| reg)
.authorize(&[])
.exchange_code();
match test_state.id_token_claims_failure() {
ClaimsVerificationError::InvalidNonce(_) => {
log_error!("ID token contains invalid nonce (expected result)")
}
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_token_endpoint_client_secret_basic() {
let test_state = TestState::init("rp-token_endpoint-client_secret_basic", |reg| {
reg.set_token_endpoint_auth_method(Some(CoreClientAuthMethod::ClientSecretBasic))
})
.set_auth_type(AuthType::BasicAuth)
.authorize(&[])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_token_endpoint_client_secret_post() {
let test_state = TestState::init("rp-token_endpoint-client_secret_post", |reg| {
reg.set_token_endpoint_auth_method(Some(CoreClientAuthMethod::ClientSecretPost))
})
.set_auth_type(AuthType::RequestBody)
.authorize(&[])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_kid_absent_single_jwks() {
let test_state = TestState::init("rp-id_token-kid-absent-single-jwks", |reg| reg)
.authorize(&[])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_iat() {
let mut test_state = TestState::init("rp-id_token-iat", |reg| reg).authorize(&[]);
let token_response = test_state
.client
.exchange_code(
test_state
.authorization_code
.take()
.expect("no authorization_code"),
)
.panic_if_fail("should have a token endpoint")
.request(&http_client);
match token_response {
Err(RequestTokenError::Parse(_, _)) => {
log_error!("ID token failed to parse without `iat` claim (expected result)")
}
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_aud() {
let test_state = TestState::init("rp-id_token-aud", |reg| reg)
.authorize(&[])
.exchange_code();
match test_state.id_token_claims_failure() {
ClaimsVerificationError::InvalidAudience(_) => {
log_error!("ID token has invalid audience (expected result)")
}
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_kid_absent_multiple_jwks() {
let test_state = TestState::init("rp-id_token-kid-absent-multiple-jwks", |reg| reg)
.authorize(&[])
.exchange_code();
match test_state.id_token_claims_failure() {
ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::AmbiguousKeyId(_),
) => log_error!("ID token has ambiguous key identification without KID (expected result)"),
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_sig_none() {
let test_state = TestState::init("rp-id_token-sig-none", |reg| reg)
.authorize(&[])
.exchange_code();
let verifier = test_state
.id_token_verifier(test_state.jwks())
.insecure_disable_signature_check();
let id_token_claims = test_state
.id_token()
.claims(&verifier, test_state.nonce.as_ref().expect("no nonce"))
.panic_if_fail("failed to validate claims");
log_debug!("ID token: {:?}", id_token_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_sig_rs256() {
let test_state = TestState::init("rp-id_token-sig-rs256", |reg| reg)
.authorize(&[])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_sig_hs256() {
let test_state = TestState::init("rp-id_token-sig-hs256", |reg| reg)
.authorize(&[])
.exchange_code();
let verifier = test_state
.id_token_verifier(test_state.jwks())
.set_allowed_algs(vec![CoreJwsSigningAlgorithm::HmacSha256]);
let id_token_claims = test_state
.id_token()
.claims(&verifier, test_state.nonce.as_ref().expect("no nonce"))
.panic_if_fail("failed to validate claims");
log_debug!("ID token: {:?}", id_token_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_sub() {
let mut test_state = TestState::init("rp-id_token-sub", |reg| reg).authorize(&[]);
let token_response = test_state
.client
.exchange_code(
test_state
.authorization_code
.take()
.expect("no authorization_code"),
)
.panic_if_fail("should have a token endpoint")
.request(&http_client);
match token_response {
Err(RequestTokenError::Parse(_, _)) => {
log_error!("ID token failed to parse without `sub` claim (expected result)")
}
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_bad_sig_rs256() {
let test_state = TestState::init("rp-id_token-bad-sig-rs256", |reg| reg)
.authorize(&[])
.exchange_code();
match test_state.id_token_claims_failure() {
ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::CryptoError(_),
) => log_error!("ID token has invalid signature (expected result)"),
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_bad_sig_hs256() {
let test_state = TestState::init("rp-id_token-bad-sig-hs256", |reg| reg)
.authorize(&[])
.exchange_code();
let verifier = test_state
.id_token_verifier(test_state.jwks())
.set_allowed_algs(vec![CoreJwsSigningAlgorithm::HmacSha256]);
let id_token_err = test_state
.id_token()
.claims(&verifier, test_state.nonce.as_ref().expect("no nonce"))
.expect_err("claims verification succeeded but was expected to fail");
match id_token_err {
ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::CryptoError(_),
) => log_error!("ID token has invalid signature (expected result)"),
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_id_token_issuer_mismatch() {
let test_state = TestState::init("rp-id_token-issuer-mismatch", |reg| reg)
.authorize(&[])
.exchange_code();
match test_state.id_token_claims_failure() {
ClaimsVerificationError::InvalidIssuer(_) => {
log_error!("ID token has invalid issuer (expected result)")
}
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_userinfo_bad_sub_claim() {
let test_state = TestState::init("rp-userinfo-bad-sub-claim", |reg| reg)
.authorize(&[Scope::new("profile".to_string())])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
match test_state.user_info_claims_failure() {
UserInfoError::ClaimsVerification(ClaimsVerificationError::InvalidSubject(_)) => {
log_error!("UserInfo response has invalid subject (expected result)")
}
other => panic!("Unexpected result verifying ID token claims: {other:?}"),
}
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_userinfo_bearer_header() {
let test_state = TestState::init("rp-userinfo-bearer-header", |reg| reg)
.authorize(&[Scope::new("profile".to_string())])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
let user_info_claims = test_state.user_info_claims();
log_debug!("UserInfo response: {:?}", user_info_claims);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_userinfo_sig() {
let test_state = TestState::init("rp-userinfo-sig", |reg| {
reg.set_userinfo_signed_response_alg(Some(CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256))
})
.authorize(&[Scope::new("profile".to_string())])
.exchange_code();
let id_token_claims = test_state.id_token_claims();
log_debug!("ID token: {:?}", id_token_claims);
let user_info_claims: CoreUserInfoClaims = test_state
.client
.user_info(
test_state.access_token().to_owned(),
Some(id_token_claims.subject().clone()),
)
.unwrap()
// For some reason, the test suite omits these claims even though the Core spec says
// that the RP SHOULD verify these.
.require_audience_match(false)
.require_issuer_match(false)
.request(&http_client)
.panic_if_fail("failed to get UserInfo");
log_debug!("UserInfo response: {:?}", user_info_claims);
log_info!("SUCCESS");
}
+140
View File
@@ -0,0 +1,140 @@
#![allow(clippy::cognitive_complexity)]
use crate::rp_common::{
get_provider_metadata, init_log, issuer_url, register_client, CERTIFICATION_BASE_URL, RP_NAME,
};
use log::{debug, info};
mod rp_common;
#[test]
#[ignore]
fn rp_discovery_openid_configuration() {
const TEST_ID: &str = "rp-discovery-openid-configuration";
init_log(TEST_ID);
let _issuer_url = issuer_url(TEST_ID);
let provider_metadata = get_provider_metadata(TEST_ID);
macro_rules! log_field {
($field:ident) => {
log_container_field!(provider_metadata.$field);
};
}
log_info!(
"Successfully retrieved provider metadata from {:?}",
_issuer_url
);
log_field!(issuer);
log_field!(authorization_endpoint);
log_field!(token_endpoint);
log_field!(userinfo_endpoint);
log_field!(jwks_uri);
log_field!(registration_endpoint);
log_field!(scopes_supported);
log_field!(response_types_supported);
log_field!(response_modes_supported);
log_field!(grant_types_supported);
log_field!(acr_values_supported);
log_field!(subject_types_supported);
log_field!(id_token_signing_alg_values_supported);
log_field!(id_token_encryption_alg_values_supported);
log_field!(id_token_encryption_enc_values_supported);
log_field!(userinfo_signing_alg_values_supported);
log_field!(userinfo_encryption_alg_values_supported);
log_field!(userinfo_encryption_enc_values_supported);
log_field!(request_object_signing_alg_values_supported);
log_field!(request_object_encryption_alg_values_supported);
log_field!(request_object_encryption_enc_values_supported);
log_field!(token_endpoint_auth_methods_supported);
log_field!(token_endpoint_auth_signing_alg_values_supported);
log_field!(display_values_supported);
log_field!(claim_types_supported);
log_field!(claims_supported);
log_field!(service_documentation);
log_field!(claims_locales_supported);
log_field!(ui_locales_supported);
log_field!(claims_parameter_supported);
log_field!(request_parameter_supported);
log_field!(request_uri_parameter_supported);
log_field!(require_request_uri_registration);
log_field!(op_policy_uri);
log_field!(op_tos_uri);
log_debug!("Provider metadata: {:?}", provider_metadata);
log_info!("SUCCESS");
}
#[test]
#[ignore]
fn rp_registration_dynamic() {
const TEST_ID: &str = "rp-registration-dynamic";
init_log(TEST_ID);
let _issuer_url = issuer_url(TEST_ID);
let provider_metadata = get_provider_metadata(TEST_ID);
let registration_response = register_client(&provider_metadata, |reg| reg);
macro_rules! log_field {
($field:ident) => {
log_container_field!(registration_response.$field);
};
}
log_field!(client_id);
log_field!(client_secret);
log_field!(registration_access_token);
log_field!(registration_client_uri);
log_field!(client_id_issued_at);
log_field!(client_secret_expires_at);
log_field!(redirect_uris);
log_field!(response_types);
log_field!(grant_types);
log_field!(application_type);
log_field!(contacts);
log_field!(client_name);
log_field!(logo_uri);
log_field!(client_uri);
log_field!(policy_uri);
log_field!(tos_uri);
log_field!(jwks_uri);
log_field!(jwks);
log_field!(sector_identifier_uri);
log_field!(subject_type);
log_field!(id_token_signed_response_alg);
log_field!(id_token_encrypted_response_alg);
log_field!(id_token_encrypted_response_enc);
log_field!(userinfo_signed_response_alg);
log_field!(userinfo_encrypted_response_alg);
log_field!(userinfo_encrypted_response_enc);
log_field!(request_object_signing_alg);
log_field!(request_object_encryption_alg);
log_field!(request_object_encryption_enc);
log_field!(token_endpoint_auth_method);
log_field!(token_endpoint_auth_signing_alg);
log_field!(default_max_age);
log_field!(require_auth_time);
log_field!(default_acr_values);
log_field!(initiate_login_uri);
log_field!(request_uris);
log_debug!("Registration response: {:?}", registration_response);
assert_eq!(
format!(
"{}/{}/registration?client_id={}",
CERTIFICATION_BASE_URL,
RP_NAME,
**registration_response.client_id()
),
registration_response
.registration_client_uri()
.unwrap()
.to_string()
);
log_info!("SUCCESS");
}
+187
View File
@@ -0,0 +1,187 @@
#![allow(clippy::cognitive_complexity, clippy::expect_fun_call)]
use log::{error, warn};
use openidconnect::core::{
CoreApplicationType, CoreClientRegistrationRequest, CoreClientRegistrationResponse,
CoreProviderMetadata,
};
use openidconnect::{
ClientContactEmail, ClientName, HttpClientError, HttpRequest, HttpResponse, IssuerUrl,
RedirectUrl,
};
use std::cell::RefCell;
use std::sync::Once;
use std::time::Duration;
pub const CERTIFICATION_BASE_URL: &str = "https://rp.certification.openid.net:8080";
pub const RP_CONTACT_EMAIL: &str = "ramos@cs.stanford.edu";
pub const RP_NAME: &str = "openidconnect-rs";
pub const RP_REDIRECT_URI: &str = "http://localhost:8080";
static INIT_LOG: Once = Once::new();
thread_local! {
static TEST_ID: RefCell<&'static str> = const { RefCell::new("UNINITIALIZED_TEST_ID") };
}
pub fn get_test_id() -> &'static str {
TEST_ID.with(|id| *id.borrow())
}
pub fn set_test_id(test_id: &'static str) {
TEST_ID.with(|id| *id.borrow_mut() = test_id);
}
#[macro_export]
macro_rules! log_error {
($($args:tt)+) => {
error!("[{}] {}", rp_common::get_test_id(), format!($($args)+))
}
}
#[macro_export]
macro_rules! log_info {
($($args:tt)+) => {
info!("[{}] {}", rp_common::get_test_id(), format!($($args)+));
}
}
#[macro_export]
macro_rules! log_debug {
($($args:tt)+) => {
debug!("[{}] {}", rp_common::get_test_id(), format!($($args)+));
}
}
#[macro_export]
macro_rules! log_container_field {
($container:ident. $field:ident) => {
log_info!(
concat!(" ", stringify!($field), " = {:?}"),
$container.$field()
);
};
}
fn _init_log() {
color_backtrace::install();
env_logger::init();
}
pub fn init_log(test_id: &'static str) {
INIT_LOG.call_once(_init_log);
set_test_id(test_id);
}
// FIXME: just clone `request` directly once we update `http` to 1.0, which implements `Clone`.
#[cfg(feature = "reqwest-blocking")]
pub(crate) fn clone_request(request: &HttpRequest) -> HttpRequest {
let mut request_copy = http::Request::builder()
.method(request.method().to_owned())
.uri(request.uri().to_owned())
.version(request.version());
for (name, value) in request.headers() {
request_copy = request_copy.header(name, value);
}
request_copy.body(request.body().to_owned()).unwrap()
}
pub fn http_client(request: HttpRequest) -> Result<HttpResponse, HttpClientError<reqwest::Error>> {
retry::retry(
(0..5).map(|i| {
if i != 0 {
warn!("Retrying HTTP request ({}/5)", i + 1)
}
Duration::from_millis(500)
}),
|| -> Result<HttpResponse, HttpClientError<reqwest::Error>> {
#[cfg(feature = "reqwest-blocking")]
{
use openidconnect::SyncHttpClient;
reqwest::blocking::Client::default().call(clone_request(&request))
}
#[cfg(not(feature = "reqwest-blocking"))]
{
let _ = &request;
panic!("reqwest-blocking feature is required")
}
},
)
.map_err(|err| match err {
retry::Error::Operation { error, .. } => error,
retry::Error::Internal(msg) => panic!("unexpected error: {msg}"),
})
}
pub trait PanicIfFail<T, F>
where
F: std::error::Error,
{
fn panic_if_fail(self, msg: &'static str) -> T;
}
impl<T, F> PanicIfFail<T, F> for Result<T, F>
where
F: std::error::Error,
{
fn panic_if_fail(self, msg: &'static str) -> T {
match self {
Ok(ret) => ret,
Err(fail) => {
let mut err_msg = format!("Panic: {msg}");
let mut cur_fail: Option<&dyn std::error::Error> = Some(&fail);
while let Some(cause) = cur_fail {
err_msg += &format!("\n caused by: {cause}");
cur_fail = cause.source();
}
error!("[{}] {}", get_test_id(), err_msg);
panic!("{}", msg);
}
}
}
}
pub fn issuer_url(test_id: &str) -> IssuerUrl {
IssuerUrl::new(format!("{CERTIFICATION_BASE_URL}/{RP_NAME}/{test_id}"))
.expect("Failed to parse issuer URL")
}
pub fn get_provider_metadata(test_id: &str) -> CoreProviderMetadata {
let _issuer_url = issuer_url(test_id);
CoreProviderMetadata::discover(&_issuer_url, &http_client).expect(&format!(
"Failed to fetch provider metadata from {_issuer_url:?}"
))
}
pub fn register_client<F>(
provider_metadata: &CoreProviderMetadata,
request_fn: F,
) -> CoreClientRegistrationResponse
where
F: FnOnce(CoreClientRegistrationRequest) -> CoreClientRegistrationRequest,
{
let registration_request_pre = CoreClientRegistrationRequest::new(
vec![RedirectUrl::new(RP_REDIRECT_URI.to_string()).unwrap()],
Default::default(),
)
.set_application_type(Some(CoreApplicationType::Native))
.set_client_name(Some(
vec![(None, ClientName::new(RP_NAME.to_string()))]
.into_iter()
.collect(),
))
.set_contacts(Some(vec![ClientContactEmail::new(
RP_CONTACT_EMAIL.to_string(),
)]));
let registration_request_post = request_fn(registration_request_pre);
let registration_endpoint = provider_metadata
.registration_endpoint()
.expect("provider does not support dynamic registration");
registration_request_post
.register(registration_endpoint, &http_client)
.expect(&format!(
"Failed to register client at {registration_endpoint:?}"
))
}