RPM build fix (reverted CI changes which will need to be un-reverted or made conditional) and vendor Rust dependencies to make builds much faster in any CI system.

This commit is contained in:
Adam Ierymenko
2022-06-08 07:32:16 -04:00
parent 373ca30269
commit d5ca4e5f52
12611 changed files with 2898014 additions and 284 deletions

205
zeroidc/vendor/oauth2/src/basic.rs vendored Normal file
View File

@@ -0,0 +1,205 @@
use std::fmt::Error as FormatterError;
use std::fmt::{Debug, Display, Formatter};
use super::{
Client, EmptyExtraTokenFields, ErrorResponseType, RequestTokenError, StandardErrorResponse,
StandardTokenResponse, TokenType,
};
use crate::{
revocation::{RevocationErrorResponseType, StandardRevocableToken},
StandardTokenIntrospectionResponse,
};
///
/// Basic OAuth2 client specialization, suitable for most applications.
///
pub type BasicClient = Client<
BasicErrorResponse,
BasicTokenResponse,
BasicTokenType,
BasicTokenIntrospectionResponse,
StandardRevocableToken,
BasicRevocationErrorResponse,
>;
///
/// Basic OAuth2 authorization token types.
///
#[derive(Clone, Debug, PartialEq)]
pub enum BasicTokenType {
///
/// Bearer token
/// ([OAuth 2.0 Bearer Tokens - RFC 6750](https://tools.ietf.org/html/rfc6750)).
///
Bearer,
///
/// MAC ([OAuth 2.0 Message Authentication Code (MAC)
/// Tokens](https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05)).
///
Mac,
///
/// An extension not defined by RFC 6749.
///
Extension(String),
}
impl BasicTokenType {
fn from_str(s: &str) -> Self {
match s {
"bearer" => BasicTokenType::Bearer,
"mac" => BasicTokenType::Mac,
ext => BasicTokenType::Extension(ext.to_string()),
}
}
}
impl AsRef<str> for BasicTokenType {
fn as_ref(&self) -> &str {
match *self {
BasicTokenType::Bearer => "bearer",
BasicTokenType::Mac => "mac",
BasicTokenType::Extension(ref ext) => ext.as_str(),
}
}
}
impl<'de> serde::Deserialize<'de> for BasicTokenType {
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))
}
}
impl serde::ser::Serialize for BasicTokenType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
impl TokenType for BasicTokenType {}
///
/// Basic OAuth2 token response.
///
pub type BasicTokenResponse = StandardTokenResponse<EmptyExtraTokenFields, BasicTokenType>;
///
/// Basic OAuth2 token introspection response.
///
pub type BasicTokenIntrospectionResponse =
StandardTokenIntrospectionResponse<EmptyExtraTokenFields, BasicTokenType>;
///
/// Basic access token error types.
///
/// These error types are defined in
/// [Section 5.2 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.2).
///
#[derive(Clone, PartialEq)]
pub enum BasicErrorResponseType {
///
/// Client authentication failed (e.g., unknown client, no client authentication included,
/// or unsupported authentication method).
///
InvalidClient,
///
/// The provided authorization grant (e.g., authorization code, resource owner credentials)
/// or refresh token is invalid, expired, revoked, does not match the redirection URI used
/// in the authorization request, or was issued to another client.
///
InvalidGrant,
///
/// The request is missing a required parameter, includes an unsupported parameter value
/// (other than grant type), repeats a parameter, includes multiple credentials, utilizes
/// more than one mechanism for authenticating the client, or is otherwise malformed.
///
InvalidRequest,
///
/// The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the
/// resource owner.
///
InvalidScope,
///
/// The authenticated client is not authorized to use this authorization grant type.
///
UnauthorizedClient,
///
/// The authorization grant type is not supported by the authorization server.
///
UnsupportedGrantType,
///
/// An extension not defined by RFC 6749.
///
Extension(String),
}
impl BasicErrorResponseType {
pub(crate) fn from_str(s: &str) -> Self {
match s {
"invalid_client" => BasicErrorResponseType::InvalidClient,
"invalid_grant" => BasicErrorResponseType::InvalidGrant,
"invalid_request" => BasicErrorResponseType::InvalidRequest,
"invalid_scope" => BasicErrorResponseType::InvalidScope,
"unauthorized_client" => BasicErrorResponseType::UnauthorizedClient,
"unsupported_grant_type" => BasicErrorResponseType::UnsupportedGrantType,
ext => BasicErrorResponseType::Extension(ext.to_string()),
}
}
}
impl AsRef<str> for BasicErrorResponseType {
fn as_ref(&self) -> &str {
match *self {
BasicErrorResponseType::InvalidClient => "invalid_client",
BasicErrorResponseType::InvalidGrant => "invalid_grant",
BasicErrorResponseType::InvalidRequest => "invalid_request",
BasicErrorResponseType::InvalidScope => "invalid_scope",
BasicErrorResponseType::UnauthorizedClient => "unauthorized_client",
BasicErrorResponseType::UnsupportedGrantType => "unsupported_grant_type",
BasicErrorResponseType::Extension(ref ext) => ext.as_str(),
}
}
}
impl<'de> serde::Deserialize<'de> for BasicErrorResponseType {
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))
}
}
impl serde::ser::Serialize for BasicErrorResponseType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
impl ErrorResponseType for BasicErrorResponseType {}
impl Debug for BasicErrorResponseType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
Display::fmt(self, f)
}
}
impl Display for BasicErrorResponseType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f, "{}", self.as_ref())
}
}
///
/// Error response specialization for basic OAuth2 implementation.
///
pub type BasicErrorResponse = StandardErrorResponse<BasicErrorResponseType>;
///
/// Token error specialization for basic OAuth2 implementation.
///
pub type BasicRequestTokenError<RE> = RequestTokenError<RE, BasicErrorResponse>;
///
/// Revocation error response specialization for basic OAuth2 implementation.
///
pub type BasicRevocationErrorResponse = StandardErrorResponse<RevocationErrorResponseType>;

