1use core::{
81 fmt,
82 future::Future,
83 pin::Pin,
84 task::{Context, Poll, Waker},
85};
86use std::{
87 sync::{Arc, Mutex, PoisonError},
88 task::Wake,
89};
90
91use djs_cache::{Backend, DashMapBackend};
92use djs_model::{
93 gateway::payload::InteractionCreate,
94 id::InteractionId,
95 interaction::{InteractionData, InteractionResponse},
96 util::Timestamp,
97};
98use djs_rest::{Error, Rest};
99use ed25519_dalek::{Signature, VerifyingKey};
100use tokio::sync::oneshot;
101
102use crate::Client;
103
104const MAX_AGE_SECS: u64 = 5 * 60;
106
107const PONG: &[u8] = br#"{"type":1}"#;
109
110type Background = Pin<Box<dyn Future<Output = ()> + Send>>;
112
113pub(crate) enum Initial {
115 Body(Vec<u8>),
117 Rest,
119}
120
121pub(crate) type InitialSender = oneshot::Sender<Initial>;
123
124pub(crate) type InitialReceiver = oneshot::Receiver<Initial>;
126
127pub(crate) struct Inline {
130 interaction: InteractionId,
131 slot: Mutex<Option<InitialSender>>,
132}
133
134impl Inline {
135 pub(crate) fn new(interaction: InteractionId) -> (Self, InitialReceiver) {
137 let (sender, receiver) = oneshot::channel();
138 let inline = Self {
139 interaction,
140 slot: Mutex::new(Some(sender)),
141 };
142 (inline, receiver)
143 }
144
145 pub(crate) fn take(&self, interaction: InteractionId) -> Option<InitialSender> {
147 if interaction != self.interaction {
148 return None;
149 }
150 self.slot
151 .lock()
152 .unwrap_or_else(PoisonError::into_inner)
153 .take()
154 }
155}
156
157pub(crate) async fn respond(
160 rest: &Rest,
161 initial: InitialSender,
162 interaction: InteractionId,
163 token: &str,
164 response: &InteractionResponse,
165) -> Result<(), Error> {
166 if response.files().is_empty()
167 && let Ok(body) = serde_json::to_vec(response)
168 {
169 let _ = initial.send(Initial::Body(body));
171 return Ok(());
172 }
173 rest.create_interaction_response(interaction, token, response)
174 .await?;
175 let _ = initial.send(Initial::Rest);
176 Ok(())
177}
178
179#[derive(Clone, Debug, PartialEq, Eq)]
185#[non_exhaustive]
186pub struct HttpResponse {
187 pub status: u16,
190 pub body: Vec<u8>,
192}
193
194impl HttpResponse {
195 const fn empty(status: u16) -> Self {
196 Self {
197 status,
198 body: Vec::new(),
199 }
200 }
201}
202
203#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
208#[error("the public key is not 64 hexadecimal digits of a valid Ed25519 key")]
209pub struct InvalidPublicKey;
210
211pub struct InteractionsEndpoint<B: Backend = DashMapBackend> {
219 client: Client<B>,
220 key: VerifyingKey,
221}
222
223impl<B: Backend> Clone for InteractionsEndpoint<B> {
224 fn clone(&self) -> Self {
225 Self {
226 client: self.client.clone(),
227 key: self.key,
228 }
229 }
230}
231
232impl<B: Backend> fmt::Debug for InteractionsEndpoint<B> {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 f.debug_struct("InteractionsEndpoint")
235 .field("client", &self.client)
236 .finish_non_exhaustive()
237 }
238}
239
240impl<B: Backend> InteractionsEndpoint<B> {
241 pub(crate) fn new(client: Client<B>, public_key: &str) -> Result<Self, InvalidPublicKey> {
242 let bytes = decode_hex::<32>(public_key).ok_or(InvalidPublicKey)?;
243 let key = VerifyingKey::from_bytes(&bytes).map_err(|_| InvalidPublicKey)?;
244 Ok(Self { client, key })
245 }
246
247 pub async fn handle(
259 &self,
260 signature: &str,
261 timestamp: &str,
262 body: &[u8],
263 ) -> (
264 HttpResponse,
265 impl Future<Output = ()> + Send + 'static + use<B>,
266 ) {
267 let idle = || -> Background { Box::pin(core::future::ready(())) };
268 if !verify(
269 &self.key,
270 signature,
271 timestamp,
272 body,
273 Timestamp::now().as_unix_secs(),
274 ) {
275 return (HttpResponse::empty(401), idle());
276 }
277 let event: InteractionCreate = match serde_json::from_slice(body) {
278 Ok(event) => event,
279 Err(error) => {
280 tracing::warn!(%error, "a signed HTTP interaction could not be decoded");
281 return (HttpResponse::empty(400), idle());
282 }
283 };
284 if matches!(event.data, InteractionData::Ping) {
285 let pong = HttpResponse {
286 status: 200,
287 body: PONG.to_vec(),
288 };
289 return (pong, idle());
290 }
291 let (mut initial, work) = self.client.dispatch_http(event);
292 let mut work = Relayed::new(work);
293 tokio::select! {
294 biased;
295 result = &mut initial => (answer(result.ok()), Box::pin(work)),
296 () = &mut work => (answer(initial.try_recv().ok()), idle()),
297 }
298 }
299}
300
301struct Relayed {
307 future: Background,
308 relay: Arc<Relay>,
309 waker: Waker,
310}
311
312struct Relay(Mutex<Option<Waker>>);
314
315impl Wake for Relay {
316 fn wake(self: Arc<Self>) {
317 self.wake_by_ref();
318 }
319
320 fn wake_by_ref(self: &Arc<Self>) {
321 if let Some(waker) = &*self.0.lock().unwrap_or_else(PoisonError::into_inner) {
322 waker.wake_by_ref();
323 }
324 }
325}
326
327impl Relayed {
328 fn new(future: Background) -> Self {
329 let relay = Arc::new(Relay(Mutex::new(None)));
330 let waker = Waker::from(Arc::clone(&relay));
331 Self {
332 future,
333 relay,
334 waker,
335 }
336 }
337}
338
339impl Future for Relayed {
340 type Output = ();
341
342 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
343 let this = self.get_mut();
344 {
345 let mut last = this.relay.0.lock().unwrap_or_else(PoisonError::into_inner);
346 if !last
347 .as_ref()
348 .is_some_and(|waker| waker.will_wake(cx.waker()))
349 {
350 *last = Some(cx.waker().clone());
351 }
352 }
353 this.future
354 .as_mut()
355 .poll(&mut Context::from_waker(&this.waker))
356 }
357}
358
359fn answer(initial: Option<Initial>) -> HttpResponse {
361 match initial {
362 Some(Initial::Body(body)) => HttpResponse { status: 200, body },
363 Some(Initial::Rest) => HttpResponse::empty(202),
364 None => {
365 tracing::warn!("the handlers of an HTTP interaction finished without responding");
366 HttpResponse::empty(500)
367 }
368 }
369}
370
371fn verify(key: &VerifyingKey, signature: &str, timestamp: &str, body: &[u8], now: i64) -> bool {
374 let Ok(signed_at) = timestamp.parse::<i64>() else {
375 return false;
376 };
377 if now.abs_diff(signed_at) > MAX_AGE_SECS {
378 return false;
379 }
380 let Some(signature) = decode_hex::<64>(signature) else {
381 return false;
382 };
383 let mut message = Vec::with_capacity(timestamp.len() + body.len());
384 message.extend_from_slice(timestamp.as_bytes());
385 message.extend_from_slice(body);
386 key.verify_strict(&message, &Signature::from_bytes(&signature))
387 .is_ok()
388}
389
390fn decode_hex<const N: usize>(hex: &str) -> Option<[u8; N]> {
392 const fn digit(c: u8) -> Option<u8> {
393 match c {
394 b'0'..=b'9' => Some(c - b'0'),
395 b'a'..=b'f' => Some(c - b'a' + 10),
396 b'A'..=b'F' => Some(c - b'A' + 10),
397 _ => None,
398 }
399 }
400 let hex = hex.as_bytes();
401 if hex.len() != 2 * N {
402 return None;
403 }
404 let mut out = [0; N];
405 for (byte, pair) in out.iter_mut().zip(hex.as_chunks::<2>().0) {
406 *byte = (digit(pair[0])? << 4) | digit(pair[1])?;
407 }
408 Some(out)
409}
410
411#[cfg(test)]
412mod tests {
413 use core::fmt::Write as _;
414
415 use ed25519_dalek::{Signer, SigningKey};
416
417 use super::*;
418
419 const NOW: i64 = 1_800_000_000;
420
421 fn hex(bytes: &[u8]) -> String {
422 bytes.iter().fold(String::new(), |mut hex, byte| {
423 let _ = write!(hex, "{byte:02x}");
424 hex
425 })
426 }
427
428 fn key() -> SigningKey {
429 SigningKey::from_bytes(&[7; 32])
430 }
431
432 fn sign(timestamp: &str, body: &[u8]) -> String {
433 let mut message = timestamp.as_bytes().to_vec();
434 message.extend_from_slice(body);
435 hex(&key().sign(&message).to_bytes())
436 }
437
438 #[test]
439 fn decodes_hex_of_the_exact_length_only() {
440 assert_eq!(decode_hex::<2>("0aFf"), Some([0x0a, 0xff]));
441 assert_eq!(decode_hex::<2>("0aF"), None);
442 assert_eq!(decode_hex::<2>("0aFf0"), None);
443 assert_eq!(decode_hex::<2>("0aFg"), None);
444 assert_eq!(decode_hex::<1>("é"), None);
445 }
446
447 #[test]
448 fn verifies_the_signature_of_the_timestamp_and_body() {
449 let public = key().verifying_key();
450 let (timestamp, body) = ("1800000000", br#"{"type":1}"#.as_slice());
451 let signature = sign(timestamp, body);
452 assert!(verify(&public, &signature, timestamp, body, NOW));
453 assert!(verify(
454 &public,
455 &signature.to_uppercase(),
456 timestamp,
457 body,
458 NOW
459 ));
460 assert!(!verify(
462 &public,
463 &signature,
464 timestamp,
465 br#"{"type":2}"#,
466 NOW
467 ));
468 assert!(!verify(&public, &signature, "1800000001", body, NOW));
469 let other = SigningKey::from_bytes(&[8; 32]).verifying_key();
470 assert!(!verify(&other, &signature, timestamp, body, NOW));
471 assert!(!verify(&public, &signature[2..], timestamp, body, NOW));
472 assert!(!verify(&public, "", timestamp, body, NOW));
473 }
474
475 #[test]
476 fn rejects_timestamps_more_than_five_minutes_away() {
477 let public = key().verifying_key();
478 let body = b"{}";
479 for (offset, valid) in [
480 (0, true),
481 (300, true),
482 (-300, true),
483 (301, false),
484 (-301, false),
485 ] {
486 let timestamp = (NOW + offset).to_string();
487 let signature = sign(×tamp, body);
488 assert_eq!(
489 verify(&public, &signature, ×tamp, body, NOW),
490 valid,
491 "{offset}"
492 );
493 }
494 let signature = sign("soon", body);
495 assert!(!verify(&public, &signature, "soon", body, NOW));
496 }
497
498 #[derive(Clone, Default)]
500 struct FirstWaker(Arc<Mutex<(bool, Option<Waker>)>>);
501
502 impl FirstWaker {
503 fn complete(&self) {
504 let mut state = self.0.lock().unwrap();
505 state.0 = true;
506 if let Some(waker) = state.1.take() {
507 waker.wake();
508 }
509 }
510 }
511
512 impl Future for FirstWaker {
513 type Output = ();
514
515 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
516 let mut state = self.0.lock().unwrap();
517 if state.0 {
518 return Poll::Ready(());
519 }
520 state.1.get_or_insert_with(|| cx.waker().clone());
521 Poll::Pending
522 }
523 }
524
525 #[tokio::test]
526 async fn background_work_resumes_in_the_task_it_moves_to() {
527 let leaf = FirstWaker::default();
528 let inner = leaf.clone();
529 let mut work = Relayed::new(Box::pin(inner));
530 let first = Waker::noop();
532 assert!(
533 Pin::new(&mut work)
534 .poll(&mut Context::from_waker(first))
535 .is_pending()
536 );
537 let task = tokio::spawn(work);
539 tokio::task::yield_now().await;
540 leaf.complete();
541 tokio::time::timeout(core::time::Duration::from_secs(5), task)
542 .await
543 .expect("the moved task was woken")
544 .unwrap();
545 }
546
547 #[test]
548 fn the_endpoint_needs_a_valid_public_key() {
549 let client = Client::builder("token").build();
550 let hex = hex(&key().verifying_key().to_bytes());
551 assert!(client.interactions_endpoint(&hex).is_ok());
552 assert_eq!(
553 client.interactions_endpoint(&hex[1..]).unwrap_err(),
554 InvalidPublicKey
555 );
556 assert_eq!(
557 client.interactions_endpoint("zz").unwrap_err(),
558 InvalidPublicKey
559 );
560 }
561}