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
/*!
* Provides types, builders, and other helpers to manipulate AWS [Amazon
* Resource Name
* (ResourceName)](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)
* strings.
*
* The ResourceName is a key component of all AWS service APIs and yet nearly
* all client toolkits treat it simply as a string. While this may be a
* reasonable and expedient decision, it seems there might be a need to not
* only ensure correctness of ResourceNames with validators but also
* constructors that allow making these strings correclt in the first place.
*
* # ResourceName Types
*
* This crate provides a number of levels of ResourceName manipulation, the
* first is the direct construction of an ResourceName type using the core
* `ResourceName`, `Identifier`, `AccountIdentifier`, and `ResourceIdentifier`
* types.
*
* ```rust
* use aws_arn::{ResourceName, ResourceIdentifier};
* use aws_arn::known::{Partition, Service};
* use std::str::FromStr;
*
* let arn = ResourceName {
* partition: Some(Partition::default().into()),
* service: Service::S3.into(),
* region: None,
* account_id: None,
* resource: ResourceIdentifier::from_str("mythings/thing-1").unwrap()
* };
* ```
*
* In the example above, as we are defining a minimal ResourceName we could use one of the defined constructor
* functions.
*
* ```rust
* use aws_arn::{ResourceName, ResourceIdentifier};
* use aws_arn::known::Service;
* use std::str::FromStr;
*
* let arn = ResourceName::aws(
* Service::S3.into(),
* ResourceIdentifier::from_str("mythings/thing-1").unwrap()
* );
* ```
*
* Alternatively, using `FromStr,` you can parse an existing ResourceName string into an ResourceName value.
*
* ```rust
* use aws_arn::ResourceName;
* use std::str::FromStr;
*
* let arn: ResourceName = "arn:aws:s3:::mythings/thing-1"
* .parse()
* .expect("didn't look like an ResourceName");
* ```
*
* Another approach is to use a more readable *builder* which also allows you to ignore those fields
* in the ResourceName you don't always need and uses a more fluent style of ResourceName construction.
*
* ```rust
* use aws_arn::builder::{ArnBuilder, ResourceBuilder};
* use aws_arn::known::{Partition, Service};
* use aws_arn::{ResourceName, Identifier, IdentifierLike};
* use std::str::FromStr;
*
* let arn: ResourceName = ArnBuilder::service_id(Service::S3.into())
* .resource(ResourceBuilder::named(Identifier::from_str("mythings").unwrap())
* .resource_name(Identifier::new_unchecked("my-layer"))
* .build_resource_path())
* .in_partition_id(Partition::Aws.into())
* .into();
* ```
*
* Finally, it is possible to use resource-type specific functions that allow an even more direct and
* simple construction (module `aws_arn::builder::{service}` - *service builder functions*, although
* at this time there are few supported services.
*
* ```rust
* use aws_arn::builder::s3;
* use aws_arn::Identifier;
* use std::str::FromStr;
*
* let arn = s3::object(
* Identifier::from_str("mythings").unwrap(),
* Identifier::from_str("thing-1").unwrap(),
* );
* ```
*
* For more, see the AWS documentation for [Amazon Resource Name
* (ResourceName)](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) documentation.
*
* # Optional Features
*
* This crate has attempted to be as lean as possible, with a really minimal set of dependencies,
* we have include the following capabilities as optional features.
*
* * `builders` adds the builder module. This feature is enabled by default, it also requires the
* `known` feature.
* * `known` adds a module containing enums for partitions, regions, and services.
* This feature is enabled by default.
* * `serde_support` adds derived `Serialize` and `Deserialize` implementations for the `ResourceName` and
* `Resource` types. This feature is enabled by default.
*
*/
// ------------------------------------------------------------------------------------------------
// Preamble
// ------------------------------------------------------------------------------------------------
#![warn(
// ---------- Stylistic
future_incompatible,
nonstandard_style,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts,
// ---------- Public
missing_debug_implementations,
missing_docs,
unreachable_pub,
// ---------- Unsafe
unsafe_code,
// ---------- Unused
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results,
)]
use lazy_static::lazy_static;
use regex::{Captures, Regex};
#[cfg(feature = "serde_support")]
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::ops::Deref;
use std::str::FromStr;
// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------
/// This trait is implemented by the `ResourceName` component types. It
/// represents a string-based identifier that is generally constructed using
/// `FromStr::from_str`.
///
pub trait IdentifierLike
where
Self: Clone + Display + FromStr + Deref<Target = str>,
{
/// Construct a new `Identifier` from the provided string **without** checking it's validity.
/// This can be a useful method to improve performance for statically, or well-known, values;
/// however, in general `FromStr::from_str` should be used.
fn new_unchecked(s: &str) -> Self
where
Self: Sized;
/// Returns `true` if the provided string is a valid `Identifier` value, else `false`.
fn is_valid(s: &str) -> bool;
/// Construct an account identifier that represents *any*.
fn any() -> Self {
Self::new_unchecked(STRING_WILD_ANY)
}
/// Return `true` if this is simply the *any* wildcard, else `false`.
fn is_any(&self) -> bool {
self.deref().chars().any(|c| c == CHAR_WILD_ANY)
}
/// Returns `true` if this identifier contains any wildcard characeters,
/// else `false`.
fn has_wildcards(&self) -> bool {
self.deref()
.chars()
.any(|c| c == CHAR_WILD_ONE || c == CHAR_WILD_ANY)
}
/// Return `true` if this identifier has no wildcards, else `false`.
fn is_plain(&self) -> bool {
!self.has_wildcards()
}
}
///
/// A string value that is used to capture the partition, service, and region components
/// of an ResourceName. These are ASCII only, may not include control characters, spaces, '/', or ':'.
///
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde_support", derive(Deserialize, Serialize))]
pub struct Identifier(String);
///
/// A string value that is used to capture the account ID component
/// of an ResourceName. These are ASCII digits only and a fixed length of 12 characters.
///
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde_support", derive(Deserialize, Serialize))]
pub struct AccountIdentifier(String);
///
/// A string value that is used to capture the resource component of an ResourceName. These are ASCII only,
/// may not include control characters but unlike `Identifier` they may include spaces, '/', and ':'.
///
/// > *The content of this part of the ResourceName varies by service. A resource identifier can be the name
/// > or ID of the resource (for example, `user/Bob` or `instance/i-1234567890abcdef0`) or a
/// > resource path. For example, some resource identifiers include a parent resource
/// > (`sub-resource-type/parent-resource/sub-resource`) or a qualifier such as a version
/// > (`resource-type:resource-name:qualifier`).*
///
/// > *Some resource ResourceNames can include a path. For example, in Amazon S3, the resource identifier
/// > is an object name that can include slashes ('/') to form a path. Similarly, IAM user names
/// > and group names can include paths.*
///
/// > *In some circumstances, paths can include a wildcard character, namely an asterisk ('*').*
///
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde_support", derive(Deserialize, Serialize))]
pub struct ResourceIdentifier(String);
///
/// Amazon Resource Names (ResourceNames) uniquely identify AWS resources. We require an ResourceName when you
/// need to specify a resource unambiguously across all of AWS, such as in IAM policies,
/// Amazon Relational Database Service (Amazon RDS) tags, and API calls.
///
/// The following are the general formats for ResourceNames; the specific components and values used
/// depend on the AWS service.
///
/// ```text
/// arn:partition:service:region:account-id:resource-id
/// arn:partition:service:region:account-id:resource-type/resource-id
/// arn:partition:service:region:account-id:resource-type:resource-id
/// ```
///
/// From [ResourceName Format](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-syntax)
///
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde_support", derive(Deserialize, Serialize))]
pub struct ResourceName {
/// The partition that the resource is in. For standard AWS Regions, the partition is` aws`.
/// If you have resources in other partitions, the partition is `aws-partitionname`. For
/// example, the partition for resources in the China partition is `aws-cn`. The module
/// `known::partition` provides common values as constants (if the `known` feature is
/// enabled).
pub partition: Option<Identifier>,
/// The service namespace that identifies the AWS. The module `known::service` provides
// common values as constants (if the `known` feature is enabled).
pub service: Identifier,
/// The Region that the resource resides in. The ResourceNames for some resources do not require
/// a Region, so this component might be omitted. The module `known::region` provides
/// common values as constants (if the `known` feature is enabled).
pub region: Option<Identifier>,
/// The ID of the AWS account that owns the resource, without the hyphens. For example,
/// `123456789012`. The ResourceNames for some resources don't require an account number, so this
/// component may be omitted.
pub account_id: Option<AccountIdentifier>,
/// The content of this part of the ResourceName varies by service. A resource identifier can
/// be the name or ID of the resource (for example, `user/Bob` or
/// `instance/i-1234567890abcdef0`) or a resource path. For example, some resource
/// identifiers include a parent resource
/// (`sub-resource-type/parent-resource/sub-resource`) or a qualifier such as a
/// version (`resource-type:resource-name:qualifier`).
pub resource: ResourceIdentifier,
}
// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------
const ARN_PREFIX: &str = "arn";
const PART_SEPARATOR: char = ':';
const PATH_SEPARATOR: char = '/';
const STRING_WILD_ANY: &str = "*";
const CHAR_ASCII_START: char = '\u{1F}';
const CHAR_ASCII_END: char = '\u{7F}';
const CHAR_SPACE: char = ' ';
const CHAR_WILD_ONE: char = '?';
const CHAR_WILD_ANY: char = '*';
const REQUIRED_COMPONENT_COUNT: usize = 6;
const PARTITION_AWS_PREFIX: &str = "aws";
const PARTITION_AWS_OTHER_PREFIX: &str = "aws-";
lazy_static! {
static ref REGEX_VARIABLE: Regex = Regex::new(r"\$\{([^$}]+)\}").unwrap();
}
// ------------------------------------------------------------------------------------------------
impl Display for Identifier {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for Identifier {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if Self::is_valid(s) {
Ok(Self(s.to_string()))
} else {
Err(Error::InvalidIdentifier(s.to_string()))
}
}
}
impl From<Identifier> for String {
fn from(v: Identifier) -> Self {
v.0
}
}
impl Deref for Identifier {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl IdentifierLike for Identifier {
fn new_unchecked(s: &str) -> Self {
Self(s.to_string())
}
fn is_valid(s: &str) -> bool {
!s.is_empty()
&& s.chars().all(|c| {
c > CHAR_ASCII_START
&& c < CHAR_ASCII_END
&& c != CHAR_SPACE
&& c != PATH_SEPARATOR
&& c != PART_SEPARATOR
})
}
}
// ------------------------------------------------------------------------------------------------
impl Display for AccountIdentifier {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for AccountIdentifier {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if Self::is_valid(s) {
Ok(Self(s.to_string()))
} else {
Err(Error::InvalidAccountId(s.to_string()))
}
}
}
impl From<AccountIdentifier> for String {
fn from(v: AccountIdentifier) -> Self {
v.0
}
}
impl From<AccountIdentifier> for ResourceName {
fn from(account: AccountIdentifier) -> Self {
ResourceName::from_str(&format!("arn:aws:iam::{}:root", account)).unwrap()
}
}
impl Deref for AccountIdentifier {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl IdentifierLike for AccountIdentifier {
fn new_unchecked(s: &str) -> Self {
Self(s.to_string())
}
fn is_valid(s: &str) -> bool {
(s.len() == 12 && s.chars().all(|c| c.is_ascii_digit()))
|| (!s.is_empty()
&& s.len() <= 12
&& s.chars()
.all(|c| c.is_ascii_digit() || c == CHAR_WILD_ONE || c == CHAR_WILD_ANY)
&& s.chars().any(|c| c == CHAR_WILD_ONE || c == CHAR_WILD_ANY))
}
}
// ------------------------------------------------------------------------------------------------
impl Display for ResourceIdentifier {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for ResourceIdentifier {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if Self::is_valid(s) {
Ok(Self(s.to_string()))
} else {
Err(Error::InvalidResource(s.to_string()))
}
}
}
impl From<ResourceIdentifier> for String {
fn from(v: ResourceIdentifier) -> Self {
v.0
}
}
impl From<Identifier> for ResourceIdentifier {
fn from(v: Identifier) -> Self {
ResourceIdentifier::new_unchecked(&v.0)
}
}
impl Deref for ResourceIdentifier {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl IdentifierLike for ResourceIdentifier {
fn new_unchecked(s: &str) -> Self {
Self(s.to_string())
}
fn is_valid(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c > '\u{1F}' && c < '\u{7F}')
}
fn is_plain(&self) -> bool {
!self.has_wildcards() && !self.has_variables()
}
}
impl ResourceIdentifier {
/// Construct a resource identifier, as a path, using the `Identifier` path components.
pub fn from_id_path(path: &[Identifier]) -> Self {
Self::new_unchecked(
&path
.iter()
.map(Identifier::to_string)
.collect::<Vec<String>>()
.join(&PATH_SEPARATOR.to_string()),
)
}
/// Construct a resource identifier, as a qualified ID, using the `Identifier` path components.
pub fn from_qualified_id(qualified: &[Identifier]) -> Self {
Self::new_unchecked(
&qualified
.iter()
.map(Identifier::to_string)
.collect::<Vec<String>>()
.join(&PART_SEPARATOR.to_string()),
)
}
/// Construct a resource identifier, as a path, using the `ResourceIdentifier` path components.
pub fn from_path(path: &[ResourceIdentifier]) -> Self {
Self::new_unchecked(
&path
.iter()
.map(ResourceIdentifier::to_string)
.collect::<Vec<String>>()
.join(&PATH_SEPARATOR.to_string()),
)
}
/// Construct a resource identifier, as a qualified ID, using the `ResourceIdentifier` path components.
pub fn from_qualified(qualified: &[ResourceIdentifier]) -> Self {
Self::new_unchecked(
&qualified
.iter()
.map(ResourceIdentifier::to_string)
.collect::<Vec<String>>()
.join(&PART_SEPARATOR.to_string()),
)
}
/// Return `true` if this identifier contains path separator characters, else `false`.
pub fn contains_path(&self) -> bool {
self.0.contains(PATH_SEPARATOR)
}
/// Return the list of path components when split using the path separator character.
pub fn path_split(&self) -> Vec<ResourceIdentifier> {
self.0
.split(PATH_SEPARATOR)
.map(ResourceIdentifier::new_unchecked)
.collect()
}
/// Return `true` if this identifier contains qualifier separator characters, else `false`.
pub fn contains_qualified(&self) -> bool {
self.0.contains(PART_SEPARATOR)
}
/// Return the list of path components when split using the qualifier separator character.
pub fn qualifier_split(&self) -> Vec<ResourceIdentifier> {
self.0
.split(PART_SEPARATOR)
.map(ResourceIdentifier::new_unchecked)
.collect()
}
/// Return `true` if the identifier contains variables of the form
/// `${name}`, else `false`.
pub fn has_variables(&self) -> bool {
REGEX_VARIABLE.is_match(self.deref())
}
/// Replace any variables in the string with values from the context,
/// returning a new value if the replacements result in a legal identifier
/// string. The
pub fn replace_variables<V>(&self, context: &HashMap<String, V>) -> Result<Self, Error>
where
V: Clone + Into<String>,
{
let new_text = REGEX_VARIABLE.replace_all(self.deref(), |caps: &Captures<'_>| {
if let Some(value) = context.get(&caps[1]) {
value.clone().into()
} else {
format!("${{{}}}", &caps[1])
}
});
Self::from_str(&new_text)
}
}
// ------------------------------------------------------------------------------------------------
impl Display for ResourceName {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
vec![
ARN_PREFIX.to_string(),
self.partition
.as_ref()
.unwrap_or(&known::Partition::default().into())
.to_string(),
self.service.to_string(),
self.region
.as_ref()
.unwrap_or(&Identifier::default())
.to_string(),
self.account_id
.as_ref()
.unwrap_or(&AccountIdentifier::default())
.to_string(),
self.resource.to_string()
]
.join(&PART_SEPARATOR.to_string())
)
}
}
impl FromStr for ResourceName {
type Err = Error;
///
/// Format:
///
/// * `arn:partition:service:region:account-id: | resource part |`
///
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts: Vec<&str> = s.split(PART_SEPARATOR).collect();
if parts.len() < REQUIRED_COMPONENT_COUNT {
Err(Error::TooFewComponents)
} else if parts[0] != ARN_PREFIX {
Err(Error::MissingPrefix)
} else {
let new_arn = ResourceName {
partition: if parts[1].is_empty() {
None
} else if parts[1] == PARTITION_AWS_PREFIX
|| parts[1].starts_with(PARTITION_AWS_OTHER_PREFIX)
{
Some(Identifier::from_str(parts[1])?)
} else {
return Err(Error::InvalidPartition);
},
service: Identifier::from_str(parts[2])?,
region: if parts[3].is_empty() {
None
} else {
Some(Identifier::from_str(parts[3])?)
},
account_id: if parts[4].is_empty() {
None
} else {
Some(AccountIdentifier::from_str(parts[4])?)
},
resource: {
let resource_parts: Vec<&str> = parts.drain(5..).collect();
ResourceIdentifier::from_str(&resource_parts.join(&PART_SEPARATOR.to_string()))?
},
};
Ok(new_arn)
}
}
}
impl ResourceName {
/// Construct a minimal `ResourceName` value with simply a service and resource.
pub fn new(service: Identifier, resource: ResourceIdentifier) -> Self {
Self {
partition: None,
service,
region: None,
account_id: None,
resource,
}
}
/// Construct a minimal `ResourceName` value with simply a service and resource in the `aws` partition.
pub fn aws(service: Identifier, resource: ResourceIdentifier) -> Self {
Self {
partition: Some(known::Partition::default().into()),
service,
region: None,
account_id: None,
resource,
}
}
/// Return `true` if the identifier contains variables of the form
/// `${name}`, else `false`.
pub fn has_variables(&self) -> bool {
self.resource.has_variables()
}
/// Replace any variables in the string with values from the context,
/// returning a new value if the replacements result in a legal identifier
/// string. The
pub fn replace_variables<V>(&self, context: &HashMap<String, V>) -> Result<Self, Error>
where
V: Clone + Into<String>,
{
Ok(Self {
resource: self.resource.replace_variables(context)?,
..self.clone()
})
}
}
// ------------------------------------------------------------------------------------------------
// Modules
// ------------------------------------------------------------------------------------------------
#[cfg(feature = "builders")]
pub mod builder;
#[cfg(feature = "known")]
pub mod known;
#[doc(hidden)]
mod error;
pub use crate::error::Error;