101
zeroidc/vendor/oauth2/src/curl.rs vendored Normal file
View File

@@ -0,0 +1,101 @@
use std::io::Read;
use curl::easy::Easy;
use http::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use http::method::Method;
use http::status::StatusCode;
use super::{HttpRequest, HttpResponse};
///
/// Error type returned by failed curl HTTP requests.
///
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Error returned by curl crate.
#[error("curl request failed")]
Curl(#[source] curl::Error),
/// Non-curl HTTP error.
#[error("HTTP error")]
Http(#[source] http::Error),
/// Other error.
#[error("Other error: {}", _0)]
Other(String),
}
///
/// Synchronous HTTP client.
///
pub fn http_client(request: HttpRequest) -> Result<HttpResponse, Error> {
let mut easy = Easy::new();
easy.url(&request.url.to_string()[..])
.map_err(Error::Curl)?;
let mut headers = curl::easy::List::new();
request
.headers
.iter()
.map(|(name, value)| {
headers
.append(&format!(
"{}: {}",
name,
value.to_str().map_err(|_| Error::Other(format!(
"invalid {} header value {:?}",
name,
value.as_bytes()
)))?
))
.map_err(Error::Curl)
})
.collect::<Result<_, _>>()?;
easy.http_headers(headers).map_err(Error::Curl)?;
if let Method::POST = request.method {
easy.post(true).map_err(Error::Curl)?;
easy.post_field_size(request.body.len() as u64)
.map_err(Error::Curl)?;
} else {
assert_eq!(request.method, Method::GET);
}
let mut form_slice = &request.body[..];
let mut data = Vec::new();
{
let mut transfer = easy.transfer();
transfer
.read_function(|buf| Ok(form_slice.read(buf).unwrap_or(0)))
.map_err(Error::Curl)?;
transfer
.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
})
.map_err(Error::Curl)?;
transfer.perform().map_err(Error::Curl)?;
}
let status_code = easy.response_code().map_err(Error::Curl)? as u16;
Ok(HttpResponse {
status_code: StatusCode::from_u16(status_code).map_err(|err| Error::Http(err.into()))?,
headers: easy
.content_type()
.map_err(Error::Curl)?
.map(|content_type| {
Ok(vec![(
CONTENT_TYPE,
HeaderValue::from_str(content_type).map_err(|err| Error::Http(err.into()))?,
)]
.into_iter()
.collect::<HeaderMap>())
})
.transpose()?
.unwrap_or_else(HeaderMap::new),
body: data,
})
}

239
zeroidc/vendor/oauth2/src/devicecode.rs vendored Normal file
View File

