From 93d158973034cdb869684818b603f402b17bfdc6 Mon Sep 17 00:00:00 2001 From: oxalica Date: Fri, 13 Sep 2024 03:30:02 -0400 Subject: [PATCH] refactor(types): `WithSig` -> `Signed` --- blah-types/src/lib.rs | 10 +++++----- blahctl/src/main.rs | 8 ++++---- blahd/src/event.rs | 4 ++-- blahd/src/lib.rs | 6 +++--- blahd/src/middleware.rs | 8 ++++---- blahd/tests/webapi.rs | 6 +++--- docs/webapi.yaml | 36 ++++++++++++++++++------------------ 7 files changed, 39 insertions(+), 39 deletions(-) diff --git a/blah-types/src/lib.rs b/blah-types/src/lib.rs index 56e13cf..496a82c 100644 --- a/blah-types/src/lib.rs +++ b/blah-types/src/lib.rs @@ -60,7 +60,7 @@ impl fmt::Display for UserKey { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct WithSig { +pub struct Signed { #[serde(with = "hex::serde")] pub sig: [u8; SIGNATURE_LENGTH], pub signee: Signee, @@ -82,7 +82,7 @@ pub fn get_timestamp() -> u64 { .as_secs() } -impl WithSig { +impl Signed { /// Sign the payload with the given `key`. pub fn sign( key: &SigningKey, @@ -308,7 +308,7 @@ impl RichText { } } -pub type SignedChatMsg = WithSig; +pub type SignedChatMsg = Signed; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RoomMetadata { @@ -551,7 +551,7 @@ mod tests { let mut fake_rng = rand::rngs::mock::StepRng::new(0x42, 1); let signing_key = SigningKey::from_bytes(&[0x42; 32]); let timestamp = 0xDEAD_BEEF; - let msg = WithSig::sign( + let msg = Signed::sign( &signing_key, timestamp, &mut fake_rng, @@ -568,7 +568,7 @@ mod tests { ]]; expect.assert_eq(&json); - let roundtrip_msg = serde_json::from_str::>(&json).unwrap(); + let roundtrip_msg = serde_json::from_str::>(&json).unwrap(); assert_eq!(roundtrip_msg, msg); roundtrip_msg.verify().unwrap(); } diff --git a/blahctl/src/main.rs b/blahctl/src/main.rs index 593664b..6761d67 100644 --- a/blahctl/src/main.rs +++ b/blahctl/src/main.rs @@ -5,7 +5,7 @@ use std::{fs, io}; use anyhow::{Context, Result}; use blah_types::{ bitflags, get_timestamp, ChatPayload, CreateGroup, CreateRoomPayload, Id, MemberPermission, - RichText, RoomAttrs, RoomMember, RoomMemberList, ServerPermission, UserKey, WithSig, + RichText, RoomAttrs, RoomMember, RoomMemberList, ServerPermission, Signed, UserKey, }; use ed25519_dalek::pkcs8::spki::der::pem::LineEnding; use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey}; @@ -227,7 +227,7 @@ async fn main_api(api_url: Url, command: ApiCommand) -> Result<()> { user: UserKey(key.verifying_key().to_bytes()), }]), }); - let payload = WithSig::sign(&key, get_timestamp(), &mut OsRng, payload)?; + let payload = Signed::sign(&key, get_timestamp(), &mut OsRng, payload)?; let ret = client .post(api_url.join("/room/create")?) @@ -249,10 +249,10 @@ async fn main_api(api_url: Url, command: ApiCommand) -> Result<()> { room: Id(room), rich_text: RichText::from(text), }; - let payload = WithSig::sign(&key, get_timestamp(), &mut OsRng, payload)?; + let payload = Signed::sign(&key, get_timestamp(), &mut OsRng, payload)?; let ret = client - .post(api_url.join(&format!("/room/{room}/item"))?) + .post(api_url.join(&format!("/room/{room}/msg"))?) .json(&payload) .send() .await? diff --git a/blahd/src/event.rs b/blahd/src/event.rs index f2986c8..db8a126 100644 --- a/blahd/src/event.rs +++ b/blahd/src/event.rs @@ -8,7 +8,7 @@ use std::task::{Context, Poll}; use anyhow::{bail, Context as _, Result}; use axum::extract::ws::{Message, WebSocket}; -use blah_types::{AuthPayload, SignedChatMsg, WithSig}; +use blah_types::{AuthPayload, Signed, SignedChatMsg}; use futures_util::future::Either; use futures_util::stream::SplitSink; use futures_util::{stream_select, SinkExt as _, Stream, StreamExt}; @@ -113,7 +113,7 @@ pub async fn handle_ws(st: Arc, ws: &mut WebSocket) -> Result>(&payload)?; + let auth = serde_json::from_str::>(&payload)?; st.verify_signed_data(&auth)?; st.db diff --git a/blahd/src/lib.rs b/blahd/src/lib.rs index 927d86c..edcfcd3 100644 --- a/blahd/src/lib.rs +++ b/blahd/src/lib.rs @@ -12,8 +12,8 @@ use axum::{Json, Router}; use axum_extra::extract::WithRejection as R; use blah_types::{ ChatPayload, CreateGroup, CreatePeerChat, CreateRoomPayload, Id, MemberPermission, RoomAdminOp, - RoomAdminPayload, RoomAttrs, RoomMetadata, ServerPermission, SignedChatMsg, Signee, UserKey, - WithMsgId, WithSig, + RoomAdminPayload, RoomAttrs, RoomMetadata, ServerPermission, Signed, SignedChatMsg, Signee, + UserKey, WithMsgId, }; use config::ServerConfig; use ed25519_dalek::SIGNATURE_LENGTH; @@ -59,7 +59,7 @@ impl AppState { } } - fn verify_signed_data(&self, data: &WithSig) -> Result<(), ApiError> { + fn verify_signed_data(&self, data: &Signed) -> Result<(), ApiError> { let Ok(()) = data.verify() else { return Err(error_response!( StatusCode::BAD_REQUEST, diff --git a/blahd/src/middleware.rs b/blahd/src/middleware.rs index 6286351..2c5e21a 100644 --- a/blahd/src/middleware.rs +++ b/blahd/src/middleware.rs @@ -6,7 +6,7 @@ use axum::extract::{FromRef, FromRequest, FromRequestParts, Request}; use axum::http::{header, request, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::{async_trait, Json}; -use blah_types::{AuthPayload, UserKey, WithSig}; +use blah_types::{AuthPayload, Signed, UserKey}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; @@ -95,7 +95,7 @@ impl From for ApiError { /// Extractor for verified JSON payload. #[derive(Debug)] -pub struct SignedJson(pub WithSig); +pub struct SignedJson(pub Signed); #[async_trait] impl FromRequest for SignedJson @@ -107,7 +107,7 @@ where type Rejection = ApiError; async fn from_request(req: Request, state: &S) -> Result { - let Json(data) = > as FromRequest>::from_request(req, state).await?; + let Json(data) = > as FromRequest>::from_request(req, state).await?; let st = >::from_ref(state); st.verify_signed_data(&data)?; Ok(Self(data)) @@ -178,7 +178,7 @@ where let st = >::from_ref(state); let data = - serde_json::from_slice::>(auth.as_bytes()).map_err(|err| { + serde_json::from_slice::>(auth.as_bytes()).map_err(|err| { AuthRejection::Invalid(error_response!( StatusCode::BAD_REQUEST, "deserialization", diff --git a/blahd/tests/webapi.rs b/blahd/tests/webapi.rs index c3e5996..3d1602c 100644 --- a/blahd/tests/webapi.rs +++ b/blahd/tests/webapi.rs @@ -9,7 +9,7 @@ use anyhow::Result; use blah_types::{ get_timestamp, AuthPayload, ChatPayload, CreateGroup, CreatePeerChat, CreateRoomPayload, Id, MemberPermission, RichText, RoomAdminOp, RoomAdminPayload, RoomAttrs, RoomMember, - RoomMemberList, RoomMetadata, ServerPermission, SignedChatMsg, UserKey, WithMsgId, WithSig, + RoomMemberList, RoomMetadata, ServerPermission, Signed, SignedChatMsg, UserKey, WithMsgId, }; use blahd::{ApiError, AppState, Database, RoomList, RoomMsgs}; use ed25519_dalek::SigningKey; @@ -241,8 +241,8 @@ async fn smoke(server: Server) { assert_eq!(got, exp); } -fn sign(key: &SigningKey, rng: &mut dyn RngCore, payload: T) -> WithSig { - WithSig::sign(key, get_timestamp(), rng, payload).unwrap() +fn sign(key: &SigningKey, rng: &mut dyn RngCore, payload: T) -> Signed { + Signed::sign(key, get_timestamp(), rng, payload).unwrap() } fn auth(key: &SigningKey, rng: &mut impl RngCore) -> String { diff --git a/docs/webapi.yaml b/docs/webapi.yaml index 19563cf..59c18ad 100644 --- a/docs/webapi.yaml +++ b/docs/webapi.yaml @@ -13,7 +13,7 @@ paths: This endpoint is for server-side-event dispatching. Once connected, client must send a JSON text message of type - `WithSig-Auth` for authentication. + `Signed-Auth` for authentication. If server does not close it immediately, it means success. Since OAPI does not support WebSocket interface, we use request and @@ -88,7 +88,7 @@ paths: in: header description: Optional proof of membership for private rooms. schema: - $ref: '#/components/schemas/WithSig-Auth' + $ref: '#/components/schemas/Signed-Auth' responses: 200: @@ -119,7 +119,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/WithSig-CreateRoom' + $ref: '#/components/schemas/Signed-CreateRoom' responses: 200: @@ -159,7 +159,7 @@ paths: in: header description: Optional proof of membership for private rooms. schema: - $ref: '#/components/schemas/WithSig-Auth' + $ref: '#/components/schemas/Signed-Auth' responses: 200: @@ -185,7 +185,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/WithSig-RoomAdmin' + $ref: '#/components/schemas/Signed-RoomAdmin' responses: 204: @@ -244,7 +244,7 @@ paths: in: header description: Optional proof of membership for private rooms. schema: - $ref: '#/components/schemas/WithSig-Auth' + $ref: '#/components/schemas/Signed-Auth' - name: top in: query @@ -284,7 +284,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/WithSig-Chat' + $ref: '#/components/schemas/Signed-Chat' responses: 200: @@ -325,7 +325,7 @@ paths: required: true description: Proof of membership for private rooms. schema: - $ref: '#/components/schemas/WithSig-Auth' + $ref: '#/components/schemas/Signed-Auth' responses: 204: @@ -345,14 +345,14 @@ components: schemas: WSClientToServer: anyOf: - - $ref: '#/components/schemas/WithSig-Auth' + - $ref: '#/components/schemas/Signed-Auth' WSServerToClient: anyOf: - type: object properties: chat: - $ref: '#/components/schemas/WithSig-Chat' + $ref: '#/components/schemas/Signed-Chat' - type: object properties: @@ -401,7 +401,7 @@ components: type: integer format: int64 last_msg: - $ref: '#/components/schemas/WithMsgId-WithSig-Chat' + $ref: '#/components/schemas/WithMsgId-Signed-Chat' last_seen_cid: description: The `cid` of the last chat being marked as seen. type: string @@ -440,7 +440,7 @@ components: description: Room messages in reversed server-received time order. type: array items: - $ref: '#/components/schemas/WithMsgId-WithSig-Chat' + $ref: '#/components/schemas/WithMsgId-Signed-Chat' skip_token: description: The token for fetching the next page. type: string @@ -481,7 +481,7 @@ components: description: Link target. - WithSig-Auth: + Signed-Auth: type: object properties: sig: @@ -499,7 +499,7 @@ components: type: string const: 'auth' - WithSig-RoomAdmin: + Signed-RoomAdmin: type: object properties: sig: @@ -551,7 +551,7 @@ components: timestamp: 1724966284 user: 83ce46ced47ec0391c64846cbb6c507250ead4985b6a044d68751edc46015dd7 - WithSig-Chat: + Signed-Chat: type: object properties: sig: @@ -583,16 +583,16 @@ components: timestamp: 1724966284 user: 83ce46ced47ec0391c64846cbb6c507250ead4985b6a044d68751edc46015dd7 - WithMsgId-WithSig-Chat: + WithMsgId-Signed-Chat: allOf: - - $ref: '#/components/schemas/WithSig-Chat' + - $ref: '#/components/schemas/Signed-Chat' - type: object properties: cid: type: string description: An opaque server-specific identifier. - WithSig-CreateRoom: + Signed-CreateRoom: type: object properties: sig: