Skip to content

Commit

Permalink
change example to use twilight_util::signature_validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Monadic-Cat committed Apr 18, 2024
1 parent 239aa94 commit 620cbfd
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 15 deletions.
3 changes: 1 addition & 2 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ version = "0.0.0"

[dev-dependencies]
anyhow = { default-features = false, features = ["std"], version = "1" }
ed25519-dalek = "2"
futures-util = { default-features = false, version = "0.3" }
hex = "0.4"
hyper = { features = ["client", "server", "http2", "runtime"], version = "0.14" }
log = { default-features = false, version = "0.4" }
once_cell = "1.4"
Expand All @@ -23,6 +21,7 @@ twilight-http = { path = "../twilight-http" }
twilight-lavalink = { path = "../twilight-lavalink" }
twilight-model = { path = "../twilight-model" }
twilight-standby = { path = "../twilight-standby" }
twilight-util = { path = "../twilight-util", features = ["signature-validation"] }

[[example]]
name = "gateway-parallel"
Expand Down
18 changes: 5 additions & 13 deletions examples/model-webhook-slash.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use ed25519_dalek::{Verifier, VerifyingKey, PUBLIC_KEY_LENGTH};
use hex::FromHex;
use hyper::{
header::CONTENT_TYPE,
http::StatusCode,
Expand All @@ -14,12 +12,10 @@ use twilight_model::{
},
http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType},
};
use twilight_util::signature_validation::Key;

/// Public key given from Discord.
static PUB_KEY: Lazy<VerifyingKey> = Lazy::new(|| {
VerifyingKey::from_bytes(&<[u8; PUBLIC_KEY_LENGTH] as FromHex>::from_hex("PUBLIC_KEY").unwrap())
.unwrap()
});
static PUB_KEY: Lazy<Key> = Lazy::new(|| Key::from_hex("PUBLIC_KEY".as_bytes()).unwrap());

/// Main request handler which will handle checking the signature.
///
Expand Down Expand Up @@ -61,10 +57,9 @@ where
// Extract the signature to check against.
let signature = if let Some(hex_sig) = req
.headers()
.get("x-signature-ed25519")
.and_then(|v| v.to_str().ok())
.get(twilight_util::signature_validation::SIGNATURE_HEADER)
{
hex_sig.parse().unwrap()
hex_sig.to_owned()
} else {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
Expand All @@ -77,10 +72,7 @@ where

// Check if the signature matches and else return a error response.
if PUB_KEY
.verify(
[timestamp.as_bytes(), &whole_body].concat().as_ref(),
&signature,
)
.verify(signature.as_bytes(), timestamp.as_bytes(), &whole_body)
.is_err()
{
return Ok(Response::builder()
Expand Down

0 comments on commit 620cbfd

Please sign in to comment.