@@ -0,0 +1,239 @@
use std::error::Error;
use std::fmt::Error as FormatterError;
use std::fmt::{Debug, Display, Formatter};
use std::marker::PhantomData;
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use super::{
DeviceCode, EndUserVerificationUrl, ErrorResponse, ErrorResponseType, RequestTokenError,
StandardErrorResponse, TokenResponse, TokenType, UserCode,
};
use crate::basic::BasicErrorResponseType;
use crate::types::VerificationUriComplete;
/// The minimum amount of time in seconds that the client SHOULD wait
/// between polling requests to the token endpoint. If no value is
/// provided, clients MUST use 5 as the default.
fn default_devicecode_interval() -> u64 {
5
}
///
/// Trait for adding extra fields to the `DeviceAuthorizationResponse`.
///
pub trait ExtraDeviceAuthorizationFields: DeserializeOwned + Debug + Serialize {}
#[derive(Clone, Debug, Deserialize, Serialize)]
///
/// Empty (default) extra token fields.
///
pub struct EmptyExtraDeviceAuthorizationFields {}
impl ExtraDeviceAuthorizationFields for EmptyExtraDeviceAuthorizationFields {}
///
/// Standard OAuth2 device authorization response.
///
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DeviceAuthorizationResponse<EF>
where
EF: ExtraDeviceAuthorizationFields,
{
/// The device verification code.
device_code: DeviceCode,
/// The end-user verification code.
user_code: UserCode,
/// The end-user verification URI on the authorization The URI should be
/// short and easy to remember as end users will be asked to manually type
/// it into their user agent.
///
/// The `verification_url` alias here is a deviation from the RFC, as
/// implementations of device code flow predate RFC 8628.
#[serde(alias = "verification_url")]
verification_uri: EndUserVerificationUrl,
/// A verification URI that includes the "user_code" (or other information
/// with the same function as the "user_code"), which is designed for
/// non-textual transmission.
#[serde(skip_serializing_if = "Option::is_none")]
verification_uri_complete: Option<VerificationUriComplete>,
/// The lifetime in seconds of the "device_code" and "user_code".
expires_in: u64,
/// The minimum amount of time in seconds that the client SHOULD wait
/// between polling requests to the token endpoint. If no value is
/// provided, clients MUST use 5 as the default.
#[serde(default = "default_devicecode_interval")]
interval: u64,
#[serde(bound = "EF: ExtraDeviceAuthorizationFields", flatten)]
extra_fields: EF,
}
impl<EF> DeviceAuthorizationResponse<EF>
where
EF: ExtraDeviceAuthorizationFields,
{
/// The device verification code.
pub fn device_code(&self) -> &DeviceCode {
&self.device_code
}
/// The end-user verification code.
pub fn user_code(&self) -> &UserCode {
&self.user_code
}
/// The end-user verification URI on the authorization The URI should be
/// short and easy to remember as end users will be asked to manually type
/// it into their user agent.
pub fn verification_uri(&self) -> &EndUserVerificationUrl {
&self.verification_uri
}
/// A verification URI that includes the "user_code" (or other information
/// with the same function as the "user_code"), which is designed for
/// non-textual transmission.
pub fn verification_uri_complete(&self) -> Option<&VerificationUriComplete> {
self.verification_uri_complete.as_ref()
}
/// The lifetime in seconds of the "device_code" and "user_code".
pub fn expires_in(&self) -> Duration {
Duration::from_secs(self.expires_in)
}
/// The minimum amount of time in seconds that the client SHOULD wait
/// between polling requests to the token endpoint. If no value is
/// provided, clients MUST use 5 as the default.
pub fn interval(&self) -> Duration {
Duration::from_secs(self.interval)
}
/// Any extra fields returned on the response.
pub fn extra_fields(&self) -> &EF {
&self.extra_fields
}
}
///
/// Standard implementation of DeviceAuthorizationResponse which throws away
/// extra received response fields.
///
pub type StandardDeviceAuthorizationResponse =
DeviceAuthorizationResponse<EmptyExtraDeviceAuthorizationFields>;
///
/// Basic access token error types.
///
/// These error types are defined in
/// [Section 5.2 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.2) and
/// [Section 3.5 of RFC 6749](https://tools.ietf.org/html/rfc8628#section-3.5)
///
#[derive(Clone, PartialEq)]
pub enum DeviceCodeErrorResponseType {
///
/// The authorization request is still pending as the end user hasn't
/// yet completed the user-interaction steps. The client SHOULD repeat the
/// access token request to the token endpoint. Before each new request,
/// the client MUST wait at least the number of seconds specified by the
/// "interval" parameter of the device authorization response, or 5 seconds
/// if none was provided, and respect any increase in the polling interval
/// required by the "slow_down" error.
///
AuthorizationPending,
///
/// A variant of "authorization_pending", the authorization request is
/// still pending and polling should continue, but the interval MUST be
/// increased by 5 seconds for this and all subsequent requests.
SlowDown,
///
/// The authorization request was denied.
///
AccessDenied,
///
/// The "device_code" has expired, and the device authorization session has
/// concluded. The client MAY commence a new device authorization request
/// but SHOULD wait for user interaction before restarting to avoid
/// unnecessary polling.
ExpiredToken,
///
/// A Basic response type
///
Basic(BasicErrorResponseType),
}
impl DeviceCodeErrorResponseType {
fn from_str(s: &str) -> Self {
match BasicErrorResponseType::from_str(s) {
BasicErrorResponseType::Extension(ext) => match ext.as_str() {
"authorization_pending" => DeviceCodeErrorResponseType::AuthorizationPending,
"slow_down" => DeviceCodeErrorResponseType::SlowDown,
"access_denied" => DeviceCodeErrorResponseType::AccessDenied,
"expired_token" => DeviceCodeErrorResponseType::ExpiredToken,
_ => DeviceCodeErrorResponseType::Basic(BasicErrorResponseType::Extension(ext)),
},
basic => DeviceCodeErrorResponseType::Basic(basic),
}
}
}
impl AsRef<str> for DeviceCodeErrorResponseType {
fn as_ref(&self) -> &str {
match self {
DeviceCodeErrorResponseType::AuthorizationPending => "authorization_pending",
DeviceCodeErrorResponseType::SlowDown => "slow_down",
DeviceCodeErrorResponseType::AccessDenied => "access_denied",
DeviceCodeErrorResponseType::ExpiredToken => "expired_token",
DeviceCodeErrorResponseType::Basic(basic) => basic.as_ref(),
}
}
}
impl<'de> serde::Deserialize<'de> for DeviceCodeErrorResponseType {
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))
}
}
impl serde::ser::Serialize for DeviceCodeErrorResponseType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
impl ErrorResponseType for DeviceCodeErrorResponseType {}
impl Debug for DeviceCodeErrorResponseType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
Display::fmt(self, f)
}
}
impl Display for DeviceCodeErrorResponseType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f, "{}", self.as_ref())
}
}
///
/// Error response specialization for device code OAuth2 implementation.
///
pub type DeviceCodeErrorResponse = StandardErrorResponse<DeviceCodeErrorResponseType>;
pub(crate) enum DeviceAccessTokenPollResult<TR, RE, TE, TT>
where
TE: ErrorResponse + 'static,
TR: TokenResponse<TT>,
TT: TokenType,
RE: Error + 'static,
{
ContinueWithNewPollInterval(Duration),
Done(Result<TR, RequestTokenError<RE, TE>>, PhantomData<TT>),
}

369
zeroidc/vendor/oauth2/src/helpers.rs vendored Normal file
View File

