forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection_service.rs
More file actions
399 lines (357 loc) · 13.6 KB
/
Copy pathcollection_service.rs
File metadata and controls
399 lines (357 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
use crate::model::{collection::Collection, request::SavedRequest};
use crate::repositories::{
collection_repository::CollectionRepository, request_repository::RequestRepository,
user_repository::UserRepository, workspace_repository::WorkspaceRepository,
};
use crate::services::sui_service::SuiService;
use crate::utils::error::AppError;
use mongodb::bson::oid::ObjectId;
use serde_json::Value;
use url::{Host, Url};
#[derive(Clone)]
pub struct CollectionService {
collection_repo: CollectionRepository,
request_repo: RequestRepository,
user_repo: UserRepository,
workspace_repo: WorkspaceRepository,
sui_service: SuiService,
}
impl CollectionService {
pub fn new(
collection_repo: CollectionRepository,
request_repo: RequestRepository,
user_repo: UserRepository,
workspace_repo: WorkspaceRepository,
sui_service: SuiService,
) -> Self {
Self {
collection_repo,
request_repo,
user_repo,
workspace_repo,
sui_service,
}
}
async fn ensure_workspace_owner(
&self,
workspace_id: ObjectId,
user_id: ObjectId,
) -> Result<(), AppError> {
let workspace = self.workspace_repo.find_by_id(workspace_id).await?;
if workspace.user_id != user_id {
return Err(AppError::Forbidden(
"Not authorized to access this workspace".into(),
));
}
Ok(())
}
fn validate_url(url_str: &str) -> Result<(), AppError> {
// Parse URL
let url = Url::parse(url_str)
.map_err(|e| AppError::BadRequest(format!("Invalid RPC URL: {e}")))?;
// Only allow HTTPS scheme
if url.scheme() != "https" {
return Err(AppError::BadRequest(
"Only HTTPS RPC URLs are allowed".into(),
));
}
match url.host() {
Some(Host::Domain(host)) if host.eq_ignore_ascii_case("localhost") => {
return Err(AppError::BadRequest(
"Localhost URLs are not allowed".into(),
));
}
Some(Host::Ipv4(v4)) => {
if v4.is_loopback() || v4.is_private() || v4.is_link_local() {
return Err(AppError::BadRequest(
"Private or link-local IP addresses are not allowed".into(),
));
}
}
Some(Host::Ipv6(v6)) => {
if v6.is_loopback() || v6.is_unique_local() || v6.is_unicast_link_local() {
return Err(AppError::BadRequest(
"Private or link-local IP addresses are not allowed".into(),
));
}
}
Some(Host::Domain(_)) | None => {}
}
Ok(())
}
// --- Collections ---
pub async fn create_collection(
&self,
user_id: ObjectId,
workspace_id: ObjectId,
name: String,
description: Option<String>,
) -> Result<Collection, AppError> {
self.ensure_workspace_owner(workspace_id, user_id).await?;
let new_collection = Collection::new(user_id, Some(workspace_id), name, description);
self.collection_repo.save(&new_collection).await
}
pub async fn get_user_collections(
&self,
user_id: ObjectId,
workspace_id: Option<ObjectId>,
) -> Result<Vec<Collection>, AppError> {
if let Some(workspace_id) = workspace_id {
self.ensure_workspace_owner(workspace_id, user_id).await?;
return self
.collection_repo
.find_all_by_user_and_workspace(user_id, workspace_id)
.await;
}
self.collection_repo.find_all_by_user(user_id).await
}
pub async fn get_collection(
&self,
collection_id: ObjectId,
user_id: ObjectId,
) -> Result<Collection, AppError> {
let collection = self.collection_repo.find_by_id(collection_id).await?;
if collection.user_id != user_id {
return Err(AppError::Forbidden(
"Not authorized to access this collection".into(),
));
}
Ok(collection)
}
pub async fn update_collection(
&self,
collection_id: ObjectId,
user_id: ObjectId,
name: String,
description: Option<String>,
) -> Result<Collection, AppError> {
let mut collection = self.get_collection(collection_id, user_id).await?;
collection.name = name;
collection.description = description;
collection.updated_at = chrono::Utc::now();
self.collection_repo.update(&collection).await
}
pub async fn delete_collection(
&self,
collection_id: ObjectId,
user_id: ObjectId,
) -> Result<(), AppError> {
let _collection = self.get_collection(collection_id, user_id).await?;
// Cascade delete requests
self.request_repo
.delete_all_by_collection(collection_id)
.await?;
self.collection_repo.delete(collection_id).await?;
Ok(())
}
// --- Requests ---
#[allow(clippy::too_many_arguments)]
pub async fn add_request(
&self,
user_id: ObjectId,
collection_id: ObjectId,
name: String,
method: String,
params: Value,
network: Option<String>,
rpc_url: Option<String>,
) -> Result<SavedRequest, AppError> {
// Verify ownership/existence of collection
let _ = self.get_collection(collection_id, user_id).await?;
let new_req = SavedRequest::new(
collection_id,
user_id,
name,
method,
params,
network,
rpc_url,
);
self.request_repo.save(&new_req).await
}
pub async fn get_collection_requests(
&self,
collection_id: ObjectId,
user_id: ObjectId,
) -> Result<Vec<SavedRequest>, AppError> {
// Verify ownership
let _ = self.get_collection(collection_id, user_id).await?;
self.request_repo
.find_all_by_collection(collection_id)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn update_request(
&self,
request_id: ObjectId,
user_id: ObjectId,
name: Option<String>,
method: Option<String>,
params: Option<Value>,
// `Some(None)` means "clear this field"; `Some(Some(v))` means "set it to v";
// `None` means the field was omitted from the request and should be left untouched.
network: Option<Option<String>>,
rpc_url: Option<Option<String>>,
last_response: Option<Option<Value>>, // Allow manual update of response (e.g. paste from UI)
) -> Result<SavedRequest, AppError> {
let mut req = self.request_repo.find_by_id(request_id).await?;
if req.user_id != user_id {
return Err(AppError::Forbidden("Not authorized".into()));
}
if let Some(n) = name {
req.name = n;
}
if let Some(m) = method {
req.method = m;
}
if let Some(p) = params {
req.params = p;
}
if let Some(network) = network {
req.network = network;
}
if let Some(rpc_url) = rpc_url {
req.rpc_url = rpc_url;
}
if let Some(last_response) = last_response {
req.last_response = last_response;
}
req.updated_at = chrono::Utc::now();
self.request_repo.update(&req).await
}
pub async fn delete_request(
&self,
request_id: ObjectId,
user_id: ObjectId,
) -> Result<(), AppError> {
let req = self.request_repo.find_by_id(request_id).await?;
if req.user_id != user_id {
return Err(AppError::Forbidden("Not authorized".into()));
}
self.request_repo.delete(request_id).await
}
pub async fn execute_request(
&self,
request_id: ObjectId,
user_id: ObjectId,
) -> Result<(SavedRequest, Value), AppError> {
let mut req = self.request_repo.find_by_id(request_id).await?;
if req.user_id != user_id {
return Err(AppError::Forbidden("Not authorized".into()));
}
// Determine RPC URL first (needed for resolution and main call)
let final_url = if let Some(ref url) = req.rpc_url {
url.clone()
} else {
let network_enum = if let Some(ref net_str) = req.network {
match net_str.to_lowercase().as_str() {
"mainnet" => crate::model::network::Network::Mainnet,
"testnet" => crate::model::network::Network::Testnet,
"devnet" => crate::model::network::Network::Devnet,
_ => crate::model::network::Network::Mainnet,
}
} else {
let user = self.user_repo.find_by_id(&user_id).await?;
user.network
};
network_enum.sui_url().to_string()
};
Self::validate_url(&final_url)?;
// 1. Resolve Parameters (SuiNS)
let suins_regex = regex::Regex::new(r"([a-zA-Z0-9-]+\.sui)").unwrap();
let mut final_params = req.params.clone();
if let Some(arr) = final_params.as_array_mut() {
for v in arr.iter_mut() {
if let Some(s) = v.as_str() {
if suins_regex.is_match(s) {
let mut new_string = s.to_string();
let mut replacements = Vec::new();
for cap in suins_regex.captures_iter(s) {
if let Some(m) = cap.get(0) {
replacements.push(m.as_str().to_string());
}
}
for name in replacements {
match self
.sui_service
.resolve_name_service_address(&final_url, &name)
.await
{
Ok(addr) => {
new_string = new_string.replace(&name, &addr);
}
Err(e) => {
// Synthesis: Return resolution error as JSON-RPC error
let err_val = self.sui_service.error_response(
-32002,
&format!("SuiNS Resolution Error for '{name}': {e}"),
);
// Update history before early return
let mut updated_req = req.clone();
updated_req.last_response = Some(err_val.clone());
updated_req.last_executed_at = Some(chrono::Utc::now());
self.request_repo.update(&updated_req).await?;
return Ok((updated_req, err_val));
}
}
}
if new_string != *s {
*v = Value::String(new_string);
}
}
}
}
}
// 3. Execute
let result = self
.sui_service
.call_rpc_direct(&final_url, user_id, &req.method, &final_params)
.await?;
// 4. Update Request History
req.last_response = Some(result.clone());
req.last_executed_at = Some(chrono::Utc::now());
self.request_repo.update(&req).await?;
Ok((req, result))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_url_allowed() {
assert!(CollectionService::validate_url("https://api.mainnet.sui.io").is_ok());
assert!(CollectionService::validate_url("https://fullnode.devnet.sui.io:443/").is_ok());
}
#[test]
fn test_validate_url_blocked_http() {
assert!(CollectionService::validate_url("http://api.mainnet.sui.io").is_err());
assert!(CollectionService::validate_url("http://1.1.1.1").is_err());
}
#[test]
fn test_validate_url_blocked_localhost() {
assert!(CollectionService::validate_url("https://localhost").is_err());
assert!(CollectionService::validate_url("https://localhost:443").is_err());
assert!(CollectionService::validate_url("https://127.0.0.1").is_err());
assert!(CollectionService::validate_url("https://[::1]").is_err());
}
#[test]
fn test_validate_url_blocked_private_ip() {
// IPv4 private ranges
assert!(CollectionService::validate_url("https://10.0.0.1").is_err());
assert!(CollectionService::validate_url("https://172.16.0.1").is_err());
assert!(CollectionService::validate_url("https://192.168.1.1").is_err());
// IPv6 unique local addresses (ULA)
assert!(CollectionService::validate_url("https://[fc00::1]").is_err());
assert!(CollectionService::validate_url("https://[fd00::1]").is_err());
}
#[test]
fn test_validate_url_blocked_link_local() {
assert!(CollectionService::validate_url("https://169.254.169.254").is_err());
assert!(CollectionService::validate_url("https://[fe80::1]").is_err());
}
#[test]
fn test_validate_url_invalid_urls() {
assert!(CollectionService::validate_url("not_a_url").is_err());
assert!(CollectionService::validate_url("https://").is_err());
}
}