1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-29 22:01:14 +03:00

PKCE support

This commit is contained in:
Quentin Gliech
2021-10-05 14:08:21 +02:00
parent af71adbe7a
commit 8ecdf7c6c8
12 changed files with 168 additions and 57 deletions

View File

@ -16,6 +16,8 @@ indoc = "1.0.3"
serde_with = { version = "1.10.0", features = ["chrono"] }
sqlx = { version = "0.5.9", default-features = false, optional = true }
chrono = "0.4.19"
sha2 = "0.9.8"
data-encoding = "2.3.2"
[features]
sqlx_type = ["sqlx"]

View File

@ -237,6 +237,7 @@ pub mod rfc6749 {
oauth2_error! {
ServerError,
code: INTERNAL_SERVER_ERROR,
"server_error" =>
"The authorization server encountered an unexpected \
condition that prevented it from fulfilling the request."

View File

@ -12,8 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::borrow::Cow;
use data_encoding::BASE64URL_NOPAD;
use parse_display::{Display, FromStr};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(
Debug,
@ -41,8 +45,34 @@ pub enum CodeChallengeMethod {
S256 = 1,
}
impl CodeChallengeMethod {
#[must_use]
pub fn compute_challenge(self, verifier: &str) -> Cow<'_, str> {
match self {
CodeChallengeMethod::Plain => verifier.into(),
CodeChallengeMethod::S256 => {
let mut hasher = Sha256::new();
hasher.update(verifier.as_bytes());
let hash = hasher.finalize();
let verifier = BASE64URL_NOPAD.encode(&hash);
verifier.into()
}
}
}
#[must_use]
pub fn verify(self, challenge: &str, verifier: &str) -> bool {
self.compute_challenge(verifier) == challenge
}
}
#[derive(Serialize, Deserialize)]
pub struct Request {
pub struct AuthorizationRequest {
pub code_challenge_method: CodeChallengeMethod,
pub code_challenge: String,
}
#[derive(Serialize, Deserialize)]
pub struct TokenRequest {
pub code_challenge_verifier: String,
}

View File

@ -200,11 +200,16 @@ pub enum TokenType {
Bearer,
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct AuthorizationCodeGrant {
pub code: String,
#[serde(default)]
pub redirect_uri: Option<Url>,
// TODO: move this somehow in the pkce module
#[serde(default)]
pub code_verifier: Option<String>,
}
#[serde_as]
@ -406,6 +411,7 @@ mod tests {
let req = AccessTokenRequest::AuthorizationCode(AuthorizationCodeGrant {
code: "abcd".into(),
redirect_uri: Some("https://example.com/redirect".parse().unwrap()),
code_verifier: None,
});
assert_serde_json(&req, expected);