@@ -0,0 +1,369 @@
use serde::ser::{Impossible, SerializeStructVariant, SerializeTupleVariant};
use serde::{de, ser};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::marker::PhantomData;
///
/// Serde case-insensitive deserializer for an untagged `enum`.
///
/// This function converts values to lowercase before deserializing as the `enum`. Requires the
/// `#[serde(rename_all = "lowercase")]` attribute to be set on the `enum`.
///
/// # Example
///
/// In example below, the following JSON values all deserialize to
/// `GroceryBasket { fruit_item: Fruit::Banana }`:
///
/// * `{"fruit_item": "banana"}`
/// * `{"fruit_item": "BANANA"}`
/// * `{"fruit_item": "Banana"}`
///
/// Note: this example does not compile automatically due to
/// [Rust issue #29286](https://github.com/rust-lang/rust/issues/29286).
///
/// ```
/// # /*
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// #[serde(rename_all = "lowercase")]
/// enum Fruit {
/// Apple,
/// Banana,
/// Orange,
/// }
///
/// #[derive(Deserialize)]
/// struct GroceryBasket {
/// #[serde(deserialize_with = "helpers::deserialize_untagged_enum_case_insensitive")]
/// fruit_item: Fruit,
/// }
/// # */
/// ```
///
pub fn deserialize_untagged_enum_case_insensitive<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: Deserialize<'de>,
D: Deserializer<'de>,
{
use serde::de::Error;
use serde_json::Value;
T::deserialize(Value::String(
String::deserialize(deserializer)?.to_lowercase(),
))
.map_err(Error::custom)
}
///
/// Serde space-delimited string deserializer for a `Vec<String>`.
///
/// This function splits a JSON string at each space character into a `Vec<String>` .
///
/// # Example
///
/// In example below, the JSON value `{"items": "foo bar baz"}` would deserialize to:
///
/// ```
/// # struct GroceryBasket {
/// # items: Vec<String>,
/// # }
/// GroceryBasket {
/// items: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]
/// };
/// ```
///
/// Note: this example does not compile automatically due to
/// [Rust issue #29286](https://github.com/rust-lang/rust/issues/29286).
///
/// ```
/// # /*
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct GroceryBasket {
/// #[serde(deserialize_with = "helpers::deserialize_space_delimited_vec")]
/// items: Vec<String>,
/// }
/// # */
/// ```
///
pub fn deserialize_space_delimited_vec<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: Default + Deserialize<'de>,
D: Deserializer<'de>,
{
use serde::de::Error;
use serde_json::Value;
if let Some(space_delimited) = Option::<String>::deserialize(deserializer)? {
let entries = space_delimited
.split(' ')
.map(|s| Value::String(s.to_string()))
.collect();
T::deserialize(Value::Array(entries)).map_err(Error::custom)
} else {
// If the JSON value is null, use the default value.
Ok(T::default())
}
}
///
/// Deserializes a string or array of strings into an array of strings
///
pub fn deserialize_optional_string_or_vec_string<'de, D>(
deserializer: D,
) -> Result<Option<Vec<String>>, D::Error>
where
D: Deserializer<'de>,
{
struct StringOrVec(PhantomData<Vec<String>>);
impl<'de> de::Visitor<'de> for StringOrVec {
type Value = Option<Vec<String>>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("string or list of strings")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Some(vec![value.to_owned()]))
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_seq<S>(self, visitor: S) -> Result<Self::Value, S::Error>
where
S: de::SeqAccess<'de>,
{
Deserialize::deserialize(de::value::SeqAccessDeserializer::new(visitor)).map(Some)
}
}
deserializer.deserialize_any(StringOrVec(PhantomData))
}
///
/// 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 fn serialize_space_delimited_vec<T, S>(
vec_opt: &Option<Vec<T>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
T: AsRef<str>,
S: Serializer,
{
if let Some(ref vec) = *vec_opt {
let space_delimited = vec.iter().map(|s| s.as_ref()).collect::<Vec<_>>().join(" ");
serializer.serialize_str(&space_delimited)
} else {
serializer.serialize_none()
}
}
///
/// Serde string serializer for an enum.
///<
/// Source:
/// [https://github.com/serde-rs/serde/issues/553](https://github.com/serde-rs/serde/issues/553)
///
pub fn variant_name<T: Serialize>(t: &T) -> &'static str {
#[derive(Debug)]
struct NotEnum;
type Result<T> = std::result::Result<T, NotEnum>;
impl std::error::Error for NotEnum {
fn description(&self) -> &str {
"not struct"
}
}
impl std::fmt::Display for NotEnum {
fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
unimplemented!()
}
}
impl ser::Error for NotEnum {
fn custom<T: std::fmt::Display>(_msg: T) -> Self {
NotEnum
}
}
struct VariantName;
impl Serializer for VariantName {
type Ok = &'static str;
type Error = NotEnum;
type SerializeSeq = Impossible<Self::Ok, Self::Error>;
type SerializeTuple = Impossible<Self::Ok, Self::Error>;
type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
type SerializeTupleVariant = Enum;
type SerializeMap = Impossible<Self::Ok, Self::Error>;
type SerializeStruct = Impossible<Self::Ok, Self::Error>;
type SerializeStructVariant = Enum;
fn serialize_bool(self, _v: bool) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_i8(self, _v: i8) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_i16(self, _v: i16) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_i32(self, _v: i32) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_i64(self, _v: i64) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_u8(self, _v: u8) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_u16(self, _v: u16) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_u32(self, _v: u32) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_u64(self, _v: u64) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_f64(self, _v: f64) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_char(self, _v: char) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_str(self, _v: &str) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_none(self) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_unit(self) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok> {
Ok(variant)
}
fn serialize_newtype_struct<T: ?Sized + Serialize>(
self,
_name: &'static str,
_value: &T,
) -> Result<Self::Ok> {
Err(NotEnum)
}
fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_value: &T,
) -> Result<Self::Ok> {
Ok(variant)
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
Err(NotEnum)
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
Err(NotEnum)
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
Err(NotEnum)
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
Ok(Enum(variant))
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
Err(NotEnum)
}
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct> {
Err(NotEnum)
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
Ok(Enum(variant))
}
}
struct Enum(&'static str);
impl SerializeStructVariant for Enum {
type Ok = &'static str;
type Error = NotEnum;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
_key: &'static str,
_value: &T,
) -> Result<()> {
Ok(())
}
fn end(self) -> Result<Self::Ok> {
Ok(self.0)
}
}
impl SerializeTupleVariant for Enum {
type Ok = &'static str;
type Error = NotEnum;
fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<()> {
Ok(())
}
fn end(self) -> Result<Self::Ok> {
Ok(self.0)
}
}
t.serialize(VariantName).unwrap()
}

3165
zeroidc/vendor/oauth2/src/lib.rs vendored Normal file

File diff suppressed because it is too large Load Diff

129
zeroidc/vendor/oauth2/src/reqwest.rs vendored Normal file
View File

@@ -0,0 +1,129 @@
use thiserror::Error;
///
/// Error type returned by failed reqwest HTTP requests.
///
#[derive(Debug, Error)]
pub enum Error<T>
where
T: std::error::Error + 'static,
{
/// Error returned by reqwest crate.
#[error("request failed")]
Reqwest(#[source] T),
/// Non-reqwest HTTP error.
#[error("HTTP error")]
Http(#[source] http::Error),
/// I/O error.
#[error("I/O error")]
Io(#[source] std::io::Error),
/// Other error.
#[error("Other error: {}", _0)]
Other(String),
}
#[cfg(not(target_arch = "wasm32"))]
pub use blocking::http_client;
///
/// Error type returned by failed reqwest blocking HTTP requests.
///
#[cfg(not(target_arch = "wasm32"))]
pub type HttpClientError = Error<blocking::reqwest::Error>;
pub use async_client::async_http_client;
///
/// Error type returned by failed reqwest async HTTP requests.
///
pub type AsyncHttpClientError = Error<reqwest::Error>;
#[cfg(not(target_arch = "wasm32"))]
mod blocking {
use super::super::{HttpRequest, HttpResponse};
use super::Error;
pub use reqwest;
use reqwest::blocking;
use reqwest::redirect::Policy as RedirectPolicy;
use std::io::Read;
///
/// Synchronous HTTP client.
///
pub fn http_client(request: HttpRequest) -> Result<HttpResponse, Error<reqwest::Error>> {
let client = blocking::Client::builder()
// Following redirects opens the client up to SSRF vulnerabilities.
.redirect(RedirectPolicy::none())
.build()
.map_err(Error::Reqwest)?;
#[cfg(feature = "reqwest")]
let mut request_builder = client
.request(request.method, request.url.as_str())
.body(request.body);
for (name, value) in &request.headers {
request_builder = request_builder.header(name.as_str(), value.as_bytes());
}
let mut response = client
.execute(request_builder.build().map_err(Error::Reqwest)?)
.map_err(Error::Reqwest)?;
let mut body = Vec::new();
response.read_to_end(&mut body).map_err(Error::Io)?;
#[cfg(feature = "reqwest")]
{
Ok(HttpResponse {
status_code: response.status(),
headers: response.headers().to_owned(),
body,
})
}
}
}
mod async_client {
use super::super::{HttpRequest, HttpResponse};
use super::Error;
pub use reqwest;
///
/// Asynchronous HTTP client.
///
pub async fn async_http_client(
request: HttpRequest,
) -> Result<HttpResponse, Error<reqwest::Error>> {
let client = {
let builder = reqwest::Client::builder();
// Following redirects opens the client up to SSRF vulnerabilities.
// but this is not possible to prevent on wasm targets
#[cfg(not(target_arch = "wasm32"))]
let builder = builder.redirect(reqwest::redirect::Policy::none());
builder.build().map_err(Error::Reqwest)?
};
let mut request_builder = client
.request(request.method, request.url.as_str())
.body(request.body);
for (name, value) in &request.headers {
request_builder = request_builder.header(name.as_str(), value.as_bytes());
}
let request = request_builder.build().map_err(Error::Reqwest)?;
let response = client.execute(request).await.map_err(Error::Reqwest)?;
let status_code = response.status();
let headers = response.headers().to_owned();
let chunks = response.bytes().await.map_err(Error::Reqwest)?;
Ok(HttpResponse {
status_code,
headers,
body: chunks.to_vec(),
})
}
}

179
zeroidc/vendor/oauth2/src/revocation.rs vendored Normal file
View File

@@ -0,0 +1,179 @@
use serde::{Deserialize, Serialize};
use std::fmt::Error as FormatterError;
use std::fmt::{Debug, Display, Formatter};
use crate::{basic::BasicErrorResponseType, ErrorResponseType};
use crate::{AccessToken, RefreshToken};
///
/// A revocable token.
///
/// Implement this trait to indicate support for token revocation per [RFC 7009 OAuth 2.0 Token Revocation](https://tools.ietf.org/html/rfc7009#section-2.2).
///
pub trait RevocableToken {
///
/// The actual token value to be revoked.
///
fn secret(&self) -> &str;
///
/// Indicates the type of the token being revoked, as defined by [RFC 7009, Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1).
///
/// Implementations should return `Some(...)` values for token types that the target authorization servers are
/// expected to know (e.g. because they are registered in the [OAuth Token Type Hints Registry](https://tools.ietf.org/html/rfc7009#section-4.1.2))
/// so that they can potentially optimize their search for the token to be revoked.
///
fn type_hint(&self) -> Option<&str>;
}
///
/// A token representation usable with authorization servers that support [RFC 7009](https://tools.ietf.org/html/rfc7009) token revocation.
///
/// For use with [`revoke_token()`].
///
/// Automatically reports the correct RFC 7009 [`token_type_hint`](https://tools.ietf.org/html/rfc7009#section-2.1) value corresponding to the token type variant used, i.e.
/// `access_token` for [`AccessToken`] and `secret_token` for [`RefreshToken`].
///
/// # Example
///
/// Per [RFC 7009, Section 2](https://tools.ietf.org/html/rfc7009#section-2) prefer revocation by refresh token which,
/// if issued to the client, must be supported by the server, otherwise fallback to access token (which may or may not
/// be supported by the server).
///
/// ```ignore
/// let token_to_revoke: StandardRevocableToken = match token_response.refresh_token() {
/// Some(token) => token.into(),
/// None => token_response.access_token().into(),
/// };
///
/// client
/// .revoke_token(token_to_revoke)
/// .request(http_client)
/// .unwrap();
/// ```
///
/// [`revoke_token()`]: crate::Client::revoke_token()
///
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub enum StandardRevocableToken {
/// A representation of an [`AccessToken`] suitable for use with [`revoke_token()`](crate::Client::revoke_token()).
AccessToken(AccessToken),
/// A representation of an [`RefreshToken`] suitable for use with [`revoke_token()`](crate::Client::revoke_token()).
RefreshToken(RefreshToken),
}
impl RevocableToken for StandardRevocableToken {
fn secret(&self) -> &str {
match self {
Self::AccessToken(token) => token.secret(),
Self::RefreshToken(token) => token.secret(),
}
}
///
/// Indicates the type of the token to be revoked, as defined by [RFC 7009, Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1), i.e.:
///
/// * `access_token`: An access token as defined in [RFC 6749,
/// Section 1.4](https://tools.ietf.org/html/rfc6749#section-1.4)
///
/// * `refresh_token`: A refresh token as defined in [RFC 6749,
/// Section 1.5](https://tools.ietf.org/html/rfc6749#section-1.5)
///
fn type_hint(&self) -> Option<&str> {
match self {
StandardRevocableToken::AccessToken(_) => Some("access_token"),
StandardRevocableToken::RefreshToken(_) => Some("refresh_token"),
}
}
}
impl From<AccessToken> for StandardRevocableToken {
fn from(token: AccessToken) -> Self {
Self::AccessToken(token)
}
}
impl From<&AccessToken> for StandardRevocableToken {
fn from(token: &AccessToken) -> Self {
Self::AccessToken(token.clone())
}
}
impl From<RefreshToken> for StandardRevocableToken {
fn from(token: RefreshToken) -> Self {
Self::RefreshToken(token)
}
}
impl From<&RefreshToken> for StandardRevocableToken {
fn from(token: &RefreshToken) -> Self {
Self::RefreshToken(token.clone())
}
}
///
/// OAuth 2.0 Token Revocation error response types.
///
/// These error types are defined in
/// [Section 2.2.1 of RFC 7009](https://tools.ietf.org/html/rfc7009#section-2.2.1) and
/// [Section 5.2 of RFC 6749](https://tools.ietf.org/html/rfc8628#section-5.2)
///
#[derive(Clone, PartialEq)]
pub enum RevocationErrorResponseType {
///
/// The authorization server does not support the revocation of the presented token type.
///
UnsupportedTokenType,
///
/// The authorization server responded with some other error as defined [RFC 6749](https://tools.ietf.org/html/rfc6749) error.
///
Basic(BasicErrorResponseType),
}
impl RevocationErrorResponseType {
fn from_str(s: &str) -> Self {
match BasicErrorResponseType::from_str(s) {
BasicErrorResponseType::Extension(ext) => match ext.as_str() {
"unsupported_token_type" => RevocationErrorResponseType::UnsupportedTokenType,
_ => RevocationErrorResponseType::Basic(BasicErrorResponseType::Extension(ext)),
},
basic => RevocationErrorResponseType::Basic(basic),
}
}
}
impl AsRef<str> for RevocationErrorResponseType {
fn as_ref(&self) -> &str {
match self {
RevocationErrorResponseType::UnsupportedTokenType => "unsupported_token_type",
RevocationErrorResponseType::Basic(basic) => basic.as_ref(),
}
}
}
impl<'de> serde::Deserialize<'de> for RevocationErrorResponseType {
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))
}
}
impl serde::ser::Serialize for RevocationErrorResponseType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
impl ErrorResponseType for RevocationErrorResponseType {}
impl Debug for RevocationErrorResponseType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
Display::fmt(self, f)
}
}
impl Display for RevocationErrorResponseType {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f, "{}", self.as_ref())
}
}

