JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Progress on refactor

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨c9f076f

⁨giterated-models/src/model/authenticated.rs⁩ - ⁨6011⁩ bytes
Raw
1 use std::fmt::Debug;
2
3 use rsa::{
4 pkcs1::DecodeRsaPrivateKey,
5 pss::SigningKey,
6 sha2::Sha256,
7 signature::{RandomizedSigner, SignatureEncoding},
8 RsaPrivateKey,
9 };
10 use serde::{Deserialize, Serialize};
11 use serde_json::Value;
12 use tracing::info;
13
14 use crate::operation::{
15 AnyObject, AnyOperation, GiteratedMessage, GiteratedObject, GiteratedOperation,
16 };
17
18 use super::{instance::Instance, user::User, MessageTarget};
19
20 #[derive(Debug, Serialize, Deserialize)]
21 pub struct UserTokenMetadata {
22 pub user: User,
23 pub generated_for: Instance,
24 pub exp: u64,
25 }
26
27 #[derive(Debug)]
28 pub struct Authenticated<O: GiteratedObject, D: GiteratedOperation<O>> {
29 pub source: Vec<Box<dyn AuthenticationSourceProvider + Send + Sync>>,
30 pub message: GiteratedMessage<O, D>,
31 }
32
33 #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
34 pub struct AuthenticatedPayload {
35 pub source: Vec<AuthenticationSource>,
36 pub object: String,
37 pub operation: String,
38 pub payload: Vec<u8>,
39 }
40
41 impl AuthenticatedPayload {
42 pub fn into_message(self) -> GiteratedMessage<AnyObject, AnyOperation> {
43 GiteratedMessage {
44 object: AnyObject(self.object),
45 operation: self.operation,
46 payload: AnyOperation(serde_json::from_slice::<Value>(&self.payload).unwrap()),
47 }
48 }
49 }
50
51 // impl<T: Serialize> From<Authenticated<T>> for AuthenticatedPayload {
52 // fn from(mut value: Authenticated<T>) -> Self {
53 // let payload = bincode::serialize(&value.message).unwrap();
54
55 // AuthenticatedPayload {
56 // target_instance: value.target_instance,
57 // source: value
58 // .source
59 // .drain(..)
60 // .map(|provider| provider.as_ref().authenticate(&payload))
61 // .collect::<Vec<_>>(),
62 // message_type: value.message_type,
63 // payload,
64 // }
65 // }
66 // }
67
68 pub trait AuthenticationSourceProvider: Debug {
69 fn authenticate(&self, payload: &Vec<u8>) -> AuthenticationSource;
70 }
71
72 pub trait AuthenticationSourceProviders: Debug {
73 fn authenticate_all(&self, payload: &Vec<u8>) -> Vec<AuthenticationSource>;
74 }
75
76 impl<A> AuthenticationSourceProviders for A
77 where
78 A: AuthenticationSourceProvider,
79 {
80 fn authenticate_all(&self, payload: &Vec<u8>) -> Vec<AuthenticationSource> {
81 vec![self.authenticate(payload)]
82 }
83 }
84
85 impl<A, B> AuthenticationSourceProviders for (A, B)
86 where
87 A: AuthenticationSourceProvider,
88 B: AuthenticationSourceProvider,
89 {
90 fn authenticate_all(&self, payload: &Vec<u8>) -> Vec<AuthenticationSource> {
91 let (first, second) = self;
92
93 vec![first.authenticate(payload), second.authenticate(payload)]
94 }
95 }
96
97 impl<O: GiteratedObject, D: GiteratedOperation<O>> Authenticated<O, D> {
98 pub fn new(message: GiteratedMessage<O, D>) -> Self {
99 Self {
100 source: vec![],
101 message,
102 }
103 }
104
105 pub fn append_authentication<P: AuthenticationSourceProvider + 'static + Send + Sync>(
106 &mut self,
107 authentication: P,
108 ) {
109 let message_payload = serde_json::to_vec(&self.message).unwrap();
110
111 info!(
112 "Verifying payload: {}",
113 std::str::from_utf8(&message_payload).unwrap()
114 );
115
116 self.source
117 .push(Box::new(authentication) as Box<dyn AuthenticationSourceProvider + Send + Sync>);
118 }
119
120 pub fn into_payload(mut self) -> AuthenticatedPayload {
121 let payload = bincode::serialize(&self.message.payload).unwrap();
122
123 AuthenticatedPayload {
124 object: self.message.object.to_string(),
125 operation: self.message.operation,
126 source: self
127 .source
128 .drain(..)
129 .map(|provider| provider.as_ref().authenticate(&payload))
130 .collect::<Vec<_>>(),
131 payload,
132 }
133 }
134 }
135
136 mod verified {}
137
138 #[derive(Clone, Debug)]
139 pub struct UserAuthenticator {
140 pub user: User,
141 pub token: UserAuthenticationToken,
142 }
143
144 impl AuthenticationSourceProvider for UserAuthenticator {
145 fn authenticate(&self, _payload: &Vec<u8>) -> AuthenticationSource {
146 AuthenticationSource::User {
147 user: self.user.clone(),
148 token: self.token.clone(),
149 }
150 }
151 }
152
153 #[derive(Debug, Clone)]
154 pub struct InstanceAuthenticator {
155 pub instance: Instance,
156 pub private_key: String,
157 }
158
159 impl AuthenticationSourceProvider for InstanceAuthenticator {
160 fn authenticate(&self, payload: &Vec<u8>) -> AuthenticationSource {
161 let mut rng = rand::thread_rng();
162
163 let private_key = RsaPrivateKey::from_pkcs1_pem(&self.private_key).unwrap();
164 let signing_key = SigningKey::<Sha256>::new(private_key);
165 let signature = signing_key.sign_with_rng(&mut rng, payload);
166
167 AuthenticationSource::Instance {
168 instance: self.instance.clone(),
169 // TODO: Actually parse signature from private key
170 signature: InstanceSignature(signature.to_bytes().into_vec()),
171 }
172 }
173 }
174
175 #[repr(transparent)]
176 #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
177 pub struct UserAuthenticationToken(String);
178
179 impl From<String> for UserAuthenticationToken {
180 fn from(value: String) -> Self {
181 Self(value)
182 }
183 }
184
185 impl ToString for UserAuthenticationToken {
186 fn to_string(&self) -> String {
187 self.0.clone()
188 }
189 }
190
191 impl AsRef<str> for UserAuthenticationToken {
192 fn as_ref(&self) -> &str {
193 &self.0
194 }
195 }
196
197 #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
198 pub struct InstanceSignature(Vec<u8>);
199
200 impl AsRef<[u8]> for InstanceSignature {
201 fn as_ref(&self) -> &[u8] {
202 &self.0
203 }
204 }
205
206 #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
207 pub enum AuthenticationSource {
208 User {
209 user: User,
210 token: UserAuthenticationToken,
211 },
212 Instance {
213 instance: Instance,
214 signature: InstanceSignature,
215 },
216 }
217