1use crate::grants::Grants;
9use std::pin::Pin;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::{Arc, Mutex};
12use std::time::Instant;
13use subtle::ConstantTimeEq;
14use tokio::sync::{mpsc, watch};
15use tokio_stream::Stream;
16use tonic::{Request, Response, Status};
17use weirdnet_ext_proto::v1::{self, host_server::Host};
18use weirdnet_ext_proto::{API_VERSION, SESSION_HEADER};
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Need {
23 Session,
25 Capability {
27 name: String,
29 target: Option<String>,
31 },
32}
33
34#[derive(Debug, Clone)]
36pub struct CallContext {
37 pub extension_id: String,
39 pub version: String,
41 pub grants: Grants,
43}
44
45pub type BoxFuture<'a, T> = Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
47
48pub trait Services: Send + Sync + 'static {
50 fn required(&self, service: &str, method: &str, payload: &[u8]) -> Option<Need>;
53
54 fn call<'a>(&'a self, ctx: &'a CallContext, service: &'a str, method: &'a str, payload: Vec<u8>) -> BoxFuture<'a, Result<Vec<u8>, Status>>;
56}
57
58#[derive(Debug, Default, Clone, Copy)]
60pub struct NoServices;
61
62impl Services for NoServices {
63 fn required(&self, _: &str, _: &str, _: &[u8]) -> Option<Need> {
64 None
65 }
66 fn call<'a>(&'a self, _: &'a CallContext, _: &'a str, _: &'a str, _: Vec<u8>) -> BoxFuture<'a, Result<Vec<u8>, Status>> {
67 Box::pin(async { Err(Status::unimplemented("no services")) })
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct LogLine {
74 pub level: v1::log_record::Level,
76 pub message: String,
78 pub fields: Vec<(String, String)>,
80}
81
82pub(crate) struct Shared {
83 pub(crate) started: Instant,
84 pub(crate) last_activity: AtomicU64,
85 pub(crate) health: watch::Sender<Option<v1::HealthReport>>,
86 pub(crate) logs: Option<mpsc::Sender<LogLine>>,
87}
88
89impl Shared {
90 pub(crate) fn touch(&self) {
91 self.last_activity.store(self.started.elapsed().as_millis() as u64, Ordering::Relaxed);
92 }
93}
94
95pub(crate) struct Broker {
96 pub(crate) id: String,
97 pub(crate) version: String,
98 pub(crate) host: String,
99 token: Mutex<Option<String>>,
100 session: Mutex<Option<String>>,
101 grants: watch::Receiver<Grants>,
102 events: Mutex<Option<mpsc::Receiver<v1::Event>>>,
103 services: Arc<dyn Services>,
104 shared: Arc<Shared>,
105}
106
107pub(crate) fn random_hex(n: usize) -> String {
108 let mut b = vec![0u8; n];
109 getrandom::fill(&mut b).expect("system randomness");
110 hex::encode(b)
111}
112
113impl Broker {
114 #[allow(clippy::too_many_arguments)]
115 pub(crate) fn new(
116 id: String,
117 version: String,
118 host: String,
119 token: String,
120 grants: watch::Receiver<Grants>,
121 events: mpsc::Receiver<v1::Event>,
122 services: Arc<dyn Services>,
123 shared: Arc<Shared>,
124 ) -> Self {
125 Self {
126 id,
127 version,
128 host,
129 token: Mutex::new(Some(token)),
130 session: Mutex::new(None),
131 grants,
132 events: Mutex::new(Some(events)),
133 services,
134 shared,
135 }
136 }
137
138 fn check_session<T>(&self, req: &Request<T>) -> Result<(), Status> {
139 let got = req.metadata().get(SESSION_HEADER).and_then(|v| v.to_str().ok()).unwrap_or("");
140 let ok = match &*self.session.lock().unwrap() {
141 Some(s) => bool::from(s.as_bytes().ct_eq(got.as_bytes())),
142 None => false,
143 };
144 if ok {
145 self.shared.touch();
146 Ok(())
147 } else {
148 Err(Status::unauthenticated("no session"))
149 }
150 }
151}
152
153type EventStream = Pin<Box<dyn Stream<Item = Result<v1::Event, Status>> + Send>>;
154
155#[tonic::async_trait]
156impl Host for Broker {
157 async fn handshake(&self, req: Request<v1::HandshakeRequest>) -> Result<Response<v1::HandshakeReply>, Status> {
158 let r = req.into_inner();
159 {
160 let mut t = self.token.lock().unwrap();
161 let ok = t.as_ref().is_some_and(|t| bool::from(t.as_bytes().ct_eq(r.token.as_bytes())));
162 if !ok {
163 return Err(Status::unauthenticated("bad or spent token"));
164 }
165 *t = None;
166 }
167 if r.extension_id != self.id {
168 return Err(Status::permission_denied("this session is for another extension"));
169 }
170 if r.api_version == 0 {
171 return Err(Status::failed_precondition("api_version 0"));
172 }
173 let session = random_hex(32);
174 *self.session.lock().unwrap() = Some(session.clone());
175 self.shared.touch();
176 tracing::debug!(ext = %self.id, version = %r.version, sdk = %r.sdk, "extension handshake");
177 Ok(Response::new(v1::HandshakeReply {
178 session,
179 api_version: r.api_version.min(API_VERSION),
180 granted: self.grants.borrow().to_proto(),
181 host: self.host.clone(),
182 }))
183 }
184
185 type EventsStream = EventStream;
186
187 async fn events(&self, req: Request<v1::EventsRequest>) -> Result<Response<Self::EventsStream>, Status> {
188 self.check_session(&req)?;
189 let rx = self.events.lock().unwrap().take().ok_or_else(|| Status::already_exists("the events stream is already open"))?;
190 let s = tokio_stream::wrappers::ReceiverStream::new(rx);
191 Ok(Response::new(Box::pin(tokio_stream::StreamExt::map(s, Ok))))
192 }
193
194 async fn call(&self, req: Request<v1::CallRequest>) -> Result<Response<v1::CallReply>, Status> {
195 self.check_session(&req)?;
196 let r = req.into_inner();
197 let grants = self.grants.borrow().clone();
198 match self.services.required(&r.service, &r.method, &r.payload) {
199 None => return Err(Status::unimplemented(format!("{}/{}", r.service, r.method))),
200 Some(Need::Session) => {}
201 Some(Need::Capability { name, target }) => {
202 if !grants.allows(&name, target.as_deref()) {
203 return Err(Status::permission_denied(format!(
204 "{name} is not granted{}",
205 target.map(|t| format!(" for {t}")).unwrap_or_default()
206 )));
207 }
208 }
209 }
210 let ctx = CallContext { extension_id: self.id.clone(), version: self.version.clone(), grants };
211 let payload = self.services.call(&ctx, &r.service, &r.method, r.payload).await?;
212 Ok(Response::new(v1::CallReply { payload }))
213 }
214
215 async fn log(&self, req: Request<v1::LogRecord>) -> Result<Response<v1::Empty>, Status> {
216 self.check_session(&req)?;
217 let r = req.into_inner();
218 let level = r.level();
219 let mut msg = r.message;
220 msg.truncate(16 << 10);
221 let mut fields: Vec<(String, String)> = r.fields.into_iter().take(32).collect();
222 fields.sort();
223 use v1::log_record::Level as L;
224 match level {
225 L::Error => tracing::error!(ext = %self.id, ?fields, "{msg}"),
226 L::Warn => tracing::warn!(ext = %self.id, ?fields, "{msg}"),
227 L::Info => tracing::info!(ext = %self.id, ?fields, "{msg}"),
228 L::Debug => tracing::debug!(ext = %self.id, ?fields, "{msg}"),
229 _ => tracing::trace!(ext = %self.id, ?fields, "{msg}"),
230 }
231 if let Some(l) = &self.shared.logs {
232 let _ = l.try_send(LogLine { level, message: msg, fields });
233 }
234 Ok(Response::new(v1::Empty {}))
235 }
236
237 async fn health(&self, req: Request<v1::HealthReport>) -> Result<Response<v1::Empty>, Status> {
238 self.check_session(&req)?;
239 let _ = self.shared.health.send(Some(req.into_inner()));
240 Ok(Response::new(v1::Empty {}))
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247 use crate::manifest::Capability;
248
249 fn broker() -> (Broker, watch::Sender<Grants>) {
250 let (gtx, grx) = watch::channel(Grants(vec![Capability::new("echo")]));
251 let (_etx, erx) = mpsc::channel(1);
252 let shared = Arc::new(Shared { started: Instant::now(), last_activity: AtomicU64::new(0), health: watch::channel(None).0, logs: None });
253 (Broker::new("com.example.x".into(), "1.0.0".into(), "test".into(), "tok".into(), grx, erx, Arc::new(Echo), shared), gtx)
254 }
255
256 struct Echo;
257 impl Services for Echo {
258 fn required(&self, s: &str, _: &str, _: &[u8]) -> Option<Need> {
259 (s == "echo").then(|| Need::Capability { name: "echo".into(), target: None })
260 }
261 fn call<'a>(&'a self, _: &'a CallContext, _: &'a str, _: &'a str, p: Vec<u8>) -> BoxFuture<'a, Result<Vec<u8>, Status>> {
262 Box::pin(async move { Ok(p) })
263 }
264 }
265
266 fn hs(token: &str, id: &str) -> Request<v1::HandshakeRequest> {
267 Request::new(v1::HandshakeRequest {
268 token: token.into(),
269 extension_id: id.into(),
270 version: "1.0.0".into(),
271 api_version: 9,
272 sdk: String::new(),
273 })
274 }
275
276 fn call(session: Option<&str>, service: &str) -> Request<v1::CallRequest> {
277 let mut r = Request::new(v1::CallRequest { service: service.into(), method: "M".into(), payload: b"p".to_vec() });
278 if let Some(s) = session {
279 r.metadata_mut().insert(SESSION_HEADER, s.parse().unwrap());
280 }
281 r
282 }
283
284 #[tokio::test]
285 async fn tokens_sessions_and_grants() {
286 let (b, gtx) = broker();
287 assert_eq!(b.call(call(None, "echo")).await.unwrap_err().code(), tonic::Code::Unauthenticated);
288 assert_eq!(b.handshake(hs("nope", "com.example.x")).await.unwrap_err().code(), tonic::Code::Unauthenticated);
289 let r = b.handshake(hs("tok", "com.example.x")).await.unwrap().into_inner();
290 assert_eq!(r.api_version, API_VERSION);
291 assert_eq!(r.granted.len(), 1);
292 assert_eq!(b.handshake(hs("tok", "com.example.x")).await.unwrap_err().code(), tonic::Code::Unauthenticated);
294 assert_eq!(b.call(call(Some("0000"), "echo")).await.unwrap_err().code(), tonic::Code::Unauthenticated);
295 assert_eq!(b.call(call(Some(&r.session), "echo")).await.unwrap().into_inner().payload, b"p");
296 assert_eq!(b.call(call(Some(&r.session), "other")).await.unwrap_err().code(), tonic::Code::Unimplemented);
297 gtx.send_replace(Grants::none());
298 assert_eq!(b.call(call(Some(&r.session), "echo")).await.unwrap_err().code(), tonic::Code::PermissionDenied);
299 let mut e = Request::new(v1::EventsRequest {});
301 e.metadata_mut().insert(SESSION_HEADER, r.session.parse().unwrap());
302 assert!(b.events(e).await.is_ok());
303 let mut e = Request::new(v1::EventsRequest {});
304 e.metadata_mut().insert(SESSION_HEADER, r.session.parse().unwrap());
305 assert_eq!(b.events(e).await.err().unwrap().code(), tonic::Code::AlreadyExists);
306 }
307
308 #[tokio::test]
309 async fn the_token_is_for_one_extension() {
310 let (b, _g) = broker();
311 assert_eq!(b.handshake(hs("tok", "com.example.y")).await.unwrap_err().code(), tonic::Code::PermissionDenied);
312 }
313}