2569
zeroidc/vendor/oauth2/src/tests.rs vendored Normal file

File diff suppressed because it is too large Load Diff

655
zeroidc/vendor/oauth2/src/types.rs vendored Normal file
View File

@@ -0,0 +1,655 @@
use std::convert::Into;
use std::fmt::Error as FormatterError;
use std::fmt::{Debug, Formatter};
use std::ops::Deref;
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use url::Url;
macro_rules! new_type {
// Convenience pattern without an impl.
(
$(#[$attr:meta])*
$name:ident(
$(#[$type_attr:meta])*
$type:ty
)
) => {
new_type![
@new_type $(#[$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 $(#[$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 $(#[$attr:meta])*,
$name:ident(
$(#[$type_attr:meta])*
$type:ty
),
$new_doc:expr,
impl {
$($item:tt)*
}
) => {
$(#[$attr])*
#[derive(Clone, Debug, PartialEq)]
pub struct $name(
$(#[$type_attr])*
$type
);
impl $name {
$($item)*
#[doc = $new_doc]
pub fn new(s: $type) -> Self {
$name(s)
}
}
impl Deref for $name {
type Target = $type;
fn deref(&self) -> &$type {
&self.0
}
}
impl Into<$type> for $name {
fn into(self) -> $type {
self.0
}
}
}
}
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]
)*
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 }
}
impl Debug for $name {
fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
write!(f, concat!(stringify!($name), "([redacted])"))
}
}
};
}
///
/// 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, String);
impl $name {
#[doc = $new_doc]
pub fn new(url: String) -> Result<Self, ::url::ParseError> {
Ok($name(Url::parse(&url)?, url))
}
#[doc = $from_url_doc]
pub fn from_url(url: Url) -> Self {
let s = url.to_string();
Self(url, s)
}
#[doc = $url_doc]
pub fn url(&self) -> &Url {
return &self.0;
}
$($item)*
}
impl Deref for $name {
type Target = String;
fn deref(&self) -> &String {
&self.1
}
}
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 {}
};
}
new_type![
///
/// Client identifier issued to the client during the registration process described by
/// [Section 2.2](https://tools.ietf.org/html/rfc6749#section-2.2).
///
#[derive(Deserialize, Serialize, Eq, Hash)]
ClientId(String)
];
new_url_type![
///
/// URL of the authorization server's authorization endpoint.
///
AuthUrl
];
new_url_type![
///
/// URL of the authorization server's token endpoint.
///
TokenUrl
];
new_url_type![
///
/// URL of the client's redirection endpoint.
///
RedirectUrl
];
new_url_type![
///
/// URL of the client's [RFC 7662 OAuth 2.0 Token Introspection](https://tools.ietf.org/html/rfc7662) endpoint.
///
IntrospectionUrl
];
new_url_type![
///
/// URL of the authorization server's RFC 7009 token revocation endpoint.
///
RevocationUrl
];
new_url_type![
///
/// URL of the client's device authorization endpoint.
///
DeviceAuthorizationUrl
];
new_url_type![
///
/// URL of the end-user verification URI on the authorization server.
///
EndUserVerificationUrl
];
new_type![
///
/// Authorization endpoint response (grant) type defined in
/// [Section 3.1.1](https://tools.ietf.org/html/rfc6749#section-3.1.1).
///
#[derive(Deserialize, Serialize, Eq, Hash)]
ResponseType(String)
];
new_type![
///
/// Resource owner's username used directly as an authorization grant to obtain an access
/// token.
///
#[derive(Deserialize, Serialize, Eq, Hash)]
ResourceOwnerUsername(String)
];
new_type![
///
/// Access token scope, as defined by the authorization server.
///
#[derive(Deserialize, Serialize, Eq, Hash)]
Scope(String)
];
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
self
}
}
new_type![
///
/// Code Challenge Method used for [PKCE]((https://tools.ietf.org/html/rfc7636)) protection
/// via the `code_challenge_method` parameter.
///
#[derive(Deserialize, Serialize, Eq, Hash)]
PkceCodeChallengeMethod(String)
];
// This type intentionally does not implement Clone in order to make it difficult to reuse PKCE
// challenges across multiple requests.
new_secret_type![
///
/// Code Verifier used for [PKCE]((https://tools.ietf.org/html/rfc7636)) protection via the
/// `code_verifier` parameter. The value must have a minimum length of 43 characters and a
/// maximum length of 128 characters. Each character must be ASCII alphanumeric or one of
/// the characters "-" / "." / "_" / "~".
///
#[derive(Deserialize, Serialize)]
PkceCodeVerifier(String)
];
///
/// Code Challenge used for [PKCE]((https://tools.ietf.org/html/rfc7636)) protection via the
/// `code_challenge` parameter.
///
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PkceCodeChallenge {
code_challenge: String,
code_challenge_method: PkceCodeChallengeMethod,
}
impl PkceCodeChallenge {
///
/// Generate a new random, base64-encoded SHA-256 PKCE code.
///
pub fn new_random_sha256() -> (Self, PkceCodeVerifier) {
Self::new_random_sha256_len(32)
}
///
/// Generate a new random, base64-encoded SHA-256 PKCE challenge code and verifier.
///
/// # Arguments
///
/// * `num_bytes` - Number of random bytes to generate, prior to base64-encoding.
/// The value must be in the range 32 to 96 inclusive in order to generate a verifier
/// with a suitable length.
///
/// # Panics
///
/// This method panics if the resulting PKCE code verifier is not of a suitable length
/// to comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).
///
pub fn new_random_sha256_len(num_bytes: u32) -> (Self, PkceCodeVerifier) {
let code_verifier = Self::new_random_len(num_bytes);
(
Self::from_code_verifier_sha256(&code_verifier),
code_verifier,
)
}
///
/// Generate a new random, base64-encoded PKCE code verifier.
///
/// # Arguments
///
/// * `num_bytes` - Number of random bytes to generate, prior to base64-encoding.
/// The value must be in the range 32 to 96 inclusive in order to generate a verifier
/// with a suitable length.
///
/// # Panics
///
/// This method panics if the resulting PKCE code verifier is not of a suitable length
/// to comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).
///
fn new_random_len(num_bytes: u32) -> PkceCodeVerifier {
// The RFC specifies that the code verifier must have "a minimum length of 43
// characters and a maximum length of 128 characters".
// This implies 32-96 octets of random data to be base64 encoded.
assert!(num_bytes >= 32 && num_bytes <= 96);
let random_bytes: Vec<u8> = (0..num_bytes).map(|_| thread_rng().gen::<u8>()).collect();
PkceCodeVerifier::new(base64::encode_config(
&random_bytes,
base64::URL_SAFE_NO_PAD,
))
}
///
/// Generate a SHA-256 PKCE code challenge from the supplied PKCE code verifier.
///
/// # Panics
///
/// This method panics if the supplied PKCE code verifier is not of a suitable length
/// to comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).
///
pub fn from_code_verifier_sha256(code_verifier: &PkceCodeVerifier) -> Self {
// The RFC specifies that the code verifier must have "a minimum length of 43
// characters and a maximum length of 128 characters".
assert!(code_verifier.secret().len() >= 43 && code_verifier.secret().len() <= 128);
let digest = Sha256::digest(code_verifier.secret().as_bytes());
let code_challenge = base64::encode_config(&digest, base64::URL_SAFE_NO_PAD);
Self {
code_challenge,
code_challenge_method: PkceCodeChallengeMethod::new("S256".to_string()),
}
}
///
/// Generate a new random, base64-encoded PKCE code.
/// Use is discouraged unless the endpoint does not support SHA-256.
///
/// # Panics
///
/// This method panics if the supplied PKCE code verifier is not of a suitable length
/// to comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).
///
#[cfg(feature = "pkce-plain")]
pub fn new_random_plain() -> (Self, PkceCodeVerifier) {
let code_verifier = Self::new_random_len(32);
(
Self::from_code_verifier_plain(&code_verifier),
code_verifier,
)
}
///
/// Generate a plain PKCE code challenge from the supplied PKCE code verifier.
/// Use is discouraged unless the endpoint does not support SHA-256.
///
/// # Panics
///
/// This method panics if the supplied PKCE code verifier is not of a suitable length
/// to comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).
///
#[cfg(feature = "pkce-plain")]
pub fn from_code_verifier_plain(code_verifier: &PkceCodeVerifier) -> Self {
// The RFC specifies that the code verifier must have "a minimum length of 43
// characters and a maximum length of 128 characters".
assert!(code_verifier.secret().len() >= 43 && code_verifier.secret().len() <= 128);
let code_challenge = code_verifier.secret().clone();
Self {
code_challenge,
code_challenge_method: PkceCodeChallengeMethod::new("plain".to_string()),
}
}
///
/// Returns the PKCE code challenge as a string.
///
pub fn as_str(&self) -> &str {
&self.code_challenge
}
///
/// Returns the PKCE code challenge method as a string.
///
pub fn method(&self) -> &PkceCodeChallengeMethod {
&self.code_challenge_method
}
}
new_secret_type![
///
/// Client password issued to the client during the registration process described by
/// [Section 2.2](https://tools.ietf.org/html/rfc6749#section-2.2).
///
#[derive(Clone, Deserialize, Serialize)]
ClientSecret(String)
];
new_secret_type![
///
/// Value used for [CSRF](https://tools.ietf.org/html/rfc6749#section-10.12) protection
/// via the `state` parameter.
///
#[must_use]
#[derive(Clone, Deserialize, Serialize)]
CsrfToken(String)
impl {
///
/// Generate a new random, base64-encoded 128-bit CSRF token.
///
pub fn new_random() -> Self {
CsrfToken::new_random_len(16)
}
///
/// Generate a new random, base64-encoded CSRF token 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();
CsrfToken::new(base64::encode_config(&random_bytes, base64::URL_SAFE_NO_PAD))
}
}
];
new_secret_type![
///
/// Authorization code returned from the authorization endpoint.
///
#[derive(Clone, Deserialize, Serialize)]
AuthorizationCode(String)
];
new_secret_type![
///
/// Refresh token used to obtain a new access token (if supported by the authorization server).
///
#[derive(Clone, Deserialize, Serialize)]
RefreshToken(String)
];
new_secret_type![
///
/// Access token returned by the token endpoint and used to access protected resources.
///
#[derive(Clone, Deserialize, Serialize)]
AccessToken(String)
];
new_secret_type![
///
/// Resource owner's password used directly as an authorization grant to obtain an access
/// token.
///
#[derive(Clone)]
ResourceOwnerPassword(String)
];
new_secret_type![
///
/// Device code returned by the device authorization endpoint and used to query the token endpoint.
///
#[derive(Clone, Deserialize, Serialize)]
DeviceCode(String)
];
new_secret_type![
///
/// Verification URI returned by the device authorization endpoint and visited by the user
/// to authorize. Contains the user code.
///
#[derive(Clone, Deserialize, Serialize)]
VerificationUriComplete(String)
];
new_secret_type![
///
/// User code returned by the device authorization endpoint and used by the user to authorize at
/// the verification URI.
///
#[derive(Clone, Deserialize, Serialize)]
UserCode(String)
];

