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
//
// Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//! Applications should always use this ManagementClient to manage ObjectScale resources.
//!
use crate::bucket::Bucket;
use crate::iam::{AccessKey, Account, AccountAccessKey, EntitiesForPolicy, Group, GroupPolicyAttachment, LoginProfile, Policy, User, UserGroupMembership, UserPolicyAttachment};
use crate::response::get_content_text;
use crate::tenant::Tenant;
use anyhow::{Context as _, Result};
use reqwest::Url;
use reqwest::blocking::{Client, ClientBuilder};
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// ManagementClient manages ObjectScale resources with the ObjectScale REST API calls.
/// It also gets and manages tokens for authentication.
///
/// # Examples
/// ```no_run
/// use objectscale_client::client::ManagementClient;
/// use objectscale_client::iam::AccountBuilder;
///
/// fn main() {
/// let endpoint = "https://192.168.1.1:443";
/// let username = "admin";
/// let password = "pass";
/// let insecure = false;
/// let account_alias = "test";
/// let mut client = ManagementClient::new(endpoint, username, password, insecure);
/// let account = AccountBuilder::default().alias(account_alias).build().expect("build account");
/// client.create_account(account).expect("create account");
/// }
/// ```
#[derive(Clone, Debug)]
pub struct ManagementClient {
pub(crate) http_client: Client,
pub(crate) endpoint: Url,
username: String,
password: String,
pub(crate) access_token: Option<String>,
expires_in: Option<u64>,
refresh_token: Option<String>,
refresh_expires_in: Option<u64>,
}
pub struct ObjectstoreClient {
pub(crate) endpoint: Url,
pub(crate) management_client: ManagementClient,
}
#[derive(Debug, Serialize)]
struct BasicAuth {
pub username: String,
pub password: String,
}
#[derive(Debug, Deserialize)]
struct AuthLoginResponse {
pub access_token: String,
pub expires_in: u64,
pub refresh_token: String,
pub refresh_expires_in: u64,
}
#[derive(Debug, Deserialize)]
struct RefreshTokenResponse {
pub access_token: String,
pub expires_in: u64,
pub refresh_token: String,
pub refresh_expires_in: u64,
pub token_type: String,
}
impl ManagementClient {
/// Build a new ManagementClient.
///
pub fn new(endpoint: &str, username: &str, password: &str, insecure: bool) -> Result<Self> {
let timeout = Duration::new(5, 0);
let http_client = ClientBuilder::new()
.timeout(timeout)
.danger_accept_invalid_certs(insecure)
.use_rustls_tls()
.build()
.expect("build client");
Ok(Self {
http_client,
endpoint: Url::parse(endpoint)?,
username: username.to_string(),
password: password.to_string(),
access_token: None,
expires_in: None,
refresh_token: None,
refresh_expires_in: None,
})
}
pub fn new_objectstore_client(&self, endpoint: &str) -> Result<ObjectstoreClient> {
Ok(ObjectstoreClient {
endpoint: Url::parse(endpoint)?,
management_client: self.clone(),
})
}
fn obtain_auth_token(&mut self) -> Result<()> {
let params = BasicAuth {
username: self.username.clone(),
password: self.password.clone(),
};
let request_url = format!("{}mgmt/auth/login", self.endpoint);
let resp = self
.http_client
.post(request_url)
.header(ACCEPT, "application/json")
.header(CONTENT_TYPE, "application/json")
.json(¶ms)
.send()?;
let text = get_content_text(resp)?;
let resp: AuthLoginResponse = serde_json::from_str(&text).with_context(|| {
format!(
"Unable to deserialise AuthLoginResponse. Body was: \"{}\"",
text
)
})?;
let obtain_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
self.access_token = Some(resp.access_token);
self.refresh_token = Some(resp.refresh_token);
self.expires_in = Some(resp.expires_in + obtain_time);
self.refresh_expires_in = Some(resp.refresh_expires_in + obtain_time);
Ok(())
}
fn refresh_auth_token(&mut self) -> Result<()> {
let request_url = format!(
"{}mgmt/auth/token?grant_type=refresh_token&refresh_token={}",
self.endpoint,
self.refresh_token.clone().unwrap()
);
let resp = self
.http_client
.post(request_url)
.header(ACCEPT, "application/json")
.header(CONTENT_TYPE, "application/json")
.send()?;
let text = get_content_text(resp)?;
let resp: RefreshTokenResponse = serde_json::from_str(&text).with_context(|| {
format!(
"Unable to deserialise RefreshTokenResponse. Body was: \"{}\"",
text
)
})?;
self.access_token = Some(resp.access_token);
self.refresh_token = Some(resp.refresh_token);
self.expires_in = Some(resp.expires_in);
self.refresh_expires_in = Some(resp.refresh_expires_in);
Ok(())
}
fn auth(&mut self) -> Result<()> {
if self.access_token.is_none() {
self.obtain_auth_token()?;
} else {
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
if self.expires_in.unwrap() > now {
} else if self.refresh_expires_in.unwrap() > now {
self.refresh_auth_token()?;
} else {
self.obtain_auth_token()?;
}
}
Ok(())
}
/// Create an IAM account.
///
/// account: Iam Account to create
///
pub fn create_account(&mut self, account: Account) -> Result<Account> {
self.auth()?;
if account.tags.is_empty() {
Account::create_account(self, account)
} else {
let tags = account.tags.clone();
let account = Account::create_account(self, account)?;
Account::tag_account(self, account.account_id.as_str(), tags)?;
Account::get_account(self, account.account_id.as_str())
}
}
/// Get an IAM account.
///
/// account_id: Id of the account
///
pub fn get_account(&mut self, account_id: &str) -> Result<Account> {
self.auth()?;
Account::get_account(self, account_id)
}
/// Delete an IAM account.
///
/// account_id: Id of the account
///
pub fn delete_account(&mut self, account_id: &str) -> Result<()> {
self.auth()?;
let account = Account::get_account(self, account_id)?;
if !account.account_disabled {
Account::disable_account(self, account_id)?;
}
Account::delete_account(self, account_id)
}
/// List all IAM accounts.
///
pub fn list_accounts(&mut self) -> Result<Vec<Account>> {
self.auth()?;
Account::list_accounts(self)
}
/// Creates a new IAM User.
///
/// user: IAM User to create
///
pub fn create_user(&mut self, user: User) -> Result<User> {
self.auth()?;
if user.tags.is_empty() {
User::create(self, user)
} else {
let tags = user.tags.clone();
let user = User::create(self, user)?;
User::tag_user(self, &user.user_name, &user.namespace, tags)?;
User::get(self, &user.user_name, &user.namespace)
}
}
/// Returns the information about the specified IAM User.
///
/// user_name: The name of the user to retrieve. Cannot be empty.
/// namespace: Namespace of the user(id of the account the user belongs to). Cannot be empty.
///
pub fn get_user(&mut self, user_name: &str, namespace: &str) -> Result<User> {
self.auth()?;
User::get(self, user_name, namespace)
}
/// Delete specified IAM User.
///
/// user_name: The name of the user to delete. Cannot be empty.
/// namespace: Namespace of the user(id of the account the user belongs to). Cannot be empty.
///
pub fn delete_user(&mut self, user_name: &str, namespace: &str) -> Result<()> {
self.auth()?;
User::delete(self, user_name, namespace)
}
/// Lists the IAM users.
///
/// namespace: Namespace of users(id of the account the user belongs to). Cannot be empty.
///
/// TODO:
/// list_user won't show tags, or permissions boundary if any
///
pub fn list_users(&mut self, namespace: &str) -> Result<Vec<User>> {
self.auth()?;
User::list(self, namespace)
}
/// Attaches the specified managed policy to the specified user.
///
/// user_policy_attachment: UserPolicyAttachment to create
///
/// PS: attach the same policy would throw error
///
pub fn create_user_policy_attachment(&mut self, user_policy_attachment: UserPolicyAttachment) -> Result<UserPolicyAttachment> {
self.auth()?;
UserPolicyAttachment::create(self, user_policy_attachment)
}
/// Remove the specified managed policy attached to the specified user.
///
/// user_policy_attachment: UserPolicyAttachment to delete.
///
pub fn delete_user_policy_attachment(&mut self, user_policy_attachment: UserPolicyAttachment) -> Result<()> {
self.auth()?;
UserPolicyAttachment::delete(self, user_policy_attachment)
}
/// Lists all managed policies that are attached to the specified IAM user.
///
/// user_name: The name of the user to list attached policies for. Cannot be empty.
/// namespace: Namespace of the user(id of the account the user belongs to). Cannot be empty.
///
pub fn list_user_policy_attachments(&mut self, user_name: &str, namespace: &str) -> Result<Vec<UserPolicyAttachment>> {
self.auth()?;
UserPolicyAttachment::list(self, user_name, namespace)
}
/// Creates a password for the specified IAM user.
///
/// login_profile: LoginProfile to create
///
pub fn create_login_profile(&mut self, login_profile: LoginProfile) -> Result<LoginProfile> {
self.auth()?;
LoginProfile::create(self, login_profile)
}
/// Retrieves the password for the specified IAM user
///
/// user_name: Name of the user to delete password. Cannot be empty.
/// namespace: Namespace of the user(id of the account the user belongs to). Cannot be empty.
///
pub fn get_login_profile(&mut self, user_name: &str, namespace: &str) -> Result<LoginProfile> {
self.auth()?;
LoginProfile::get(self, user_name, namespace)
}
/// Deletes the password for the specified IAM user
///
/// user_name: Name of the user to delete password. Cannot be empty.
/// namespace: Namespace of the user(id of the account the user belongs to). Cannot be empty.
///
pub fn delete_login_profile(&mut self, user_name: &str, namespace: &str) -> Result<()> {
self.auth()?;
LoginProfile::delete(self, user_name, namespace)
}
/// Creates AccessKey for user.
///
/// access_key: AccessKey to create
///
pub fn create_access_key(&mut self, access_key: AccessKey) -> Result<AccessKey> {
self.auth()?;
AccessKey::create(self, access_key)
}
/// Deletes the access key pair associated with the specified IAM user.
///
/// access_key_id: The ID of the access key you want to delete. Cannot be empty.
/// user_name: Name of the user to delete accesskeys. Cannot be empty.
/// namespace: Namespace of the access key(id of the account the access key belongs to). Cannot be empty.
///
pub fn delete_access_key(&mut self, access_key_id: &str, user_name: &str, namespace: &str) -> Result<()> {
self.auth()?;
AccessKey::delete(self, access_key_id, user_name, namespace)
}
/// Returns information about the access key IDs associated with the specified IAM user.
///
/// user_name: Name of the user to list accesskeys. Cannot be empty.
/// namespace: Namespace of the access key(id of the account the access key belongs to). Cannot be empty.
///
pub fn list_access_keys(&mut self, user_name: &str, namespace: &str) -> Result<Vec<AccessKey>> {
self.auth()?;
AccessKey::list(self, user_name, namespace)
}
/// Creates account AccessKey.
///
/// account_access_key: Account Access Key to create
///
pub fn create_account_access_key(&mut self, account_access_key: AccountAccessKey) -> Result<AccountAccessKey> {
self.auth()?;
AccountAccessKey::create(self, account_access_key)
}
/// Deletes the access key pair associated with the specified IAM account.
///
/// access_key_id: The ID of the access key. Cannot be empty.
/// account_id: The id of the account. Cannot be empty.
///
pub fn delete_account_access_key(&mut self, access_key_id: &str, account_id: &str) -> Result<()> {
self.auth()?;
AccountAccessKey::delete(self, access_key_id, account_id)
}
/// Returns information about the access key IDs associated with the specified IAM account.
///
/// account_id: The id of the account. Cannot be empty.
///
pub fn list_account_access_keys(&mut self, account_id: &str) -> Result<Vec<AccountAccessKey>> {
self.auth()?;
AccountAccessKey::list(self, account_id)
}
/// Create a new Managed Policy.
///
/// policy: IAM Policy to create
///
pub fn create_policy(&mut self, policy: Policy) -> Result<Policy> {
self.auth()?;
Policy::create(self, policy)
}
/// Retrieve information about the specified Managed Policy.
///
/// policy_arn: Arn of the policy to retrieve. Cannot be empty.
/// namespace: Namespace of the policy(id of the account the policy belongs to). Cannot be empty.
///
pub fn get_policy(&mut self, policy_arn: &str, namespace: &str) -> Result<Policy> {
self.auth()?;
Policy::get(self, policy_arn, namespace)
}
/// Delete the specified Managed Policy.
///
/// policy_arn: Arn of the policy to delete. Cannot be empty.
/// namespace: Namespace of the policy(id of the account the policy belongs to). Cannot be empty.
///
pub fn delete_policy(&mut self, policy_arn: &str, namespace: &str) -> Result<()> {
self.auth()?;
Policy::delete(self, policy_arn, namespace)
}
/// Lists IAM Managed Policies.
///
/// namespace: Namespace of the policies(id of the account policies belongs to). Cannot be empty.
///
pub fn list_policies(&mut self, namespace: &str) -> Result<Vec<Policy>> {
self.auth()?;
Policy::list(self, namespace)
}
/// Creates a new IAM Group.
///
/// group: IAM Group to create
///
pub fn create_group(&mut self, group: Group) -> Result<Group> {
self.auth()?;
Group::create(self, group)
}
/// Returns the information about the specified IAM Group.
///
/// group_name: The name of the group to retrieve. Cannot be empty.
/// namespace: Namespace of the group(id of the account the group belongs to). Cannot be empty.
///
/// TODO:
/// show contained users in separate method
///
pub fn get_group(&mut self, group_name: &str, namespace: &str) -> Result<Group> {
self.auth()?;
Group::get(self, group_name, namespace)
}
/// Delete specified IAM User.
///
/// group_name: The name of the group to delete. Cannot be empty.
/// namespace: Namespace of the group(id of the account the group belongs to). Cannot be empty.
///
pub fn delete_group(&mut self, group_name: &str, namespace: &str) -> Result<()> {
self.auth()?;
Group::delete(self, group_name, namespace)
}
/// Lists the IAM groups.
///
/// namespace: Namespace of groups(id of the account groups belongs to). Cannot be empty.
///
pub fn list_groups(&mut self, namespace: &str) -> Result<Vec<Group>> {
self.auth()?;
Group::list(self, namespace)
}
/// Attaches the specified managed policy to the specified group.
///
/// group_policy_attachment: GroupPolicyAttachment to create
///
pub fn create_group_policy_attachment(&mut self, group_policy_attachment: GroupPolicyAttachment) -> Result<GroupPolicyAttachment> {
self.auth()?;
GroupPolicyAttachment::create(self, group_policy_attachment)
}
/// Remove the specified managed policy attached to the specified group.
///
/// group_policy_attachment: GroupPolicyAttachment to delete.
///
pub fn delete_group_policy_attachment(&mut self, group_policy_attachment: GroupPolicyAttachment) -> Result<()> {
self.auth()?;
GroupPolicyAttachment::delete(self, group_policy_attachment)
}
/// Lists all managed policies that are attached to the specified IAM Group.
///
/// group_name: The name of the group to list attached policies for. Cannot be empty.
/// namespace: Namespace of the group(id of the account the group belongs to). Cannot be empty.
///
pub fn list_group_policy_attachments(&mut self, group_name: &str, namespace: &str) -> Result<Vec<GroupPolicyAttachment>> {
self.auth()?;
GroupPolicyAttachment::list(self, group_name, namespace)
}
/// Lists all IAM users, groups, and roles that the specified managed policy is attached to.
///
/// policy_arn: Arn of the policy to list entities for. Cannot be empty.
/// namespace: Namespace of the policy(id of the account the policy belongs to). Cannot be empty.
/// entity_filter: The entity type to use for filtering the results. Valid values: User, Role, Group
/// usage_filter: The policy usage method to use for filtering the results. Valid values: PermissionsPolicy, PermissionsBoundary
///
pub fn get_entities_for_policy(&mut self, policy_arn: &str, namespace: &str, entity_filter: &str, usage_filter: &str) -> Result<EntitiesForPolicy> {
self.auth()?;
EntitiesForPolicy::get(self, policy_arn, namespace, entity_filter, usage_filter)
}
/// Adds the specified user to the specified group.
///
/// user_group_membership: UserGroupMembership to create
///
pub fn create_user_group_membership(&mut self, user_group_membership: UserGroupMembership) -> Result<UserGroupMembership> {
self.auth()?;
UserGroupMembership::create(self, user_group_membership)
}
/// Removes the specified user from the specified group.
///
/// user_group_membership: GroupPolicyAttachment to delete.
///
pub fn delete_user_group_membership(&mut self, user_group_membership: UserGroupMembership) -> Result<()> {
self.auth()?;
UserGroupMembership::delete(self, user_group_membership)
}
/// Lists the IAM groups that the specified IAM user belongs to.
///
/// user_name: The name of the user to list group membership for. Cannot be empty.
/// namespace: Namespace of the user(id of the account the user belongs to). Cannot be empty.
///
pub fn list_user_group_memberships_by_user(&mut self, user_name: &str, namespace: &str) -> Result<Vec<UserGroupMembership>> {
self.auth()?;
UserGroupMembership::list_by_user(self, user_name, namespace)
}
/// Lists the IAM users that the specified IAM group contains.
///
/// group_name: The name of the group to list contained users for. Cannot be empty.
/// namespace: Namespace of the group(id of the account the group belongs to). Cannot be empty.
///
pub fn list_user_group_memberships_by_group(&mut self, group_name: &str, namespace: &str) -> Result<Vec<UserGroupMembership>> {
self.auth()?;
UserGroupMembership::list_by_group(self, group_name, namespace)
}
}
impl ObjectstoreClient {
/// Create an bucket.
///
/// bucket: Bucket to create.
///
pub fn create_bucket(&mut self, bucket: Bucket) -> Result<Bucket> {
self.management_client.auth()?;
let namespace = bucket.namespace.clone();
let name = Bucket::create(self, bucket)?;
Bucket::get(self, &name, &namespace)
}
/// Gets bucket information for the specified bucket.
///
/// name: Bucket name for which information will be retrieved. Cannot be empty.
/// namespace: Namespace associated. Cannot be empty.
///
pub fn get_bucket(&mut self, name: &str, namespace: &str) -> Result<Bucket> {
self.management_client.auth()?;
Bucket::get(self, name, namespace)
}
/// Deletes the specified bucket.
///
/// name: Bucket name to be deleted. Cannot be empty.
/// namespace: Namespace associated. Cannot be empty.
/// emptyBucket: If true, the contents of the bucket will be emptied as part of the delete, otherwise it will fail if the bucket is not empty..
///
pub fn delete_bucket(&mut self, name: &str, namespace: &str, empty_bucket: bool) -> Result<()> {
self.management_client.auth()?;
Bucket::delete(self, name, namespace, empty_bucket)
}
/// Gets the list of buckets for the specified namespace.
///
/// namespace: Namespace for which buckets should be listed. Cannot be empty.
/// name_prefix: Case sensitive prefix of the Bucket name with a wild card(*). Can be empty or any_prefix_string*.
///
pub fn list_buckets(&mut self, namespace: &str, name_prefix: &str) -> Result<Vec<Bucket>> {
self.management_client.auth()?;
Bucket::list(self, namespace, name_prefix)
}
/// Creates the tenant which will associate an IAM Account within an objectstore.
///
/// tenant: Tenant to create
///
pub fn create_tenant(&mut self, tenant: Tenant) -> Result<Tenant> {
self.management_client.auth()?;
Tenant::create(self, tenant)
}
/// Delete the tenant from an object store. Tenant must not own any buckets.
///
/// name: The associated account id. Cannot be empty.
///
pub fn delete_tenant(&mut self, name: &str) -> Result<()> {
self.management_client.auth()?;
Tenant::delete(self, name)
}
/// Get the tenant.
///
/// name: The associated account id. Cannot be empty.
///
pub fn get_tenant(&mut self, name: &str) -> Result<Tenant> {
self.management_client.auth()?;
Tenant::get(self, name)
}
/// Get the list of tenants.
///
/// name_prefix: Case sensitive prefix of the tenant name with a wild card(*). Can be empty or any_prefix_string*.
///
pub fn list_tenants(&mut self, name_prefix: &str) -> Result<Vec<Tenant>> {
self.management_client.auth()?;
Tenant::list(self, name_prefix)
}
}