Skip to main content

minco_aws_dynamodb/
lib.rs

1//! Validated AWS `DynamoDB` provider primitives for application-owned access models.
2#![forbid(unsafe_code)]
3
4use minco_core::{
5    CapabilityProvision, IdleCostClass, Plugin, PluginContext, PluginDescriptor, PluginError,
6    PluginId, PluginStability, ResourceIntent, ResourceKind,
7};
8use serde::{Deserialize, Serialize};
9
10pub mod audit_v2;
11
12#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct DynamoDbConfig {
15    table_name: String,
16    region: String,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    endpoint_url: Option<String>,
19}
20
21impl std::fmt::Debug for DynamoDbConfig {
22    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        formatter
24            .debug_struct("DynamoDbConfig")
25            .field("table_name", &"[REDACTED]")
26            .field("region", &self.region)
27            .field(
28                "endpoint_url",
29                &self.endpoint_url.as_ref().map(|_| "[REDACTED]"),
30            )
31            .finish()
32    }
33}
34
35impl DynamoDbConfig {
36    #[must_use]
37    pub fn new(
38        table_name: impl Into<String>,
39        region: impl Into<String>,
40        endpoint_url: Option<String>,
41    ) -> Self {
42        Self {
43            table_name: table_name.into(),
44            region: region.into(),
45            endpoint_url,
46        }
47    }
48
49    pub fn validate(&self) -> Result<(), DynamoDbError> {
50        if !valid_table_name(&self.table_name) {
51            return Err(DynamoDbError::InvalidConfiguration("table name is invalid"));
52        }
53        if !valid_region(&self.region) {
54            return Err(DynamoDbError::InvalidConfiguration("region is invalid"));
55        }
56        if self
57            .endpoint_url
58            .as_deref()
59            .is_some_and(|endpoint| !valid_endpoint(endpoint))
60        {
61            return Err(DynamoDbError::InvalidConfiguration(
62                "endpoint override is invalid",
63            ));
64        }
65        Ok(())
66    }
67
68    #[must_use]
69    pub fn table_name(&self) -> &str {
70        &self.table_name
71    }
72
73    #[must_use]
74    pub fn region(&self) -> &str {
75        &self.region
76    }
77
78    #[must_use]
79    pub fn endpoint_url(&self) -> Option<&str> {
80        self.endpoint_url.as_deref()
81    }
82
83    pub async fn build(&self) -> Result<DynamoDbProvider, DynamoDbError> {
84        self.validate()?;
85        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest())
86            .region(aws_config::Region::new(self.region.clone()));
87        if let Some(endpoint_url) = &self.endpoint_url {
88            loader = loader.endpoint_url(endpoint_url);
89        }
90        let shared = loader.load().await;
91        let client = aws_sdk_dynamodb::Client::new(&shared);
92        DynamoDbProvider::new(client, self.clone())
93    }
94}
95
96#[derive(Clone)]
97pub struct DynamoDbProvider {
98    client: aws_sdk_dynamodb::Client,
99    config: DynamoDbConfig,
100}
101
102impl std::fmt::Debug for DynamoDbProvider {
103    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        formatter
105            .debug_struct("DynamoDbProvider")
106            .field("config", &self.config)
107            .field("client", &"[REDACTED PROVIDER]")
108            .finish()
109    }
110}
111
112impl DynamoDbProvider {
113    pub fn new(
114        client: aws_sdk_dynamodb::Client,
115        config: DynamoDbConfig,
116    ) -> Result<Self, DynamoDbError> {
117        config.validate()?;
118        Ok(Self { client, config })
119    }
120
121    #[must_use]
122    pub const fn client(&self) -> &aws_sdk_dynamodb::Client {
123        &self.client
124    }
125
126    #[must_use]
127    pub fn table_name(&self) -> &str {
128        self.config.table_name()
129    }
130
131    pub async fn ready(&self) -> Result<(), DynamoDbError> {
132        self.client
133            .describe_table()
134            .table_name(self.table_name())
135            .send()
136            .await
137            .map(|_| ())
138            .map_err(|_| DynamoDbError::Provider("DescribeTable"))
139    }
140}
141
142#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
143pub enum DynamoDbError {
144    #[error("DynamoDB configuration is invalid: {0}")]
145    InvalidConfiguration(&'static str),
146    #[error("DynamoDB provider operation failed: {0}")]
147    Provider(&'static str),
148}
149
150#[derive(Debug, Clone, Copy, Default)]
151pub struct DynamoDbProviderPlugin;
152
153impl Plugin for DynamoDbProviderPlugin {
154    fn descriptor(&self) -> PluginDescriptor {
155        let mut descriptor = PluginDescriptor::new(
156            PluginId::new("aws-dynamodb").expect("static plugin ID"),
157            env!("CARGO_PKG_VERSION")
158                .parse()
159                .expect("package version is semver"),
160            "Validated AWS DynamoDB provider primitives for explicit access models",
161        );
162        descriptor.documentation = Some("https://docs.rs/minco-aws-dynamodb".into());
163        descriptor.core_compatibility = concat!("^", env!("CARGO_PKG_VERSION"))
164            .parse()
165            .expect("package version");
166        descriptor.stability = PluginStability::Beta;
167        descriptor.provides.push(CapabilityProvision {
168            name: "aws.dynamodb.client".into(),
169            version: env!("CARGO_PKG_VERSION")
170                .parse()
171                .expect("package version is semver"),
172        });
173        descriptor.resources.push(ResourceIntent {
174            id: "aws-dynamodb-table".into(),
175            kind: ResourceKind::DynamoDb,
176            idle_cost: IdleCostClass::StorageOnly,
177            wake_sources: Vec::new(),
178            dependencies: Vec::new(),
179        });
180        descriptor
181    }
182
183    fn install(&self, _context: &mut PluginContext<'_>) -> Result<(), PluginError> {
184        Ok(())
185    }
186}
187
188fn valid_table_name(value: &str) -> bool {
189    (3..=255).contains(&value.len())
190        && value
191            .bytes()
192            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
193}
194
195fn valid_region(value: &str) -> bool {
196    (3..=64).contains(&value.len())
197        && value
198            .bytes()
199            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
200        && value.contains('-')
201}
202
203fn valid_endpoint(value: &str) -> bool {
204    let Ok(uri) = value.parse::<http::Uri>() else {
205        return false;
206    };
207    let Some(authority) = uri.authority() else {
208        return false;
209    };
210    let Some(host) = uri.host() else {
211        return false;
212    };
213    if authority.as_str().contains('@')
214        || uri.query().is_some()
215        || !matches!(uri.path(), "" | "/")
216        || !matches!(uri.scheme_str(), Some("https" | "http"))
217    {
218        return false;
219    }
220    uri.scheme_str() == Some("https") || is_loopback_host(host)
221}
222
223fn is_loopback_host(host: &str) -> bool {
224    let host = host
225        .strip_prefix('[')
226        .and_then(|value| value.strip_suffix(']'))
227        .unwrap_or(host);
228    host.eq_ignore_ascii_case("localhost")
229        || host
230            .parse::<std::net::IpAddr>()
231            .is_ok_and(|address| address.is_loopback())
232}