73
zeroidc/vendor/oauth2/src/ureq.rs vendored Normal file
View File

@@ -0,0 +1,73 @@
use http::{
header::{HeaderMap, HeaderValue, CONTENT_TYPE},
method::Method,
status::StatusCode,
};
use super::{HttpRequest, HttpResponse};
///
/// Error type returned by failed ureq HTTP requests.
///
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Non-ureq HTTP error.
#[error("HTTP error")]
Http(#[from] http::Error),
/// IO error
#[error("IO error")]
IO(#[from] std::io::Error),
/// Other error.
#[error("Other error: {}", _0)]
Other(String),
/// Error returned by ureq crate.
// boxed due to https://github.com/algesten/ureq/issues/296
#[error("ureq request failed")]
Ureq(#[from] Box<ureq::Error>),
}
///
/// Synchronous HTTP client for ureq.
///
pub fn http_client(request: HttpRequest) -> Result<HttpResponse, Error> {
let mut req = if let Method::POST = request.method {
ureq::post(&request.url.to_string())
} else {
ureq::get(&request.url.to_string())
};
for (name, value) in request.headers {
if let Some(name) = name {
req = req.set(
&name.to_string(),
value.to_str().map_err(|_| {
Error::Other(format!(
"invalid {} header value {:?}",
name,
value.as_bytes()
))
})?,
);
}
}
let response = if let Method::POST = request.method {
req.send(&*request.body)
} else {
req.call()
}
.map_err(Box::new)?;
Ok(HttpResponse {
status_code: StatusCode::from_u16(response.status())
.map_err(|err| Error::Http(err.into()))?,
headers: vec![(
CONTENT_TYPE,
HeaderValue::from_str(response.content_type())
.map_err(|err| Error::Http(err.into()))?,
)]
.into_iter()
.collect::<HeaderMap>(),
body: response.into_string()?.as_bytes().into(),
})
}