Skip to main content

hyprstream_core/services/oauth/
rpc_handler.rs

1//! OAuth RPC handler for user CRUD operations.
2//!
3//! Implements the `OauthHandler` trait (generated from `oauth.capnp`)
4//! and `RequestService` for ZMQ transport. Delegates to `UserService` for
5//! shared CRUD logic.
6
7use std::sync::Arc;
8
9use anyhow::{anyhow, Result};
10use async_trait::async_trait;
11use hyprstream_rpc::prelude::*;
12use hyprstream_rpc::service::{Continuation, EnvelopeContext, RequestService};
13use hyprstream_rpc::transport::TransportConfig;
14
15use crate::auth::{decode_pubkey_base64, UserFilter};
16use crate::services::generated::oauth_client::{dispatch_oauth, serialize_response, OauthHandler};
17use hyprstream_rpc_std::oauth_client::{
18    AddPubkey, ErrorInfo, ListUsers, OauthResponseVariant, PubkeyEntry as RpcPubkeyEntry,
19    RegisterUser, RemovePubkey, UpdateUser, UserInfo as RpcUserInfo, UserListResult,
20};
21
22use super::state::OAuthState;
23use super::user_service::{self, UserUpdate};
24
25/// Local-control RPC handler for OAuth user management.
26///
27/// Wraps `UserService` and implements the generated `OauthHandler` trait
28/// for Cap'n Proto serialization. Network transports must not install this
29/// handler until they provide independently verified application/session proof.
30pub struct OAuthRpcHandler {
31    state: Arc<OAuthState>,
32    transport: TransportConfig,
33    signing_key: SigningKey,
34}
35
36impl OAuthRpcHandler {
37    pub fn new(
38        state: Arc<OAuthState>,
39        transport: TransportConfig,
40        signing_key: SigningKey,
41    ) -> Self {
42        Self {
43            state,
44            transport,
45            signing_key,
46        }
47    }
48
49    fn user_service(&self) -> Result<&Arc<user_service::UserService>> {
50        self.state
51            .user_service
52            .as_ref()
53            .ok_or_else(|| anyhow!("User service not configured"))
54    }
55
56    fn user_info_to_rpc(info: &user_service::UserInfo) -> RpcUserInfo {
57        RpcUserInfo {
58            username: info.username.clone(),
59            sub: info.sub.clone(),
60            pubkey_base64: info.pubkey_base64.clone(),
61            name: info.name.clone().unwrap_or_default(),
62            email: info.email.clone().unwrap_or_default(),
63            email_verified: info.email_verified,
64            active: info.active,
65            external_id: info.external_id.clone().unwrap_or_default(),
66            atproto_did: info.atproto_did.clone(),
67            pubkeys: info
68                .pubkeys
69                .iter()
70                .map(|pk| hyprstream_rpc_std::oauth_client::PubkeyEntry {
71                    fingerprint: pk.fingerprint.clone(),
72                    pubkey_base64: pk.pubkey_base64.clone(),
73                    label: pk.label.clone().unwrap_or_default(),
74                    created_at: pk.created_at,
75                    last_used_at: pk.last_used_at.unwrap_or(0),
76                    algorithm: pk.algorithm.as_str().to_owned(),
77                    pq_pubkey: pk.pq_pubkey.clone().unwrap_or_default(),
78                })
79                .collect(),
80        }
81    }
82}
83
84#[async_trait(?Send)]
85impl OauthHandler for OAuthRpcHandler {
86    async fn authorize(
87        &self,
88        ctx: &EnvelopeContext,
89        resource: &str,
90        operation: &str,
91    ) -> Result<()> {
92        // This handler is restricted to the authenticated local control plane.
93        // Subject names (including JWT-derived `system` / `service:*`) cannot
94        // establish locality. OAuth iroh does not install this handler at all.
95        anyhow::ensure!(
96            ctx.is_local_caller(),
97            "OAuth user management requires an authenticated local service boundary"
98        );
99        // Locality is transport provenance, not account-management authority.
100        // Relay the verified caller credential, never ask as this OAuth deputy
101        // (whose own grant permits account administration). Policy derives the
102        // subject and tenant from that credential, not request body fields.
103        let bearer = ctx
104            .jwt_token()
105            .ok_or_else(|| anyhow!("OAuth user management requires a verified caller bearer"))?;
106        let allowed = self
107            .state
108            .policy_client
109            .clone()
110            .with_delegated_bearer(bearer.to_owned())
111            .check(&hyprstream_rpc_std::policy_client::PolicyCheck {
112                subject: String::new(),
113                domain: String::new(),
114                resource: resource.to_owned(),
115                operation: operation.to_owned(),
116            })
117            .await?;
118        anyhow::ensure!(allowed, "Unauthorized OAuth user management operation");
119        Ok(())
120    }
121
122    async fn handle_register_user(
123        &self,
124        _ctx: &EnvelopeContext,
125        _request_id: u64,
126        data: &RegisterUser,
127    ) -> Result<OauthResponseVariant> {
128        let svc = self.user_service()?;
129        let pubkey_b64 = data.pubkey_base64.as_deref().unwrap_or("");
130        let info = svc.register(&data.username, pubkey_b64).await?;
131        Ok(OauthResponseVariant::RegisterUserResult(
132            Self::user_info_to_rpc(&info),
133        ))
134    }
135
136    async fn handle_get_user(
137        &self,
138        _ctx: &EnvelopeContext,
139        _request_id: u64,
140        username: &str,
141    ) -> Result<OauthResponseVariant> {
142        let svc = self.user_service()?;
143        match svc.get(username).await? {
144            Some(info) => Ok(OauthResponseVariant::GetUserResult(Self::user_info_to_rpc(
145                &info,
146            ))),
147            None => Ok(OauthResponseVariant::Error(ErrorInfo {
148                message: format!("User '{}' not found", username),
149                code: "NOT_FOUND".to_owned(),
150                details: String::new(),
151            })),
152        }
153    }
154
155    async fn handle_list_users(
156        &self,
157        _ctx: &EnvelopeContext,
158        _request_id: u64,
159        data: &ListUsers,
160    ) -> Result<OauthResponseVariant> {
161        let svc = self.user_service()?;
162        let filter = UserFilter {
163            filter: if data.filter.is_empty() {
164                None
165            } else {
166                Some(data.filter.clone())
167            },
168            active_only: if data.active_only { Some(true) } else { None },
169            count: if data.count > 0 {
170                Some(data.count as usize)
171            } else {
172                None
173            },
174            start_index: if data.start_index > 0 {
175                Some(data.start_index as usize)
176            } else {
177                None
178            },
179            sort_by: None,
180            sort_order: None,
181        };
182        let list = svc.list(&filter).await?;
183        Ok(OauthResponseVariant::ListUsersResult(UserListResult {
184            users: list.users.iter().map(Self::user_info_to_rpc).collect(),
185            total_results: list.total_results as u32,
186        }))
187    }
188
189    async fn handle_update_user(
190        &self,
191        _ctx: &EnvelopeContext,
192        _request_id: u64,
193        data: &UpdateUser,
194    ) -> Result<OauthResponseVariant> {
195        let svc = self.user_service()?;
196        let update = UserUpdate {
197            name: data
198                .name
199                .as_ref()
200                .filter(|s| !s.is_empty())
201                .map(|s| Some(s.clone())),
202            email: data
203                .email
204                .as_ref()
205                .filter(|s| !s.is_empty())
206                .map(|s| Some(s.clone())),
207            external_id: data
208                .external_id
209                .as_ref()
210                .filter(|s| !s.is_empty())
211                .map(|s| Some(s.clone())),
212            email_verified: None,
213            atproto_did: None,
214        };
215        match svc.update(&data.username, update).await {
216            Ok(info) => Ok(OauthResponseVariant::UpdateUserResult(
217                Self::user_info_to_rpc(&info),
218            )),
219            Err(e) => Ok(OauthResponseVariant::Error(ErrorInfo {
220                message: e.to_string(),
221                code: "NOT_FOUND".to_owned(),
222                details: String::new(),
223            })),
224        }
225    }
226
227    async fn handle_suspend_user(
228        &self,
229        _ctx: &EnvelopeContext,
230        _request_id: u64,
231        username: &str,
232    ) -> Result<OauthResponseVariant> {
233        let svc = self.user_service()?;
234        svc.suspend(username).await?;
235        Ok(OauthResponseVariant::SuspendUserResult)
236    }
237
238    async fn handle_resume_user(
239        &self,
240        _ctx: &EnvelopeContext,
241        _request_id: u64,
242        username: &str,
243    ) -> Result<OauthResponseVariant> {
244        let svc = self.user_service()?;
245        svc.resume(username).await?;
246        Ok(OauthResponseVariant::ResumeUserResult)
247    }
248
249    async fn handle_remove_user(
250        &self,
251        _ctx: &EnvelopeContext,
252        _request_id: u64,
253        username: &str,
254    ) -> Result<OauthResponseVariant> {
255        let svc = self.user_service()?;
256        svc.remove(username).await?;
257        Ok(OauthResponseVariant::RemoveUserResult)
258    }
259
260    async fn handle_add_pubkey(
261        &self,
262        _ctx: &EnvelopeContext,
263        _request_id: u64,
264        data: &AddPubkey,
265    ) -> Result<OauthResponseVariant> {
266        let svc = self.user_service()?;
267        let vk = decode_pubkey_base64(&data.pubkey_base64)?;
268        let label = data.label.as_ref().filter(|s| !s.is_empty()).cloned();
269        let entry = svc.add_pubkey(&data.username, vk, label).await?;
270        Ok(OauthResponseVariant::AddPubkeyResult(RpcPubkeyEntry {
271            fingerprint: entry.fingerprint,
272            pubkey_base64: entry.pubkey_base64,
273            label: entry.label.unwrap_or_default(),
274            created_at: entry.created_at,
275            last_used_at: entry.last_used_at.unwrap_or(0),
276            algorithm: entry.algorithm.as_str().to_owned(),
277            pq_pubkey: entry.pq_pubkey.clone().unwrap_or_default(),
278        }))
279    }
280
281    async fn handle_remove_pubkey(
282        &self,
283        _ctx: &EnvelopeContext,
284        _request_id: u64,
285        data: &RemovePubkey,
286    ) -> Result<OauthResponseVariant> {
287        let svc = self.user_service()?;
288        let removed = svc.remove_pubkey(&data.username, &data.fingerprint).await?;
289        Ok(OauthResponseVariant::RemovePubkeyResult(removed))
290    }
291
292    async fn handle_list_pubkeys(
293        &self,
294        _ctx: &EnvelopeContext,
295        _request_id: u64,
296        username: &str,
297    ) -> Result<OauthResponseVariant> {
298        let svc = self.user_service()?;
299        let entries = svc.list_pubkeys(username).await?;
300        Ok(OauthResponseVariant::ListPubkeysResult(
301            entries
302                .into_iter()
303                .map(|e| RpcPubkeyEntry {
304                    fingerprint: e.fingerprint,
305                    pubkey_base64: e.pubkey_base64,
306                    label: e.label.unwrap_or_default(),
307                    created_at: e.created_at,
308                    last_used_at: e.last_used_at.unwrap_or(0),
309                    algorithm: e.algorithm.as_str().to_owned(),
310                    pq_pubkey: e.pq_pubkey.clone().unwrap_or_default(),
311                })
312                .collect(),
313        ))
314    }
315}
316
317#[async_trait(?Send)]
318impl RequestService for OAuthRpcHandler {
319    fn decode_request_body(
320        &self,
321        signed_body: &[u8],
322    ) -> anyhow::Result<hyprstream_rpc::service::DecodedRequestBody> {
323        // The ONE bounded decode (v16 ยง5.2): the generated decoder derives
324        // the full method leaf and returns the decoded message that policy,
325        // MAC, and dispatch below all consume.
326        crate::services::generated::oauth_client::decode_oauth_request_body(signed_body)
327    }
328
329    async fn handle_request(
330        &self,
331        ctx: &EnvelopeContext,
332        body: &hyprstream_rpc::service::DecodedRequestBody,
333    ) -> Result<(Vec<u8>, Option<Continuation>)> {
334        dispatch_oauth(self, ctx, body).await
335    }
336
337    fn name(&self) -> &str {
338        "oauth"
339    }
340
341    fn transport(&self) -> &TransportConfig {
342        &self.transport
343    }
344
345    fn signing_key(&self) -> SigningKey {
346        self.signing_key.clone()
347    }
348
349    fn build_error_payload(&self, request_id: u64, error: &str) -> Vec<u8> {
350        let variant = OauthResponseVariant::Error(ErrorInfo {
351            message: error.to_owned(),
352            code: "INTERNAL".to_owned(),
353            details: String::new(),
354        });
355        serialize_response(request_id, &variant).unwrap_or_default()
356    }
357}