-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathadmin.rs
More file actions
724 lines (613 loc) · 23.2 KB
/
admin.rs
File metadata and controls
724 lines (613 loc) · 23.2 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! Admin API client implementation
//!
//! This module provides the AdminClient that implements the AdminApi trait
//! using HTTP requests with AWS SigV4 signing.
use async_trait::async_trait;
use aws_credential_types::Credentials;
use aws_sigv4::http_request::{
SignableBody, SignableRequest, SignatureLocation, SigningSettings, sign,
};
use aws_sigv4::sign::v4;
use rc_core::admin::{
AdminApi, BucketQuota, ClusterInfo, CreateServiceAccountRequest, Group, GroupStatus,
HealStartRequest, HealStatus, Policy, PolicyEntity, PolicyInfo, ServiceAccount,
UpdateGroupMembersRequest, User, UserStatus,
};
use rc_core::{Alias, Error, Result};
use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, Method, StatusCode};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::SystemTime;
/// Admin API client for RustFS/MinIO-compatible servers
pub struct AdminClient {
http_client: Client,
endpoint: String,
access_key: String,
secret_key: String,
region: String,
}
impl AdminClient {
/// Create a new AdminClient from an Alias
pub fn new(alias: &Alias) -> Result<Self> {
let http_client = Client::builder()
.danger_accept_invalid_certs(alias.insecure)
.build()
.map_err(|e| Error::Network(format!("Failed to create HTTP client: {e}")))?;
Ok(Self {
http_client,
endpoint: alias.endpoint.trim_end_matches('/').to_string(),
access_key: alias.access_key.clone(),
secret_key: alias.secret_key.clone(),
region: alias.region.clone(),
})
}
/// Build the base URL for admin API
fn admin_url(&self, path: &str) -> String {
format!("{}/rustfs/admin/v3{}", self.endpoint, path)
}
/// Calculate SHA256 hash of the body
fn sha256_hash(body: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(body);
hex::encode(hasher.finalize())
}
/// Sign a request using AWS SigV4
async fn sign_request(
&self,
method: &Method,
url: &str,
headers: &HeaderMap,
body: &[u8],
) -> Result<HeaderMap> {
let credentials = Credentials::new(
&self.access_key,
&self.secret_key,
None,
None,
"admin-client",
);
let identity = credentials.into();
let mut signing_settings = SigningSettings::default();
signing_settings.signature_location = SignatureLocation::Headers;
let signing_params = v4::SigningParams::builder()
.identity(&identity)
.region(&self.region)
.name("s3")
.time(SystemTime::now())
.settings(signing_settings)
.build()
.map_err(|e| Error::Auth(format!("Failed to build signing params: {e}")))?;
// Convert headers to a vec of tuples
let header_pairs: Vec<(&str, &str)> = headers
.iter()
.filter_map(|(k, v)| v.to_str().ok().map(|v| (k.as_str(), v)))
.collect();
let signable_body = SignableBody::Bytes(body);
let signable_request = SignableRequest::new(
method.as_str(),
url,
header_pairs.into_iter(),
signable_body,
)
.map_err(|e| Error::Auth(format!("Failed to create signable request: {e}")))?;
let (signing_instructions, _signature) = sign(signable_request, &signing_params.into())
.map_err(|e| Error::Auth(format!("Failed to sign request: {e}")))?
.into_parts();
// Apply signing instructions to create new headers
let mut signed_headers = headers.clone();
for (name, value) in signing_instructions.headers() {
let header_name = HeaderName::try_from(&name.to_string())
.map_err(|e| Error::Auth(format!("Invalid header name: {e}")))?;
let header_value = HeaderValue::try_from(&value.to_string())
.map_err(|e| Error::Auth(format!("Invalid header value: {e}")))?;
signed_headers.insert(header_name, header_value);
}
Ok(signed_headers)
}
/// Make a signed request to the admin API
async fn request<T: for<'de> Deserialize<'de>>(
&self,
method: Method,
path: &str,
query: Option<&[(&str, &str)]>,
body: Option<&[u8]>,
) -> Result<T> {
let mut url = self.admin_url(path);
if let Some(q) = query {
let query_string: String = q
.iter()
.map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
.collect::<Vec<_>>()
.join("&");
if !query_string.is_empty() {
url.push('?');
url.push_str(&query_string);
}
}
let body_bytes = body.unwrap_or(&[]);
let content_hash = Self::sha256_hash(body_bytes);
let mut headers = HeaderMap::new();
headers.insert("x-amz-content-sha256", content_hash.parse().unwrap());
headers.insert("host", self.get_host().parse().unwrap());
if !body_bytes.is_empty() {
headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
}
let signed_headers = self
.sign_request(&method, &url, &headers, body_bytes)
.await?;
let mut request_builder = self.http_client.request(method.clone(), &url);
for (name, value) in signed_headers.iter() {
request_builder = request_builder.header(name, value);
}
if !body_bytes.is_empty() {
request_builder = request_builder.body(body_bytes.to_vec());
}
let response = request_builder
.send()
.await
.map_err(|e| Error::Network(format!("Request failed: {e}")))?;
let status = response.status();
if !status.is_success() {
let error_body = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(self.map_error(status, &error_body));
}
let text = response
.text()
.await
.map_err(|e| Error::Network(format!("Failed to read response: {e}")))?;
if text.is_empty() {
// Return empty/default for empty responses
serde_json::from_str("null").map_err(Error::Json)
} else {
serde_json::from_str(&text).map_err(Error::Json)
}
}
/// Make a signed request that returns no body
async fn request_no_response(
&self,
method: Method,
path: &str,
query: Option<&[(&str, &str)]>,
body: Option<&[u8]>,
) -> Result<()> {
let mut url = self.admin_url(path);
if let Some(q) = query {
let query_string: String = q
.iter()
.map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
.collect::<Vec<_>>()
.join("&");
if !query_string.is_empty() {
url.push('?');
url.push_str(&query_string);
}
}
let body_bytes = body.unwrap_or(&[]);
let content_hash = Self::sha256_hash(body_bytes);
let mut headers = HeaderMap::new();
headers.insert("x-amz-content-sha256", content_hash.parse().unwrap());
headers.insert("host", self.get_host().parse().unwrap());
if !body_bytes.is_empty() {
headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
}
let signed_headers = self
.sign_request(&method, &url, &headers, body_bytes)
.await?;
let mut request_builder = self.http_client.request(method.clone(), &url);
for (name, value) in signed_headers.iter() {
request_builder = request_builder.header(name, value);
}
if !body_bytes.is_empty() {
request_builder = request_builder.body(body_bytes.to_vec());
}
let response = request_builder
.send()
.await
.map_err(|e| Error::Network(format!("Request failed: {e}")))?;
let status = response.status();
if !status.is_success() {
let error_body = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(self.map_error(status, &error_body));
}
Ok(())
}
/// Extract host from endpoint
fn get_host(&self) -> String {
self.endpoint
.trim_start_matches("http://")
.trim_start_matches("https://")
.to_string()
}
/// Map HTTP status codes to appropriate errors
fn map_error(&self, status: StatusCode, body: &str) -> Error {
match status {
StatusCode::NOT_FOUND => Error::NotFound(body.to_string()),
StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED => Error::Auth(body.to_string()),
StatusCode::CONFLICT => Error::Conflict(body.to_string()),
StatusCode::BAD_REQUEST => Error::InvalidPath(body.to_string()),
_ => Error::Network(format!("HTTP {}: {}", status.as_u16(), body)),
}
}
}
/// Response wrapper for user list
#[derive(Debug, Deserialize)]
struct UserListResponse(HashMap<String, UserInfo>);
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct UserInfo {
#[serde(default)]
status: String,
#[serde(default)]
policy_name: Option<String>,
#[serde(default)]
member_of: Option<Vec<String>>,
}
/// Response wrapper for policy list
#[derive(Debug, Deserialize)]
struct PolicyListResponse(HashMap<String, serde_json::Value>);
/// Request body for creating a user
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct CreateUserRequest {
secret_key: String,
status: String,
}
/// Request body for creating a group
#[derive(Debug, Serialize)]
struct CreateGroupRequest {
group: String,
#[serde(skip_serializing_if = "Option::is_none")]
members: Option<Vec<String>>,
}
/// Response for service account list
#[derive(Debug, Deserialize)]
struct ServiceAccountListResponse {
accounts: Option<Vec<ServiceAccountInfo>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ServiceAccountInfo {
access_key: String,
#[serde(default)]
parent_user: Option<String>,
#[serde(default)]
account_status: Option<String>,
#[serde(default)]
expiration: Option<String>,
}
/// Request body for setting bucket quota
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct SetBucketQuotaApiRequest {
quota: u64,
quota_type: String,
}
#[async_trait]
impl AdminApi for AdminClient {
// ==================== Cluster Operations ====================
async fn cluster_info(&self) -> Result<ClusterInfo> {
self.request(Method::GET, "/info", None, None).await
}
async fn heal_status(&self) -> Result<HealStatus> {
self.request(Method::GET, "/heal/status", None, None).await
}
async fn heal_start(&self, request: HealStartRequest) -> Result<HealStatus> {
let body = serde_json::to_vec(&request).map_err(Error::Json)?;
self.request(Method::POST, "/heal/start", None, Some(&body))
.await
}
async fn heal_stop(&self) -> Result<()> {
self.request_no_response(Method::POST, "/heal/stop", None, None)
.await
}
// ==================== User Operations ====================
async fn list_users(&self) -> Result<Vec<User>> {
let response: UserListResponse =
self.request(Method::GET, "/list-users", None, None).await?;
Ok(response
.0
.into_iter()
.map(|(access_key, info)| User {
access_key,
secret_key: None,
status: if info.status == "disabled" {
UserStatus::Disabled
} else {
UserStatus::Enabled
},
policy_name: info.policy_name,
member_of: info.member_of.unwrap_or_default(),
})
.collect())
}
async fn get_user(&self, access_key: &str) -> Result<User> {
let query = [("accessKey", access_key)];
let response: UserInfo = self
.request(Method::GET, "/user-info", Some(&query), None)
.await?;
Ok(User {
access_key: access_key.to_string(),
secret_key: None,
status: if response.status == "disabled" {
UserStatus::Disabled
} else {
UserStatus::Enabled
},
policy_name: response.policy_name,
member_of: response.member_of.unwrap_or_default(),
})
}
async fn create_user(&self, access_key: &str, secret_key: &str) -> Result<User> {
let query = [("accessKey", access_key)];
let body = serde_json::to_vec(&CreateUserRequest {
secret_key: secret_key.to_string(),
status: "enabled".to_string(),
})
.map_err(Error::Json)?;
self.request_no_response(Method::PUT, "/add-user", Some(&query), Some(&body))
.await?;
Ok(User {
access_key: access_key.to_string(),
secret_key: Some(secret_key.to_string()),
status: UserStatus::Enabled,
policy_name: None,
member_of: vec![],
})
}
async fn delete_user(&self, access_key: &str) -> Result<()> {
let query = [("accessKey", access_key)];
self.request_no_response(Method::DELETE, "/remove-user", Some(&query), None)
.await
}
async fn set_user_status(&self, access_key: &str, status: UserStatus) -> Result<()> {
let status_str = match status {
UserStatus::Enabled => "enabled",
UserStatus::Disabled => "disabled",
};
let query = [("accessKey", access_key), ("status", status_str)];
self.request_no_response(Method::PUT, "/set-user-status", Some(&query), None)
.await
}
// ==================== Policy Operations ====================
async fn list_policies(&self) -> Result<Vec<PolicyInfo>> {
let response: PolicyListResponse = self
.request(Method::GET, "/list-canned-policies", None, None)
.await?;
Ok(response
.0
.into_keys()
.map(|name| PolicyInfo { name })
.collect())
}
async fn get_policy(&self, name: &str) -> Result<Policy> {
let query = [("name", name)];
let policy_doc: serde_json::Value = self
.request(Method::GET, "/info-canned-policy", Some(&query), None)
.await?;
Ok(Policy {
name: name.to_string(),
policy: serde_json::to_string_pretty(&policy_doc).unwrap_or_default(),
})
}
async fn create_policy(&self, name: &str, policy_document: &str) -> Result<()> {
let query = [("name", name)];
let body = policy_document.as_bytes();
self.request_no_response(Method::POST, "/add-canned-policy", Some(&query), Some(body))
.await
}
async fn delete_policy(&self, name: &str) -> Result<()> {
let query = [("name", name)];
self.request_no_response(Method::DELETE, "/remove-canned-policy", Some(&query), None)
.await
}
async fn attach_policy(
&self,
policy_names: &[String],
entity_type: PolicyEntity,
entity_name: &str,
) -> Result<()> {
let policy_name = policy_names.join(",");
let is_group = entity_type == PolicyEntity::Group;
let query = [
("policyName", policy_name.as_str()),
("userOrGroup", entity_name),
("isGroup", if is_group { "true" } else { "false" }),
];
self.request_no_response(Method::PUT, "/set-user-or-group-policy", Some(&query), None)
.await
}
async fn detach_policy(
&self,
policy_names: &[String],
entity_type: PolicyEntity,
entity_name: &str,
) -> Result<()> {
// Detach by setting empty policy
// In RustFS/MinIO, you typically set a new policy which replaces the old one
// For detach, we need to get current policies and remove the specified ones
let _ = (policy_names, entity_type, entity_name);
Err(Error::UnsupportedFeature(
"Policy detach not directly supported. Use attach with remaining policies instead."
.to_string(),
))
}
// ==================== Group Operations ====================
async fn list_groups(&self) -> Result<Vec<String>> {
let response: Vec<String> = self.request(Method::GET, "/groups", None, None).await?;
Ok(response)
}
async fn get_group(&self, name: &str) -> Result<Group> {
let query = [("group", name)];
let response: Group = self
.request(Method::GET, "/group", Some(&query), None)
.await?;
Ok(response)
}
async fn create_group(&self, name: &str, members: Option<&[String]>) -> Result<Group> {
let body = serde_json::to_vec(&CreateGroupRequest {
group: name.to_string(),
members: members.map(|m| m.to_vec()),
})
.map_err(Error::Json)?;
self.request_no_response(Method::POST, "/groups", None, Some(&body))
.await?;
Ok(Group {
name: name.to_string(),
policy: None,
members: members.map(|m| m.to_vec()).unwrap_or_default(),
status: GroupStatus::Enabled,
})
}
async fn delete_group(&self, name: &str) -> Result<()> {
let path = format!("/group/{}", urlencoding::encode(name));
self.request_no_response(Method::DELETE, &path, None, None)
.await
}
async fn set_group_status(&self, name: &str, status: GroupStatus) -> Result<()> {
let status_str = match status {
GroupStatus::Enabled => "enabled",
GroupStatus::Disabled => "disabled",
};
let query = [("group", name), ("status", status_str)];
self.request_no_response(Method::PUT, "/set-group-status", Some(&query), None)
.await
}
async fn add_group_members(&self, group: &str, members: &[String]) -> Result<()> {
let body = serde_json::to_vec(&UpdateGroupMembersRequest {
group: group.to_string(),
members: members.to_vec(),
is_remove: false,
})
.map_err(Error::Json)?;
self.request_no_response(Method::PUT, "/update-group-members", None, Some(&body))
.await
}
async fn remove_group_members(&self, group: &str, members: &[String]) -> Result<()> {
let body = serde_json::to_vec(&UpdateGroupMembersRequest {
group: group.to_string(),
members: members.to_vec(),
is_remove: true,
})
.map_err(Error::Json)?;
self.request_no_response(Method::PUT, "/update-group-members", None, Some(&body))
.await
}
// ==================== Service Account Operations ====================
async fn list_service_accounts(&self, user: Option<&str>) -> Result<Vec<ServiceAccount>> {
let query: Vec<(&str, &str)> = user.map(|u| vec![("user", u)]).unwrap_or_default();
let query_ref: Option<&[(&str, &str)]> = if query.is_empty() { None } else { Some(&query) };
let response: ServiceAccountListResponse = self
.request(Method::GET, "/list-service-accounts", query_ref, None)
.await?;
Ok(response
.accounts
.unwrap_or_default()
.into_iter()
.map(|sa| ServiceAccount {
access_key: sa.access_key,
secret_key: None,
parent_user: sa.parent_user,
policy: None,
account_status: sa.account_status,
expiration: sa.expiration,
})
.collect())
}
async fn get_service_account(&self, access_key: &str) -> Result<ServiceAccount> {
let query = [("accessKey", access_key)];
let response: ServiceAccount = self
.request(Method::GET, "/info-service-account", Some(&query), None)
.await?;
Ok(response)
}
async fn create_service_account(
&self,
request: CreateServiceAccountRequest,
) -> Result<ServiceAccount> {
let body = serde_json::to_vec(&request).map_err(Error::Json)?;
let response: ServiceAccount = self
.request(Method::PUT, "/add-service-account", None, Some(&body))
.await?;
Ok(response)
}
async fn delete_service_account(&self, access_key: &str) -> Result<()> {
let query = [("accessKey", access_key)];
self.request_no_response(
Method::DELETE,
"/delete-service-account",
Some(&query),
None,
)
.await
}
// ==================== Bucket Quota Operations ====================
async fn set_bucket_quota(&self, bucket: &str, quota: u64) -> Result<BucketQuota> {
let path = format!("/quota/{}", urlencoding::encode(bucket));
let body = serde_json::to_vec(&SetBucketQuotaApiRequest {
quota,
quota_type: "HARD".to_string(),
})
.map_err(Error::Json)?;
self.request(Method::PUT, &path, None, Some(&body)).await
}
async fn get_bucket_quota(&self, bucket: &str) -> Result<BucketQuota> {
let path = format!("/quota/{}", urlencoding::encode(bucket));
self.request(Method::GET, &path, None, None).await
}
async fn clear_bucket_quota(&self, bucket: &str) -> Result<BucketQuota> {
let path = format!("/quota/{}", urlencoding::encode(bucket));
self.request(Method::DELETE, &path, None, None).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_admin_url_construction() {
let alias = Alias::new("test", "http://localhost:9000", "access", "secret");
let client = AdminClient::new(&alias).unwrap();
assert_eq!(
client.admin_url("/list-users"),
"http://localhost:9000/rustfs/admin/v3/list-users"
);
}
#[test]
fn test_admin_url_with_trailing_slash() {
let alias = Alias::new("test", "http://localhost:9000/", "access", "secret");
let client = AdminClient::new(&alias).unwrap();
assert_eq!(
client.admin_url("/list-users"),
"http://localhost:9000/rustfs/admin/v3/list-users"
);
}
#[test]
fn test_get_host() {
let alias = Alias::new("test", "https://s3.example.com", "access", "secret");
let client = AdminClient::new(&alias).unwrap();
assert_eq!(client.get_host(), "s3.example.com");
}
#[test]
fn test_sha256_hash() {
let hash = AdminClient::sha256_hash(b"test");
assert_eq!(
hash,
"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
);
}
#[test]
fn test_sha256_hash_empty() {
let hash = AdminClient::sha256_hash(b"");
assert_eq!(
hash,
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
}